diff --git a/app/src/main/java/org/oxycblt/auxio/MainFragment.kt b/app/src/main/java/org/oxycblt/auxio/MainFragment.kt index 0c51e1c5a..bbcadcb66 100644 --- a/app/src/main/java/org/oxycblt/auxio/MainFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/MainFragment.kt @@ -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()) { diff --git a/app/src/main/java/org/oxycblt/auxio/detail/DetailViewModel.kt b/app/src/main/java/org/oxycblt/auxio/detail/DetailViewModel.kt index c9996f65c..eb6c3d2d7 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/DetailViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/DetailViewModel.kt @@ -69,47 +69,35 @@ constructor( private val playbackSettings: PlaybackSettings, detailGeneratorFactory: DetailGenerator.Factory, ) : ViewModel(), DetailGenerator.Invalidator { - private val _toShow = MutableEvent() - /** * A [Show] command that is awaiting a view capable of responding to it. Null if none currently. */ val toShow: Event - get() = _toShow + field = MutableEvent() // --- SONG --- - private val _currentSong = MutableStateFlow(null) - /** The current [Song] to display. Null if there is nothing to show. */ val currentSong: StateFlow - get() = _currentSong - - private val _currentSongProperties = MutableStateFlow>(listOf()) + field = MutableStateFlow(null) /** The current properties of [currentSong]. Empty if nothing to show. */ val currentSongProperties: StateFlow> - get() = _currentSongProperties + field = MutableStateFlow>(listOf()) // --- ALBUM --- - private val _currentAlbum = MutableStateFlow(null) - /** The current [Album] to display. Null if there is nothing to show. */ val currentAlbum: StateFlow - get() = _currentAlbum - - private val _albumSongList = MutableStateFlow(listOf()) + field = MutableStateFlow(null) /** The current list data derived from [currentAlbum]. */ val albumSongList: StateFlow> - get() = _albumSongList - - private val _albumSongInstructions = MutableEvent() + field = MutableStateFlow(listOf()) /** Instructions for updating [albumSongList] in the UI. */ val albumSongInstructions: Event - get() = _albumSongInstructions + field = MutableEvent() /** The current [Sort] used for [Song]s in [albumSongList]. */ val albumSongSort: Sort @@ -121,22 +109,18 @@ constructor( // --- ARTIST --- - private val _currentArtist = MutableStateFlow(null) - /** The current [Artist] to display. Null if there is nothing to show. */ val currentArtist: StateFlow - get() = _currentArtist + field = MutableStateFlow(null) private val _artistSongList = MutableStateFlow(listOf()) /** The current list derived from [currentArtist]. */ val artistSongList: StateFlow> = _artistSongList - private val _artistSongInstructions = MutableEvent() - /** Instructions for updating [artistSongList] in the UI. */ val artistSongInstructions: Event - get() = _artistSongInstructions + field = MutableEvent() /** The current [Sort] used for [Song]s in [artistSongList]. */ val artistSongSort: Sort @@ -148,22 +132,18 @@ constructor( // --- GENRE --- - private val _currentGenre = MutableStateFlow(null) - /** The current [Genre] to display. Null if there is nothing to show. */ val currentGenre: StateFlow - get() = _currentGenre + field = MutableStateFlow(null) private val _genreSongList = MutableStateFlow(listOf()) /** The current list data derived from [currentGenre]. */ val genreSongList: StateFlow> = _genreSongList - private val _genreSongInstructions = MutableEvent() - /** Instructions for updating [artistSongList] in the UI. */ val genreSongInstructions: Event - get() = _genreSongInstructions + field = MutableEvent() /** The current [Sort] used for [Song]s in [genreSongList]. */ val genreSongSort: Sort @@ -175,31 +155,25 @@ constructor( // --- PLAYLIST --- - private val _currentPlaylist = MutableStateFlow(null) - /** The current [Playlist] to display. Null if there is nothing to do. */ val currentPlaylist: StateFlow - get() = _currentPlaylist + field = MutableStateFlow(null) private val _playlistSongList = MutableStateFlow(listOf()) /** The current list data derived from [currentPlaylist] */ val playlistSongList: StateFlow> = _playlistSongList - private val _playlistSongInstructions = MutableEvent() - /** Instructions for updating [playlistSongList] in the UI. */ val playlistSongInstructions: Event - get() = _playlistSongInstructions - - private val _editedPlaylist = MutableStateFlow?>(null) + field = MutableEvent() /** * The new playlist songs created during the current editing session. Null if no editing session * is occurring. */ val editedPlaylist: StateFlow?> - get() = _editedPlaylist + field = MutableStateFlow?>(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 } } diff --git a/app/src/main/java/org/oxycblt/auxio/detail/ReadOnlyTextInput.kt b/app/src/main/java/org/oxycblt/auxio/detail/ReadOnlyTextInput.kt index 928cd0f16..30515ff78 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/ReadOnlyTextInput.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/ReadOnlyTextInput.kt @@ -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 } } diff --git a/app/src/main/java/org/oxycblt/auxio/detail/decision/DetailDecisionViewModel.kt b/app/src/main/java/org/oxycblt/auxio/detail/decision/DetailDecisionViewModel.kt index cd31361d5..59a062993 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/decision/DetailDecisionViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/decision/DetailDecisionViewModel.kt @@ -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(null) /** The current set of [Artist] choices to show in the picker, or null if to show nothing. */ val artistChoices: StateFlow - get() = _artistChoices + field = MutableStateFlow(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") diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/AlbumDetailListAdapter.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/AlbumDetailListAdapter.kt index febec346b..ac0c28182 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/AlbumDetailListAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/AlbumDetailListAdapter.kt @@ -86,12 +86,14 @@ class AlbumDetailListAdapter(private val listener: Listener) : val DIFF_CALLBACK = object : SimpleDiffCallback() { 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. diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/ArtistDetailListAdapter.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/ArtistDetailListAdapter.kt index 2c5d2a4d9..f21243256 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/ArtistDetailListAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/ArtistDetailListAdapter.kt @@ -73,11 +73,13 @@ class ArtistDetailListAdapter(private val listener: Listener) : val DIFF_CALLBACK = object : SimpleDiffCallback() { 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) } } diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/DetailListAdapter.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/DetailListAdapter.kt index 3658dcca7..76ba93d77 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/DetailListAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/DetailListAdapter.kt @@ -89,13 +89,16 @@ abstract class DetailListAdapter( val DIFF_CALLBACK = object : SimpleDiffCallback() { 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 } } diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/GenreDetailListAdapter.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/GenreDetailListAdapter.kt index 29ecd6185..6859de9c2 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/GenreDetailListAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/GenreDetailListAdapter.kt @@ -64,11 +64,13 @@ class GenreDetailListAdapter(private val listener: Listener) : val DIFF_CALLBACK = object : SimpleDiffCallback() { 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) } } diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDetailListAdapter.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDetailListAdapter.kt index 15f1074e9..ec5452d06 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDetailListAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDetailListAdapter.kt @@ -128,14 +128,16 @@ class PlaylistDetailListAdapter(private val listener: Listener) : val DIFF_CALLBACK = object : SimpleDiffCallback() { 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) } } diff --git a/app/src/main/java/org/oxycblt/auxio/home/HomeSettings.kt b/app/src/main/java/org/oxycblt/auxio/home/HomeSettings.kt index 96d6e3455..54fda63e4 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/HomeSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/HomeSettings.kt @@ -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)) diff --git a/app/src/main/java/org/oxycblt/auxio/home/HomeViewModel.kt b/app/src/main/java/org/oxycblt/auxio/home/HomeViewModel.kt index 1402de7b1..a5ac431ec 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/HomeViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/HomeViewModel.kt @@ -52,15 +52,13 @@ constructor( private val playbackSettings: PlaybackSettings, homeGeneratorFactory: HomeGenerator.Factory, ) : ViewModel(), HomeGenerator.Invalidator { - private val _songList = MutableStateFlow(listOf()) /** A list of [Song]s, sorted by the preferred [Sort], to be shown in the home view. */ val songList: StateFlow> - get() = _songList + field = MutableStateFlow(listOf()) - private val _songInstructions = MutableEvent() /** Instructions for how to update [songList] in the UI. */ val songInstructions: Event - get() = _songInstructions + field = MutableEvent() /** The current [Sort] used for [songList]. */ val songSort: Sort @@ -70,15 +68,13 @@ constructor( val playWith get() = playbackSettings.playInListWith - private val _albumList = MutableStateFlow(listOf()) /** A list of [Album]s, sorted by the preferred [Sort], to be shown in the home view. */ val albumList: StateFlow> - get() = _albumList + field = MutableStateFlow(listOf()) - private val _albumInstructions = MutableEvent() /** Instructions for how to update [albumList] in the UI. */ val albumInstructions: Event - get() = _albumInstructions + field = MutableEvent() /** The current [Sort] used for [albumList]. */ val albumSort: Sort @@ -92,42 +88,36 @@ constructor( val artistList: MutableStateFlow> get() = _artistList - private val _artistInstructions = MutableEvent() /** Instructions for how to update [artistList] in the UI. */ val artistInstructions: Event - get() = _artistInstructions + field = MutableEvent() /** The current [Sort] used for [artistList]. */ val artistSort: Sort get() = listSettings.artistSort - private val _genreList = MutableStateFlow(listOf()) /** A list of [Genre]s, sorted by the preferred [Sort], to be shown in the home view. */ val genreList: StateFlow> - get() = _genreList + field = MutableStateFlow(listOf()) - private val _genreInstructions = MutableEvent() /** Instructions for how to update [genreList] in the UI. */ val genreInstructions: Event - get() = _genreInstructions + field = MutableEvent() /** The current [Sort] used for [genreList]. */ val genreSort: Sort get() = listSettings.genreSort - private val _playlistList = MutableStateFlow(listOf()) /** A list of [Playlist]s, sorted by the preferred [Sort], to be shown in the home view. */ val playlistList: StateFlow> - get() = _playlistList + field = MutableStateFlow(listOf()) - private val _empty = MutableStateFlow(false) val empty: StateFlow - get() = _empty + field = MutableStateFlow(false) - private val _playlistInstructions = MutableEvent() /** Instructions for how to update [genreList] in the UI. */ val playlistInstructions: Event - get() = _playlistInstructions + field = MutableEvent() /** The current [Sort] used for [genreList]. */ val playlistSort: Sort @@ -146,68 +136,64 @@ constructor( /** The [MusicType] of the currently shown [Tab]. */ val currentTabType: StateFlow = _currentTabType - private val _shouldRecreate = MutableEvent() /** * 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 - get() = _shouldRecreate + field = MutableEvent() private val _isFastScrolling = MutableStateFlow(false) /** A marker for whether the user is fast-scrolling in the home view or not. */ val isFastScrolling: StateFlow = _isFastScrolling - private val _showOuter = MutableEvent() val showOuter: Event - get() = _showOuter + field = MutableEvent() - private val _chooseMusicLocations = MutableEvent() val chooseMusicLocations: Event - get() = _chooseMusicLocations + field = MutableEvent() 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) } } diff --git a/app/src/main/java/org/oxycblt/auxio/home/ThemedSpeedDialView.kt b/app/src/main/java/org/oxycblt/auxio/home/ThemedSpeedDialView.kt index 2ace71bce..17e6b05b9 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/ThemedSpeedDialView.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/ThemedSpeedDialView.kt @@ -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) { diff --git a/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt b/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt index 0eaa655b3..9080c1d6e 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt @@ -31,7 +31,7 @@ class NullCovers(private val storage: CoverStorage) : MutableCovers { override suspend fun create(file: File, metadata: Metadata) = CoverResult.Hit(NullCover) override suspend fun cleanup(excluding: Collection) { - storage.ls(setOf()).map { storage.rm(it) } + storage.ls(setOf()).forEach { storage.rm(it) } } } diff --git a/app/src/main/java/org/oxycblt/auxio/list/ListViewModel.kt b/app/src/main/java/org/oxycblt/auxio/list/ListViewModel.kt index b2eccb15a..41928e7bc 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/ListViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/ListViewModel.kt @@ -48,10 +48,9 @@ class ListViewModel @Inject constructor(private val listSettings: ListSettings, private val musicRepository: MusicRepository) : ViewModel(), MusicRepository.UpdateListener { - private val _selected = MutableStateFlow(listOf()) /** The currently selected items. These are ordered in earliest selected and latest selected. */ val selected: StateFlow> - get() = _selected + field = MutableStateFlow(listOf()) private val _menu = MutableEvent() /** @@ -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 { 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() } } /** diff --git a/app/src/main/java/org/oxycblt/auxio/list/menu/MenuDialogFragment.kt b/app/src/main/java/org/oxycblt/auxio/list/menu/MenuDialogFragment.kt index ed20326bd..57bf93a6d 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/menu/MenuDialogFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/menu/MenuDialogFragment.kt @@ -100,6 +100,7 @@ abstract class MenuDialogFragment : binding.menuOptionRecycler.adapter = null } + @SuppressLint("RestrictedApi") private fun updateMenu(menu: Menu?) { if (menu == null) { L.d("No menu to show, navigating away") diff --git a/app/src/main/java/org/oxycblt/auxio/list/recycler/DialogRecyclerView.kt b/app/src/main/java/org/oxycblt/auxio/list/recycler/DialogRecyclerView.kt index 01c3caa7b..3dcdaacf7 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/recycler/DialogRecyclerView.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/recycler/DialogRecyclerView.kt @@ -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, diff --git a/app/src/main/java/org/oxycblt/auxio/list/recycler/FastScrollRecyclerView.kt b/app/src/main/java/org/oxycblt/auxio/list/recycler/FastScrollRecyclerView.kt index 0b6d796b0..c010f6be9 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/recycler/FastScrollRecyclerView.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/recycler/FastScrollRecyclerView.kt @@ -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) { diff --git a/app/src/main/java/org/oxycblt/auxio/list/recycler/MaterialDragCallback.kt b/app/src/main/java/org/oxycblt/auxio/list/recycler/MaterialDragCallback.kt index 068603ded..120b626ed 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/recycler/MaterialDragCallback.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/recycler/MaterialDragCallback.kt @@ -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, diff --git a/app/src/main/java/org/oxycblt/auxio/list/sort/SortDialog.kt b/app/src/main/java/org/oxycblt/auxio/list/sort/SortDialog.kt index db99dd6bc..fa819c2bb 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/sort/SortDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/sort/SortDialog.kt @@ -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 diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 2715a5898..f8b8cb881 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -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 = - 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 { val split = mutableListOf() diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt index bde670b0d..713c2b085 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt @@ -62,24 +62,19 @@ constructor( /** The current music loading state, or null if no loading is going on. */ val indexingState: StateFlow = _indexingState - private val _statistics = MutableStateFlow(null) - /** [Statistics] about the last completed music load. */ val statistics: StateFlow - get() = _statistics - - private val _playlistDecision = MutableEvent() + field = MutableStateFlow(null) /** * A [PlaylistDecision] command that is awaiting a view capable of responding to it. Null if * none currently. */ val playlistDecision: Event - get() = _playlistDecision + field = MutableEvent() - private val _playlistMessage = MutableEvent() val playlistMessage: Event - get() = _playlistMessage + field = MutableEvent() 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)) } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistPickerViewModel.kt b/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistPickerViewModel.kt index d5a3f44ea..a7111084c 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistPickerViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistPickerViewModel.kt @@ -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(null) /** A new [Playlist] having it's name chosen by the user. Null if none yet. */ val currentPendingNewPlaylist: StateFlow - get() = _currentPendingNewPlaylist + field = MutableStateFlow(null) - private val _currentPendingRenamePlaylist = MutableStateFlow(null) /** An existing [Playlist] that is being renamed. Null if none yet. */ val currentPendingRenamePlaylist: StateFlow - get() = _currentPendingRenamePlaylist + field = MutableStateFlow(null) - private val _currentPlaylistToExport = MutableStateFlow(null) /** An existing [Playlist] that is being exported. Null if none yet. */ val currentPlaylistToExport: StateFlow - get() = _currentPlaylistToExport + field = MutableStateFlow(null) - private val _currentExportConfig = MutableStateFlow(DEFAULT_EXPORT_CONFIG) /** The current [ExportConfig] to use when exporting a playlist. */ val currentExportConfig: StateFlow - get() = _currentExportConfig + field = MutableStateFlow(DEFAULT_EXPORT_CONFIG) - private val _currentPlaylistToDelete = MutableStateFlow(null) /** The current [Playlist] that needs it's deletion confirmed. Null if none yet. */ val currentPlaylistToDelete: StateFlow - get() = _currentPlaylistToDelete + field = MutableStateFlow(null) - private val _chosenName = MutableStateFlow(ChosenName.Empty) /** The users chosen name for [currentPendingNewPlaylist] or [currentPendingRenamePlaylist]. */ val chosenName: StateFlow - get() = _chosenName + field = MutableStateFlow(ChosenName.Empty) - private val _currentSongsToAdd = MutableStateFlow?>(null) /** A batch of [Song]s to add to a playlist chosen by the user. Null if none yet. */ val currentSongsToAdd: StateFlow?> - get() = _currentSongsToAdd + field = MutableStateFlow?>(null) - private val _playlistAddChoices = MutableStateFlow>(listOf()) /** The [Playlist]s that [currentSongsToAdd] could be added to. */ val playlistAddChoices: StateFlow> - get() = _playlistAddChoices + field = MutableStateFlow>(listOf()) init { musicRepository.addUpdateListener(this) @@ -91,8 +83,8 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M var refreshChoicesWith: List? = 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) { 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) { 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)) diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/MediaItemTranslation.kt b/app/src/main/java/org/oxycblt/auxio/music/service/MediaItemTranslation.kt index e439f6191..22a6d9aba 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/MediaItemTranslation.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/MediaItemTranslation.kt @@ -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 } } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/MusicBrowser.kt b/app/src/main/java/org/oxycblt/auxio/music/service/MusicBrowser.kt index e6f5673e3..fd2fdeda0 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/MusicBrowser.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/MusicBrowser.kt @@ -183,7 +183,7 @@ private constructor( getChildMediaItems(mediaSessionUID.uid) } null -> { - return null + null } } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBarFragment.kt b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBarFragment.kt index 93e00848d..b3d8dd277 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBarFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBarFragment.kt @@ -51,7 +51,6 @@ class PlaybackBarFragment : ViewBindingFragment() { savedInstanceState: Bundle?, ) { super.onBindingCreated(binding, savedInstanceState) - val context = requireContext() // --- UI SETUP --- binding.root.apply { diff --git a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackPanelFragment.kt b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackPanelFragment.kt index 9bffcbb8e..7a9cc9a45 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackPanelFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackPanelFragment.kt @@ -82,7 +82,6 @@ class PlaybackPanelFragment : private val queueModel: QueueViewModel by viewModels() private var equalizerLauncher: ActivityResultLauncher? = 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 {} } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackViewModel.kt b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackViewModel.kt index 8365abbc8..c81238290 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackViewModel.kt @@ -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(null) /** The currently playing song. */ val song: StateFlow - get() = _song + field = MutableStateFlow(null) private val _parent = MutableStateFlow(null) /** The [MusicParent] currently being played. Null if playback is occurring from all songs. */ val parent: StateFlow = _parent - private val _isPlaying = MutableStateFlow(false) + /** Whether playback is ongoing or paused. */ val isPlaying: StateFlow - get() = _isPlaying + field = MutableStateFlow(false) - private val _positionDs = MutableStateFlow(0L) /** The current position, in deci-seconds (1/10th of a second). */ val positionDs: StateFlow - get() = _positionDs + field = MutableStateFlow(0L) - private val _repeatMode = MutableStateFlow(RepeatMode.NONE) /** The current [RepeatMode]. */ val repeatMode: StateFlow - get() = _repeatMode + field = MutableStateFlow(RepeatMode.NONE) - private val _isShuffled = MutableStateFlow(false) /** Whether the queue is shuffled or not. */ val isShuffled: StateFlow - 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 - get() = _currentBarAction + field = MutableStateFlow(playbackSettings.barAction) - private val _openPanel = MutableEvent() /** * A [OpenPanel] command that is awaiting a view capable of responding to it. Null if none * currently. */ val openPanel: Event - get() = _openPanel + field = MutableEvent() private val _pagerQueue = MutableStateFlow(PagerQueue(listOf(), 0)) /** The current queue in a special bundled format suitable for the cover ViewPager2. */ val pagerQueue: StateFlow = _pagerQueue - private val _pagerCommand = MutableEvent() /** Specialized ViewPager2-friendly queue commands */ val pagerCommand: Event - get() = _pagerCommand + field = MutableEvent() - private val _playbackDecision = MutableEvent() /** * A [PlaybackDecision] command that is awaiting a view capable of responding to it. Null if * none currently. */ val playbackDecision: Event - get() = _playbackDecision + field = MutableEvent() /** * 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, 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 { diff --git a/app/src/main/java/org/oxycblt/auxio/playback/decision/PlaybackPickerViewModel.kt b/app/src/main/java/org/oxycblt/auxio/playback/decision/PlaybackPickerViewModel.kt index 95fae0c5a..3e0e5957e 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/decision/PlaybackPickerViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/decision/PlaybackPickerViewModel.kt @@ -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(null) /** The current set of [Artist] choices to show in the picker, or null if to show nothing. */ val currentPickerSong: StateFlow - get() = _currentPickerSong + field = MutableStateFlow(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") } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueViewModel.kt b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueViewModel.kt index 20abf7881..54ee8c6ce 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueViewModel.kt @@ -47,15 +47,14 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt private val _queueInstructions = MutableEvent() /** Instructions for how to update [queue] in the UI. */ val queueInstructions: Event = _queueInstructions - private val _scrollTo = MutableEvent() + /** Controls whether the queue should be force-scrolled to a particular location. */ val scrollTo: Event - get() = _scrollTo + field = MutableEvent() - private val _index = MutableStateFlow(playbackManager.index) /** The index of the currently playing song in the queue. */ val index: StateFlow - 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, 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) } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/replaygain/ReplayGainAudioProcessor.kt b/app/src/main/java/org/oxycblt/auxio/playback/replaygain/ReplayGainAudioProcessor.kt index c41e98e48..3cb16cde3 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/replaygain/ReplayGainAudioProcessor.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/replaygain/ReplayGainAudioProcessor.kt @@ -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( diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/ExoPlaybackStateHolder.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/ExoPlaybackStateHolder.kt index f177ffaf4..58a3b1430 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/ExoPlaybackStateHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/ExoPlaybackStateHolder.kt @@ -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) { diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionHolder.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionHolder.kt index 892dd32d9..b5e6706f7 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionHolder.kt @@ -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") diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionInterface.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionInterface.kt index b1246b2fb..8a1217993 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionInterface.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionInterface.kt @@ -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) diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/PlaybackServiceFragment.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/PlaybackServiceFragment.kt index 387295be2..b24838f5b 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/PlaybackServiceFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/PlaybackServiceFragment.kt @@ -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() } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/ForcedLTRFrameLayout.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/ForcedLTRFrameLayout.kt index 2df5c7a8b..e28c97f2d 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/ui/ForcedLTRFrameLayout.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/ForcedLTRFrameLayout.kt @@ -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 } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/StepperOverlay.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/StepperOverlay.kt index 07dcb246a..399f52018 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/StepperOverlay.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/StepperOverlay.kt @@ -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, ) diff --git a/app/src/main/java/org/oxycblt/auxio/search/SearchAdapter.kt b/app/src/main/java/org/oxycblt/auxio/search/SearchAdapter.kt index 32f9b09a0..4e68fd58f 100644 --- a/app/src/main/java/org/oxycblt/auxio/search/SearchAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/search/SearchAdapter.kt @@ -89,21 +89,28 @@ class SearchAdapter(private val listener: SelectableListListener) : val DIFF_CALLBACK = object : SimpleDiffCallback() { 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 } } diff --git a/app/src/main/java/org/oxycblt/auxio/search/SearchViewModel.kt b/app/src/main/java/org/oxycblt/auxio/search/SearchViewModel.kt index abff42b6f..417107f9c 100644 --- a/app/src/main/java/org/oxycblt/auxio/search/SearchViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/search/SearchViewModel.kt @@ -57,10 +57,9 @@ constructor( private var lastQuery: String? = null private var currentSearchJob: Job? = null - private val _searchResults = MutableStateFlow(listOf()) /** The results of the last [search] call, if any. */ val searchResults: StateFlow> - get() = _searchResults + field = MutableStateFlow(listOf()) /** 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() } } } diff --git a/app/src/main/java/org/oxycblt/auxio/settings/ui/IntListPreference.kt b/app/src/main/java/org/oxycblt/auxio/settings/ui/IntListPreference.kt index 8dbd67b40..b45ea79d1 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/ui/IntListPreference.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/ui/IntListPreference.kt @@ -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() } diff --git a/app/src/main/java/org/oxycblt/auxio/ui/Animations.kt b/app/src/main/java/org/oxycblt/auxio/ui/Animations.kt index 5e3fa7fc1..2be3a50c0 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/Animations.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/Animations.kt @@ -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, diff --git a/app/src/main/java/org/oxycblt/auxio/ui/AuxioToolbar.kt b/app/src/main/java/org/oxycblt/auxio/ui/AuxioToolbar.kt index 95f91826e..8ea7a0e2d 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/AuxioToolbar.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/AuxioToolbar.kt @@ -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() @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) { diff --git a/app/src/main/java/org/oxycblt/auxio/ui/BaseBottomSheetBehavior.kt b/app/src/main/java/org/oxycblt/auxio/ui/BaseBottomSheetBehavior.kt index 8f4488a7d..8f4806a1c 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/BaseBottomSheetBehavior.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/BaseBottomSheetBehavior.kt @@ -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(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. diff --git a/app/src/main/java/org/oxycblt/auxio/ui/MultiToolbar.kt b/app/src/main/java/org/oxycblt/auxio/ui/MultiToolbar.kt index aac4221ab..fbcf0b1ab 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/MultiToolbar.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/MultiToolbar.kt @@ -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 } } diff --git a/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingBottomSheetDialogFragment.kt b/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingBottomSheetDialogFragment.kt index 453e866dc..76622652e 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingBottomSheetDialogFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingBottomSheetDialogFragment.kt @@ -114,7 +114,7 @@ abstract class ViewBindingBottomSheetDialogFragment : L.d("Fragment destroyed") } - private inner class TweakedBottomSheetDialog + private class TweakedBottomSheetDialog @JvmOverloads constructor(context: Context, @StyleRes theme: Int = 0) : BackportBottomSheetDialog(context, theme) { diff --git a/app/src/main/java/org/oxycblt/auxio/util/LangUtil.kt b/app/src/main/java/org/oxycblt/auxio/util/LangUtil.kt index f1273fcc5..d5f9465f0 100644 --- a/app/src/main/java/org/oxycblt/auxio/util/LangUtil.kt +++ b/app/src/main/java/org/oxycblt/auxio/util/LangUtil.kt @@ -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 { - val split = mutableListOf() - 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 -} diff --git a/app/src/main/java/org/oxycblt/auxio/widgets/WidgetProvider.kt b/app/src/main/java/org/oxycblt/auxio/widgets/WidgetProvider.kt index f287863a7..b97f6079d 100644 --- a/app/src/main/java/org/oxycblt/auxio/widgets/WidgetProvider.kt +++ b/app/src/main/java/org/oxycblt/auxio/widgets/WidgetProvider.kt @@ -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") diff --git a/app/src/main/res/values/attrs.xml b/app/src/main/res/values/attrs.xml index d455a22ab..867d55d43 100644 --- a/app/src/main/res/values/attrs.xml +++ b/app/src/main/res/values/attrs.xml @@ -17,7 +17,7 @@ - + diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index bd1c7c39b..44b7f1bcd 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -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(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) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/CoverIdentifier.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/CoverIdentifier.kt index 1526effcb..2bff28724 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/CoverIdentifier.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/CoverIdentifier.kt @@ -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 = diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt index 79bcc286d..ca503d5fc 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt @@ -56,7 +56,7 @@ private constructor( @OptIn(ExperimentalCoroutinesApi::class) override suspend fun explore(files: Channel): Deferred> = coroutineScope { - tryAsyncWith(files, Dispatchers.IO) { + tryAsyncWith(files, Dispatchers.IO) { _ -> val projection = BASE_PROJECTION + pathInterpreterFactory.projection var selector = BASE_SELECTOR val args = mutableListOf() diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt index 9637e32c0..ae011c9ae 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt @@ -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(), ) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt index c4cfefca5..45ee6dfbf 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt @@ -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()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/graph/MusicGraph.kt b/musikr/src/main/java/org/oxycblt/musikr/graph/MusicGraph.kt index 27a4b3c75..05c5209db 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/graph/MusicGraph.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/graph/MusicGraph.kt @@ -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) diff --git a/musikr/src/main/java/org/oxycblt/musikr/model/LibraryFactory.kt b/musikr/src/main/java/org/oxycblt/musikr/model/LibraryFactory.kt index ca01987e8..4bec69ff0 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/model/LibraryFactory.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/model/LibraryFactory.kt @@ -46,7 +46,7 @@ internal interface LibraryFactory { } } -private class LibraryFactoryImpl() : LibraryFactory { +private class LibraryFactoryImpl : LibraryFactory { override fun create( graph: MusicGraph, storedPlaylists: StoredPlaylists, diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt index 34ff75ecf..b7dfcbe9e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt @@ -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) diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/FlowUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/FlowUtil.kt index 56e259ac8..eecdbb08e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/FlowUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/FlowUtil.kt @@ -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 Flow.distributedMap( - n: Int, - on: CoroutineContext = Dispatchers.Main, - buffer: Int = Channel.UNLIMITED, - block: suspend (T) -> R, -): Flow { - val posChannels = List(n) { Channel(Channel.UNLIMITED) } - val managerFlow = - flow { - 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 Flow.tryMap(transform: suspend (T) -> R): Flow = flow { collect { value -> @@ -72,15 +30,3 @@ internal fun Flow.tryMap(transform: suspend (T) -> R): Flow = flow } } } - -internal suspend fun Flow.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 -} diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt index 06288de4f..193c5666b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt @@ -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 -> { // Working directory is shallower than the path, can just append the // non-common remainder of the path relativeComponents = relativeComponents.child(depth(commonIndex)) diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/Naming.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/Naming.kt index 43d1ce4e3..60284a5a4 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/Naming.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/Naming.kt @@ -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. diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagFields.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagFields.kt index 1800f9cca..ea962e6ac 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagFields.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagFields.kt @@ -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) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt index 247f8474e..f6ab582e1 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt @@ -34,14 +34,15 @@ import org.oxycblt.musikr.tag.Date fun CoroutineScope.tryAsync( context: CoroutineContext, block: suspend () -> Unit, -): Deferred> = async { - try { - block() - Result.success(Unit) - } catch (e: Throwable) { - Result.failure(e) +): Deferred> = + async(context = context) { + try { + block() + Result.success(Unit) + } catch (e: Throwable) { + Result.failure(e) + } } -} fun CoroutineScope.tryAsyncWith( channel: Channel, @@ -70,7 +71,6 @@ fun CoroutineScope.map( block(item)?.let { output.send(it) } } output.close() - Unit } }