Merge branch 'dev' into feature/cover_carousel

This commit is contained in:
Alexander Capehart
2023-08-21 07:50:23 -06:00
committed by GitHub
131 changed files with 2748 additions and 1527 deletions
@@ -29,6 +29,7 @@ import org.oxycblt.auxio.home.HomeSettings
import org.oxycblt.auxio.image.ImageSettings
import org.oxycblt.auxio.playback.PlaybackSettings
import org.oxycblt.auxio.ui.UISettings
import timber.log.Timber
/**
* A simple, rational music player for android.
@@ -44,6 +45,10 @@ class Auxio : Application() {
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
// Migrate any settings that may have changed in an app update.
imageSettings.migrate()
playbackSettings.migrate()
@@ -27,8 +27,6 @@ import androidx.core.view.ViewCompat
import androidx.core.view.isInvisible
import androidx.core.view.updatePadding
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.google.android.material.R as MR
@@ -40,6 +38,7 @@ import kotlin.math.max
import kotlin.math.min
import org.oxycblt.auxio.databinding.FragmentMainBinding
import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.detail.Show
import org.oxycblt.auxio.home.HomeViewModel
import org.oxycblt.auxio.home.Outer
import org.oxycblt.auxio.list.ListViewModel
@@ -49,7 +48,9 @@ import org.oxycblt.auxio.playback.OpenPanel
import org.oxycblt.auxio.playback.PlaybackBottomSheetBehavior
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.queue.QueueBottomSheetBehavior
import org.oxycblt.auxio.ui.DialogAwareNavigationListener
import org.oxycblt.auxio.ui.ViewBindingFragment
import org.oxycblt.auxio.util.collect
import org.oxycblt.auxio.util.collectImmediately
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.coordinatorLayoutBehavior
@@ -67,9 +68,7 @@ import org.oxycblt.auxio.util.unlikelyToBeNull
*/
@AndroidEntryPoint
class MainFragment :
ViewBindingFragment<FragmentMainBinding>(),
ViewTreeObserver.OnPreDrawListener,
NavController.OnDestinationChangedListener {
ViewBindingFragment<FragmentMainBinding>(), ViewTreeObserver.OnPreDrawListener {
private val detailModel: DetailViewModel by activityViewModels()
private val homeModel: HomeViewModel by activityViewModels()
private val listModel: ListViewModel by activityViewModels()
@@ -77,9 +76,9 @@ class MainFragment :
private var sheetBackCallback: SheetBackPressedCallback? = null
private var detailBackCallback: DetailBackPressedCallback? = null
private var selectionBackCallback: SelectionBackPressedCallback? = null
private var selectionNavigationListener: DialogAwareNavigationListener? = null
private var lastInsets: WindowInsets? = null
private var elevationNormal = 0f
private var initialNavDestinationChange = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -111,6 +110,8 @@ class MainFragment :
val selectionBackCallback =
SelectionBackPressedCallback(listModel).also { selectionBackCallback = it }
selectionNavigationListener = DialogAwareNavigationListener(listModel::dropSelection)
// --- UI SETUP ---
val context = requireActivity()
@@ -150,6 +151,11 @@ class MainFragment :
}
// --- VIEWMODEL SETUP ---
// This has to be done here instead of the playback panel to make sure that it's prioritized
// by StateFlow over any detail fragment.
// FIXME: This is a consequence of sharing events across several consumers. There has to be
// a better way of doing this.
collect(detailModel.toShow.flow, ::handleShow)
collectImmediately(detailModel.editedPlaylist, detailBackCallback::invalidateEnabled)
collectImmediately(homeModel.showOuter.flow, ::handleShowOuter)
collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled)
@@ -162,8 +168,8 @@ class MainFragment :
val binding = requireBinding()
// Once we add the destination change callback, we will receive another initialization call,
// so handle that by resetting the flag.
initialNavDestinationChange = false
binding.exploreNavHost.findNavController().addOnDestinationChangedListener(this)
requireNotNull(selectionNavigationListener) { "NavigationListener was not available" }
.attach(binding.exploreNavHost.findNavController())
// Listener could still reasonably fire even if we clear the binding, attach/detach
// our pre-draw listener our listener in onStart/onStop respectively.
binding.playbackSheet.viewTreeObserver.addOnPreDrawListener(this@MainFragment)
@@ -184,7 +190,8 @@ class MainFragment :
override fun onStop() {
super.onStop()
val binding = requireBinding()
binding.exploreNavHost.findNavController().removeOnDestinationChangedListener(this)
requireNotNull(selectionNavigationListener) { "NavigationListener was not available" }
.release(binding.exploreNavHost.findNavController())
binding.playbackSheet.viewTreeObserver.removeOnPreDrawListener(this)
}
@@ -193,6 +200,7 @@ class MainFragment :
sheetBackCallback = null
detailBackCallback = null
selectionBackCallback = null
selectionNavigationListener = null
}
override fun onPreDraw(): Boolean {
@@ -286,19 +294,18 @@ class MainFragment :
return true
}
override fun onDestinationChanged(
controller: NavController,
destination: NavDestination,
arguments: Bundle?
) {
// Drop the initial call by NavController that simply provides us with the current
// destination. This would cause the selection state to be lost every time the device
// rotates.
if (!initialNavDestinationChange) {
initialNavDestinationChange = true
return
private fun handleShow(show: Show?) {
when (show) {
is Show.SongAlbumDetails,
is Show.ArtistDetails,
is Show.AlbumDetails -> playbackModel.openMain()
is Show.SongDetails,
is Show.SongArtistDecision,
is Show.AlbumArtistDecision,
is Show.GenreDetails,
is Show.PlaylistDetails,
null -> {}
}
listModel.dropSelection()
}
private fun handleShowOuter(outer: Outer?) {
@@ -101,7 +101,7 @@ class AlbumDetailFragment :
setNavigationOnClickListener { findNavController().navigateUp() }
overrideOnOverflowMenuClick {
listModel.openMenu(
R.menu.item_detail_album, unlikelyToBeNull(detailModel.currentAlbum.value))
R.menu.detail_album, unlikelyToBeNull(detailModel.currentAlbum.value))
}
}
@@ -145,7 +145,7 @@ class AlbumDetailFragment :
}
override fun onOpenMenu(item: Song) {
listModel.openMenu(R.menu.item_album_song, item, detailModel.playInAlbumWith)
listModel.openMenu(R.menu.album_song, item, detailModel.playInAlbumWith)
}
override fun onPlay() {
@@ -243,6 +243,7 @@ class AlbumDetailFragment :
when (menu) {
is Menu.ForSong -> AlbumDetailFragmentDirections.openSongMenu(menu.parcel)
is Menu.ForAlbum -> AlbumDetailFragmentDirections.openAlbumMenu(menu.parcel)
is Menu.ForSelection -> AlbumDetailFragmentDirections.openSelectionMenu(menu.parcel)
is Menu.ForArtist,
is Menu.ForGenre,
is Menu.ForPlaylist -> error("Unexpected menu $menu")
@@ -100,7 +100,7 @@ class ArtistDetailFragment :
setOnMenuItemClickListener(this@ArtistDetailFragment)
overrideOnOverflowMenuClick {
listModel.openMenu(
R.menu.item_detail_parent, unlikelyToBeNull(detailModel.currentArtist.value))
R.menu.detail_parent, unlikelyToBeNull(detailModel.currentArtist.value))
}
}
@@ -152,9 +152,8 @@ class ArtistDetailFragment :
override fun onOpenMenu(item: Music) {
when (item) {
is Song ->
listModel.openMenu(R.menu.item_artist_song, item, detailModel.playInArtistWith)
is Album -> listModel.openMenu(R.menu.item_artist_album, item)
is Song -> listModel.openMenu(R.menu.artist_song, item, detailModel.playInArtistWith)
is Album -> listModel.openMenu(R.menu.artist_album, item)
else -> error("Unexpected datatype: ${item::class.simpleName}")
}
}
@@ -222,8 +221,16 @@ class ArtistDetailFragment :
.navigateSafe(ArtistDetailFragmentDirections.showArtist(show.artist.uid))
}
}
is Show.SongArtistDecision,
is Show.AlbumArtistDecision,
is Show.SongArtistDecision -> {
logD("Navigating to artist choices for ${show.song}")
findNavController()
.navigateSafe(ArtistDetailFragmentDirections.showArtistChoices(show.song.uid))
}
is Show.AlbumArtistDecision -> {
logD("Navigating to artist choices for ${show.album}")
findNavController()
.navigateSafe(ArtistDetailFragmentDirections.showArtistChoices(show.album.uid))
}
is Show.GenreDetails,
is Show.PlaylistDetails -> {
error("Unexpected show command $show")
@@ -239,6 +246,8 @@ class ArtistDetailFragment :
is Menu.ForSong -> ArtistDetailFragmentDirections.openSongMenu(menu.parcel)
is Menu.ForAlbum -> ArtistDetailFragmentDirections.openAlbumMenu(menu.parcel)
is Menu.ForArtist -> ArtistDetailFragmentDirections.openArtistMenu(menu.parcel)
is Menu.ForSelection ->
ArtistDetailFragmentDirections.openSelectionMenu(menu.parcel)
is Menu.ForGenre,
is Menu.ForPlaylist -> error("Unexpected menu $menu")
}
@@ -98,7 +98,7 @@ class GenreDetailFragment :
setOnMenuItemClickListener(this@GenreDetailFragment)
overrideOnOverflowMenuClick {
listModel.openMenu(
R.menu.item_detail_parent, unlikelyToBeNull(detailModel.currentGenre.value))
R.menu.detail_parent, unlikelyToBeNull(detailModel.currentGenre.value))
}
}
@@ -150,8 +150,8 @@ class GenreDetailFragment :
override fun onOpenMenu(item: Music) {
when (item) {
is Artist -> listModel.openMenu(R.menu.item_parent, item)
is Song -> listModel.openMenu(R.menu.item_song, item, detailModel.playInGenreWith)
is Artist -> listModel.openMenu(R.menu.parent, item)
is Song -> listModel.openMenu(R.menu.song, item, detailModel.playInGenreWith)
else -> error("Unexpected datatype: ${item::class.simpleName}")
}
}
@@ -240,6 +240,7 @@ class GenreDetailFragment :
is Menu.ForSong -> GenreDetailFragmentDirections.openSongMenu(menu.parcel)
is Menu.ForArtist -> GenreDetailFragmentDirections.openArtistMenu(menu.parcel)
is Menu.ForGenre -> GenreDetailFragmentDirections.openGenreMenu(menu.parcel)
is Menu.ForSelection -> GenreDetailFragmentDirections.openSelectionMenu(menu.parcel)
is Menu.ForAlbum,
is Menu.ForPlaylist -> error("Unexpected menu $menu")
}
@@ -20,9 +20,8 @@ package org.oxycblt.auxio.detail
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.ConcatAdapter
@@ -51,6 +50,7 @@ import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.playback.PlaybackDecision
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.ui.DialogAwareNavigationListener
import org.oxycblt.auxio.util.collect
import org.oxycblt.auxio.util.collectImmediately
import org.oxycblt.auxio.util.logD
@@ -68,8 +68,7 @@ import org.oxycblt.auxio.util.unlikelyToBeNull
class PlaylistDetailFragment :
ListFragment<Song, FragmentDetailBinding>(),
DetailHeaderAdapter.Listener,
PlaylistDetailListAdapter.Listener,
NavController.OnDestinationChangedListener {
PlaylistDetailListAdapter.Listener {
private val detailModel: DetailViewModel by activityViewModels()
override val listModel: ListViewModel by activityViewModels()
override val musicModel: MusicViewModel by activityViewModels()
@@ -80,7 +79,7 @@ class PlaylistDetailFragment :
private val playlistHeaderAdapter = PlaylistDetailHeaderAdapter(this)
private val playlistListAdapter = PlaylistDetailListAdapter(this)
private var touchHelper: ItemTouchHelper? = null
private var initialNavDestinationChange = false
private var editNavigationListener: DialogAwareNavigationListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -98,14 +97,15 @@ class PlaylistDetailFragment :
override fun onBindingCreated(binding: FragmentDetailBinding, savedInstanceState: Bundle?) {
super.onBindingCreated(binding, savedInstanceState)
editNavigationListener = DialogAwareNavigationListener(detailModel::dropPlaylistEdit)
// --- UI SETUP ---
binding.detailNormalToolbar.apply {
setNavigationOnClickListener { findNavController().navigateUp() }
setOnMenuItemClickListener(this@PlaylistDetailFragment)
overrideOnOverflowMenuClick {
listModel.openMenu(
R.menu.item_detail_playlist,
unlikelyToBeNull(detailModel.currentPlaylist.value))
R.menu.detail_playlist, unlikelyToBeNull(detailModel.currentPlaylist.value))
}
}
@@ -148,17 +148,31 @@ class PlaylistDetailFragment :
collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision)
}
override fun onMenuItemClick(item: MenuItem): Boolean {
if (super.onMenuItemClick(item)) {
return true
}
if (item.itemId == R.id.action_save) {
detailModel.savePlaylistEdit()
return true
}
return false
}
override fun onStart() {
super.onStart()
// Once we add the destination change callback, we will receive another initialization call,
// so handle that by resetting the flag.
initialNavDestinationChange = false
findNavController().addOnDestinationChangedListener(this)
requireNotNull(editNavigationListener) { "NavigationListener was not available" }
.attach(findNavController())
}
override fun onStop() {
super.onStop()
findNavController().removeOnDestinationChangedListener(this)
requireNotNull(editNavigationListener) { "NavigationListener was not available" }
.release(findNavController())
}
override fun onDestroyBinding(binding: FragmentDetailBinding) {
@@ -169,26 +183,7 @@ class PlaylistDetailFragment :
// Avoid possible race conditions that could cause a bad replace instruction to be consumed
// during list initialization and crash the app. Could happen if the user is fast enough.
detailModel.playlistSongInstructions.consume()
}
override fun onDestinationChanged(
controller: NavController,
destination: NavDestination,
arguments: Bundle?
) {
// Drop the initial call by NavController that simply provides us with the current
// destination. This would cause the selection state to be lost every time the device
// rotates.
if (!initialNavDestinationChange) {
initialNavDestinationChange = true
return
}
if (destination.id != R.id.playlist_detail_fragment &&
destination.id != R.id.playlist_song_sort_dialog) {
// Drop any pending playlist edits when navigating away. This could actually happen
// if the user is quick enough.
detailModel.dropPlaylistEdit()
}
editNavigationListener = null
}
override fun onRealClick(item: Song) {
@@ -200,7 +195,7 @@ class PlaylistDetailFragment :
}
override fun onOpenMenu(item: Song) {
listModel.openMenu(R.menu.item_playlist_song, item, detailModel.playInPlaylistWith)
listModel.openMenu(R.menu.playlist_song, item, detailModel.playInPlaylistWith)
}
override fun onPlay() {
@@ -302,6 +297,8 @@ class PlaylistDetailFragment :
is Menu.ForSong -> PlaylistDetailFragmentDirections.openSongMenu(menu.parcel)
is Menu.ForPlaylist ->
PlaylistDetailFragmentDirections.openPlaylistMenu(menu.parcel)
is Menu.ForSelection ->
PlaylistDetailFragmentDirections.openSelectionMenu(menu.parcel)
is Menu.ForArtist,
is Menu.ForAlbum,
is Menu.ForGenre -> error("Unexpected menu $menu")
@@ -0,0 +1,89 @@
/*
* Copyright (c) 2023 Auxio Project
* ErrorDetailsDialog.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.home
import android.content.ClipData
import android.content.ClipboardManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.navigation.fragment.navArgs
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogErrorDetailsBinding
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.getSystemServiceCompat
import org.oxycblt.auxio.util.openInBrowser
import org.oxycblt.auxio.util.showToast
/**
* A dialog that shows a stack trace for a music loading error.
*
* @author Alexander Capehart (OxygenCobalt)
*
* TODO: Extend to other errors
*/
class ErrorDetailsDialog : ViewBindingMaterialDialogFragment<DialogErrorDetailsBinding>() {
private val args: ErrorDetailsDialogArgs by navArgs()
private var clipboardManager: ClipboardManager? = null
override fun onConfigDialog(builder: AlertDialog.Builder) {
builder
.setTitle(R.string.lbl_error_info)
.setPositiveButton(R.string.lbl_report) { _, _ ->
requireContext().openInBrowser(LINK_ISSUES)
}
.setNegativeButton(R.string.lbl_cancel, null)
}
override fun onCreateBinding(inflater: LayoutInflater) =
DialogErrorDetailsBinding.inflate(inflater)
override fun onBindingCreated(binding: DialogErrorDetailsBinding, savedInstanceState: Bundle?) {
super.onBindingCreated(binding, savedInstanceState)
clipboardManager = requireContext().getSystemServiceCompat(ClipboardManager::class)
// --- UI SETUP ---
binding.errorStackTrace.text = args.error.stackTraceToString().trimEnd('\n')
binding.errorCopy.setOnClickListener { copyStackTrace() }
}
override fun onDestroyBinding(binding: DialogErrorDetailsBinding) {
super.onDestroyBinding(binding)
clipboardManager = null
}
private fun copyStackTrace() {
requireNotNull(clipboardManager) { "Clipboard was unavailable" }
.setPrimaryClip(
ClipData.newPlainText("Exception Stack Trace", args.error.stackTraceToString()))
// A copy notice is shown by the system from Android 13 onwards
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
requireContext().showToast(R.string.lbl_copied)
}
}
private companion object {
/** The URL to the bug report issue form */
const val LINK_ISSUES =
"https://github.com/OxygenCobalt/Auxio/issues/new" +
"?assignees=OxygenCobalt&labels=bug&projects=&template=bug-crash-report.yml"
}
}
@@ -51,7 +51,7 @@ constructor(
// Apply the new configuration possibly set in flipTo. This should occur even if
// a flip was canceled by a hide.
pendingConfig?.run {
this@FlipFloatingActionButton.logD("Applying pending configuration")
logD("Applying pending configuration")
setImageResource(iconRes)
contentDescription = context.getString(contentDescriptionRes)
setOnClickListener(clickListener)
@@ -330,7 +330,7 @@ class HomeFragment :
}
}
private fun setupCompleteState(binding: FragmentHomeBinding, error: Throwable?) {
private fun setupCompleteState(binding: FragmentHomeBinding, error: Exception?) {
if (error == null) {
logD("Received ok response")
binding.homeFab.show()
@@ -342,13 +342,13 @@ class HomeFragment :
val context = requireContext()
binding.homeIndexingContainer.visibility = View.VISIBLE
binding.homeIndexingProgress.visibility = View.INVISIBLE
binding.homeIndexingActions.visibility = View.VISIBLE
when (error) {
is NoAudioPermissionException -> {
logD("Showing permission prompt")
binding.homeIndexingStatus.text = context.getString(R.string.err_no_perms)
// Configure the action to act as a permission launcher.
binding.homeIndexingAction.apply {
visibility = View.VISIBLE
binding.homeIndexingTry.apply {
text = context.getString(R.string.lbl_grant)
setOnClickListener {
requireNotNull(storagePermissionLauncher) {
@@ -357,26 +357,34 @@ class HomeFragment :
.launch(PERMISSION_READ_AUDIO)
}
}
binding.homeIndexingMore.visibility = View.GONE
}
is NoMusicException -> {
logD("Showing no music error")
binding.homeIndexingStatus.text = context.getString(R.string.err_no_music)
// Configure the action to act as a reload trigger.
binding.homeIndexingAction.apply {
binding.homeIndexingTry.apply {
visibility = View.VISIBLE
text = context.getString(R.string.lbl_retry)
setOnClickListener { musicModel.refresh() }
}
binding.homeIndexingMore.visibility = View.GONE
}
else -> {
logD("Showing generic error")
binding.homeIndexingStatus.text = context.getString(R.string.err_index_failed)
// Configure the action to act as a reload trigger.
binding.homeIndexingAction.apply {
binding.homeIndexingTry.apply {
visibility = View.VISIBLE
text = context.getString(R.string.lbl_retry)
setOnClickListener { musicModel.rescan() }
}
binding.homeIndexingMore.apply {
visibility = View.VISIBLE
setOnClickListener {
findNavController().navigateSafe(HomeFragmentDirections.reportError(error))
}
}
}
}
}
@@ -385,7 +393,7 @@ class HomeFragment :
// Remove all content except for the progress indicator.
binding.homeIndexingContainer.visibility = View.VISIBLE
binding.homeIndexingProgress.visibility = View.VISIBLE
binding.homeIndexingAction.visibility = View.INVISIBLE
binding.homeIndexingActions.visibility = View.INVISIBLE
when (progress) {
is IndexingProgress.Indeterminate -> {
@@ -501,6 +509,7 @@ class HomeFragment :
is Menu.ForArtist -> HomeFragmentDirections.openArtistMenu(menu.parcel)
is Menu.ForGenre -> HomeFragmentDirections.openGenreMenu(menu.parcel)
is Menu.ForPlaylist -> HomeFragmentDirections.openPlaylistMenu(menu.parcel)
is Menu.ForSelection -> HomeFragmentDirections.openSelectionMenu(menu.parcel)
}
findNavController().navigateSafe(directions)
}
@@ -140,7 +140,7 @@ class AlbumListFragment :
}
override fun onOpenMenu(item: Album) {
listModel.openMenu(R.menu.item_album, item)
listModel.openMenu(R.menu.album, item)
}
private fun updateAlbums(albums: List<Album>) {
@@ -116,7 +116,7 @@ class ArtistListFragment :
}
override fun onOpenMenu(item: Artist) {
listModel.openMenu(R.menu.item_parent, item)
listModel.openMenu(R.menu.parent, item)
}
private fun updateArtists(artists: List<Artist>) {
@@ -115,7 +115,7 @@ class GenreListFragment :
}
override fun onOpenMenu(item: Genre) {
listModel.openMenu(R.menu.item_parent, item)
listModel.openMenu(R.menu.parent, item)
}
private fun updateGenres(genres: List<Genre>) {
@@ -113,7 +113,7 @@ class PlaylistListFragment :
}
override fun onOpenMenu(item: Playlist) {
listModel.openMenu(R.menu.item_playlist, item)
listModel.openMenu(R.menu.playlist, item)
}
private fun updatePlaylists(playlists: List<Playlist>) {
@@ -139,7 +139,7 @@ class SongListFragment :
}
override fun onOpenMenu(item: Song) {
listModel.openMenu(R.menu.item_song, item, homeModel.playWith)
listModel.openMenu(R.menu.song, item, homeModel.playWith)
}
private fun updateSongs(songs: List<Song>) {
@@ -109,6 +109,22 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
_selected.value = selected
}
/**
* Clear the current selection and return it.
*
* @return A list of [Song]s collated from each item selected.
*/
fun peekSelection() =
_selected.value.flatMap {
when (it) {
is Song -> listOf(it)
is Album -> listSettings.albumSongSort.songs(it.songs)
is Artist -> listSettings.artistSongSort.songs(it.songs)
is Genre -> listSettings.genreSongSort.songs(it.songs)
is Playlist -> it.songs
}
}
/**
* Clear the current selection and return it.
*
@@ -116,17 +132,7 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
*/
fun takeSelection(): List<Song> {
logD("Taking selection")
return _selected.value
.flatMap {
when (it) {
is Song -> listOf(it)
is Album -> listSettings.albumSongSort.songs(it.songs)
is Artist -> listSettings.artistSongSort.songs(it.songs)
is Genre -> listSettings.genreSongSort.songs(it.songs)
is Playlist -> it.songs
}
}
.also { _selected.value = listOf() }
return peekSelection().also { _selected.value = listOf() }
}
/**
@@ -201,6 +207,18 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
openImpl(Menu.ForPlaylist(menuRes, playlist))
}
/**
* Open a menu for a [Song] selection. This is not a popup menu, instead actually a dialog of
* menu options with additional information.
*
* @param menuRes The resource of the menu to use.
* @param songs The [Song] selection to show.
*/
fun openMenu(@MenuRes menuRes: Int, songs: List<Song>) {
logD("Opening menu for ${songs.size} songs")
openImpl(Menu.ForSelection(menuRes, songs))
}
private fun openImpl(menu: Menu) {
val existing = _menu.flow.value
if (existing != null) {
@@ -26,7 +26,7 @@ import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.ui.ViewBindingFragment
import org.oxycblt.auxio.util.share
import org.oxycblt.auxio.util.overrideOnOverflowMenuClick
import org.oxycblt.auxio.util.showToast
/**
@@ -48,6 +48,9 @@ abstract class SelectionFragment<VB : ViewBinding> :
// Add cancel and menu item listeners to manage what occurs with the selection.
setNavigationOnClickListener { listModel.dropSelection() }
setOnMenuItemClickListener(this@SelectionFragment)
overrideOnOverflowMenuClick {
listModel.openMenu(R.menu.selection, listModel.peekSelection())
}
}
}
@@ -67,23 +70,6 @@ abstract class SelectionFragment<VB : ViewBinding> :
musicModel.addToPlaylist(listModel.takeSelection())
true
}
R.id.action_selection_queue_add -> {
playbackModel.addToQueue(listModel.takeSelection())
requireContext().showToast(R.string.lng_queue_added)
true
}
R.id.action_selection_play -> {
playbackModel.play(listModel.takeSelection())
true
}
R.id.action_selection_shuffle -> {
playbackModel.shuffle(listModel.takeSelection())
true
}
R.id.action_selection_share -> {
requireContext().share(listModel.takeSelection())
true
}
else -> false
}
@@ -99,4 +99,11 @@ sealed interface Menu {
@Parcelize data class Parcel(val res: Int, val playlistUid: Music.UID) : Menu.Parcel
}
class ForSelection(@MenuRes override val res: Int, val songs: List<Song>) : Menu {
override val parcel: Parcel
get() = Parcel(res, songs.map { it.uid })
@Parcelize data class Parcel(val res: Int, val songUids: List<Music.UID>) : Menu.Parcel
}
}
@@ -34,6 +34,7 @@ import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.util.getPlural
import org.oxycblt.auxio.util.share
import org.oxycblt.auxio.util.showToast
@@ -78,10 +79,10 @@ class SongMenuDialogFragment : MenuDialogFragment<Menu.ForSong>() {
playbackModel.addToQueue(menu.song)
requireContext().showToast(R.string.lng_queue_added)
}
R.id.action_playlist_add -> musicModel.addToPlaylist(menu.song)
R.id.action_artist_details -> detailModel.showArtist(menu.song)
R.id.action_album_details -> detailModel.showAlbum(menu.song.album)
R.id.action_share -> requireContext().share(menu.song)
R.id.action_playlist_add -> musicModel.addToPlaylist(menu.song)
R.id.action_detail -> detailModel.showSong(menu.song)
else -> error("Unexpected menu item selected $item")
}
@@ -321,3 +322,51 @@ class PlaylistMenuDialogFragment : MenuDialogFragment<Menu.ForPlaylist>() {
}
}
}
/**
* [MenuDialogFragment] implementation for a [Song] selection.
*
* @author Alexander Capehart (OxygenCobalt)
*/
@AndroidEntryPoint
class SelectionMenuDialogFragment : MenuDialogFragment<Menu.ForSelection>() {
override val menuModel: MenuViewModel by activityViewModels()
override val listModel: ListViewModel by activityViewModels()
private val musicModel: MusicViewModel by activityViewModels()
private val playbackModel: PlaybackViewModel by activityViewModels()
private val args: SelectionMenuDialogFragmentArgs by navArgs()
override val parcel
get() = args.parcel
// Nothing to disable in song menus.
override fun getDisabledItemIds(menu: Menu.ForSelection) = setOf<Int>()
override fun updateMenu(binding: DialogMenuBinding, menu: Menu.ForSelection) {
binding.menuCover.bind(
menu.songs, getString(R.string.desc_selection_image), R.drawable.ic_song_24)
binding.menuType.text = getString(R.string.lbl_selection)
binding.menuName.text =
requireContext().getPlural(R.plurals.fmt_song_count, menu.songs.size)
binding.menuInfo.text = menu.songs.sumOf { it.durationMs }.formatDurationMs(true)
}
override fun onClick(item: MenuItem, menu: Menu.ForSelection) {
listModel.dropSelection()
when (item.itemId) {
R.id.action_play -> playbackModel.play(menu.songs)
R.id.action_shuffle -> playbackModel.shuffle(menu.songs)
R.id.action_play_next -> {
playbackModel.playNext(menu.songs)
requireContext().showToast(R.string.lng_queue_added)
}
R.id.action_queue_add -> {
playbackModel.addToQueue(menu.songs)
requireContext().showToast(R.string.lng_queue_added)
}
R.id.action_playlist_add -> musicModel.addToPlaylist(menu.songs)
R.id.action_share -> requireContext().share(menu.songs)
else -> error("Unexpected menu item selected $item")
}
}
}
@@ -66,6 +66,7 @@ class MenuViewModel @Inject constructor(private val musicRepository: MusicReposi
is Menu.ForArtist.Parcel -> unpackArtistParcel(parcel)
is Menu.ForGenre.Parcel -> unpackGenreParcel(parcel)
is Menu.ForPlaylist.Parcel -> unpackPlaylistParcel(parcel)
is Menu.ForSelection.Parcel -> unpackSelectionParcel(parcel)
}
private fun unpackSongParcel(parcel: Menu.ForSong.Parcel): Menu.ForSong? {
@@ -94,4 +95,10 @@ class MenuViewModel @Inject constructor(private val musicRepository: MusicReposi
val playlist = musicRepository.userLibrary?.findPlaylist(parcel.playlistUid) ?: return null
return Menu.ForPlaylist(parcel.res, playlist)
}
private fun unpackSelectionParcel(parcel: Menu.ForSelection.Parcel): Menu.ForSelection? {
val deviceLibrary = musicRepository.deviceLibrary ?: return null
val songs = parcel.songUids.mapNotNull(deviceLibrary::findSong)
return Menu.ForSelection(parcel.res, songs)
}
}
@@ -47,7 +47,7 @@ sealed interface IndexingState {
* @param error If music loading has failed, the error that occurred will be here. Otherwise, it
* will be null.
*/
data class Completed(val error: Throwable?) : IndexingState
data class Completed(val error: Exception?) : IndexingState
}
/**
@@ -223,7 +223,8 @@ constructor(
private val mediaStoreExtractor: MediaStoreExtractor,
private val tagExtractor: TagExtractor,
private val deviceLibraryFactory: DeviceLibrary.Factory,
private val userLibraryFactory: UserLibrary.Factory
private val userLibraryFactory: UserLibrary.Factory,
private val musicSettings: MusicSettings
) : MusicRepository {
private val updateListeners = mutableListOf<MusicRepository.UpdateListener>()
private val indexingListeners = mutableListOf<MusicRepository.IndexingListener>()
@@ -371,6 +372,7 @@ constructor(
// parallel.
logD("Starting MediaStore query")
emitIndexingProgress(IndexingProgress.Indeterminate)
val mediaStoreQueryJob =
worker.scope.async {
val query =
@@ -43,7 +43,7 @@ interface MusicSettings : Settings<MusicSettings.Listener> {
/** Whether to be actively watching for changes in the music library. */
val shouldBeObserving: Boolean
/** A [String] of characters representing the desired characters to denote multi-value tags. */
var multiValueSeparators: String
var separators: String
/** Whether to enable more advanced sorting by articles and numbers. */
val intelligentSorting: Boolean
@@ -85,7 +85,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext context: Context
override val shouldBeObserving: Boolean
get() = sharedPreferences.getBoolean(getString(R.string.set_key_observing), false)
override var multiValueSeparators: String
override var separators: String
// Differ from convention and store a string of separator characters instead of an int
// code. This makes it easier to use and more extendable.
get() = sharedPreferences.getString(getString(R.string.set_key_separators), "") ?: ""
@@ -63,9 +63,9 @@ data class CachedSong(
/** @see RawSong */
var durationMs: Long,
/** @see RawSong.replayGainTrackAdjustment */
val replayGainTrackAdjustment: Float?,
val replayGainTrackAdjustment: Float? = null,
/** @see RawSong.replayGainAlbumAdjustment */
val replayGainAlbumAdjustment: Float?,
val replayGainAlbumAdjustment: Float? = null,
/** @see RawSong.musicBrainzId */
var musicBrainzId: String? = null,
/** @see RawSong.name */
@@ -32,10 +32,8 @@ import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogMusicChoicesBinding
import org.oxycblt.auxio.list.ClickableListListener
import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.music.PlaylistDecision
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.collect
import org.oxycblt.auxio.util.collectImmediately
import org.oxycblt.auxio.util.logD
import org.oxycblt.auxio.util.navigateSafe
@@ -76,7 +74,7 @@ class AddToPlaylistDialog :
// --- VIEWMODEL SETUP ---
pickerModel.setSongsToAdd(args.songUids)
collect(musicModel.playlistDecision.flow, ::handleDecision)
musicModel.playlistDecision.consume()
collectImmediately(pickerModel.currentSongsToAdd, ::updatePendingSongs)
collectImmediately(pickerModel.playlistAddChoices, ::updatePlaylistChoices)
}
@@ -93,26 +91,16 @@ class AddToPlaylistDialog :
}
override fun onNewPlaylist() {
musicModel.createPlaylist(songs = pickerModel.currentSongsToAdd.value ?: return)
}
private fun handleDecision(decision: PlaylistDecision?) {
when (decision) {
is PlaylistDecision.Add -> {
logD("Navigated to playlist add dialog")
musicModel.playlistDecision.consume()
}
is PlaylistDecision.New -> {
logD("Navigating to new playlist dialog")
findNavController()
.navigateSafe(
AddToPlaylistDialogDirections.newPlaylist(
decision.songs.map { it.uid }.toTypedArray()))
}
is PlaylistDecision.Rename,
is PlaylistDecision.Delete -> error("Unexpected decision $decision")
null -> {}
}
// TODO: This is a temporary fix. Eventually I want to make this navigate away and
// instead have primary fragments launch navigation to the new playlist dialog.
// This should be better design (dialog layering is uh... probably not good) and
// preserves the existing navigation system.
// I could also roll some kind of new playlist textbox into the dialog, but that's
// a lot harder.
val songs = pickerModel.currentSongsToAdd.value ?: return
findNavController()
.navigateSafe(
AddToPlaylistDialogDirections.newPlaylist(songs.map { it.uid }.toTypedArray()))
}
private fun updatePendingSongs(songs: List<Song>?) {
@@ -32,6 +32,8 @@ import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.fs.contentResolverSafe
import org.oxycblt.auxio.music.fs.useQuery
import org.oxycblt.auxio.music.info.Name
import org.oxycblt.auxio.music.metadata.Separators
import org.oxycblt.auxio.util.logW
import org.oxycblt.auxio.util.unlikelyToBeNull
@@ -107,7 +109,7 @@ interface DeviceLibrary {
*/
suspend fun create(
rawSongs: Channel<RawSong>,
processedSongs: Channel<RawSong>
processedSongs: Channel<RawSong>,
): DeviceLibraryImpl
}
}
@@ -118,6 +120,9 @@ class DeviceLibraryFactoryImpl @Inject constructor(private val musicSettings: Mu
rawSongs: Channel<RawSong>,
processedSongs: Channel<RawSong>
): DeviceLibraryImpl {
val nameFactory = Name.Known.Factory.from(musicSettings)
val separators = Separators.from(musicSettings)
val songGrouping = mutableMapOf<Music.UID, SongImpl>()
val albumGrouping = mutableMapOf<RawAlbum.Key, Grouping<RawAlbum, SongImpl>>()
val artistGrouping = mutableMapOf<RawArtist.Key, Grouping<RawArtist, Music>>()
@@ -127,7 +132,7 @@ class DeviceLibraryFactoryImpl @Inject constructor(private val musicSettings: Mu
// All music information is grouped as it is indexed by other components.
for (rawSong in rawSongs) {
val song = SongImpl(rawSong, musicSettings)
val song = SongImpl(rawSong, nameFactory, separators)
// At times the indexer produces duplicate songs, try to filter these. Comparing by
// UID is sufficient for something like this, and also prevents collisions from
// causing severe issues elsewhere.
@@ -207,7 +212,7 @@ class DeviceLibraryFactoryImpl @Inject constructor(private val musicSettings: Mu
// Now that all songs are processed, also process albums and group them into their
// respective artists.
val albums = albumGrouping.values.mapTo(mutableSetOf()) { AlbumImpl(it, musicSettings) }
val albums = albumGrouping.values.mapTo(mutableSetOf()) { AlbumImpl(it, nameFactory) }
for (album in albums) {
for (rawArtist in album.rawArtists) {
val key = RawArtist.Key(rawArtist)
@@ -243,8 +248,8 @@ class DeviceLibraryFactoryImpl @Inject constructor(private val musicSettings: Mu
}
// Artists and genres do not need to be grouped and can be processed immediately.
val artists = artistGrouping.values.mapTo(mutableSetOf()) { ArtistImpl(it, musicSettings) }
val genres = genreGrouping.values.mapTo(mutableSetOf()) { GenreImpl(it, musicSettings) }
val artists = artistGrouping.values.mapTo(mutableSetOf()) { ArtistImpl(it, nameFactory) }
val genres = genreGrouping.values.mapTo(mutableSetOf()) { GenreImpl(it, nameFactory) }
return DeviceLibraryImpl(songGrouping.values.toSet(), albums, artists, genres)
}
@@ -25,7 +25,6 @@ import org.oxycblt.auxio.music.Album
import org.oxycblt.auxio.music.Artist
import org.oxycblt.auxio.music.Genre
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.fs.MimeType
@@ -36,8 +35,8 @@ import org.oxycblt.auxio.music.info.Date
import org.oxycblt.auxio.music.info.Disc
import org.oxycblt.auxio.music.info.Name
import org.oxycblt.auxio.music.info.ReleaseType
import org.oxycblt.auxio.music.metadata.Separators
import org.oxycblt.auxio.music.metadata.parseId3GenreNames
import org.oxycblt.auxio.music.metadata.parseMultiValue
import org.oxycblt.auxio.playback.replaygain.ReplayGainAdjustment
import org.oxycblt.auxio.util.positiveOrNull
import org.oxycblt.auxio.util.toUuidOrNull
@@ -48,10 +47,15 @@ import org.oxycblt.auxio.util.update
* Library-backed implementation of [Song].
*
* @param rawSong The [RawSong] to derive the member data from.
* @param musicSettings [MusicSettings] to for user parsing configuration.
* @param nameFactory The [Name.Known.Factory] to interpret name information with.
* @param separators The [Separators] to parse multi-value tags with.
* @author Alexander Capehart (OxygenCobalt)
*/
class SongImpl(private val rawSong: RawSong, musicSettings: MusicSettings) : Song {
class SongImpl(
private val rawSong: RawSong,
private val nameFactory: Name.Known.Factory,
private val separators: Separators
) : Song {
override val uid =
// Attempt to use a MusicBrainz ID first before falling back to a hashed UID.
rawSong.musicBrainzId?.toUuidOrNull()?.let { Music.UID.musicBrainz(MusicType.SONGS, it) }
@@ -70,10 +74,8 @@ class SongImpl(private val rawSong: RawSong, musicSettings: MusicSettings) : Son
update(rawSong.albumArtistNames)
}
override val name =
Name.Known.from(
requireNotNull(rawSong.name) { "Invalid raw: No title" },
rawSong.sortName,
musicSettings)
nameFactory.parse(
requireNotNull(rawSong.name) { "Invalid raw: No title" }, rawSong.sortName)
override val track = rawSong.track
override val disc = rawSong.disc?.let { Disc(it, rawSong.subtitle) }
@@ -95,42 +97,11 @@ class SongImpl(private val rawSong: RawSong, musicSettings: MusicSettings) : Son
track = rawSong.replayGainTrackAdjustment, album = rawSong.replayGainAlbumAdjustment)
override val dateAdded = requireNotNull(rawSong.dateAdded) { "Invalid raw: No date added" }
private var _album: AlbumImpl? = null
override val album: Album
get() = unlikelyToBeNull(_album)
private val hashCode = 31 * uid.hashCode() + rawSong.hashCode()
override fun hashCode() = hashCode
override fun equals(other: Any?) =
other is SongImpl && uid == other.uid && rawSong == other.rawSong
override fun toString() = "Song(uid=$uid, name=$name)"
private val artistMusicBrainzIds = rawSong.artistMusicBrainzIds.parseMultiValue(musicSettings)
private val artistNames = rawSong.artistNames.parseMultiValue(musicSettings)
private val artistSortNames = rawSong.artistSortNames.parseMultiValue(musicSettings)
private val rawIndividualArtists =
artistNames.mapIndexed { i, name ->
RawArtist(
artistMusicBrainzIds.getOrNull(i)?.toUuidOrNull(),
name,
artistSortNames.getOrNull(i))
}
private val albumArtistMusicBrainzIds =
rawSong.albumArtistMusicBrainzIds.parseMultiValue(musicSettings)
private val albumArtistNames = rawSong.albumArtistNames.parseMultiValue(musicSettings)
private val albumArtistSortNames = rawSong.albumArtistSortNames.parseMultiValue(musicSettings)
private val rawAlbumArtists =
albumArtistNames.mapIndexed { i, name ->
RawArtist(
albumArtistMusicBrainzIds.getOrNull(i)?.toUuidOrNull(),
name,
albumArtistSortNames.getOrNull(i))
}
private val _artists = mutableListOf<ArtistImpl>()
override val artists: List<Artist>
get() = _artists
@@ -143,40 +114,90 @@ class SongImpl(private val rawSong: RawSong, musicSettings: MusicSettings) : Son
* The [RawAlbum] instances collated by the [Song]. This can be used to group [Song]s into an
* [Album].
*/
val rawAlbum =
RawAlbum(
mediaStoreId = requireNotNull(rawSong.albumMediaStoreId) { "Invalid raw: No album id" },
musicBrainzId = rawSong.albumMusicBrainzId?.toUuidOrNull(),
name = requireNotNull(rawSong.albumName) { "Invalid raw: No album name" },
sortName = rawSong.albumSortName,
releaseType = ReleaseType.parse(rawSong.releaseTypes.parseMultiValue(musicSettings)),
rawArtists =
rawAlbumArtists
.ifEmpty { rawIndividualArtists }
.distinctBy { it.key }
.ifEmpty { listOf(RawArtist(null, null)) })
val rawAlbum: RawAlbum
/**
* The [RawArtist] instances collated by the [Song]. The artists of the song take priority,
* followed by the album artists. If there are no artists, this field will be a single "unknown"
* [RawArtist]. This can be used to group up [Song]s into an [Artist].
*/
val rawArtists =
rawIndividualArtists
.ifEmpty { rawAlbumArtists }
.distinctBy { it.key }
.ifEmpty { listOf(RawArtist()) }
val rawArtists: List<RawArtist>
/**
* The [RawGenre] instances collated by the [Song]. This can be used to group up [Song]s into a
* [Genre]. ID3v2 Genre names are automatically converted to their resolved names.
*/
val rawGenres =
rawSong.genreNames
.parseId3GenreNames(musicSettings)
.map { RawGenre(it) }
.distinctBy { it.key }
.ifEmpty { listOf(RawGenre()) }
val rawGenres: List<RawGenre>
private var hashCode: Int = uid.hashCode()
init {
val artistMusicBrainzIds = separators.split(rawSong.artistMusicBrainzIds)
val artistNames = separators.split(rawSong.artistNames)
val artistSortNames = separators.split(rawSong.artistSortNames)
val rawIndividualArtists =
artistNames
.mapIndexedTo(mutableSetOf()) { i, name ->
RawArtist(
artistMusicBrainzIds.getOrNull(i)?.toUuidOrNull(),
name,
artistSortNames.getOrNull(i))
}
.toList()
val albumArtistMusicBrainzIds = separators.split(rawSong.albumArtistMusicBrainzIds)
val albumArtistNames = separators.split(rawSong.albumArtistNames)
val albumArtistSortNames = separators.split(rawSong.albumArtistSortNames)
val rawAlbumArtists =
albumArtistNames
.mapIndexedTo(mutableSetOf()) { i, name ->
RawArtist(
albumArtistMusicBrainzIds.getOrNull(i)?.toUuidOrNull(),
name,
albumArtistSortNames.getOrNull(i))
}
.toList()
rawAlbum =
RawAlbum(
mediaStoreId =
requireNotNull(rawSong.albumMediaStoreId) { "Invalid raw: No album id" },
musicBrainzId = rawSong.albumMusicBrainzId?.toUuidOrNull(),
name = requireNotNull(rawSong.albumName) { "Invalid raw: No album name" },
sortName = rawSong.albumSortName,
releaseType = ReleaseType.parse(separators.split(rawSong.releaseTypes)),
rawArtists =
rawAlbumArtists
.ifEmpty { rawIndividualArtists }
.ifEmpty { listOf(RawArtist()) })
rawArtists =
rawIndividualArtists.ifEmpty { rawAlbumArtists }.ifEmpty { listOf(RawArtist()) }
val genreNames =
(rawSong.genreNames.parseId3GenreNames() ?: separators.split(rawSong.genreNames))
rawGenres =
genreNames
.mapTo(mutableSetOf()) { RawGenre(it) }
.toList()
.ifEmpty { listOf(RawGenre()) }
hashCode = 31 * rawSong.hashCode()
hashCode = 31 * nameFactory.hashCode()
}
override fun hashCode() = hashCode
// Since equality on public-facing music models is not identical to the tag equality,
// we just compare raw instances and how they are interpreted.
override fun equals(other: Any?) =
other is SongImpl &&
uid == other.uid &&
nameFactory == other.nameFactory &&
separators == other.separators &&
rawSong == other.rawSong
override fun toString() = "Song(uid=$uid, name=$name)"
/**
* Links this [Song] with a parent [Album].
@@ -242,12 +263,12 @@ class SongImpl(private val rawSong: RawSong, musicSettings: MusicSettings) : Son
* Library-backed implementation of [Album].
*
* @param grouping [Grouping] to derive the member data from.
* @param musicSettings [MusicSettings] to for user parsing configuration.
* @param nameFactory The [Name.Known.Factory] to interpret name information with.
* @author Alexander Capehart (OxygenCobalt)
*/
class AlbumImpl(
grouping: Grouping<RawAlbum, SongImpl>,
musicSettings: MusicSettings,
private val nameFactory: Name.Known.Factory
) : Album {
private val rawAlbum = grouping.raw.inner
@@ -261,7 +282,7 @@ class AlbumImpl(
update(rawAlbum.name)
update(rawAlbum.rawArtists.map { it.name })
}
override val name = Name.Known.from(rawAlbum.name, rawAlbum.sortName, musicSettings)
override val name = nameFactory.parse(rawAlbum.name, rawAlbum.sortName)
override val dates: Date.Range?
override val releaseType = rawAlbum.releaseType ?: ReleaseType.Album(null)
override val coverUri = CoverUri(rawAlbum.mediaStoreId.toCoverUri(), grouping.raw.src.uri)
@@ -311,13 +332,20 @@ class AlbumImpl(
dateAdded = earliestDateAdded
hashCode = 31 * hashCode + rawAlbum.hashCode()
hashCode = 31 * nameFactory.hashCode()
hashCode = 31 * hashCode + songs.hashCode()
}
override fun hashCode() = hashCode
// Since equality on public-facing music models is not identical to the tag equality,
// we just compare raw instances and how they are interpreted.
override fun equals(other: Any?) =
other is AlbumImpl && uid == other.uid && rawAlbum == other.rawAlbum && songs == other.songs
other is AlbumImpl &&
uid == other.uid &&
rawAlbum == other.rawAlbum &&
nameFactory == other.nameFactory &&
songs == other.songs
override fun toString() = "Album(uid=$uid, name=$name)"
@@ -362,10 +390,13 @@ class AlbumImpl(
* Library-backed implementation of [Artist].
*
* @param grouping [Grouping] to derive the member data from.
* @param musicSettings [MusicSettings] to for user parsing configuration.
* @param nameFactory The [Name.Known.Factory] to interpret name information with.
* @author Alexander Capehart (OxygenCobalt)
*/
class ArtistImpl(grouping: Grouping<RawArtist, Music>, musicSettings: MusicSettings) : Artist {
class ArtistImpl(
grouping: Grouping<RawArtist, Music>,
private val nameFactory: Name.Known.Factory
) : Artist {
private val rawArtist = grouping.raw.inner
override val uid =
@@ -373,7 +404,7 @@ class ArtistImpl(grouping: Grouping<RawArtist, Music>, musicSettings: MusicSetti
rawArtist.musicBrainzId?.let { Music.UID.musicBrainz(MusicType.ARTISTS, it) }
?: Music.UID.auxio(MusicType.ARTISTS) { update(rawArtist.name) }
override val name =
rawArtist.name?.let { Name.Known.from(it, rawArtist.sortName, musicSettings) }
rawArtist.name?.let { nameFactory.parse(it, rawArtist.sortName) }
?: Name.Unknown(R.string.def_artist)
override val songs: Set<Song>
@@ -414,6 +445,7 @@ class ArtistImpl(grouping: Grouping<RawArtist, Music>, musicSettings: MusicSetti
durationMs = songs.sumOf { it.durationMs }.positiveOrNull()
hashCode = 31 * hashCode + rawArtist.hashCode()
hashCode = 31 * hashCode + nameFactory.hashCode()
hashCode = 31 * hashCode + songs.hashCode()
}
@@ -421,10 +453,13 @@ class ArtistImpl(grouping: Grouping<RawArtist, Music>, musicSettings: MusicSetti
// the same UID but different songs are not equal.
override fun hashCode() = hashCode
// Since equality on public-facing music models is not identical to the tag equality,
// we just compare raw instances and how they are interpreted.
override fun equals(other: Any?) =
other is ArtistImpl &&
uid == other.uid &&
rawArtist == other.rawArtist &&
nameFactory == other.nameFactory &&
songs == other.songs
override fun toString() = "Artist(uid=$uid, name=$name)"
@@ -459,15 +494,18 @@ class ArtistImpl(grouping: Grouping<RawArtist, Music>, musicSettings: MusicSetti
* Library-backed implementation of [Genre].
*
* @param grouping [Grouping] to derive the member data from.
* @param musicSettings [MusicSettings] to for user parsing configuration.
* @param nameFactory The [Name.Known.Factory] to interpret name information with.
* @author Alexander Capehart (OxygenCobalt)
*/
class GenreImpl(grouping: Grouping<RawGenre, SongImpl>, musicSettings: MusicSettings) : Genre {
class GenreImpl(
grouping: Grouping<RawGenre, SongImpl>,
private val nameFactory: Name.Known.Factory
) : Genre {
private val rawGenre = grouping.raw.inner
override val uid = Music.UID.auxio(MusicType.GENRES) { update(rawGenre.name) }
override val name =
rawGenre.name?.let { Name.Known.from(it, rawGenre.name, musicSettings) }
rawGenre.name?.let { nameFactory.parse(it, rawGenre.name) }
?: Name.Unknown(R.string.def_genre)
override val songs: Set<Song>
@@ -491,13 +529,18 @@ class GenreImpl(grouping: Grouping<RawGenre, SongImpl>, musicSettings: MusicSett
durationMs = totalDuration
hashCode = 31 * hashCode + rawGenre.hashCode()
hashCode = 31 * nameFactory.hashCode()
hashCode = 31 * hashCode + songs.hashCode()
}
override fun hashCode() = hashCode
override fun equals(other: Any?) =
other is GenreImpl && uid == other.uid && rawGenre == other.rawGenre && songs == other.songs
other is GenreImpl &&
uid == other.uid &&
rawGenre == other.rawGenre &&
nameFactory == other.nameFactory &&
songs == other.songs
override fun toString() = "Genre(uid=$uid, name=$name)"
@@ -20,6 +20,7 @@ package org.oxycblt.auxio.music.info
import android.content.Context
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import java.text.CollationKey
import java.text.Collator
import org.oxycblt.auxio.music.MusicSettings
@@ -54,36 +55,7 @@ sealed interface Name : Comparable<Name> {
abstract val sort: String?
/** A tokenized version of the name that will be compared. */
protected abstract val sortTokens: List<SortToken>
/** An individual part of a name string that can be compared intelligently. */
protected data class SortToken(val collationKey: CollationKey, val type: Type) :
Comparable<SortToken> {
override fun compareTo(other: SortToken): Int {
// Numeric tokens should always be lower than lexicographic tokens.
val modeComp = type.compareTo(other.type)
if (modeComp != 0) {
return modeComp
}
// Numeric strings must be ordered by magnitude, thus immediately short-circuit
// the comparison if the lengths do not match.
if (type == Type.NUMERIC &&
collationKey.sourceString.length != other.collationKey.sourceString.length) {
return collationKey.sourceString.length - other.collationKey.sourceString.length
}
return collationKey.compareTo(other.collationKey)
}
/** Denotes the type of comparison to be performed with this token. */
enum class Type {
/** Compare as a digit string, like "65". */
NUMERIC,
/** Compare as a standard alphanumeric string, like "65daysofstatic" */
LEXICOGRAPHIC
}
}
@VisibleForTesting(VisibleForTesting.PROTECTED) abstract val sortTokens: List<SortToken>
final override val thumb: String
get() =
@@ -108,20 +80,30 @@ sealed interface Name : Comparable<Name> {
is Unknown -> 1
}
companion object {
interface Factory {
/**
* Create a new instance of [Name.Known]
*
* @param raw The raw name obtained from the music item
* @param sort The raw sort name obtained from the music item
* @param musicSettings [MusicSettings] required for name configuration.
*/
fun from(raw: String, sort: String?, musicSettings: MusicSettings): Known =
if (musicSettings.intelligentSorting) {
IntelligentKnownName(raw, sort)
} else {
SimpleKnownName(raw, sort)
}
fun parse(raw: String, sort: String?): Known
companion object {
/**
* Creates a new instance from the **current state** of the given [MusicSettings]'s
* user-defined name configuration.
*
* @param settings The [MusicSettings] to use.
* @return A [Factory] instance reflecting the configuration state.
*/
fun from(settings: MusicSettings) =
if (settings.intelligentSorting) {
IntelligentKnownName.Factory
} else {
SimpleKnownName.Factory
}
}
}
}
@@ -148,22 +130,28 @@ sealed interface Name : Comparable<Name> {
private val collator: Collator = Collator.getInstance().apply { strength = Collator.PRIMARY }
private val punctRegex by lazy { Regex("[\\p{Punct}+]") }
// TODO: Consider how you want to handle whitespace and "gaps" in names.
/**
* Plain [Name.Known] implementation that is internationalization-safe.
*
* @author Alexander Capehart (OxygenCobalt)
*/
private data class SimpleKnownName(override val raw: String, override val sort: String?) :
Name.Known() {
@VisibleForTesting
data class SimpleKnownName(override val raw: String, override val sort: String?) : Name.Known() {
override val sortTokens = listOf(parseToken(sort ?: raw))
private fun parseToken(name: String): SortToken {
// Remove excess punctuation from the string, as those usually aren't considered in sorting.
val stripped = name.replace(punctRegex, "").ifEmpty { name }
val stripped = name.replace(punctRegex, "").trim().ifEmpty { name }
val collationKey = collator.getCollationKey(stripped)
// Always use lexicographic mode since we aren't parsing any numeric components
return SortToken(collationKey, SortToken.Type.LEXICOGRAPHIC)
}
data object Factory : Name.Known.Factory {
override fun parse(raw: String, sort: String?) = SimpleKnownName(raw, sort)
}
}
/**
@@ -171,7 +159,8 @@ private data class SimpleKnownName(override val raw: String, override val sort:
*
* @author Alexander Capehart (OxygenCobalt)
*/
private data class IntelligentKnownName(override val raw: String, override val sort: String?) :
@VisibleForTesting
data class IntelligentKnownName(override val raw: String, override val sort: String?) :
Name.Known() {
override val sortTokens = parseTokens(sort ?: raw)
@@ -180,7 +169,8 @@ private data class IntelligentKnownName(override val raw: String, override val s
// optimize it
val stripped =
name
// Remove excess punctuation from the string, as those u
// Remove excess punctuation from the string, as those usually aren't
// considered in sorting.
.replace(punctRegex, "")
.ifEmpty { name }
.run {
@@ -218,7 +208,40 @@ private data class IntelligentKnownName(override val raw: String, override val s
}
}
data object Factory : Name.Known.Factory {
override fun parse(raw: String, sort: String?) = IntelligentKnownName(raw, sort)
}
companion object {
private val TOKEN_REGEX by lazy { Regex("(\\d+)|(\\D+)") }
}
}
/** An individual part of a name string that can be compared intelligently. */
@VisibleForTesting(VisibleForTesting.PROTECTED)
data class SortToken(val collationKey: CollationKey, val type: Type) : Comparable<SortToken> {
override fun compareTo(other: SortToken): Int {
// Numeric tokens should always be lower than lexicographic tokens.
val modeComp = type.compareTo(other.type)
if (modeComp != 0) {
return modeComp
}
// Numeric strings must be ordered by magnitude, thus immediately short-circuit
// the comparison if the lengths do not match.
if (type == Type.NUMERIC &&
collationKey.sourceString.length != other.collationKey.sourceString.length) {
return collationKey.sourceString.length - other.collationKey.sourceString.length
}
return collationKey.compareTo(other.collationKey)
}
/** Denotes the type of comparison to be performed with this token. */
enum class Type {
/** Compare as a digit string, like "65". */
NUMERIC,
/** Compare as a standard alphanumeric string, like "65daysofstatic" */
LEXICOGRAPHIC
}
}
@@ -0,0 +1,76 @@
/*
* Copyright (c) 2023 Auxio Project
* Separators.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.music.metadata
import androidx.annotation.VisibleForTesting
import org.oxycblt.auxio.music.MusicSettings
/**
* Defines the user-specified parsing of multi-value tags. This should be used to parse any tags
* that may be delimited with a separator character.
*
* @author Alexander Capehart (OxygenCobalt)
*/
interface Separators {
/**
* Parse a separated value from one or more strings. If the value is already composed of more
* than one value, nothing is done. Otherwise, it will attempt to split it based on the user's
* separator preferences.
*
* @return A new list of one or more [String]s parsed by the separator configuration
*/
fun split(strings: List<String>): List<String>
companion object {
const val COMMA = ','
const val SEMICOLON = ';'
const val SLASH = '/'
const val PLUS = '+'
const val AND = '&'
/**
* Creates a new instance from the **current state** of the given [MusicSettings]'s
* user-defined separator configuration.
*
* @param settings The [MusicSettings] to use.
* @return A new [Separators] instance reflecting the configuration state.
*/
fun from(settings: MusicSettings) = from(settings.separators)
@VisibleForTesting
fun from(chars: String) =
if (chars.isNotEmpty()) {
CharSeparators(chars.toSet())
} else {
NoSeparators
}
}
}
private data class CharSeparators(private val chars: Set<Char>) : Separators {
override fun split(strings: List<String>) =
if (strings.size == 1) splitImpl(strings.first()) else strings
private fun splitImpl(string: String) =
string.splitEscaped { chars.contains(it) }.correctWhitespace()
}
private object NoSeparators : Separators {
override fun split(strings: List<String>) = strings
}
@@ -52,7 +52,7 @@ class SeparatorsDialog : ViewBindingMaterialDialogFragment<DialogSeparatorsBindi
.setTitle(R.string.set_separators)
.setNegativeButton(R.string.lbl_cancel, null)
.setPositiveButton(R.string.lbl_save) { _, _ ->
musicSettings.multiValueSeparators = getCurrentSeparators()
musicSettings.separators = getCurrentSeparators()
}
}
@@ -68,8 +68,7 @@ class SeparatorsDialog : ViewBindingMaterialDialogFragment<DialogSeparatorsBindi
// More efficient to do one iteration through the separator list and initialize
// the corresponding CheckBox for each character instead of doing an iteration
// through the separator list for each CheckBox.
(savedInstanceState?.getString(KEY_PENDING_SEPARATORS)
?: musicSettings.multiValueSeparators)
(savedInstanceState?.getString(KEY_PENDING_SEPARATORS) ?: musicSettings.separators)
.forEach {
when (it) {
Separators.COMMA -> binding.separatorComma.isChecked = true
@@ -102,14 +101,6 @@ class SeparatorsDialog : ViewBindingMaterialDialogFragment<DialogSeparatorsBindi
return separators
}
private object Separators {
const val COMMA = ','
const val SEMICOLON = ';'
const val SLASH = '/'
const val PLUS = '+'
const val AND = '&'
}
private companion object {
const val KEY_PENDING_SEPARATORS = BuildConfig.APPLICATION_ID + ".key.PENDING_SEPARATORS"
}
@@ -18,29 +18,15 @@
package org.oxycblt.auxio.music.metadata
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.util.positiveOrNull
/// --- GENERIC PARSING ---
/**
* Parse a multi-value tag based on the user configuration. If the value is already composed of more
* than one value, nothing is done. Otherwise, this function will attempt to split it based on the
* user's separator preferences.
*
* @param settings [MusicSettings] required to obtain user separator configuration.
* @return A new list of one or more [String]s.
*/
fun List<String>.parseMultiValue(settings: MusicSettings) =
if (size == 1) {
first().maybeParseBySeparators(settings)
} else {
// Nothing to do.
this
}
// TODO: Remove the escaping checks, it's too expensive to do this for every single tag.
// TODO: I want to eventually be able to move a lot of this into TagWorker once I no longer have
// to deal with the cross-module dependencies of MediaStoreExtractor.
/**
* Split a [String] by the given selector, automatically handling escaped characters that satisfy
* the selector.
@@ -101,17 +87,6 @@ fun String.correctWhitespace() = trim().ifBlank { null }
*/
fun List<String>.correctWhitespace() = mapNotNull { it.correctWhitespace() }
/**
* Attempt to parse a string by the user's separator preferences.
*
* @param settings [MusicSettings] required to obtain user separator configuration.
* @return A list of one or more [String]s that were split up by the user-defined separators.
*/
private fun String.maybeParseBySeparators(settings: MusicSettings): List<String> {
if (settings.multiValueSeparators.isEmpty()) return listOf(this)
return splitEscaped { settings.multiValueSeparators.contains(it) }.correctWhitespace()
}
/// --- ID3v2 PARSING ---
/**
@@ -165,12 +140,12 @@ fun transformPositionField(pos: Int?, total: Int?) =
* representations of genre fields into their named counterparts, and split up singular ID3v2-style
* integer genre fields into one or more genres.
*
* @param settings [MusicSettings] required to obtain user separator configuration.
* @return A list of one or more genre names..
* @return A list of one or more genre names, or null if this multi-value list has no valid
* formatting.
*/
fun List<String>.parseId3GenreNames(settings: MusicSettings) =
fun List<String>.parseId3GenreNames() =
if (size == 1) {
first().parseId3MultiValueGenre(settings)
first().parseId3MultiValueGenre()
} else {
// Nothing to split, just map any ID3v1 genres to their name counterparts.
map { it.parseId3v1Genre() ?: it }
@@ -179,11 +154,10 @@ fun List<String>.parseId3GenreNames(settings: MusicSettings) =
/**
* Parse a single ID3v1/ID3v2 integer genre field into their named representations.
*
* @param settings [MusicSettings] required to obtain user separator configuration.
* @return A list of one or more genre names.
* @return list of one or more genre names, or null if this is not in ID3v2 format.
*/
private fun String.parseId3MultiValueGenre(settings: MusicSettings) =
parseId3v1Genre()?.let { listOf(it) } ?: parseId3v2Genre() ?: maybeParseBySeparators(settings)
private fun String.parseId3MultiValueGenre() =
parseId3v1Genre()?.let { listOf(it) } ?: parseId3v2Genre()
/**
* Parse an ID3v1 integer genre field.
@@ -77,7 +77,6 @@ private class TagWorkerImpl(
private val rawSong: RawSong,
private val future: Future<TrackGroupArray>
) : TagWorker {
override fun poll(): RawSong? {
if (!future.isDone) {
// Not done yet, nothing to do.
@@ -19,7 +19,6 @@
package org.oxycblt.auxio.music.user
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.music.MusicType
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
@@ -51,10 +50,10 @@ private constructor(
* Clone the data in this instance to a new [PlaylistImpl] with the given [name].
*
* @param name The new name to use.
* @param musicSettings [MusicSettings] required for name configuration.
* @param nameFactory The [Name.Known.Factory] to interpret name information with.
*/
fun edit(name: String, musicSettings: MusicSettings) =
PlaylistImpl(uid, Name.Known.from(name, null, musicSettings), songs)
fun edit(name: String, nameFactory: Name.Known.Factory) =
PlaylistImpl(uid, nameFactory.parse(name, null), songs)
/**
* Clone the data in this instance to a new [PlaylistImpl] with the given [Song]s.
@@ -76,29 +75,26 @@ private constructor(
*
* @param name The name of the playlist.
* @param songs The songs to initially populate the playlist with.
* @param musicSettings [MusicSettings] required for name configuration.
* @param nameFactory The [Name.Known.Factory] to interpret name information with.
*/
fun from(name: String, songs: List<Song>, musicSettings: MusicSettings) =
PlaylistImpl(
Music.UID.auxio(MusicType.PLAYLISTS),
Name.Known.from(name, null, musicSettings),
songs)
fun from(name: String, songs: List<Song>, nameFactory: Name.Known.Factory) =
PlaylistImpl(Music.UID.auxio(MusicType.PLAYLISTS), nameFactory.parse(name, null), songs)
/**
* Populate a new instance from a read [RawPlaylist].
*
* @param rawPlaylist The [RawPlaylist] to read from.
* @param deviceLibrary The [DeviceLibrary] to initialize from.
* @param musicSettings [MusicSettings] required for name configuration.
* @param nameFactory The [Name.Known.Factory] to interpret name information with.
*/
fun fromRaw(
rawPlaylist: RawPlaylist,
deviceLibrary: DeviceLibrary,
musicSettings: MusicSettings
nameFactory: Name.Known.Factory
) =
PlaylistImpl(
rawPlaylist.playlistInfo.playlistUid,
Name.Known.from(rawPlaylist.playlistInfo.name, null, musicSettings),
nameFactory.parse(rawPlaylist.playlistInfo.name, null),
rawPlaylist.songs.mapNotNull { deviceLibrary.findSong(it.songUid) })
}
}
@@ -26,6 +26,7 @@ import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.music.Playlist
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.music.device.DeviceLibrary
import org.oxycblt.auxio.music.info.Name
import org.oxycblt.auxio.util.logD
import org.oxycblt.auxio.util.logE
@@ -144,7 +145,9 @@ constructor(private val playlistDao: PlaylistDao, private val musicSettings: Mus
UserLibrary.Factory {
override suspend fun query() =
try {
playlistDao.readRawPlaylists()
val rawPlaylists = playlistDao.readRawPlaylists()
logD("Successfully read ${rawPlaylists.size} playlists")
rawPlaylists
} catch (e: Exception) {
logE("Unable to read playlists: $e")
listOf()
@@ -154,11 +157,10 @@ constructor(private val playlistDao: PlaylistDao, private val musicSettings: Mus
rawPlaylists: List<RawPlaylist>,
deviceLibrary: DeviceLibrary
): MutableUserLibrary {
logD("Successfully read ${rawPlaylists.size} playlists")
// Convert the database playlist information to actual usable playlists.
val nameFactory = Name.Known.Factory.from(musicSettings)
val playlistMap = mutableMapOf<Music.UID, PlaylistImpl>()
for (rawPlaylist in rawPlaylists) {
val playlistImpl = PlaylistImpl.fromRaw(rawPlaylist, deviceLibrary, musicSettings)
val playlistImpl = PlaylistImpl.fromRaw(rawPlaylist, deviceLibrary, nameFactory)
playlistMap[playlistImpl.uid] = playlistImpl
}
return UserLibraryImpl(playlistDao, playlistMap, musicSettings)
@@ -184,7 +186,7 @@ private class UserLibraryImpl(
override fun findPlaylist(name: String) = playlistMap.values.find { it.name.raw == name }
override suspend fun createPlaylist(name: String, songs: List<Song>): Playlist? {
val playlistImpl = PlaylistImpl.from(name, songs, musicSettings)
val playlistImpl = PlaylistImpl.from(name, songs, Name.Known.Factory.from(musicSettings))
synchronized(this) { playlistMap[playlistImpl.uid] = playlistImpl }
val rawPlaylist =
RawPlaylist(
@@ -207,7 +209,9 @@ private class UserLibraryImpl(
val playlistImpl =
synchronized(this) {
requireNotNull(playlistMap[playlist.uid]) { "Cannot rename invalid playlist" }
.also { playlistMap[it.uid] = it.edit(name, musicSettings) }
.also {
playlistMap[it.uid] = it.edit(name, Name.Known.Factory.from(musicSettings))
}
}
return try {
@@ -38,7 +38,6 @@ import kotlin.math.abs
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.FragmentPlaybackPanelBinding
import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.detail.Show
import org.oxycblt.auxio.list.ListViewModel
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.auxio.music.Song
@@ -48,7 +47,6 @@ import org.oxycblt.auxio.playback.queue.QueueViewModel
import org.oxycblt.auxio.playback.state.RepeatMode
import org.oxycblt.auxio.playback.ui.StyledSeekBar
import org.oxycblt.auxio.ui.ViewBindingFragment
import org.oxycblt.auxio.util.collect
import org.oxycblt.auxio.util.collectImmediately
import org.oxycblt.auxio.util.lazyReflectedField
import org.oxycblt.auxio.util.logD
@@ -107,7 +105,7 @@ class PlaybackPanelFragment :
playbackModel.song.value?.let {
// No playback options are actually available in the menu, so use a junk
// PlaySong option.
listModel.openMenu(R.menu.item_playback_song, it, PlaySong.ByItself)
listModel.openMenu(R.menu.playback_song, it, PlaySong.ByItself)
}
}
}
@@ -120,6 +118,20 @@ class PlaybackPanelFragment :
val recycler = VP_RECYCLER_FIELD.get(this@apply) as RecyclerView
recycler.isNestedScrollingEnabled = false
}
// Set up marquee on song information, alongside click handlers that navigate to each
// respective item.
binding.playbackSong.apply {
isSelected = true
setOnClickListener { navigateToCurrentSong() }
}
binding.playbackArtist.apply {
isSelected = true
setOnClickListener { navigateToCurrentArtist() }
}
binding.playbackAlbum.apply {
isSelected = true
setOnClickListener { navigateToCurrentAlbum() }
}
binding.playbackSeekBar.listener = this
@@ -140,7 +152,6 @@ class PlaybackPanelFragment :
collectImmediately(playbackModel.isShuffled, ::updateShuffled)
collectImmediately(queueModel.queue, ::updateQueue)
collectImmediately(queueModel.index, ::updateQueuePosition)
collect(detailModel.toShow.flow, ::handleShow)
}
override fun onDestroyBinding(binding: FragmentPlaybackPanelBinding) {
@@ -226,25 +237,8 @@ class PlaybackPanelFragment :
requireBinding().playbackShuffle.isActivated = isShuffled
}
private fun handleShow(show: Show?) {
when (show) {
is Show.SongAlbumDetails,
is Show.ArtistDetails,
is Show.AlbumDetails -> playbackModel.openMain()
is Show.SongDetails,
is Show.SongArtistDecision,
is Show.AlbumArtistDecision,
is Show.GenreDetails,
is Show.PlaylistDetails,
null -> {}
}
}
override fun navigateToCurrentSong() {
playbackModel.song.value?.let {
detailModel.showAlbum(it)
playbackModel.openMain()
}
playbackModel.song.value?.let(detailModel::showAlbum)
}
override fun navigateToCurrentArtist() {
@@ -338,8 +338,7 @@ constructor(
song,
object : BitmapProvider.Target {
override fun onCompleted(bitmap: Bitmap?) {
this@MediaSessionComponent.logD(
"Bitmap loaded, applying media session and posting notification")
logD("Bitmap loaded, applying media session and posting notification")
builder.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, bitmap)
builder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmap)
val metadata = builder.build()
@@ -119,7 +119,7 @@ class SearchFragment : ListFragment<Music, FragmentSearchBinding>() {
if (!launchedKeyboard) {
// Auto-open the keyboard when this view is shown
this@SearchFragment.logD("Keyboard is not shown yet")
logD("Keyboard is not shown yet")
showKeyboard(this)
launchedKeyboard = true
}
@@ -184,11 +184,11 @@ class SearchFragment : ListFragment<Music, FragmentSearchBinding>() {
override fun onOpenMenu(item: Music) {
when (item) {
is Song -> listModel.openMenu(R.menu.item_song, item, searchModel.playWith)
is Album -> listModel.openMenu(R.menu.item_album, item)
is Artist -> listModel.openMenu(R.menu.item_parent, item)
is Genre -> listModel.openMenu(R.menu.item_parent, item)
is Playlist -> listModel.openMenu(R.menu.item_playlist, item)
is Song -> listModel.openMenu(R.menu.song, item, searchModel.playWith)
is Album -> listModel.openMenu(R.menu.album, item)
is Artist -> listModel.openMenu(R.menu.parent, item)
is Genre -> listModel.openMenu(R.menu.parent, item)
is Playlist -> listModel.openMenu(R.menu.playlist, item)
}
}
@@ -261,6 +261,7 @@ class SearchFragment : ListFragment<Music, FragmentSearchBinding>() {
is Menu.ForArtist -> SearchFragmentDirections.openArtistMenu(menu.parcel)
is Menu.ForGenre -> SearchFragmentDirections.openGenreMenu(menu.parcel)
is Menu.ForPlaylist -> SearchFragmentDirections.openPlaylistMenu(menu.parcel)
is Menu.ForSelection -> SearchFragmentDirections.openSelectionMenu(menu.parcel)
}
findNavController().navigateSafe(directions)
// Keyboard is no longer needed.
@@ -18,13 +18,8 @@
package org.oxycblt.auxio.settings
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import androidx.core.net.toUri
import androidx.core.view.updatePadding
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
@@ -37,8 +32,7 @@ import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.playback.formatDurationMs
import org.oxycblt.auxio.ui.ViewBindingFragment
import org.oxycblt.auxio.util.collectImmediately
import org.oxycblt.auxio.util.logD
import org.oxycblt.auxio.util.showToast
import org.oxycblt.auxio.util.openInBrowser
import org.oxycblt.auxio.util.systemBarInsetsCompat
/**
@@ -69,10 +63,10 @@ class AboutFragment : ViewBindingFragment<FragmentAboutBinding>() {
}
binding.aboutVersion.text = BuildConfig.VERSION_NAME
binding.aboutCode.setOnClickListener { openLinkInBrowser(LINK_SOURCE) }
binding.aboutWiki.setOnClickListener { openLinkInBrowser(LINK_WIKI) }
binding.aboutLicenses.setOnClickListener { openLinkInBrowser(LINK_LICENSES) }
binding.aboutAuthor.setOnClickListener { openLinkInBrowser(LINK_AUTHOR) }
binding.aboutCode.setOnClickListener { requireContext().openInBrowser(LINK_SOURCE) }
binding.aboutWiki.setOnClickListener { requireContext().openInBrowser(LINK_WIKI) }
binding.aboutLicenses.setOnClickListener { requireContext().openInBrowser(LINK_LICENSES) }
binding.aboutAuthor.setOnClickListener { requireContext().openInBrowser(LINK_AUTHOR) }
// VIEWMODEL SETUP
collectImmediately(musicModel.statistics, ::updateStatistics)
@@ -93,74 +87,6 @@ class AboutFragment : ViewBindingFragment<FragmentAboutBinding>() {
(statistics?.durationMs ?: 0).formatDurationMs(false))
}
/**
* Open the given URI in a web browser.
*
* @param uri The URL to open.
*/
private fun openLinkInBrowser(uri: String) {
logD("Opening $uri")
val context = requireContext()
val browserIntent =
Intent(Intent.ACTION_VIEW, uri.toUri()).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Android 11 seems to now handle the app chooser situations on its own now
// [along with adding a new permission that breaks the old manual code], so
// we just do a typical activity launch.
logD("Using API 30+ chooser")
try {
context.startActivity(browserIntent)
} catch (e: ActivityNotFoundException) {
// No app installed to open the link
context.showToast(R.string.err_no_app)
}
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
// On older versions of android, opening links from an ACTION_VIEW intent might
// not work in all cases, especially when no default app was set. If that is the
// case, we will try to manually handle these cases before we try to launch the
// browser.
logD("Resolving browser activity for chooser")
val pkgName =
context.packageManager
.resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY)
?.run { activityInfo.packageName }
if (pkgName != null) {
if (pkgName == "android") {
// No default browser [Must open app chooser, may not be supported]
logD("No default browser found")
openAppChooser(browserIntent)
} else logD("Opening browser intent")
try {
browserIntent.setPackage(pkgName)
startActivity(browserIntent)
} catch (e: ActivityNotFoundException) {
// Not a browser but an app chooser
browserIntent.setPackage(null)
openAppChooser(browserIntent)
}
} else {
// No app installed to open the link
context.showToast(R.string.err_no_app)
}
}
}
/**
* Open an app chooser for a given [Intent].
*
* @param intent The [Intent] to show an app chooser for.
*/
private fun openAppChooser(intent: Intent) {
logD("Opening app chooser for ${intent.action}")
val chooserIntent =
Intent(Intent.ACTION_CHOOSER)
.putExtra(Intent.EXTRA_INTENT, intent)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(chooserIntent)
}
private companion object {
/** The URL to the source code. */
const val LINK_SOURCE = "https://github.com/OxygenCobalt/Auxio"
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2023 Auxio Project
* DialogAwareNavigationListener.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.ui
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.NavDestination
/**
* A [NavController.OnDestinationChangedListener] that will call [callback] when moving between
* fragments only (not between dialogs or anything similar).
*
* Note: This only works because of special naming used in Auxio's navigation graphs. Keep this in
* mind when porting to other projects.
*
* @author Alexander Capehart (OxygenCobalt)
*/
class DialogAwareNavigationListener(private val callback: () -> Unit) :
NavController.OnDestinationChangedListener {
private var currentDestination: NavDestination? = null
/**
* Attach this instance to a [NavController]. This should be done in the onStart method of a
* Fragment.
*
* @param navController The [NavController] to add to.
*/
fun attach(navController: NavController) {
currentDestination = null
navController.addOnDestinationChangedListener(this)
}
/**
* Remove this listener from it's [NavController]. This should be done in the onStop method of a
* Fragment.
*
* @param navController The [NavController] to remove from. Should be the same on used in
* [attach].
*/
fun release(navController: NavController) {
currentDestination = null
navController.removeOnDestinationChangedListener(this)
}
override fun onDestinationChanged(
controller: NavController,
destination: NavDestination,
arguments: Bundle?
) {
// Drop the initial call by NavController that simply provides us with the current
// destination. This would cause the selection state to be lost every time the device
// rotates.
val lastDestination = currentDestination
currentDestination = destination
if (lastDestination == null) {
return
}
if (!lastDestination.isDialog() && !destination.isDialog()) {
callback()
}
}
private fun NavDestination.isDialog() = label?.endsWith("dialog") == true
}
@@ -26,9 +26,11 @@ import android.view.ViewGroup
import androidx.annotation.StyleRes
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BackportBottomSheetBehavior
import com.google.android.material.bottomsheet.BackportBottomSheetDialog
import com.google.android.material.bottomsheet.BackportBottomSheetDialogFragment
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import org.oxycblt.auxio.util.getDimenPixels
import org.oxycblt.auxio.util.logD
import org.oxycblt.auxio.util.unlikelyToBeNull
@@ -39,10 +41,10 @@ import org.oxycblt.auxio.util.unlikelyToBeNull
* @author Alexander Capehart (OxygenCobalt)
*/
abstract class ViewBindingBottomSheetDialogFragment<VB : ViewBinding> :
BottomSheetDialogFragment() {
BackportBottomSheetDialogFragment() {
private var _binding: VB? = null
override fun onCreateDialog(savedInstanceState: Bundle?): BottomSheetDialog =
override fun onCreateDialog(savedInstanceState: Bundle?): BackportBottomSheetDialog =
TweakedBottomSheetDialog(requireContext(), theme)
/**
@@ -109,19 +111,29 @@ abstract class ViewBindingBottomSheetDialogFragment<VB : ViewBinding> :
private inner class TweakedBottomSheetDialog
@JvmOverloads
constructor(context: Context, @StyleRes theme: Int = 0) : BottomSheetDialog(context, theme) {
constructor(context: Context, @StyleRes theme: Int = 0) :
BackportBottomSheetDialog(context, theme) {
private var avoidUnusableCollapsedState = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Collapsed state is bugged in phone landscape mode and shows only 10% of the dialog.
// Just disable it and go directly from expanded -> hidden.
behavior.skipCollapsed = true
// Automatic peek height calculations are bugged in phone landscape mode and show only
// 10% of the dialog. Just disable it in that case and go directly from expanded ->
// hidden.
val metrics = context.resources.displayMetrics
avoidUnusableCollapsedState =
metrics.heightPixels - metrics.widthPixels <
context.getDimenPixels(
com.google.android.material.R.dimen.design_bottom_sheet_peek_height_min)
behavior.skipCollapsed = avoidUnusableCollapsedState
}
override fun onStart() {
super.onStart()
// Manually trigger an expanded transition to make window insets actually apply to
// the dialog on the first layout pass. I don't know why this works.
behavior.state = BottomSheetBehavior.STATE_EXPANDED
if (avoidUnusableCollapsedState) {
// skipCollapsed isn't enough, also need to immediately snap to expanded state.
behavior.state = BackportBottomSheetBehavior.STATE_EXPANDED
}
}
}
}
@@ -18,7 +18,10 @@
package org.oxycblt.auxio.util
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.PointF
import android.graphics.drawable.Drawable
import android.os.Build
@@ -28,10 +31,12 @@ import androidx.annotation.RequiresApi
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.appcompat.widget.ActionMenuView
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ShareCompat
import androidx.core.graphics.Insets
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.net.toUri
import androidx.core.view.children
import androidx.navigation.NavController
import androidx.navigation.NavDirections
@@ -40,6 +45,7 @@ import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.google.android.material.appbar.MaterialToolbar
import java.lang.IllegalArgumentException
import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.auxio.music.Song
@@ -111,7 +117,7 @@ val ViewBinding.context: Context
* Override the behavior of a [MaterialToolbar]'s overflow menu to do something else. This is
* extremely dumb, but required to hook overflow menus to bottom sheet menus.
*/
fun MaterialToolbar.overrideOnOverflowMenuClick(block: (View) -> Unit) {
fun Toolbar.overrideOnOverflowMenuClick(block: (View) -> Unit) {
for (toolbarChild in children) {
if (toolbarChild is ActionMenuView) {
for (menuChild in toolbarChild.children) {
@@ -321,3 +327,65 @@ fun Context.share(songs: Collection<Song>) {
builder.setType(mimeTypes.singleOrNull() ?: "audio/*").startChooser()
}
/**
* Open the given URI in a web browser.
*
* @param uri The URL to open.
*/
fun Context.openInBrowser(uri: String) {
fun openAppChooser(intent: Intent) {
logD("Opening app chooser for ${intent.action}")
val chooserIntent =
Intent(Intent.ACTION_CHOOSER)
.putExtra(Intent.EXTRA_INTENT, intent)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(chooserIntent)
}
logD("Opening $uri")
val browserIntent =
Intent(Intent.ACTION_VIEW, uri.toUri()).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Android 11 seems to now handle the app chooser situations on its own now
// [along with adding a new permission that breaks the old manual code], so
// we just do a typical activity launch.
logD("Using API 30+ chooser")
try {
startActivity(browserIntent)
} catch (e: ActivityNotFoundException) {
// No app installed to open the link
showToast(R.string.err_no_app)
}
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
// On older versions of android, opening links from an ACTION_VIEW intent might
// not work in all cases, especially when no default app was set. If that is the
// case, we will try to manually handle these cases before we try to launch the
// browser.
logD("Resolving browser activity for chooser")
val pkgName =
packageManager.resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY)?.run {
activityInfo.packageName
}
if (pkgName != null) {
if (pkgName == "android") {
// No default browser [Must open app chooser, may not be supported]
logD("No default browser found")
openAppChooser(browserIntent)
} else logD("Opening browser intent")
try {
browserIntent.setPackage(pkgName)
startActivity(browserIntent)
} catch (e: ActivityNotFoundException) {
// Not a browser but an app chooser
browserIntent.setPackage(null)
openAppChooser(browserIntent)
}
} else {
// No app installed to open the link
showToast(R.string.err_no_app)
}
}
}
@@ -82,8 +82,10 @@ fun lazyReflectedField(clazz: KClass<*>, field: String) = lazy {
* @param clazz The [KClass] to reflect into.
* @param method The name of the method to obtain.
*/
fun lazyReflectedMethod(clazz: KClass<*>, method: String) = lazy {
clazz.java.getDeclaredMethod(method).also { it.isAccessible = true }
fun lazyReflectedMethod(clazz: KClass<*>, method: String, vararg params: KClass<*>) = lazy {
clazz.java.getDeclaredMethod(method, *params.map { it.java }.toTypedArray()).also {
it.isAccessible = true
}
}
/**
@@ -18,27 +18,24 @@
package org.oxycblt.auxio.util
import android.util.Log
import org.oxycblt.auxio.BuildConfig
// Shortcut functions for logging.
// Yes, I know timber exists but this does what I need.
import timber.log.Timber
/**
* Log an object to the debug channel. Automatically handles tags.
*
* @param obj The object to log.
*/
fun Any.logD(obj: Any?) = logD("$obj")
fun logD(obj: Any?) = logD("$obj")
/**
* Log a string message to the debug channel. Automatically handles tags.
*
* @param msg The message to log.
*/
fun Any.logD(msg: String) {
fun logD(msg: String) {
if (BuildConfig.DEBUG && !copyleftNotice()) {
Log.d(autoTag, msg)
Timber.d(msg)
}
}
@@ -47,21 +44,14 @@ fun Any.logD(msg: String) {
*
* @param msg The message to log.
*/
fun Any.logW(msg: String) = Log.w(autoTag, msg)
fun logW(msg: String) = Timber.w(msg)
/**
* Log a string message to the error channel. Automatically handles tags.
*
* @param msg The message to log.
*/
fun Any.logE(msg: String) = Log.e(autoTag, msg)
/**
* The LogCat-suitable tag for this string. Consists of the object's name, or "Anonymous Object" if
* the object does not exist.
*/
private val Any.autoTag: String
get() = "Auxio.${this::class.simpleName ?: "Anonymous Object"}"
fun logE(msg: String) = Timber.e(msg)
/**
* Please don't plagiarize Auxio! You are free to remove this as long as you continue to keep your
@@ -71,7 +61,7 @@ private val Any.autoTag: String
private fun copyleftNotice(): Boolean {
if (BuildConfig.APPLICATION_ID != "org.oxycblt.auxio" &&
BuildConfig.APPLICATION_ID != "org.oxycblt.auxio.debug") {
Log.d(
Timber.d(
"Auxio Project",
"Friendly reminder: Auxio is licensed under the " +
"GPLv3 and all derivative apps must be made open source!")