Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e12f00c49b | ||
|
|
66947b80bc | ||
|
|
208e48a97b | ||
|
|
65bfdf6b7d | ||
|
|
f492410484 | ||
|
|
39deae7644 | ||
|
|
38bd9cd260 | ||
|
|
ecd71d2699 | ||
|
|
366945499e | ||
|
|
843bf55fd1 | ||
|
|
e4cca068db | ||
|
|
a9f6c82041 | ||
|
|
e4d4da371d | ||
|
|
ac0966c8ea | ||
|
|
960061e615 | ||
|
|
3387ccedaf | ||
|
|
18fde00a41 | ||
|
|
e206acde3f | ||
|
|
7ad4fe5f8c | ||
|
|
442a066136 | ||
|
|
1f3e319552 | ||
|
|
7efa7bff59 | ||
|
|
037c5b1382 | ||
|
|
93c8f8f05f | ||
|
|
a251d5fc2d | ||
|
|
9f2b8894df | ||
|
|
18332d8478 | ||
|
|
94170a8079 | ||
|
|
a1615f3c1b | ||
|
|
f1e999effc | ||
|
|
9c6380489c | ||
|
|
1b5134f854 | ||
|
|
642a3add27 | ||
|
|
6e2a260df9 | ||
|
|
0d6a3240ad | ||
|
|
23135fe80d | ||
|
|
a8e898d5e9 | ||
|
|
c784b4cebd | ||
|
|
ecc6f34a02 | ||
|
|
b7c425b410 | ||
|
|
7c130ac6c3 | ||
|
|
d17f789dd2 | ||
|
|
a19bfbaddf | ||
|
|
ecc90524c6 | ||
|
|
7d0549e775 | ||
|
|
f3003f3a8a | ||
|
|
c8d3ba55fc |
@@ -6,3 +6,5 @@
|
||||
path = musikr/src/main/cpp/taglib
|
||||
url = https://github.com/taglib/taglib.git
|
||||
tag = ee1931b
|
||||
# build_taglib.sh installs per-ABI trees into taglib/pkg/ on every native build
|
||||
ignore = untracked
|
||||
|
||||
+10
-2
@@ -16,8 +16,8 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
applicationId namespace
|
||||
versionName "4.1.5-fork.1"
|
||||
versionCode 76
|
||||
versionName "4.1.5-fork.4"
|
||||
versionCode 79
|
||||
|
||||
minSdk min_sdk
|
||||
// randomly flickers between deprecated and required depending on what mood my gradle is in
|
||||
@@ -75,6 +75,12 @@ android {
|
||||
viewBinding true
|
||||
buildConfig true
|
||||
}
|
||||
|
||||
// Return default values from android.jar stubs in unit tests instead of throwing.
|
||||
// PlaybackStateManagerImpl construction calls Progression.nil() -> SystemClock.elapsedRealtime().
|
||||
testOptions {
|
||||
unitTests.returnDefaultValues = true
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
@@ -86,6 +92,8 @@ kotlin {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation "junit:junit:4.13.2"
|
||||
|
||||
androidTestImplementation "androidx.test:runner:1.7.0"
|
||||
androidTestImplementation "androidx.test.ext:junit:1.3.0"
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.isInvisible
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.fragment.app.activityViewModels
|
||||
import androidx.navigation.fragment.NavHostFragment
|
||||
import androidx.navigation.findNavController
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import com.google.android.material.R as MR
|
||||
@@ -57,6 +58,7 @@ 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.playback.queue.QueueViewModel
|
||||
import org.oxycblt.auxio.ui.DialogAwareNavigationListener
|
||||
import org.oxycblt.auxio.ui.UISettings
|
||||
import org.oxycblt.auxio.ui.ViewBindingFragment
|
||||
@@ -71,6 +73,11 @@ import org.oxycblt.auxio.util.navigateSafe
|
||||
import org.oxycblt.auxio.util.unlikelyToBeNull
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.Album
|
||||
import org.oxycblt.musikr.Artist
|
||||
import org.oxycblt.musikr.Genre
|
||||
import org.oxycblt.musikr.MusicParent
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
@@ -88,6 +95,7 @@ class MainFragment :
|
||||
private val homeModel: HomeViewModel by activityViewModels()
|
||||
private val listModel: ListViewModel by activityViewModels()
|
||||
private val playbackModel: PlaybackViewModel by activityViewModels()
|
||||
private val queueModel: QueueViewModel by activityViewModels()
|
||||
private var sheetBackCallback: SheetBackPressedCallback? = null
|
||||
private var detailBackCallback: DetailBackPressedCallback? = null
|
||||
private var selectionBackCallback: SelectionBackPressedCallback? = null
|
||||
@@ -121,6 +129,9 @@ class MainFragment :
|
||||
binding.queueSheet.coordinatorLayoutBehavior as QueueBottomSheetBehavior?
|
||||
queueSheetBehavior?.uiSettings = uiSettings
|
||||
|
||||
// --- QUEUE SHEET SETUP ---
|
||||
binding.queueClear.setOnClickListener { queueModel.clearQueue() }
|
||||
|
||||
elevationNormal = binding.context.getDimen(MR.dimen.m3_sys_elevation_level1)
|
||||
|
||||
// Currently all back press callbacks are handled in MainFragment, as it's not guaranteed
|
||||
@@ -214,6 +225,7 @@ class MainFragment :
|
||||
// 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)
|
||||
collect(playbackModel.parentNavigation.flow, ::handleParentNavigation)
|
||||
collectImmediately(detailModel.editedPlaylist, detailBackCallback::invalidateEnabled)
|
||||
collectImmediately(homeModel.showOuter.flow, ::handleShowOuter)
|
||||
collectImmediately(homeModel.currentTabType, ::updateCurrentTab)
|
||||
@@ -222,6 +234,7 @@ class MainFragment :
|
||||
collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled)
|
||||
collectImmediately(playbackModel.song, ::updateSong)
|
||||
collectImmediately(playbackModel.openPanel.flow, ::handlePanel)
|
||||
collectImmediately(queueModel.queue, ::updateQueueClearButton)
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
@@ -555,6 +568,25 @@ class MainFragment :
|
||||
binding.sheetScrim.isInvisible = !open
|
||||
}
|
||||
|
||||
private fun handleParentNavigation(parent: MusicParent?) {
|
||||
parent ?: return
|
||||
L.d("Navigating to parent $parent")
|
||||
playbackModel.parentNavigation.consume()
|
||||
val navController =
|
||||
(childFragmentManager.findFragmentById(R.id.explore_nav_host) as NavHostFragment)
|
||||
.navController
|
||||
// Root-level actions: the header tap must work no matter which page is in front.
|
||||
when (parent) {
|
||||
is Album -> navController.navigateSafe(InnerDirections.showAlbumGlobally(parent.uid))
|
||||
is Artist -> navController.navigateSafe(InnerDirections.showArtistGlobally(parent.uid))
|
||||
is Genre -> navController.navigateSafe(InnerDirections.showGenreGlobally(parent.uid))
|
||||
is Playlist ->
|
||||
navController.navigateSafe(InnerDirections.showPlaylistGlobally(parent.uid))
|
||||
else -> return
|
||||
}
|
||||
tryClosePlaybackPanel()
|
||||
}
|
||||
|
||||
private fun handleShow(show: Show?) {
|
||||
when (show) {
|
||||
is Show.SongAlbumDetails,
|
||||
@@ -624,6 +656,10 @@ class MainFragment :
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateQueueClearButton(queue: List<Song>) {
|
||||
requireBinding().queueClear.isVisible = queue.isNotEmpty()
|
||||
}
|
||||
|
||||
private fun tryClosePlaybackPanel() {
|
||||
val binding = requireBinding()
|
||||
val playbackSheetBehavior =
|
||||
|
||||
@@ -25,6 +25,7 @@ import android.view.View
|
||||
import androidx.core.view.updatePadding
|
||||
import androidx.fragment.app.activityViewModels
|
||||
import androidx.navigation.findNavController
|
||||
import androidx.recyclerview.widget.ItemTouchHelper
|
||||
import com.google.android.material.appbar.AppBarLayout
|
||||
import com.google.android.material.transition.MaterialSharedAxis
|
||||
import kotlin.math.abs
|
||||
@@ -36,6 +37,7 @@ import org.oxycblt.auxio.databinding.FragmentDetailBinding
|
||||
import org.oxycblt.auxio.detail.list.DetailListAdapter
|
||||
import org.oxycblt.auxio.list.ListFragment
|
||||
import org.oxycblt.auxio.list.ListViewModel
|
||||
import org.oxycblt.auxio.list.recycler.SwipeActionsCallback
|
||||
import org.oxycblt.auxio.music.MusicViewModel
|
||||
import org.oxycblt.auxio.playback.PlaybackViewModel
|
||||
import org.oxycblt.auxio.util.getDimenPixels
|
||||
@@ -122,6 +124,24 @@ abstract class DetailFragment<P : MusicParent, C : Music> :
|
||||
|
||||
binding.detailRecycler.apply { adapter = getDetailListAdapter() }
|
||||
|
||||
ItemTouchHelper(
|
||||
SwipeActionsCallback(
|
||||
// Queue swipes are inert during multi-select and while a playlist is being
|
||||
// edited (the editing gestures — reorder, remove — own the rows then).
|
||||
isEnabled = {
|
||||
listModel.selected.value.isEmpty() &&
|
||||
detailModel.editedPlaylist.value == null
|
||||
}
|
||||
) { song,
|
||||
action ->
|
||||
when (action) {
|
||||
SwipeActionsCallback.SwipeAction.QUEUE -> playbackModel.addToQueue(song)
|
||||
SwipeActionsCallback.SwipeAction.PLAY_NEXT -> playbackModel.playNext(song)
|
||||
}
|
||||
}
|
||||
)
|
||||
.attachToRecyclerView(binding.detailRecycler)
|
||||
|
||||
spacingSmall = requireContext().getDimenPixels(R.dimen.spacing_small)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* SwipeActionsCallback.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.list.recycler
|
||||
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.graphics.drawable.Drawable
|
||||
import androidx.appcompat.content.res.AppCompatResources
|
||||
import androidx.recyclerview.widget.ItemTouchHelper
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.google.android.material.R as MR
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sign
|
||||
import org.oxycblt.auxio.R
|
||||
import org.oxycblt.auxio.list.adapter.FlexibleListAdapter
|
||||
import org.oxycblt.auxio.util.getAttrColorCompat
|
||||
import org.oxycblt.auxio.util.getDimenPixels
|
||||
import org.oxycblt.musikr.Song
|
||||
|
||||
/**
|
||||
* An [ItemTouchHelper.Callback] giving song rows swipe actions: swipe-right queues the song at
|
||||
* the back of the deck, swipe-left plays it next at the deck's front. The row slides freely up
|
||||
* to a square underlay cell revealing the action's icon, rubber-bands past it, and on release
|
||||
* always springs back home — every release takes the touch helper's cancel animation, which is
|
||||
* that spring-back. Committing is tracked here: armed when the finger passes the cell, disarmed
|
||||
* when pulled back, fired as the row settles ([clearView]).
|
||||
*
|
||||
* @param isEnabled Whether swipes are currently allowed (false during multi-select).
|
||||
* @param onAction Called with the swiped [Song] and the committed [SwipeAction].
|
||||
* @author OxygenCobalt (Fork)
|
||||
*/
|
||||
class SwipeActionsCallback(
|
||||
private val isEnabled: () -> Boolean,
|
||||
private val onAction: (Song, SwipeAction) -> Unit,
|
||||
) : ItemTouchHelper.Callback() {
|
||||
|
||||
/** The action committed by a swipe. */
|
||||
enum class SwipeAction {
|
||||
/** Swipe-right: queue the song at the back of the deck. */
|
||||
QUEUE,
|
||||
|
||||
/** Swipe-left: play the song next at the deck's front. */
|
||||
PLAY_NEXT,
|
||||
}
|
||||
|
||||
private val paint = Paint().apply { isAntiAlias = true }
|
||||
private var queueIcon: Drawable? = null
|
||||
private var playNextIcon: Drawable? = null
|
||||
|
||||
private var armedViewHolder: RecyclerView.ViewHolder? = null
|
||||
private var armedAction: SwipeAction? = null
|
||||
|
||||
override fun getMovementFlags(
|
||||
recyclerView: RecyclerView,
|
||||
viewHolder: RecyclerView.ViewHolder,
|
||||
): Int {
|
||||
if (!isEnabled()) {
|
||||
return 0
|
||||
}
|
||||
// Gate on the item, not the ViewHolder: detail pages use their own row types.
|
||||
val position = viewHolder.bindingAdapterPosition
|
||||
if (position == RecyclerView.NO_POSITION) {
|
||||
return 0
|
||||
}
|
||||
val item = (recyclerView.adapter as? FlexibleListAdapter<*, *>)?.getItem(position)
|
||||
return if (item is Song) {
|
||||
makeMovementFlags(0, ItemTouchHelper.START or ItemTouchHelper.END)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMove(
|
||||
recyclerView: RecyclerView,
|
||||
viewHolder: RecyclerView.ViewHolder,
|
||||
target: RecyclerView.ViewHolder,
|
||||
) = false
|
||||
|
||||
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
|
||||
// Never fires: releases always take the cancel path (see getSwipeThreshold), so the row
|
||||
// springs back instead of flying off, and commits are handled in clearView.
|
||||
}
|
||||
|
||||
/** Never auto-commit: the release always springs back, and we track commits ourselves. */
|
||||
override fun getSwipeThreshold(viewHolder: RecyclerView.ViewHolder) = 2f
|
||||
|
||||
/** Fling-to-commit would fly the row off-screen; disable it for a consistent spring-back. */
|
||||
override fun getSwipeEscapeVelocity(defaultValue: Float) = Float.MAX_VALUE
|
||||
|
||||
override fun getSwipeVelocityThreshold(defaultValue: Float) = Float.MAX_VALUE
|
||||
|
||||
override fun onChildDraw(
|
||||
c: Canvas,
|
||||
recyclerView: RecyclerView,
|
||||
viewHolder: RecyclerView.ViewHolder,
|
||||
dX: Float,
|
||||
dY: Float,
|
||||
actionState: Int,
|
||||
isCurrentlyActive: Boolean,
|
||||
) {
|
||||
// Free slide up to the square cell, then rubber-band resistance past it.
|
||||
val clampedDX =
|
||||
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
|
||||
rubberBand(dX, revealWidth(viewHolder).toFloat())
|
||||
} else {
|
||||
dX
|
||||
}
|
||||
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
|
||||
if (isCurrentlyActive) {
|
||||
// Arm when the finger passes the cell; disarm when pulled back inside it.
|
||||
val raw = abs(dX)
|
||||
val reveal = revealWidth(viewHolder).toFloat()
|
||||
if (raw > reveal) {
|
||||
armedViewHolder = viewHolder
|
||||
armedAction = if (dX > 0) SwipeAction.QUEUE else SwipeAction.PLAY_NEXT
|
||||
} else if (raw < reveal * 0.5f) {
|
||||
armedViewHolder = null
|
||||
armedAction = null
|
||||
}
|
||||
}
|
||||
// Draw whenever the row is displaced, including the spring-back's frames.
|
||||
if (clampedDX != 0f) {
|
||||
drawUnderlay(c, viewHolder, clampedDX)
|
||||
}
|
||||
}
|
||||
super.onChildDraw(c, recyclerView, viewHolder, clampedDX, dY, actionState, isCurrentlyActive)
|
||||
}
|
||||
|
||||
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
|
||||
super.clearView(recyclerView, viewHolder)
|
||||
// The row has settled home; commit if this gesture armed an action.
|
||||
if (armedViewHolder === viewHolder) {
|
||||
val action = armedAction
|
||||
armedViewHolder = null
|
||||
armedAction = null
|
||||
if (action != null) {
|
||||
val position = viewHolder.bindingAdapterPosition
|
||||
val song =
|
||||
(recyclerView.adapter as? FlexibleListAdapter<*, *>)?.getItem(position)
|
||||
as? Song
|
||||
if (song != null) {
|
||||
onAction(song, action)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a raw drag to its visual translation: one-to-one up to [reveal], then increasing
|
||||
* resistance asymptotic to three times the reveal, so the row can be pulled well past the
|
||||
* cell but fights back more the further it goes.
|
||||
*/
|
||||
private fun rubberBand(dX: Float, reveal: Float): Float {
|
||||
val past = abs(dX) - reveal
|
||||
if (past <= 0f) {
|
||||
return dX
|
||||
}
|
||||
return sign(dX) * (reveal + past / (1f + past / (2f * reveal)))
|
||||
}
|
||||
|
||||
/** The square underlay cell's width: a standard large touchable size. */
|
||||
private fun revealWidth(viewHolder: RecyclerView.ViewHolder) =
|
||||
viewHolder.itemView.context.getDimenPixels(R.dimen.size_touchable_large)
|
||||
|
||||
/** Draw the revealed action underlay behind the sliding row. */
|
||||
private fun drawUnderlay(c: Canvas, viewHolder: RecyclerView.ViewHolder, dX: Float) {
|
||||
val view = viewHolder.itemView
|
||||
val context = view.context
|
||||
val reveal = revealWidth(viewHolder).toFloat()
|
||||
val swipingEnd = dX > 0
|
||||
|
||||
val containerAttr: Int
|
||||
val onContainerAttr: Int
|
||||
val icon: Drawable
|
||||
if (swipingEnd) {
|
||||
containerAttr = MR.attr.colorTertiaryContainer
|
||||
onContainerAttr = MR.attr.colorOnTertiaryContainer
|
||||
icon =
|
||||
queueIcon
|
||||
?: AppCompatResources.getDrawable(context, R.drawable.ic_queue_add_24)!!.also {
|
||||
queueIcon = it
|
||||
}
|
||||
} else {
|
||||
containerAttr = MR.attr.colorPrimaryContainer
|
||||
onContainerAttr = MR.attr.colorOnPrimaryContainer
|
||||
icon =
|
||||
playNextIcon
|
||||
?: AppCompatResources.getDrawable(context, R.drawable.ic_play_next_24)!!.also {
|
||||
playNextIcon = it
|
||||
}
|
||||
}
|
||||
|
||||
paint.color = context.getAttrColorCompat(containerAttr).defaultColor
|
||||
val top = view.top.toFloat()
|
||||
val bottom = view.bottom.toFloat()
|
||||
val strip =
|
||||
if (swipingEnd) {
|
||||
RectF(view.left.toFloat(), top, view.left + dX, bottom)
|
||||
} else {
|
||||
RectF(view.right + dX, top, view.right.toFloat(), bottom)
|
||||
}
|
||||
c.drawRect(strip, paint)
|
||||
|
||||
// The icon sits centered in the square cell, fading in as the cell is revealed.
|
||||
val size = context.getDimenPixels(R.dimen.size_icon_medium).toFloat()
|
||||
icon.setTintList(context.getAttrColorCompat(onContainerAttr))
|
||||
icon.alpha = (255 * min(strip.width(), reveal) / reveal).toInt()
|
||||
val centerY = (top + bottom) / 2
|
||||
val centerX =
|
||||
if (swipingEnd) {
|
||||
view.left + reveal / 2
|
||||
} else {
|
||||
view.right - reveal / 2
|
||||
}
|
||||
icon.setBounds(
|
||||
(centerX - size / 2).toInt(),
|
||||
(centerY - size / 2).toInt(),
|
||||
(centerX + size / 2).toInt(),
|
||||
(centerY + size / 2).toInt(),
|
||||
)
|
||||
icon.draw(c)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import java.util.UUID
|
||||
import javax.inject.Inject
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import org.oxycblt.auxio.BuildConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -411,6 +412,15 @@ constructor(
|
||||
val start = System.currentTimeMillis()
|
||||
val result = Musikr.new(context, config).run(::emitIndexingProgress)
|
||||
L.d("Index finished in ${System.currentTimeMillis() - start}ms")
|
||||
if (BuildConfig.DEBUG) {
|
||||
// Surface parsed ReplayGain values for logcat verification.
|
||||
for (song in result.library.songs) {
|
||||
val rg = song.replayGainAdjustment
|
||||
if (rg.track != null || rg.album != null) {
|
||||
L.d("RG: ${song.name.raw} track=${rg.track} album=${rg.album}")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Music loading completed, update the revision right now so we re-use this work
|
||||
// later.
|
||||
L.d("Revisioning from $currentRevision -> $newRevision")
|
||||
|
||||
@@ -53,6 +53,7 @@ class MusicViewModel
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
private val listSettings: ListSettings,
|
||||
private val musicSettings: MusicSettings,
|
||||
private val musicRepository: MusicRepository,
|
||||
) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener {
|
||||
private val externalPlaylistManager = ExternalPlaylistManager.from(context)
|
||||
@@ -160,24 +161,19 @@ constructor(
|
||||
fun importPlaylist(uri: Uri? = null, target: Playlist? = null) {
|
||||
if (uri != null) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val importedPlaylist = externalPlaylistManager.import(uri)
|
||||
val library = musicRepository.library ?: return@launch
|
||||
val importedPlaylist =
|
||||
externalPlaylistManager.import(
|
||||
uri,
|
||||
musicSettings.safQuery.source.map { it.path },
|
||||
library,
|
||||
)
|
||||
if (importedPlaylist == null) {
|
||||
L.e("Could not import playlist")
|
||||
playlistMessage.put(PlaylistMessage.ImportFailed)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val library = musicRepository.library ?: return@launch
|
||||
val songs =
|
||||
importedPlaylist.paths.mapNotNull {
|
||||
it.firstNotNullOfOrNull(library::findSongByPath)
|
||||
}
|
||||
|
||||
if (songs.isEmpty()) {
|
||||
L.e("No songs found")
|
||||
playlistMessage.put(PlaylistMessage.ImportFailed)
|
||||
return@launch
|
||||
}
|
||||
val songs = importedPlaylist.songs
|
||||
|
||||
if (target !== null) {
|
||||
if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) {
|
||||
|
||||
@@ -109,6 +109,8 @@ class PlaybackPanelFragment :
|
||||
binding.playbackToolbar.apply {
|
||||
setNavigationOnClickListener { playbackModel.openMain() }
|
||||
setOnMenuItemClickListener(this@PlaybackPanelFragment)
|
||||
// Tapping the Now Playing header navigates to the parent (album, playlist, etc.).
|
||||
setOnClickListener { playbackModel.navigateToParent() }
|
||||
}
|
||||
|
||||
binding.playbackPager?.apply {
|
||||
@@ -119,7 +121,7 @@ class PlaybackPanelFragment :
|
||||
UserAwarePagerCallback(this) {
|
||||
// Posting the queue goto command prevents the seekbar pos from desyncing
|
||||
// from the song's duration, which creates a visual flicker in the seekbar.
|
||||
post { queueModel.goto(it) }
|
||||
post { queueModel.gotoTimelinePosition(it) }
|
||||
}
|
||||
.also { it.attach() }
|
||||
setPageTransformer(CarouselTransformer())
|
||||
@@ -275,8 +277,9 @@ class PlaybackPanelFragment :
|
||||
private fun updateParent(parent: MusicParent?) {
|
||||
val binding = requireBinding()
|
||||
val context = requireContext()
|
||||
binding.playbackToolbar.subtitle =
|
||||
parent?.run { name.resolve(context) } ?: context.getString(R.string.lbl_all_songs)
|
||||
// No subtitle without a parent: the header carries a tap action, so it must not name
|
||||
// a destination it cannot navigate to.
|
||||
binding.playbackToolbar.subtitle = parent?.run { name.resolve(context) }
|
||||
}
|
||||
|
||||
private fun updatePosition(positionDs: Long) {
|
||||
@@ -344,8 +347,9 @@ class PlaybackPanelFragment :
|
||||
// but only on some devices.
|
||||
val binding = binding ?: return
|
||||
|
||||
val command = playbackModel.pagerCommand.consume()
|
||||
if (command == null) {
|
||||
val commands = playbackModel.drainPagerCommands()
|
||||
L.d("Pager: applying ${commands.size} command(s), pager at ${binding.playbackPager.currentItem}")
|
||||
if (commands.isEmpty()) {
|
||||
// This probably shouldn't happen in practice, as QueueViewModel directly
|
||||
// attaches to PlaybackStateManager and will basically always initialize
|
||||
// with a command as a result.
|
||||
@@ -357,24 +361,28 @@ class PlaybackPanelFragment :
|
||||
return
|
||||
}
|
||||
|
||||
if (command.update != null) {
|
||||
// queue needs to be updated.
|
||||
coverPagerAdapter.update(queue.queue, command.update)
|
||||
}
|
||||
|
||||
if (command.scroll != null) {
|
||||
// we need to scroll, however the smooth scroll only really looks best
|
||||
// when we are only doing next/prev due to various factors. better to
|
||||
// just not animate on outright gotos or queue updates
|
||||
val delta = binding.playbackPager.currentItem - command.scroll
|
||||
if (delta == 0) {
|
||||
// user scroll, carry on
|
||||
return
|
||||
// Apply every command in order; each carries the queue state it was made against, so a
|
||||
// burst (like a drain's removal plus scroll) cannot lose its intermediate step.
|
||||
for ((commandQueue, command) in commands) {
|
||||
if (command.update != null) {
|
||||
// queue needs to be updated.
|
||||
coverPagerAdapter.update(commandQueue.queue, command.update)
|
||||
}
|
||||
if (command.update == null && abs(delta) == 1) {
|
||||
binding.playbackPager.smoothScrollByPageTo(command.scroll)
|
||||
} else {
|
||||
binding.playbackPager.setCurrentItem(command.scroll, false)
|
||||
|
||||
if (command.scroll != null) {
|
||||
// we need to scroll, however the smooth scroll only really looks best
|
||||
// when we are only doing next/prev due to various factors. better to
|
||||
// just not animate on outright gotos or queue updates
|
||||
val delta = binding.playbackPager.currentItem - command.scroll
|
||||
if (delta == 0) {
|
||||
// user scroll, carry on
|
||||
continue
|
||||
}
|
||||
if (command.update == null && abs(delta) == 1) {
|
||||
binding.playbackPager.smoothScrollByPageTo(command.scroll)
|
||||
} else {
|
||||
binding.playbackPager.setCurrentItem(command.scroll, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,13 +101,37 @@ constructor(
|
||||
val openPanel: Event<OpenPanel>
|
||||
field = MutableEvent<OpenPanel>()
|
||||
|
||||
/** Requests navigation to the parent of the current playback, from the Now Playing header. */
|
||||
val parentNavigation: Event<MusicParent>
|
||||
field = MutableEvent<MusicParent>()
|
||||
|
||||
private val _pagerQueue = MutableStateFlow(PagerQueue(listOf(), 0))
|
||||
/** The current queue in a special bundled format suitable for the cover ViewPager2. */
|
||||
val pagerQueue: StateFlow<PagerQueue> = _pagerQueue
|
||||
|
||||
/** Specialized ViewPager2-friendly queue commands */
|
||||
val pagerCommand: Event<PagerCommand>
|
||||
field = MutableEvent<PagerCommand>()
|
||||
// Manager callbacks can arrive on any thread; the panel drains on the main thread.
|
||||
private val pagerLock = Any()
|
||||
private val pendingPagerCommands = ArrayDeque<Pair<PagerQueue, PagerCommand>>()
|
||||
|
||||
/**
|
||||
* Drain the pager commands accumulated since the last drain, as (queue, command) pairs in
|
||||
* order. Each pair is a complete intermediate state, so applying them sequentially is safe
|
||||
* even when a single event (like a drain) produces several commands in one burst.
|
||||
*/
|
||||
fun drainPagerCommands(): List<Pair<PagerQueue, PagerCommand>> =
|
||||
synchronized(pagerLock) {
|
||||
val drained = pendingPagerCommands.toList()
|
||||
pendingPagerCommands.clear()
|
||||
drained
|
||||
}
|
||||
|
||||
/** Update the pager's queue and enqueue the command describing the change. */
|
||||
private fun updatePagerQueue(queue: List<Song>, index: Int, command: PagerCommand) {
|
||||
val pagerQueue = PagerQueue(queue, index)
|
||||
L.d("Pager: enqueue $command, queue size ${queue.size}, index $index")
|
||||
synchronized(pagerLock) { pendingPagerCommands += pagerQueue to command }
|
||||
_pagerQueue.value = pagerQueue
|
||||
}
|
||||
|
||||
/**
|
||||
* A [PlaybackDecision] command that is awaiting a view capable of responding to it. Null if
|
||||
@@ -137,8 +161,7 @@ constructor(
|
||||
positionDs.value = playbackManager.progression.calculateElapsedPositionMs().msToDs()
|
||||
song.value = playbackManager.currentSong
|
||||
|
||||
pagerCommand.put(PagerCommand(update = null, scroll = index))
|
||||
_pagerQueue.value = _pagerQueue.value.copy(index = index)
|
||||
updatePagerQueue(_pagerQueue.value.queue, index, PagerCommand(update = null, scroll = index))
|
||||
}
|
||||
|
||||
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
|
||||
@@ -148,21 +171,21 @@ constructor(
|
||||
song.value = playbackManager.currentSong
|
||||
}
|
||||
|
||||
pagerCommand.put(
|
||||
updatePagerQueue(
|
||||
queue,
|
||||
index,
|
||||
PagerCommand(
|
||||
update = change.instructions,
|
||||
scroll = index.takeIf { change.type != QueueChange.Type.MAPPING },
|
||||
)
|
||||
),
|
||||
)
|
||||
_pagerQueue.value = PagerQueue(queue = queue, index = index)
|
||||
}
|
||||
|
||||
override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) {
|
||||
L.d("Queue completely changed, updating current song")
|
||||
this.isShuffled.value = isShuffled
|
||||
|
||||
pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
|
||||
_pagerQueue.value = PagerQueue(queue = queue, index = index)
|
||||
updatePagerQueue(queue, index, PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
|
||||
}
|
||||
|
||||
override fun onNewPlayback(
|
||||
@@ -176,8 +199,7 @@ constructor(
|
||||
_parent.value = parent
|
||||
this.isShuffled.value = isShuffled
|
||||
|
||||
pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
|
||||
_pagerQueue.value = PagerQueue(queue = queue, index = index)
|
||||
updatePagerQueue(queue, index, PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
|
||||
}
|
||||
|
||||
override fun onProgressionChanged(progression: Progression) {
|
||||
@@ -544,63 +566,63 @@ constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a [Song] to the end of the queue.
|
||||
* Add a [Song] to the deck.
|
||||
*
|
||||
* @param song The [Song] to add.
|
||||
*/
|
||||
fun addToQueue(song: Song) {
|
||||
L.d("Adding $song to queue")
|
||||
playbackManager.addToQueue(song)
|
||||
L.d("Adding $song to deck")
|
||||
playbackManager.playAfter(song)
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a [Album] to the end of the queue.
|
||||
* Add a [Album] to the deck.
|
||||
*
|
||||
* @param album The [Album] to add.
|
||||
*/
|
||||
fun addToQueue(album: Album) {
|
||||
L.d("Adding $album to queue")
|
||||
playbackManager.addToQueue(listSettings.albumSongSort.songs(album.songs))
|
||||
L.d("Adding $album to deck")
|
||||
playbackManager.playAfter(listSettings.albumSongSort.songs(album.songs))
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a [Artist] to the end of the queue.
|
||||
* Add a [Artist] to the deck.
|
||||
*
|
||||
* @param artist The [Artist] to add.
|
||||
*/
|
||||
fun addToQueue(artist: Artist) {
|
||||
L.d("Adding $artist to queue")
|
||||
playbackManager.addToQueue(listSettings.artistSongSort.songs(artist.songs))
|
||||
L.d("Adding $artist to deck")
|
||||
playbackManager.playAfter(listSettings.artistSongSort.songs(artist.songs))
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a [Genre] to the end of the queue.
|
||||
* Add a [Genre] to the deck.
|
||||
*
|
||||
* @param genre The [Genre] to add.
|
||||
*/
|
||||
fun addToQueue(genre: Genre) {
|
||||
L.d("Adding $genre to queue")
|
||||
playbackManager.addToQueue(listSettings.genreSongSort.songs(genre.songs))
|
||||
L.d("Adding $genre to deck")
|
||||
playbackManager.playAfter(listSettings.genreSongSort.songs(genre.songs))
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a [Playlist] to the end of the queue.
|
||||
* Add a [Playlist] to the deck.
|
||||
*
|
||||
* @param playlist The [Playlist] to add.
|
||||
*/
|
||||
fun addToQueue(playlist: Playlist) {
|
||||
L.d("Adding $playlist to queue")
|
||||
playbackManager.addToQueue(playlist.songs)
|
||||
L.d("Adding $playlist to deck")
|
||||
playbackManager.playAfter(playlist.songs)
|
||||
}
|
||||
|
||||
/**
|
||||
* Add [Song]s to the end of the queue.
|
||||
* Add [Song]s to the deck.
|
||||
*
|
||||
* @param songs The [Song]s to add.
|
||||
*/
|
||||
fun addToQueue(songs: List<Song>) {
|
||||
L.d("Adding ${songs.size} songs to queue")
|
||||
playbackManager.addToQueue(songs)
|
||||
L.d("Adding ${songs.size} songs to deck")
|
||||
playbackManager.playAfter(songs)
|
||||
}
|
||||
|
||||
// --- STATUS FUNCTIONS ---
|
||||
@@ -632,6 +654,12 @@ constructor(
|
||||
/** Open the main panel, closing all other panels. */
|
||||
fun openMain() = openImpl(OpenPanel.MAIN)
|
||||
|
||||
/** Navigate to the parent of the current playback. Does nothing when playback is parentless. */
|
||||
fun navigateToParent() {
|
||||
val parent = parent.value ?: return
|
||||
parentNavigation.put(parent)
|
||||
}
|
||||
|
||||
/** Open the playback panel, closing the queue panel if needed. */
|
||||
fun openPlayback() = openImpl(OpenPanel.PLAYBACK)
|
||||
|
||||
|
||||
@@ -37,8 +37,14 @@ import org.oxycblt.musikr.Music
|
||||
* @author Alexander Capehart
|
||||
*/
|
||||
@Database(
|
||||
entities = [PlaybackState::class, QueueHeapItem::class, QueueShuffledMappingItem::class],
|
||||
version = 38,
|
||||
entities =
|
||||
[
|
||||
PlaybackState::class,
|
||||
QueueHeapItem::class,
|
||||
QueueShuffledMappingItem::class,
|
||||
QueueDeckItem::class,
|
||||
],
|
||||
version = 39,
|
||||
exportSchema = false,
|
||||
)
|
||||
@TypeConverters(Music.UID.TypeConverters::class)
|
||||
@@ -65,6 +71,18 @@ abstract class PersistenceDatabase : RoomDatabase() {
|
||||
it.execSQL("ALTER TABLE queue_heap RENAME TO QueueHeapItem")
|
||||
it.execSQL("ALTER TABLE queue_mapping RENAME TO QueueMappingItem")
|
||||
}
|
||||
|
||||
val MIGRATION_38_39 =
|
||||
Migration(38, 39) {
|
||||
// The deck is its own ordered table, and the current song's deck membership
|
||||
// is a flag on the playback state.
|
||||
it.execSQL(
|
||||
"CREATE TABLE IF NOT EXISTS `QueueDeckItem` (`id` INTEGER PRIMARY KEY NOT NULL, `uid` TEXT NOT NULL)"
|
||||
)
|
||||
it.execSQL(
|
||||
"ALTER TABLE `PlaybackState` ADD COLUMN `deckCurrent` INTEGER NOT NULL DEFAULT 0"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,6 +153,23 @@ interface QueueDao {
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.ABORT)
|
||||
suspend fun insertShuffledMapping(mapping: List<QueueShuffledMappingItem>)
|
||||
|
||||
/**
|
||||
* Get the persisted deck entries.
|
||||
*
|
||||
* @return A list of persisted [QueueDeckItem]s wrapping each deck song in order.
|
||||
*/
|
||||
@Query("SELECT * FROM QueueDeckItem") suspend fun getDeck(): List<QueueDeckItem>
|
||||
|
||||
/** Delete any previously persisted [QueueDeckItem]s. */
|
||||
@Query("DELETE FROM QueueDeckItem") suspend fun nukeDeck()
|
||||
|
||||
/**
|
||||
* Insert new deck entries into the database.
|
||||
*
|
||||
* @param deck The list of wrapped [QueueDeckItem]s to insert.
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.ABORT) suspend fun insertDeck(deck: List<QueueDeckItem>)
|
||||
}
|
||||
|
||||
// TODO: Figure out how to get RepeatMode to map to an int instead of a string
|
||||
@@ -146,8 +181,11 @@ data class PlaybackState(
|
||||
val repeatMode: RepeatMode,
|
||||
val songUid: Music.UID,
|
||||
val parentUid: Music.UID?,
|
||||
val deckCurrent: Boolean,
|
||||
)
|
||||
|
||||
@Entity data class QueueHeapItem(@PrimaryKey val id: Int, val uid: Music.UID)
|
||||
|
||||
@Entity data class QueueShuffledMappingItem(@PrimaryKey val id: Int, val index: Int)
|
||||
|
||||
@Entity data class QueueDeckItem(@PrimaryKey val id: Int, val uid: Music.UID)
|
||||
|
||||
@@ -46,7 +46,7 @@ class PersistenceRoomModule {
|
||||
"playback_persistence.db",
|
||||
)
|
||||
.fallbackToDestructiveMigration()
|
||||
.addMigrations(PersistenceDatabase.MIGRATION_27_32)
|
||||
.addMigrations(PersistenceDatabase.MIGRATION_27_32, PersistenceDatabase.MIGRATION_38_39)
|
||||
.build()
|
||||
|
||||
@Provides fun playbackStateDao(database: PersistenceDatabase) = database.playbackStateDao()
|
||||
|
||||
@@ -54,10 +54,12 @@ constructor(
|
||||
val playbackState: PlaybackState
|
||||
val heapItems: List<QueueHeapItem>
|
||||
val mappingItems: List<QueueShuffledMappingItem>
|
||||
val deckItems: List<QueueDeckItem>
|
||||
try {
|
||||
playbackState = playbackStateDao.getState() ?: return null
|
||||
heapItems = queueDao.getHeap()
|
||||
mappingItems = queueDao.getShuffledMapping()
|
||||
deckItems = queueDao.getDeck()
|
||||
} catch (e: Exception) {
|
||||
L.e("Unable read playback state")
|
||||
L.e(e.stackTraceToString())
|
||||
@@ -66,6 +68,7 @@ constructor(
|
||||
|
||||
val heap = heapItems.map { library.findSong(it.uid) }
|
||||
val shuffledMapping = mappingItems.map { it.index }
|
||||
val deck = deckItems.map { library.findSong(it.uid) }
|
||||
val parent = playbackState.parentUid?.let { musicRepository.find(it) as? MusicParent }
|
||||
|
||||
return PlaybackStateManager.SavedState(
|
||||
@@ -74,6 +77,8 @@ constructor(
|
||||
parent = parent,
|
||||
heap = heap,
|
||||
shuffledMapping = shuffledMapping,
|
||||
deck = deck,
|
||||
deckCurrent = playbackState.deckCurrent,
|
||||
index = playbackState.index,
|
||||
songUid = playbackState.songUid,
|
||||
)
|
||||
@@ -84,6 +89,7 @@ constructor(
|
||||
playbackStateDao.nukeState()
|
||||
queueDao.nukeHeap()
|
||||
queueDao.nukeShuffledMapping()
|
||||
queueDao.nukeDeck()
|
||||
} catch (e: Exception) {
|
||||
L.e("Unable to clear previous state")
|
||||
L.e(e.stackTraceToString())
|
||||
@@ -101,18 +107,23 @@ constructor(
|
||||
repeatMode = state.repeatMode,
|
||||
songUid = state.songUid,
|
||||
parentUid = state.parent?.uid,
|
||||
deckCurrent = state.deckCurrent,
|
||||
)
|
||||
|
||||
// Convert the remaining queue information do their database-specific counterparts.
|
||||
val heap =
|
||||
state.heap.mapIndexed { i, song -> QueueHeapItem(i, requireNotNull(song).uid) }
|
||||
|
||||
val deck =
|
||||
state.deck.mapIndexed { i, song -> QueueDeckItem(i, requireNotNull(song).uid) }
|
||||
|
||||
val shuffledMapping =
|
||||
state.shuffledMapping.mapIndexed { i, index -> QueueShuffledMappingItem(i, index) }
|
||||
|
||||
try {
|
||||
playbackStateDao.insertState(playbackState)
|
||||
queueDao.insertHeap(heap)
|
||||
queueDao.insertDeck(deck)
|
||||
queueDao.insertShuffledMapping(shuffledMapping)
|
||||
} catch (e: Exception) {
|
||||
L.e("Unable to write new state")
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* DeckRowDiff.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.playback.queue
|
||||
|
||||
import org.oxycblt.auxio.list.adapter.UpdateInstructions
|
||||
import org.oxycblt.musikr.Song
|
||||
|
||||
/**
|
||||
* Compute the minimal [UpdateInstructions] transforming the queue drawer's rows from [old] to
|
||||
* [new]. Returns null when nothing changed. Falls back to [UpdateInstructions.Replace] from the
|
||||
* first divergence when no single add, remove, or move explains the change.
|
||||
*/
|
||||
internal fun diffDeckRows(old: List<Song>, new: List<Song>): UpdateInstructions? {
|
||||
val oldUids = old.map { it.uid }
|
||||
val newUids = new.map { it.uid }
|
||||
if (oldUids == newUids) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Common prefix and suffix frame the changed window.
|
||||
var prefix = 0
|
||||
while (prefix < minOf(oldUids.size, newUids.size) && oldUids[prefix] == newUids[prefix]) {
|
||||
prefix++
|
||||
}
|
||||
var suffix = 0
|
||||
while (suffix < minOf(oldUids.size, newUids.size) - prefix &&
|
||||
oldUids[oldUids.size - 1 - suffix] == newUids[newUids.size - 1 - suffix]
|
||||
) {
|
||||
suffix++
|
||||
}
|
||||
|
||||
val oldWindow = oldUids.subList(prefix, oldUids.size - suffix)
|
||||
val newWindow = newUids.subList(prefix, newUids.size - suffix)
|
||||
return when {
|
||||
// Pure addition or removal.
|
||||
oldWindow.isEmpty() -> UpdateInstructions.Add(prefix, newWindow.size)
|
||||
newWindow.isEmpty() -> UpdateInstructions.Remove(prefix, oldWindow.size)
|
||||
// A single element moved within the window.
|
||||
oldWindow.size == newWindow.size -> {
|
||||
val move = findSingleMove(oldWindow, newWindow)
|
||||
if (move != null) {
|
||||
UpdateInstructions.Move(prefix + move.first, prefix + move.second)
|
||||
} else {
|
||||
UpdateInstructions.Replace(prefix)
|
||||
}
|
||||
}
|
||||
else -> UpdateInstructions.Replace(prefix)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the single element move transforming [old] into [new], as its indices in each list. Null
|
||||
* when no single move explains the difference (including replacements, which equalize on removal
|
||||
* without the element actually moving).
|
||||
*/
|
||||
private fun <T> findSingleMove(old: List<T>, new: List<T>): Pair<Int, Int>? {
|
||||
for (from in old.indices) {
|
||||
val remainder = old.toMutableList().apply { removeAt(from) }
|
||||
for (to in new.indices) {
|
||||
if (old[from] == new[to] && new.toMutableList().apply { removeAt(to) } == remainder) {
|
||||
return from to to
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -51,7 +51,7 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
|
||||
// Since PlayingIndicator adapter relies on an item value, we cannot use it for this
|
||||
// adapter, as one item can appear at several points in the UI. Use a similar implementation
|
||||
// with an index value instead.
|
||||
private var currentIndex = 0
|
||||
private var currentIndex = -1
|
||||
private var isPlaying = false
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
|
||||
@@ -69,7 +69,6 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
|
||||
viewHolder.bind(getItem(position), listener)
|
||||
}
|
||||
|
||||
viewHolder.isFuture = position > currentIndex
|
||||
viewHolder.updatePlayingIndicator(position == currentIndex, isPlaying)
|
||||
}
|
||||
|
||||
@@ -91,7 +90,7 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
|
||||
// TODO: Don't update when the index has not moved.
|
||||
if (currentIndex < lastIndex) {
|
||||
L.d("Moved backwards, must update items above last index")
|
||||
val since = if (incremental) currentIndex else 0
|
||||
val since = (if (incremental) currentIndex else 0).coerceAtLeast(0)
|
||||
notifyItemRangeChanged(
|
||||
since,
|
||||
lastIndex - since + 1,
|
||||
@@ -99,17 +98,20 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
|
||||
)
|
||||
} else if (currentIndex > lastIndex) {
|
||||
L.d("Moved forwards, update items after index")
|
||||
val since = if (incremental) lastIndex else 0
|
||||
val since = (if (incremental) lastIndex else 0).coerceAtLeast(0)
|
||||
notifyItemRangeChanged(
|
||||
since,
|
||||
currentIndex - since + 1,
|
||||
PAYLOAD_UPDATE_POSITION,
|
||||
)
|
||||
} else if (!incremental && currentIndex >= 0) {
|
||||
// A list operation replaced the playing row's occupant without moving the index.
|
||||
notifyItemChanged(currentIndex, PAYLOAD_UPDATE_POSITION)
|
||||
}
|
||||
|
||||
val lastIsPlaying = this.isPlaying
|
||||
this.isPlaying = isPlaying
|
||||
if (this.isPlaying != lastIsPlaying) {
|
||||
if (currentIndex >= 0 && this.isPlaying != lastIsPlaying) {
|
||||
L.d("Changed play state")
|
||||
notifyItemChanged(currentIndex)
|
||||
}
|
||||
@@ -128,7 +130,11 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
|
||||
*/
|
||||
class QueueSongViewHolder private constructor(private val binding: ItemEditableSongBinding) :
|
||||
PlayingIndicatorAdapter.ViewHolder(binding.root), MaterialDragCallback.ViewHolder {
|
||||
override val enabled = true
|
||||
/** Whether this row is the playing row; the playing row is neither draggable nor swipeable. */
|
||||
private var isActiveRow = false
|
||||
|
||||
override val enabled: Boolean
|
||||
get() = !isActiveRow
|
||||
override val root = binding.root
|
||||
override val body = binding.body
|
||||
override val delete = binding.background
|
||||
@@ -143,18 +149,6 @@ class QueueSongViewHolder private constructor(private val binding: ItemEditableS
|
||||
fillColor = binding.context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this ViewHolder should be full-opacity to represent a future item, or greyed out to
|
||||
* represent a past item. True if former, false if latter.
|
||||
*/
|
||||
var isFuture: Boolean
|
||||
get() = binding.songAlbumCover.isEnabled
|
||||
set(value) {
|
||||
binding.songAlbumCover.isEnabled = value
|
||||
binding.songName.isEnabled = value
|
||||
binding.songInfo.isEnabled = value
|
||||
}
|
||||
|
||||
init {
|
||||
binding.body.background = LayerDrawable(arrayOf(roundableBackground, liftableBackground))
|
||||
}
|
||||
@@ -177,8 +171,11 @@ class QueueSongViewHolder private constructor(private val binding: ItemEditableS
|
||||
}
|
||||
|
||||
override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) {
|
||||
isActiveRow = isActive
|
||||
binding.interactBody.isSelected = isActive
|
||||
binding.songAlbumCover.setPlaying(isPlaying)
|
||||
// The playing row is neither draggable nor swipeable; hide the drag affordance.
|
||||
binding.songDragHandle.isInvisible = isActive
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -23,6 +23,7 @@ import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
import androidx.coordinatorlayout.widget.CoordinatorLayout
|
||||
import androidx.core.view.updatePadding
|
||||
import com.google.android.material.R as MR
|
||||
import com.google.android.material.shape.MaterialShapeDrawable
|
||||
import com.google.android.material.shape.ShapeAppearanceModel
|
||||
@@ -106,6 +107,10 @@ class QueueBottomSheetBehavior<V : View>(context: Context, attributeSet: Attribu
|
||||
val bars = insets.systemBarInsetsCompat
|
||||
val effectiveBarHeight = if (barHeight > 0) barHeight else getIdealBarHeight(child.context)
|
||||
expandedOffset = effectiveBarHeight + barSpacing
|
||||
// The sheet is measured at full height from its expanded offset, so its bottom extends
|
||||
// that far below the screen. Pad the content so it ends at the visible bottom instead
|
||||
// (which also keeps the empty-queue hint visually centered).
|
||||
child.updatePadding(bottom = expandedOffset + bars.bottom)
|
||||
return insets.replaceSystemBarInsetsCompat(
|
||||
bars.left,
|
||||
bars.top,
|
||||
|
||||
@@ -21,6 +21,7 @@ package org.oxycblt.auxio.playback.queue
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import androidx.core.view.isInvisible
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.fragment.app.activityViewModels
|
||||
import androidx.fragment.app.viewModels
|
||||
import androidx.recyclerview.widget.ItemTouchHelper
|
||||
@@ -88,9 +89,9 @@ class QueueFragment : ViewBindingFragment<FragmentQueueBinding>(), EditClickList
|
||||
super.onDestroyBinding(binding)
|
||||
touchHelper = null
|
||||
binding.queueRecycler.adapter = null
|
||||
// Avoid possible race conditions that could cause a bad instruction to be consumed
|
||||
// during list initialization and crash the app. Could happen if the user is fast enough.
|
||||
queueModel.queueInstructions.consume()
|
||||
// Discard any updates accumulated while the view was gone; a recreated view rebuilds
|
||||
// from the current rows.
|
||||
queueModel.drainQueueUpdates()
|
||||
}
|
||||
|
||||
override fun onClick(item: Song, viewHolder: RecyclerView.ViewHolder) {
|
||||
@@ -111,9 +112,10 @@ class QueueFragment : ViewBindingFragment<FragmentQueueBinding>(), EditClickList
|
||||
private fun updateQueue(queue: List<Song>, index: Int, isPlaying: Boolean) {
|
||||
val binding = requireBinding()
|
||||
|
||||
val instructions = queueModel.queueInstructions.consume()
|
||||
queueAdapter.update(queue, instructions)
|
||||
queueAdapter.setPosition(index, isPlaying, instructions == null)
|
||||
val updates = queueModel.drainQueueUpdates()
|
||||
updates.forEach { (rows, instructions) -> queueAdapter.update(rows, instructions) }
|
||||
queueAdapter.setPosition(index, isPlaying, updates.isEmpty())
|
||||
binding.queueEmpty.isVisible = queue.isEmpty()
|
||||
|
||||
// If requested, scroll to a new item (occurs when the index moves)
|
||||
val scrollTo = queueModel.scrollTo.consume()
|
||||
|
||||
@@ -33,7 +33,8 @@ import org.oxycblt.musikr.Song
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
* A [ViewModel] that manages the current queue state and allows navigation through the queue.
|
||||
* A [ViewModel] that exposes the deck as the queue drawer's rows and translates drawer-row
|
||||
* actions into deck coordinates.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@@ -42,49 +43,53 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
|
||||
ViewModel(), PlaybackStateManager.Listener {
|
||||
|
||||
private val _queue = MutableStateFlow(listOf<Song>())
|
||||
/** The current queue. */
|
||||
/** The drawer rows: the playing deck song (if any) followed by the waiting deck songs. */
|
||||
val queue: StateFlow<List<Song>> = _queue
|
||||
private val _queueInstructions = MutableEvent<UpdateInstructions>()
|
||||
/** Instructions for how to update [queue] in the UI. */
|
||||
val queueInstructions: Event<UpdateInstructions> = _queueInstructions
|
||||
|
||||
// Manager callbacks can arrive on any thread; the fragment drains on the main thread.
|
||||
private val pendingLock = Any()
|
||||
private val pendingUpdates = ArrayDeque<Pair<List<Song>, UpdateInstructions>>()
|
||||
|
||||
/**
|
||||
* Drain the row updates accumulated since the last drain, as (rows, instructions) pairs in
|
||||
* order. Each pair is a complete intermediate state, so applying them sequentially is safe
|
||||
* even when flow emissions were conflated.
|
||||
*/
|
||||
fun drainQueueUpdates(): List<Pair<List<Song>, UpdateInstructions>> =
|
||||
synchronized(pendingLock) {
|
||||
val drained = pendingUpdates.toList()
|
||||
pendingUpdates.clear()
|
||||
drained
|
||||
}
|
||||
|
||||
/** Controls whether the queue should be force-scrolled to a particular location. */
|
||||
val scrollTo: Event<Int>
|
||||
field = MutableEvent<Int>()
|
||||
|
||||
/** The index of the currently playing song in the queue. */
|
||||
/** The row of the playing deck song (0), or -1 when no deck song is playing. */
|
||||
val index: StateFlow<Int>
|
||||
field = MutableStateFlow(playbackManager.index)
|
||||
field = MutableStateFlow(-1)
|
||||
|
||||
init {
|
||||
playbackManager.addListener(this)
|
||||
republish()
|
||||
}
|
||||
|
||||
override fun onIndexMoved(index: Int) {
|
||||
L.d("Index moved, synchronizing and scrolling to new position")
|
||||
scrollTo.put(index)
|
||||
this.index.value = index
|
||||
}
|
||||
|
||||
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
|
||||
// Queue changed trivially due to item mo -> Diff queue, stay at current index.
|
||||
L.d("Updating queue display")
|
||||
_queueInstructions.put(change.instructions)
|
||||
_queue.value = queue
|
||||
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")
|
||||
this.index.value = index
|
||||
val hadPlayingDeckSong = this.index.value == 0
|
||||
republish()
|
||||
if (!hadPlayingDeckSong && this.index.value == 0) {
|
||||
// A deck song started playing; make sure it is visible.
|
||||
scrollTo.put(0)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
|
||||
republish()
|
||||
}
|
||||
|
||||
override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) {
|
||||
// Queue changed completely -> Replace queue, update index
|
||||
L.d("Queue changed completely, replacing queue and position")
|
||||
_queueInstructions.put(UpdateInstructions.Replace(0))
|
||||
scrollTo.put(index)
|
||||
_queue.value = queue
|
||||
this.index.value = index
|
||||
republish()
|
||||
}
|
||||
|
||||
override fun onNewPlayback(
|
||||
@@ -93,12 +98,7 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
|
||||
index: Int,
|
||||
isShuffled: Boolean,
|
||||
) {
|
||||
// Entirely new queue -> Replace queue, update index
|
||||
L.d("New playback, replacing queue and position")
|
||||
_queueInstructions.put(UpdateInstructions.Replace(0))
|
||||
scrollTo.put(index)
|
||||
_queue.value = queue
|
||||
this.index.value = index
|
||||
republish()
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
@@ -106,46 +106,76 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
|
||||
}
|
||||
|
||||
/**
|
||||
* Start playing the the queue item at the given index.
|
||||
* Start playing the deck row at the given index.
|
||||
*
|
||||
* @param adapterIndex The index of the queue item to play. Does nothing if the index is out of
|
||||
* range.
|
||||
* @param adapterIndex The deck row to play. Does nothing if the row is out of range.
|
||||
*/
|
||||
fun goto(adapterIndex: Int) {
|
||||
if (adapterIndex !in queue.value.indices) {
|
||||
return
|
||||
}
|
||||
L.d("Going to position $adapterIndex in queue")
|
||||
playbackManager.goto(adapterIndex)
|
||||
L.d("Going to deck row $adapterIndex")
|
||||
playbackManager.gotoDeck(adapterIndex)
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a queue item at the given index.
|
||||
* Jump to the timeline position at the given index, as the cover pager does. The pager
|
||||
* mirrors the whole timeline, so this speaks timeline coordinates rather than deck rows.
|
||||
*
|
||||
* @param adapterIndex The index of the queue item to play. Does nothing if the index is out of
|
||||
* range.
|
||||
* @param timelineIndex The timeline position to play. Does nothing if out of range.
|
||||
*/
|
||||
fun gotoTimelinePosition(timelineIndex: Int) {
|
||||
if (timelineIndex !in playbackManager.queue.indices) {
|
||||
return
|
||||
}
|
||||
L.d("Going to timeline position $timelineIndex")
|
||||
playbackManager.goto(timelineIndex)
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the deck row at the given index.
|
||||
*
|
||||
* @param adapterIndex The deck row to remove. Does nothing if the row is out of range.
|
||||
*/
|
||||
fun removeQueueDataItem(adapterIndex: Int) {
|
||||
if (adapterIndex !in queue.value.indices) {
|
||||
return
|
||||
}
|
||||
L.d("Removing item $adapterIndex in queue")
|
||||
playbackManager.removeQueueItem(adapterIndex)
|
||||
L.d("Removing deck row $adapterIndex")
|
||||
playbackManager.removeDeckItem(adapterIndex)
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a queue item from one index to another index.
|
||||
* Move a deck row from one index to another.
|
||||
*
|
||||
* @param adapterFrom The index of the queue item to move.
|
||||
* @param adapterTo The destination index for the queue item.
|
||||
* @return true if the items were moved, false otherwise.
|
||||
* @param adapterFrom The deck row to move.
|
||||
* @param adapterTo The destination deck row.
|
||||
* @return true if the rows were moved, false otherwise.
|
||||
*/
|
||||
fun moveQueueDataItems(adapterFrom: Int, adapterTo: Int): Boolean {
|
||||
if (adapterFrom !in queue.value.indices || adapterTo !in queue.value.indices) {
|
||||
return false
|
||||
}
|
||||
L.d("Moving $adapterFrom to $adapterFrom in queue")
|
||||
playbackManager.moveQueueItem(adapterFrom, adapterTo)
|
||||
L.d("Moving deck row $adapterFrom to row $adapterTo")
|
||||
playbackManager.moveDeckItems(adapterFrom, adapterTo)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Clear the queue of all waiting deck songs. */
|
||||
fun clearQueue() {
|
||||
L.d("Clearing the queue")
|
||||
playbackManager.clearQueue()
|
||||
}
|
||||
|
||||
/** Republish the drawer rows from the manager's deck state. */
|
||||
private fun republish() {
|
||||
val rows = listOfNotNull(playbackManager.deckCurrent) + playbackManager.deck
|
||||
val instructions = diffDeckRows(_queue.value, rows)
|
||||
if (instructions != null) {
|
||||
// Complete (rows, instruction) pairs chain correctly under flow conflation.
|
||||
synchronized(pendingLock) { pendingUpdates += rows to instructions }
|
||||
}
|
||||
_queue.value = rows
|
||||
index.value = if (playbackManager.deckCurrent != null) 0 else -1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +125,36 @@ class BetterShuffleOrder(private val shuffled: IntArray) : ShuffleOrder {
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Create a shuffle over [length] items with the [deckSize] items physically after
|
||||
* [anchor] pinned in order behind it and the rest shuffled. An anchor of -1 pins the
|
||||
* deck (physically at 1..[deckSize]) behind a random first item.
|
||||
*/
|
||||
fun createDeckPinned(length: Int, anchor: Int, deckSize: Int): BetterShuffleOrder {
|
||||
val deckStart = if (anchor >= 0) anchor + 1 else 1
|
||||
val deck = deckStart until deckStart + deckSize
|
||||
val rest = (0 until length).filter { it != anchor && it !in deck }.shuffled()
|
||||
val top = if (anchor >= 0) listOf(anchor) else rest.take(1)
|
||||
val tail = if (anchor >= 0) rest else rest.drop(1)
|
||||
return BetterShuffleOrder((top + deck + tail).toIntArray())
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a shuffle from the unscrambled queue [indices] (playback order as timeline
|
||||
* indices, played history included): [anchor] (a timeline index) on top, the [deckSize]
|
||||
* deck items after it pinned in order, the rest shuffled.
|
||||
*/
|
||||
fun createDeckPinned(
|
||||
indices: List<Int>,
|
||||
anchor: Int,
|
||||
deckSize: Int,
|
||||
): BetterShuffleOrder {
|
||||
val anchorAt = indices.indexOf(anchor)
|
||||
val pinned = indices.subList(anchorAt, anchorAt + 1 + deckSize)
|
||||
val rest = indices.take(anchorAt) + indices.drop(anchorAt + 1 + deckSize)
|
||||
return BetterShuffleOrder((pinned + rest.shuffled()).toIntArray())
|
||||
}
|
||||
|
||||
private fun createShuffledList(length: Int, startIndex: Int): IntArray {
|
||||
val shuffled = IntArray(length)
|
||||
for (i in 0 until length) {
|
||||
|
||||
@@ -246,16 +246,21 @@ class ExoPlaybackStateHolder(
|
||||
deferSave()
|
||||
}
|
||||
|
||||
override fun newPlayback(command: PlaybackCommand) {
|
||||
override fun newPlayback(command: PlaybackCommand, deck: List<Song>) {
|
||||
parent = command.parent
|
||||
player.shuffleModeEnabled = command.shuffled
|
||||
player.setMediaItems(command.queue.map { it.buildMediaItem() })
|
||||
val startIndex =
|
||||
command.song
|
||||
?.let { command.queue.indexOf(it) }
|
||||
.also { check(it != -1) { "Start song not in queue" } }
|
||||
// Retain the deck directly after the start song.
|
||||
val items = command.queue.map { it.buildMediaItem() }.toMutableList()
|
||||
items.addAll((startIndex ?: 0) + 1, deck.map { it.buildMediaItem() })
|
||||
player.setMediaItems(items)
|
||||
if (command.shuffled) {
|
||||
player.setShuffleOrder(BetterShuffleOrder(command.queue.size, startIndex ?: -1))
|
||||
player.setShuffleOrder(
|
||||
BetterShuffleOrder.createDeckPinned(items.size, startIndex ?: -1, deck.size)
|
||||
)
|
||||
}
|
||||
val target = startIndex ?: player.currentTimeline.getFirstWindowIndex(command.shuffled)
|
||||
player.seekTo(target, C.TIME_UNSET)
|
||||
@@ -265,14 +270,19 @@ class ExoPlaybackStateHolder(
|
||||
deferSave()
|
||||
}
|
||||
|
||||
override fun shuffled(shuffled: Boolean) {
|
||||
override fun shuffled(shuffled: Boolean, deckSize: Int) {
|
||||
// Walk the current order before the toggle, while the deck still occupies the playback
|
||||
// positions directly behind the current song.
|
||||
val indices = player.unscrambleQueueIndices()
|
||||
player.setShuffleModeEnabled(shuffled)
|
||||
if (player.shuffleModeEnabled) {
|
||||
// Have to manually refresh the shuffle seed and anchor it to the new current songs
|
||||
if (shuffled) {
|
||||
// The deck stays pinned ahead in order; the heap shuffles beneath it.
|
||||
player.setShuffleOrder(
|
||||
BetterShuffleOrder(player.mediaItemCount, player.currentMediaItemIndex)
|
||||
BetterShuffleOrder.createDeckPinned(indices, player.currentMediaItemIndex, deckSize)
|
||||
)
|
||||
}
|
||||
// TODO: The unshuffle direction must rebuild the physical layout: deck block spliced
|
||||
// after the current item, greyed heap history above it, resume song and tail below.
|
||||
playbackManager.ack(this, StateAck.QueueReordered)
|
||||
deferSave()
|
||||
}
|
||||
@@ -353,6 +363,19 @@ class ExoPlaybackStateHolder(
|
||||
deferSave()
|
||||
}
|
||||
|
||||
override fun playAfter(songs: List<Song>, ack: StateAck.PlayNext) {
|
||||
val indices = player.unscrambleQueueIndices()
|
||||
val items = songs.map { it.buildMediaItem() }
|
||||
// ack.at is a resolved-queue position; translate it to a timeline position.
|
||||
if (indices.isEmpty() || ack.at >= indices.size) {
|
||||
player.addMediaItems(items)
|
||||
} else {
|
||||
player.addMediaItems(indices[ack.at], items)
|
||||
}
|
||||
playbackManager.ack(this, ack)
|
||||
deferSave()
|
||||
}
|
||||
|
||||
override fun addToQueue(songs: List<Song>, ack: StateAck.AddToQueue) {
|
||||
player.addMediaItems(songs.map { it.buildMediaItem() })
|
||||
playbackManager.ack(this, ack)
|
||||
|
||||
@@ -105,7 +105,7 @@ constructor(
|
||||
else -> return
|
||||
}
|
||||
val song = library.songs.find { it.uid == songUid } ?: return
|
||||
playbackManager.addToQueue(song)
|
||||
playbackManager.playAfter(song)
|
||||
}
|
||||
|
||||
override fun onRemoveQueueItem(description: MediaDescriptionCompat) {
|
||||
|
||||
@@ -51,8 +51,14 @@ interface PlaybackStateHolder {
|
||||
/** The current audio session ID of the audio player. */
|
||||
val audioSessionId: Int
|
||||
|
||||
/** Applies a completely new playback state to the holder. */
|
||||
fun newPlayback(command: PlaybackCommand)
|
||||
/**
|
||||
* Applies a completely new playback state to the holder.
|
||||
*
|
||||
* @param command The parameters to start playback with.
|
||||
* @param deck The deck songs to retain directly after the start song. Empty when no deck
|
||||
* exists.
|
||||
*/
|
||||
fun newPlayback(command: PlaybackCommand, deck: List<Song>)
|
||||
|
||||
/**
|
||||
* Update the playing state of the audio player.
|
||||
@@ -96,6 +102,15 @@ interface PlaybackStateHolder {
|
||||
*/
|
||||
fun playNext(songs: List<Song>, ack: StateAck.PlayNext)
|
||||
|
||||
/**
|
||||
* Add songs after the last deck item in the queue.
|
||||
*
|
||||
* @param songs The songs to add.
|
||||
* @param ack The [StateAck.PlayNext] to return to [PlaybackStateManager]. [StateAck.PlayNext.at]
|
||||
* is the resolved-queue position to insert at.
|
||||
*/
|
||||
fun playAfter(songs: List<Song>, ack: StateAck.PlayNext)
|
||||
|
||||
/**
|
||||
* Add songs to the end of the queue.
|
||||
*
|
||||
@@ -126,8 +141,9 @@ interface PlaybackStateHolder {
|
||||
* Reorder the queue.
|
||||
*
|
||||
* @param shuffled Whether the queue should be shuffled.
|
||||
* @param deckSize The number of deck songs to pin in order behind the current song.
|
||||
*/
|
||||
fun shuffled(shuffled: Boolean)
|
||||
fun shuffled(shuffled: Boolean, deckSize: Int)
|
||||
|
||||
/**
|
||||
* Handle a deferred playback action.
|
||||
|
||||
@@ -60,6 +60,12 @@ interface PlaybackStateManager {
|
||||
/** The current queue of [Song]s. */
|
||||
val queue: List<Song>
|
||||
|
||||
/** The upcoming deck [Song]s, in order. The deck sits directly behind the current song. */
|
||||
val deck: List<Song>
|
||||
|
||||
/** The current [Song] when it came from the deck. Null when the heap is playing. */
|
||||
val deckCurrent: Song?
|
||||
|
||||
/** The index of the currently playing [Song] in the queue. */
|
||||
val index: Int
|
||||
|
||||
@@ -162,6 +168,21 @@ interface PlaybackStateManager {
|
||||
*/
|
||||
fun addToQueue(song: Song) = addToQueue(listOf(song))
|
||||
|
||||
/**
|
||||
* Add [Song]s to the end of the deck: directly after the current [Song] if the deck is
|
||||
* empty, otherwise after the last deck [Song].
|
||||
*
|
||||
* @param songs The [Song]s to add.
|
||||
*/
|
||||
fun playAfter(songs: List<Song>)
|
||||
|
||||
/**
|
||||
* Add a [Song] to the end of the deck.
|
||||
*
|
||||
* @param song The [Song] to add.
|
||||
*/
|
||||
fun playAfter(song: Song) = playAfter(listOf(song))
|
||||
|
||||
/**
|
||||
* Move a [Song] in the queue.
|
||||
*
|
||||
@@ -177,6 +198,41 @@ interface PlaybackStateManager {
|
||||
*/
|
||||
fun removeQueueItem(at: Int)
|
||||
|
||||
/**
|
||||
* Clear the queue of all waiting deck [Song]s. The currently playing [Song] is unaffected,
|
||||
* even if it came from the deck.
|
||||
*/
|
||||
fun clearQueue()
|
||||
|
||||
/**
|
||||
* Start playing the deck [Song] at the given drawer row. Row 0 is the currently playing
|
||||
* deck [Song] when there is one (tapping it restarts the song); otherwise the rows are the
|
||||
* waiting deck [Song]s in order. A tapped waiting [Song] plays immediately while the rest
|
||||
* of the deck keeps its place and order: a displaced playing deck [Song] drains, a
|
||||
* displaced heap [Song] passes by as if played.
|
||||
*
|
||||
* @param row The drawer row to play. Does nothing if out of range.
|
||||
*/
|
||||
fun gotoDeck(row: Int)
|
||||
|
||||
/**
|
||||
* Remove the deck [Song] at the given drawer row. Only waiting rows are removable; the
|
||||
* playing row is refused.
|
||||
*
|
||||
* @param row The drawer row to remove. Does nothing if it is the playing row or out of
|
||||
* range.
|
||||
*/
|
||||
fun removeDeckItem(row: Int)
|
||||
|
||||
/**
|
||||
* Move the deck [Song] at one drawer row to another. Only waiting rows participate; drags
|
||||
* involving the playing row are refused.
|
||||
*
|
||||
* @param fromRow The drawer row of the [Song] to move.
|
||||
* @param toRow The drawer row to move it to.
|
||||
*/
|
||||
fun moveDeckItems(fromRow: Int, toRow: Int)
|
||||
|
||||
/**
|
||||
* (Re)shuffle or (Re)order this instance.
|
||||
*
|
||||
@@ -329,6 +385,10 @@ interface PlaybackStateManager {
|
||||
val parent: MusicParent?,
|
||||
val heap: List<Song?>,
|
||||
val shuffledMapping: List<Int>,
|
||||
/** The upcoming deck songs, in order. Also physically present in [heap]. */
|
||||
val deck: List<Song?>,
|
||||
/** Whether the current song (at [index]) came from the deck. */
|
||||
val deckCurrent: Boolean,
|
||||
val index: Int,
|
||||
val songUid: Music.UID,
|
||||
)
|
||||
@@ -362,6 +422,14 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
@Volatile private var pendingDeferredPlayback: DeferredPlayback? = null
|
||||
@Volatile private var isInitialized = false
|
||||
|
||||
/** The upcoming deck songs, in order. The deck sits directly behind the current song. */
|
||||
override var deck = emptyList<Song>()
|
||||
private set
|
||||
|
||||
/** The current song when it came from the deck. Null when the heap is playing. */
|
||||
override var deckCurrent: Song? = null
|
||||
private set
|
||||
|
||||
override val progression
|
||||
get() = stateMirror.progression
|
||||
|
||||
@@ -452,7 +520,9 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
L.d("Playing $command")
|
||||
// Played something, so we are initialized now
|
||||
isInitialized = true
|
||||
stateHolder.newPlayback(command)
|
||||
// The deck is retained ahead of the new heap; a deck-sourced current song is excluded
|
||||
// and drains with the replaced timeline.
|
||||
stateHolder.newPlayback(command, deck)
|
||||
}
|
||||
|
||||
// --- QUEUE FUNCTIONS ---
|
||||
@@ -486,6 +556,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
} else {
|
||||
val stateHolder = stateHolder ?: return
|
||||
L.d("Adding ${songs.size} songs to start of queue")
|
||||
// The ack joins the songs to the deck, so that listeners observe the final state.
|
||||
stateHolder.playNext(songs, StateAck.PlayNext(stateMirror.index + 1, songs.size))
|
||||
}
|
||||
}
|
||||
@@ -502,6 +573,20 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun playAfter(songs: List<Song>) {
|
||||
if (currentSong == null) {
|
||||
L.d("Nothing playing, short-circuiting to new playback")
|
||||
play(QueueCommand(songs))
|
||||
} else {
|
||||
val stateHolder = stateHolder ?: return
|
||||
val at = stateMirror.index + 1 + deck.size
|
||||
L.d("Adding ${songs.size} songs at deck end $at")
|
||||
// The ack grows the deck, so that listeners observe the final state.
|
||||
stateHolder.playAfter(songs, StateAck.PlayNext(at, songs.size))
|
||||
}
|
||||
}
|
||||
|
||||
private class QueueCommand(override val queue: List<Song>) : PlaybackCommand {
|
||||
override val song: Song? = null
|
||||
override val parent: MusicParent? = null
|
||||
@@ -522,11 +607,75 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
stateHolder.remove(at, StateAck.Remove(at))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun clearQueue() {
|
||||
val stateHolder = stateHolder ?: return
|
||||
L.d("Clearing the deck (${deck.size} waiting songs)")
|
||||
// The waiting deck entries sit directly behind the current song; removing at the same
|
||||
// position repeatedly pops them in order. The ack handler shrinks the deck each time.
|
||||
while (deck.isNotEmpty()) {
|
||||
stateHolder.remove(stateMirror.index + 1, StateAck.Remove(stateMirror.index + 1))
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun gotoDeck(row: Int) {
|
||||
val stateHolder = stateHolder ?: return
|
||||
val rowCount = deck.size + if (deckCurrent != null) 1 else 0
|
||||
if (row !in 0 until rowCount) {
|
||||
return
|
||||
}
|
||||
L.d("Going to deck row $row")
|
||||
if (deckCurrent != null && row == 0) {
|
||||
// Tapping the playing row restarts the song.
|
||||
stateHolder.goto(stateMirror.index)
|
||||
return
|
||||
}
|
||||
// Pull the target to the front of the deck block and step into it. The move ack keeps
|
||||
// the rest of the deck in order behind it; the goto ack drains a displaced playing deck
|
||||
// song and marks the target as the playing deck song.
|
||||
val deckIndex = if (deckCurrent != null) row - 1 else row
|
||||
val targetAt = stateMirror.index + 1 + deckIndex
|
||||
val frontAt = stateMirror.index + 1
|
||||
if (deckIndex > 0) {
|
||||
stateHolder.move(targetAt, frontAt, StateAck.Move(targetAt, frontAt))
|
||||
}
|
||||
stateHolder.goto(frontAt)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun removeDeckItem(row: Int) {
|
||||
val stateHolder = stateHolder ?: return
|
||||
// Only waiting entries are removable; the playing row plays on.
|
||||
val deckIndex = if (deckCurrent != null) row - 1 else row
|
||||
if (deckIndex !in deck.indices) {
|
||||
return
|
||||
}
|
||||
L.d("Removing deck row $row")
|
||||
val at = stateMirror.index + 1 + deckIndex
|
||||
stateHolder.remove(at, StateAck.Remove(at))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun moveDeckItems(fromRow: Int, toRow: Int) {
|
||||
val stateHolder = stateHolder ?: return
|
||||
// Only waiting entries are draggable; the playing row stays put.
|
||||
val fromIndex = if (deckCurrent != null) fromRow - 1 else fromRow
|
||||
val toIndex = if (deckCurrent != null) toRow - 1 else toRow
|
||||
if (fromIndex !in deck.indices || toIndex !in deck.indices) {
|
||||
return
|
||||
}
|
||||
L.d("Moving deck row $fromRow to row $toRow")
|
||||
val from = stateMirror.index + 1 + fromIndex
|
||||
val to = stateMirror.index + 1 + toIndex
|
||||
stateHolder.move(from, to, StateAck.Move(from, to))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun shuffled(shuffled: Boolean) {
|
||||
val stateHolder = stateHolder ?: return
|
||||
L.d("Reordering queue [shuffled=$shuffled]")
|
||||
stateHolder.shuffled(shuffled)
|
||||
stateHolder.shuffled(shuffled, deck.size)
|
||||
}
|
||||
|
||||
// --- INTERNAL PLAYER FUNCTIONS ---
|
||||
@@ -590,8 +739,24 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
|
||||
when (ack) {
|
||||
is StateAck.IndexMoved -> {
|
||||
val departed = currentSong
|
||||
// The departed song always sits at the old index — transitions never reorder.
|
||||
val departedAt = stateMirror.index
|
||||
val rawQueue = stateHolder.resolveQueue()
|
||||
stateMirror = stateMirror.copy(index = rawQueue.resolveIndex(), rawQueue = rawQueue)
|
||||
// Leaving a deck song drains it: a different song is playing now. A rewind
|
||||
// acks without departing and drains nothing.
|
||||
if (departed != null && departed !== currentSong && departed === deckCurrent) {
|
||||
deckCurrent = null
|
||||
stateHolder.remove(departedAt, StateAck.Remove(departedAt))
|
||||
}
|
||||
// Entering the deck: the song that started playing leaves the upcoming deck.
|
||||
if (deck.isNotEmpty() && currentSong === deck[0]) {
|
||||
deckCurrent = deck[0]
|
||||
deck = deck.drop(1)
|
||||
}
|
||||
// Notify only after the deck bookkeeping settles, so listeners observe the
|
||||
// final state.
|
||||
listeners.forEach { it.onIndexMoved(stateMirror.index) }
|
||||
}
|
||||
is StateAck.PlayNext -> {
|
||||
@@ -599,6 +764,12 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
val change =
|
||||
QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size))
|
||||
stateMirror = stateMirror.copy(queue = rawQueue.resolveSongs(), rawQueue = rawQueue)
|
||||
// The inserted songs join the deck before anyone is told, so listeners observe
|
||||
// the final state. The insert lands at the deck's end (playAfter) or front
|
||||
// (playNext).
|
||||
val block = stateMirror.queue.subList(ack.at, ack.at + ack.size)
|
||||
val deckInsertAt = (ack.at - (stateMirror.index + 1)).coerceIn(0, deck.size)
|
||||
deck = deck.toMutableList().apply { addAll(deckInsertAt, block) }
|
||||
listeners.forEach {
|
||||
it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
|
||||
}
|
||||
@@ -613,6 +784,13 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
}
|
||||
}
|
||||
is StateAck.Move -> {
|
||||
// Capture the pre-move coordinates and the moved song for the deck update.
|
||||
val movedSong = stateMirror.queue.getOrNull(ack.from)
|
||||
val deckFrom = ack.from - (stateMirror.index + 1)
|
||||
val deckTo = ack.to - (stateMirror.index + 1)
|
||||
// Deck membership is positional within the deck block, confirmed by identity:
|
||||
// the same instance can also sit in the heap.
|
||||
val fromIsDeck = deckFrom in deck.indices && deck[deckFrom] === movedSong
|
||||
val rawQueue = stateHolder.resolveQueue()
|
||||
val newIndex = rawQueue.resolveIndex()
|
||||
val change =
|
||||
@@ -629,11 +807,26 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
rawQueue = rawQueue,
|
||||
)
|
||||
|
||||
// Deck membership follows the moved song: reorder inside, leave, or enter.
|
||||
deck =
|
||||
when {
|
||||
fromIsDeck && deckTo in deck.indices ->
|
||||
deck.toMutableList().apply { add(deckTo, removeAt(deckFrom)) }
|
||||
fromIsDeck -> deck.toMutableList().apply { removeAt(deckFrom) }
|
||||
deckTo in deck.indices && movedSong != null ->
|
||||
deck.toMutableList().apply { add(deckTo, movedSong) }
|
||||
else -> deck
|
||||
}
|
||||
|
||||
listeners.forEach {
|
||||
it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
|
||||
}
|
||||
}
|
||||
is StateAck.Remove -> {
|
||||
// Capture the pre-removal position relations for the deck update.
|
||||
val removedSong = stateMirror.queue.getOrNull(ack.index)
|
||||
val removedCurrent = ack.index == stateMirror.index
|
||||
val deckIndex = ack.index - (stateMirror.index + 1)
|
||||
val rawQueue = stateHolder.resolveQueue()
|
||||
val newIndex = rawQueue.resolveIndex()
|
||||
val change =
|
||||
@@ -653,6 +846,13 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
rawQueue = rawQueue,
|
||||
)
|
||||
|
||||
// Deck membership is positional within the deck block, confirmed by identity.
|
||||
if (deckIndex in deck.indices && deck[deckIndex] === removedSong) {
|
||||
deck = deck.toMutableList().apply { removeAt(deckIndex) }
|
||||
}
|
||||
// Only removing the current position clears the playing deck song.
|
||||
if (removedCurrent) deckCurrent = null
|
||||
|
||||
listeners.forEach {
|
||||
it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
|
||||
}
|
||||
@@ -684,6 +884,9 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
isShuffled = rawQueue.isShuffled,
|
||||
rawQueue = rawQueue,
|
||||
)
|
||||
// A deck-sourced current song drains with the replaced timeline; the upcoming
|
||||
// deck is retained (the holder spliced it into the new heap).
|
||||
deckCurrent = null
|
||||
listeners.forEach {
|
||||
it.onNewPlayback(
|
||||
stateMirror.parent,
|
||||
@@ -718,6 +921,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
parent = stateMirror.parent,
|
||||
heap = stateMirror.rawQueue.heap,
|
||||
shuffledMapping = stateMirror.rawQueue.shuffledMapping,
|
||||
deck = deck,
|
||||
deckCurrent = deckCurrent != null,
|
||||
index = stateMirror.index,
|
||||
songUid = currentSong.uid,
|
||||
)
|
||||
@@ -782,6 +987,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
}
|
||||
|
||||
if (index < 0) {
|
||||
deck = emptyList()
|
||||
deckCurrent = null
|
||||
stateHolder.reset(StateAck.NewPlayback)
|
||||
return
|
||||
}
|
||||
@@ -806,6 +1013,34 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
|
||||
StateAck.NewPlayback,
|
||||
)
|
||||
|
||||
// Restore the deck: within the block directly behind the current song, keep the
|
||||
// entries whose UIDs were saved, in order; missing songs drop out individually.
|
||||
val deckStart = stateMirror.index + 1
|
||||
val savedDeckUids = savedState.deck.mapNotNull { it?.uid }
|
||||
deck =
|
||||
if (deckStart <= stateMirror.queue.size) {
|
||||
stateMirror.queue
|
||||
.subList(
|
||||
deckStart,
|
||||
minOf(deckStart + savedDeckUids.size, stateMirror.queue.size),
|
||||
)
|
||||
.filter { it.uid in savedDeckUids }
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
deckCurrent = if (savedState.deckCurrent) currentSong else null
|
||||
|
||||
isInitialized = true
|
||||
|
||||
// The deck restore ran after the holder's NewPlayback ack; re-notify with the final
|
||||
// state so listeners observe the restored deck.
|
||||
listeners.forEach {
|
||||
it.onNewPlayback(
|
||||
savedState.parent,
|
||||
stateMirror.queue,
|
||||
stateMirror.index,
|
||||
stateMirror.rawQueue.isShuffled,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,10 +31,12 @@ import androidx.fragment.app.activityViewModels
|
||||
import androidx.fragment.app.viewModels
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import androidx.recyclerview.widget.ItemTouchHelper
|
||||
import com.google.android.material.transition.MaterialSharedAxis
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import org.oxycblt.auxio.R
|
||||
import org.oxycblt.auxio.databinding.FragmentSearchBinding
|
||||
import org.oxycblt.auxio.list.recycler.SwipeActionsCallback
|
||||
import org.oxycblt.auxio.detail.DetailViewModel
|
||||
import org.oxycblt.auxio.detail.Show
|
||||
import org.oxycblt.auxio.list.Item
|
||||
@@ -181,6 +183,18 @@ class SearchFragment : ListFragment<Music, FragmentSearchBinding>() {
|
||||
}
|
||||
}
|
||||
|
||||
ItemTouchHelper(
|
||||
SwipeActionsCallback(isEnabled = { listModel.selected.value.isEmpty() }) {
|
||||
song,
|
||||
action ->
|
||||
when (action) {
|
||||
SwipeActionsCallback.SwipeAction.QUEUE -> playbackModel.addToQueue(song)
|
||||
SwipeActionsCallback.SwipeAction.PLAY_NEXT -> playbackModel.playNext(song)
|
||||
}
|
||||
}
|
||||
)
|
||||
.attachToRecyclerView(binding.searchRecycler)
|
||||
|
||||
// --- VIEWMODEL SETUP ---
|
||||
|
||||
collectImmediately(searchModel.searchResults, ::updateSearchResults)
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Lucide 'list-start' (lucide-static v1.72.0, ISC License) -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:tint="?attr/colorControlNormal"
|
||||
android:viewportWidth="960"
|
||||
android:viewportHeight="960">
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M780,900L720,840L840,720L720,600L780,540L960,720L780,900ZM320,840L320,760L160,760Q127,760 103.5,736.5Q80,713 80,680L80,200Q80,167 103.5,143.5Q127,120 160,120L800,120Q833,120 856.5,143.5Q880,167 880,200L880,480L800,480L800,200Q800,200 800,200Q800,200 800,200L160,200Q160,200 160,200Q160,200 160,200L160,680Q160,680 160,680Q160,680 160,680L680,680L680,760L600,760L600,840L320,840ZM440,600L520,600L520,480L640,480L640,400L520,400L520,280L440,280L440,400L320,400L320,480L440,480L440,600ZM160,680L160,680Q160,680 160,680Q160,680 160,680L160,200Q160,200 160,200Q160,200 160,200L160,200Q160,200 160,200Q160,200 160,200L160,680L160,680L160,680Z" />
|
||||
android:strokeColor="@android:color/white"
|
||||
android:strokeWidth="2"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M3 5h6 M3 12h13 M3 19h13 M16 8l-3-3 3-3 M21 19V7a2 2 0 0 0-2-2h-6" />
|
||||
</vector>
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Lucide 'list-end' (lucide-static v1.72.0, ISC License) -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:tint="?attr/colorControlNormal"
|
||||
android:viewportWidth="960"
|
||||
android:viewportHeight="960">
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M440,600L520,600L520,480L640,480L640,400L520,400L520,280L440,280L440,400L320,400L320,480L440,480L440,600ZM320,840L320,760L160,760Q127,760 103.5,736.5Q80,713 80,680L80,200Q80,167 103.5,143.5Q127,120 160,120L800,120Q833,120 856.5,143.5Q880,167 880,200L880,680Q880,713 856.5,736.5Q833,760 800,760L640,760L640,840L320,840ZM160,680L800,680Q800,680 800,680Q800,680 800,680L800,200Q800,200 800,200Q800,200 800,200L160,200Q160,200 160,200Q160,200 160,200L160,680Q160,680 160,680Q160,680 160,680ZM160,680Q160,680 160,680Q160,680 160,680L160,200Q160,200 160,200Q160,200 160,200L160,200Q160,200 160,200Q160,200 160,200L160,680Q160,680 160,680Q160,680 160,680L160,680Z" />
|
||||
android:strokeColor="@android:color/white"
|
||||
android:strokeWidth="2"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round"
|
||||
android:pathData="M16 5H3 M16 12H3 M9 19H3 M16 16l-3 3 3 3 M21 5v12a2 2 0 0 1-2 2h-6" />
|
||||
</vector>
|
||||
|
||||
@@ -108,16 +108,30 @@
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
app:layout_constraintStart_toEndOf="@+id/playback_panel_fragment">
|
||||
|
||||
<TextView
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="64dp"
|
||||
android:gravity="center"
|
||||
android:text="@string/lbl_queue"
|
||||
android:textAppearance="?attr/textAppearanceLabelLargeEmphasized"
|
||||
android:textColor="?attr/colorOnSurfaceVariant"
|
||||
app:layout_constraintBottom_toBottomOf="@+id/handle"
|
||||
app:layout_constraintEnd_toEndOf="@+id/handle"
|
||||
app:layout_constraintStart_toStartOf="parent" />
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<TextView
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="64dp"
|
||||
android:layout_weight="1"
|
||||
android:gravity="center"
|
||||
android:text="@string/lbl_queue"
|
||||
android:textAppearance="?attr/textAppearanceLabelLargeEmphasized"
|
||||
android:textColor="?attr/colorOnSurfaceVariant" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/queue_clear"
|
||||
style="@style/Widget.Auxio.Button.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/action_clear"
|
||||
android:visibility="gone" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.fragment.app.FragmentContainerView
|
||||
android:id="@+id/queue_fragment"
|
||||
|
||||
@@ -126,6 +126,17 @@
|
||||
app:layout_constraintEnd_toEndOf="@+id/queue_handle"
|
||||
app:layout_constraintStart_toStartOf="parent" />
|
||||
|
||||
<com.google.android.material.button.MaterialButton
|
||||
android:id="@+id/queue_clear"
|
||||
style="@style/Widget.Auxio.Button.TextButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/action_clear"
|
||||
android:visibility="gone"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
|
||||
<androidx.fragment.app.FragmentContainerView
|
||||
|
||||
@@ -17,4 +17,14 @@
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/queue_empty"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center"
|
||||
android:text="@string/lbl_queue_empty"
|
||||
android:textAppearance="?attr/textAppearanceBodyLarge"
|
||||
android:textColor="?attr/colorOnSurfaceVariant"
|
||||
android:visibility="gone" />
|
||||
|
||||
</FrameLayout>
|
||||
|
||||
@@ -2,8 +2,24 @@
|
||||
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:id="@+id/inner"
|
||||
app:startDestination="@id/home_fragment">
|
||||
|
||||
<!-- Root-level actions usable from any destination, for the Now Playing header's parent
|
||||
navigation, which must work no matter which page is in front. -->
|
||||
<action
|
||||
android:id="@+id/show_album_globally"
|
||||
app:destination="@id/album_detail_fragment" />
|
||||
<action
|
||||
android:id="@+id/show_artist_globally"
|
||||
app:destination="@id/artist_detail_fragment" />
|
||||
<action
|
||||
android:id="@+id/show_genre_globally"
|
||||
app:destination="@id/genre_detail_fragment" />
|
||||
<action
|
||||
android:id="@+id/show_playlist_globally"
|
||||
app:destination="@id/playlist_detail_fragment" />
|
||||
|
||||
<fragment
|
||||
android:id="@+id/home_fragment"
|
||||
android:name="org.oxycblt.auxio.home.HomeFragment"
|
||||
|
||||
@@ -123,6 +123,8 @@
|
||||
<string name="lbl_shuffle">Shuffle</string>
|
||||
|
||||
<string name="lbl_queue">Queue</string>
|
||||
<string name="lbl_queue_empty">Nothing queued</string>
|
||||
<string name="action_clear">Clear</string>
|
||||
<string name="lbl_play_next">Play next</string>
|
||||
<string name="lbl_queue_add">Add to queue</string>
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* DeckRowDiffTest.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.playback.queue
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import org.oxycblt.auxio.list.adapter.UpdateInstructions
|
||||
import org.oxycblt.auxio.playback.state.fakeSong
|
||||
|
||||
/**
|
||||
* The queue drawer renders deck rows; every update must carry the minimal [UpdateInstructions]
|
||||
* for the change, or the list flashes (full replaces) and ghosts (desynced drags). See the D9
|
||||
* device round.
|
||||
*/
|
||||
class DeckRowDiffTest {
|
||||
|
||||
@Test
|
||||
fun `identical rows produce no instruction`() {
|
||||
val rows = listOf(fakeSong(), fakeSong())
|
||||
assertNull(diffDeckRows(rows, rows.toList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `appending rows produces an Add`() {
|
||||
val old = listOf(fakeSong(), fakeSong(), fakeSong())
|
||||
val new = old + fakeSong() + fakeSong()
|
||||
assertEquals(UpdateInstructions.Add(at = 3, size = 2), diffDeckRows(old, new))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the deck advancing drops row 0 with a Remove`() {
|
||||
val old = listOf(fakeSong(), fakeSong(), fakeSong())
|
||||
val new = old.drop(1)
|
||||
assertEquals(UpdateInstructions.Remove(at = 0, size = 1), diffDeckRows(old, new))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `removing an interior row produces a Remove`() {
|
||||
val old = listOf(fakeSong(), fakeSong(), fakeSong())
|
||||
val new = listOf(old[0], old[2])
|
||||
assertEquals(UpdateInstructions.Remove(at = 1, size = 1), diffDeckRows(old, new))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `emptying the rows produces a Remove`() {
|
||||
val old = listOf(fakeSong(), fakeSong())
|
||||
assertEquals(UpdateInstructions.Remove(at = 0, size = 2), diffDeckRows(old, emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an end drag produces a Move`() {
|
||||
val old = listOf(fakeSong(), fakeSong(), fakeSong())
|
||||
val new = listOf(old[1], old[2], old[0])
|
||||
assertEquals(UpdateInstructions.Move(from = 0, to = 2), diffDeckRows(old, new))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an adjacent drag produces a Move`() {
|
||||
val old = listOf(fakeSong(), fakeSong(), fakeSong())
|
||||
val new = listOf(old[0], old[2], old[1])
|
||||
assertEquals(UpdateInstructions.Move(from = 1, to = 2), diffDeckRows(old, new))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a replacement produces a Replace from the first divergence`() {
|
||||
val old = listOf(fakeSong(), fakeSong(), fakeSong())
|
||||
val new = listOf(old[0], fakeSong(), old[2])
|
||||
assertEquals(UpdateInstructions.Replace(from = 1), diffDeckRows(old, new))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a wholesale change produces a Replace`() {
|
||||
val old = listOf(fakeSong(), fakeSong())
|
||||
val new = listOf(fakeSong(), fakeSong(), fakeSong())
|
||||
assertEquals(UpdateInstructions.Replace(from = 0), diffDeckRows(old, new))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* BetterShuffleOrderTest.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.playback.service
|
||||
|
||||
import androidx.media3.common.C
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class BetterShuffleOrderTest {
|
||||
/**
|
||||
* The pin anchors at the current song wherever it sits in the timeline — including inside
|
||||
* played history: the anchor and the deck block after it lead the permutation, and the
|
||||
* rest shuffles beneath.
|
||||
*/
|
||||
@Test
|
||||
fun `createDeckPinned pins the anchor and its deck, not the list head`() {
|
||||
// A ten-item timeline in physical order; the current song is timeline index 5 with a
|
||||
// two-song deck behind it.
|
||||
val indices = (0 until 10).toList()
|
||||
val order = BetterShuffleOrder.createDeckPinned(indices, 5, 2)
|
||||
|
||||
// Walk the playback order.
|
||||
val playbackOrder = mutableListOf(order.getFirstIndex())
|
||||
while (true) {
|
||||
val next = order.getNextIndex(playbackOrder.last())
|
||||
if (next == C.INDEX_UNSET) break
|
||||
playbackOrder += next
|
||||
}
|
||||
|
||||
// The anchor and its deck lead; the unpinned indices all follow.
|
||||
assertEquals(listOf(5, 6, 7), playbackOrder.take(3))
|
||||
assertEquals((0 until 10).toSet(), playbackOrder.toSet())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* Fakes.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.playback.state
|
||||
|
||||
import android.net.Uri
|
||||
import java.util.UUID
|
||||
import org.oxycblt.musikr.Album
|
||||
import org.oxycblt.musikr.Artist
|
||||
import org.oxycblt.musikr.Genre
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.MusicParent
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.covers.Cover
|
||||
import org.oxycblt.musikr.fs.Format
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.tag.Date
|
||||
import org.oxycblt.musikr.tag.Disc
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import org.oxycblt.musikr.tag.ReplayGainAdjustment
|
||||
|
||||
/**
|
||||
* A [PlaybackStateHolder] test double.
|
||||
*
|
||||
* Keeps a plain [RawQueue], records insertion receipts in [insertions], and returns
|
||||
* [StateAck.NewPlayback] immediately from [newPlayback].
|
||||
*/
|
||||
class FakePlaybackStateHolder : PlaybackStateHolder {
|
||||
/** The manager to return receipts to. Set before [newPlayback] is called. */
|
||||
var manager: PlaybackStateManager? = null
|
||||
|
||||
/** Every [StateAck.PlayNext] receipt handed to this holder, in order. */
|
||||
val insertions = mutableListOf<StateAck.PlayNext>()
|
||||
|
||||
var rawQueue = RawQueue.nil()
|
||||
private set
|
||||
|
||||
override val progression = Progression.nil()
|
||||
override var repeatMode = RepeatMode.NONE
|
||||
private set
|
||||
override var parent: MusicParent? = null
|
||||
private set
|
||||
override val audioSessionId = 0
|
||||
|
||||
override fun resolveQueue() = rawQueue
|
||||
|
||||
/** Advance to [index] and return the [StateAck.IndexMoved] receipt, as a track change would. */
|
||||
fun moveTo(index: Int) {
|
||||
rawQueue = rawQueue.copy(heapIndex = index)
|
||||
manager?.ack(this, StateAck.IndexMoved)
|
||||
}
|
||||
|
||||
/** Advance to the next song in playback order, as a natural track end does. */
|
||||
fun advanceToNext() {
|
||||
val queue = rawQueue
|
||||
val nextResolved = queue.resolveIndex() + 1
|
||||
val next =
|
||||
if (queue.isShuffled) {
|
||||
queue.shuffledMapping.getOrNull(nextResolved)
|
||||
} else {
|
||||
nextResolved.takeIf { it < queue.heap.size }
|
||||
}
|
||||
if (next != null) moveTo(next)
|
||||
}
|
||||
|
||||
/** Return the [StateAck.IndexMoved] receipt without moving, as a rewind-in-place does. */
|
||||
fun rewind() {
|
||||
manager?.ack(this, StateAck.IndexMoved)
|
||||
}
|
||||
|
||||
override fun newPlayback(command: PlaybackCommand, deck: List<Song>) {
|
||||
val heap = command.queue.toMutableList()
|
||||
val startIndex = command.song?.let(command.queue::indexOf) ?: 0
|
||||
// Retain the deck directly after the start song.
|
||||
heap.addAll(startIndex + 1, deck)
|
||||
rawQueue = RawQueue(heap, emptyList(), startIndex)
|
||||
manager?.ack(this, StateAck.NewPlayback)
|
||||
}
|
||||
|
||||
override fun playNext(songs: List<Song>, ack: StateAck.PlayNext) {
|
||||
insertions += ack
|
||||
insertAt(ack.at, songs)
|
||||
manager?.ack(this, ack)
|
||||
}
|
||||
|
||||
override fun playAfter(songs: List<Song>, ack: StateAck.PlayNext) {
|
||||
insertions += ack
|
||||
insertAt(ack.at, songs)
|
||||
manager?.ack(this, ack)
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert at the resolved-queue position [resolvedAt], translated to a timeline position as
|
||||
* ExoPlaybackStateHolder does with unscrambleQueueIndices.
|
||||
*/
|
||||
private fun insertAt(resolvedAt: Int, songs: List<Song>) {
|
||||
val queue = rawQueue
|
||||
val heap = queue.heap.toMutableList()
|
||||
val trueAt =
|
||||
when {
|
||||
!queue.isShuffled -> resolvedAt.coerceAtMost(heap.size)
|
||||
resolvedAt < queue.shuffledMapping.size -> queue.shuffledMapping[resolvedAt]
|
||||
else -> heap.size
|
||||
}
|
||||
heap.addAll(trueAt, songs)
|
||||
val mapping =
|
||||
if (queue.isShuffled) {
|
||||
// Existing timeline indices shift right of the insertion; the new items take
|
||||
// their playback position at resolvedAt.
|
||||
val shifted =
|
||||
queue.shuffledMapping.map { if (it >= trueAt) it + songs.size else it }
|
||||
shifted.subList(0, resolvedAt) +
|
||||
(trueAt until trueAt + songs.size).toList() +
|
||||
shifted.subList(resolvedAt, shifted.size)
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
rawQueue =
|
||||
RawQueue(
|
||||
heap = heap,
|
||||
shuffledMapping = mapping,
|
||||
heapIndex =
|
||||
if (trueAt <= queue.heapIndex) queue.heapIndex + songs.size
|
||||
else queue.heapIndex,
|
||||
)
|
||||
}
|
||||
|
||||
override fun playing(playing: Boolean) {}
|
||||
|
||||
override fun seekTo(positionMs: Long) {}
|
||||
|
||||
override fun repeatMode(repeatMode: RepeatMode) {}
|
||||
|
||||
override fun next() {}
|
||||
|
||||
override fun prev() {
|
||||
// Step back one position, as a skip back does.
|
||||
if (rawQueue.heapIndex > 0) {
|
||||
moveTo(rawQueue.heapIndex - 1)
|
||||
}
|
||||
}
|
||||
|
||||
override fun goto(index: Int) {
|
||||
// A jump is an advance to the position, as the real holder's seek is.
|
||||
moveTo(index)
|
||||
}
|
||||
|
||||
override fun addToQueue(songs: List<Song>, ack: StateAck.AddToQueue) {
|
||||
insertAt(ack.at, songs)
|
||||
manager?.ack(this, ack)
|
||||
}
|
||||
|
||||
override fun move(from: Int, to: Int, ack: StateAck.Move) {
|
||||
// A move is a removal plus an insertion at resolved positions.
|
||||
val song = rawQueue.resolveSongs()[from]
|
||||
removeAtResolved(from)
|
||||
insertAt(to, listOf(song))
|
||||
manager?.ack(this, StateAck.Move(from, to))
|
||||
}
|
||||
|
||||
override fun remove(at: Int, ack: StateAck.Remove) {
|
||||
removeAtResolved(at)
|
||||
manager?.ack(this, StateAck.Remove(at))
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the song at the resolved-queue position [at], translating to a timeline position
|
||||
* under shuffle and maintaining the permutation, as ExoPlayer's cloneAndRemove does.
|
||||
*/
|
||||
private fun removeAtResolved(at: Int) {
|
||||
val queue = rawQueue
|
||||
val trueAt = if (queue.isShuffled) queue.shuffledMapping[at] else at
|
||||
val heap = queue.heap.toMutableList()
|
||||
heap.removeAt(trueAt)
|
||||
val mapping =
|
||||
if (queue.isShuffled) {
|
||||
// The permutation loses the removed timeline index; later indices shift down.
|
||||
queue.shuffledMapping
|
||||
.filter { it != trueAt }
|
||||
.map { if (it > trueAt) it - 1 else it }
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
rawQueue =
|
||||
RawQueue(
|
||||
heap = heap,
|
||||
shuffledMapping = mapping,
|
||||
// Removing ahead of the playhead shifts it back, as ExoPlayer shifts it.
|
||||
heapIndex =
|
||||
if (trueAt < queue.heapIndex) queue.heapIndex - 1 else queue.heapIndex,
|
||||
)
|
||||
}
|
||||
|
||||
override fun shuffled(shuffled: Boolean, deckSize: Int) {
|
||||
rawQueue =
|
||||
rawQueue.copy(
|
||||
shuffledMapping =
|
||||
if (shuffled) {
|
||||
// Stand-in pinned shuffle: current on top, deck in order, the rest
|
||||
// reversed.
|
||||
val current = rawQueue.heapIndex
|
||||
val deck = current + 1..current + deckSize
|
||||
val rest =
|
||||
rawQueue.heap.indices.filter { it != current && it !in deck }
|
||||
listOf(current) + deck.toList() + rest.reversed()
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
)
|
||||
manager?.ack(this, StateAck.QueueReordered)
|
||||
}
|
||||
|
||||
override fun handleDeferred(action: DeferredPlayback) = false
|
||||
|
||||
override fun applySavedState(
|
||||
parent: MusicParent?,
|
||||
rawQueue: RawQueue,
|
||||
positionMs: Long,
|
||||
repeatMode: RepeatMode,
|
||||
ack: StateAck.NewPlayback?,
|
||||
) {
|
||||
this.parent = parent
|
||||
this.rawQueue = rawQueue
|
||||
this.repeatMode = repeatMode
|
||||
if (ack != null) manager?.ack(this, ack)
|
||||
}
|
||||
|
||||
override fun endSession() {}
|
||||
|
||||
override fun reset(ack: StateAck.NewPlayback) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A [Song] whose every property throws except [uid], which is real: persistence and restore
|
||||
* key on it.
|
||||
*
|
||||
* The manager moves songs in lists without reading them. Grow a member when a test needs it.
|
||||
*/
|
||||
fun fakeSong(): Song =
|
||||
object : Song {
|
||||
override val uid: Music.UID =
|
||||
requireNotNull(Music.UID.fromString("uas${UUID.randomUUID()}"))
|
||||
override val name: Name.Known get() = TODO()
|
||||
override val track: Int? get() = TODO()
|
||||
override val disc: Disc? get() = TODO()
|
||||
override val date: Date? get() = TODO()
|
||||
override val uri: Uri get() = TODO()
|
||||
override val path: Path get() = TODO()
|
||||
override val format: Format get() = TODO()
|
||||
override val size: Long get() = TODO()
|
||||
override val durationMs: Long get() = TODO()
|
||||
override val bitrateKbps: Int get() = TODO()
|
||||
override val sampleRateHz: Int get() = TODO()
|
||||
override val replayGainAdjustment: ReplayGainAdjustment get() = TODO()
|
||||
override val modifiedMs: Long get() = TODO()
|
||||
override val addedMs: Long get() = TODO()
|
||||
override val cover: Cover? get() = TODO()
|
||||
override val album: Album get() = TODO()
|
||||
override val artists: List<Artist> get() = TODO()
|
||||
override val genres: List<Genre> get() = TODO()
|
||||
}
|
||||
@@ -0,0 +1,822 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* PlaybackStateManagerImplTest.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.playback.state
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Test
|
||||
|
||||
class PlaybackStateManagerImplTest {
|
||||
/**
|
||||
* Regression (D9): listeners must observe the final deck state at notification time. The
|
||||
* deck bookkeeping used to run after notifying, leaving the UI one update behind and the
|
||||
* playing row unhighlighted.
|
||||
*/
|
||||
@Test
|
||||
fun `listeners observe the final deck state at notification time`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Record the deck state observed at each callback.
|
||||
val observedDecks = mutableListOf<List<Song>>()
|
||||
val observedCurrent = mutableListOf<Boolean>()
|
||||
manager.addListener(
|
||||
object : PlaybackStateManager.Listener {
|
||||
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
|
||||
observedDecks += manager.deck.toList()
|
||||
}
|
||||
|
||||
override fun onIndexMoved(index: Int) {
|
||||
observedCurrent += manager.deckCurrent != null
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Playing index 2 of a 10-song queue; queue two songs in separate actions.
|
||||
val heap = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// The second action's callback observes both deck entries, not the pre-append state.
|
||||
assertEquals(2, observedDecks.last().size)
|
||||
|
||||
// Entering the deck: the callback observes the playing song as deck-sourced.
|
||||
holder.moveTo(3)
|
||||
assertEquals(true, observedCurrent.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Drag-reordering deck rows reorders the waiting entries; drags involving the playing row
|
||||
* are refused.
|
||||
*/
|
||||
@Test
|
||||
fun `moveDeckItems reorders waiting drawer rows`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue; deck of three songs.
|
||||
val heap = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||
|
||||
// Drag the first waiting row to the end: the deck reorders.
|
||||
val a = manager.queue[3]
|
||||
val b = manager.queue[4]
|
||||
val c = manager.queue[5]
|
||||
manager.moveDeckItems(0, 2)
|
||||
assertEquals(b, manager.queue[3])
|
||||
assertEquals(c, manager.queue[4])
|
||||
assertEquals(a, manager.queue[5])
|
||||
|
||||
// Enter the deck: drags involving the playing row 0 are refused.
|
||||
holder.moveTo(3)
|
||||
manager.moveDeckItems(0, 1)
|
||||
assertEquals(c, manager.queue[4])
|
||||
assertEquals(a, manager.queue[5])
|
||||
manager.moveDeckItems(1, 0)
|
||||
assertEquals(c, manager.queue[4])
|
||||
assertEquals(a, manager.queue[5])
|
||||
|
||||
// A waiting-to-waiting drag still works.
|
||||
manager.moveDeckItems(1, 2)
|
||||
assertEquals(a, manager.queue[4])
|
||||
assertEquals(c, manager.queue[5])
|
||||
}
|
||||
|
||||
/**
|
||||
* Swipe-removing a waiting deck row deletes that entry only; swiping the playing row or an
|
||||
* out-of-range row is refused.
|
||||
*/
|
||||
@Test
|
||||
fun `removeDeckItem removes a waiting drawer row`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue; deck of three songs.
|
||||
val heap = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||
|
||||
// Remove the middle waiting row: the others survive in order.
|
||||
val first = manager.queue[3]
|
||||
val last = manager.queue[5]
|
||||
manager.removeDeckItem(1)
|
||||
assertEquals(12, manager.queue.size)
|
||||
assertEquals(first, manager.queue[3])
|
||||
assertEquals(last, manager.queue[4])
|
||||
|
||||
// Enter the deck: the playing row cannot be swiped away.
|
||||
holder.moveTo(3)
|
||||
val playing = manager.currentSong
|
||||
manager.removeDeckItem(0)
|
||||
assertEquals(12, manager.queue.size)
|
||||
assertEquals(playing, manager.currentSong)
|
||||
|
||||
// The remaining waiting row (now row 1) is still removable, leaving the heap directly
|
||||
// behind the playing song.
|
||||
manager.removeDeckItem(1)
|
||||
assertEquals(11, manager.queue.size)
|
||||
assertEquals(playing, manager.currentSong)
|
||||
assertEquals(heap[3], manager.queue[4])
|
||||
|
||||
// Out-of-range rows are refused.
|
||||
manager.removeDeckItem(3)
|
||||
assertEquals(11, manager.queue.size)
|
||||
}
|
||||
|
||||
/**
|
||||
* Tapping a deck row plays it immediately in drawer-row coordinates: row 0 restarts the
|
||||
* playing deck song; a waiting row pulls the song out of line and plays it, retaining the
|
||||
* rest of the queue. A displaced deck song drains; a displaced heap song passes by behind
|
||||
* the playhead, the heap resuming at its successor once the queue drains.
|
||||
*/
|
||||
@Test
|
||||
fun `gotoDeck plays a drawer row`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue; deck of three songs.
|
||||
val heap = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||
|
||||
// Enter the first deck song: row 0 = playing, rows 1-2 = waiting.
|
||||
holder.moveTo(3)
|
||||
val playing = manager.currentSong
|
||||
|
||||
// Row 0 restarts the playing song: no movement, no drain.
|
||||
manager.gotoDeck(0)
|
||||
assertEquals(playing, manager.currentSong)
|
||||
assertEquals(13, manager.queue.size)
|
||||
|
||||
// Tapping the last waiting row: the displaced playing deck song drains, the tapped
|
||||
// song plays, and the skipped waiting entry keeps its place.
|
||||
val tapped = manager.queue[5]
|
||||
val skipped = manager.queue[4]
|
||||
manager.gotoDeck(2)
|
||||
assertEquals(12, manager.queue.size)
|
||||
assertEquals(tapped, manager.currentSong)
|
||||
assertEquals(skipped, manager.queue[4])
|
||||
|
||||
// Playing the queue out resumes the heap after the interrupted song.
|
||||
holder.advanceToNext()
|
||||
holder.advanceToNext()
|
||||
assertEquals(heap[3], manager.currentSong)
|
||||
assertEquals(10, manager.queue.size)
|
||||
|
||||
// With a heap song playing, tapping a waiting row keeps everything: the interrupted
|
||||
// heap song passes by behind the playhead, and the waiting entries keep their order.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||
val tappedAgain = manager.queue[5]
|
||||
val firstWaiting = manager.queue[4]
|
||||
val lastWaiting = manager.queue[6]
|
||||
manager.gotoDeck(1)
|
||||
assertEquals(13, manager.queue.size)
|
||||
assertEquals(tappedAgain, manager.currentSong)
|
||||
assertEquals(heap[3], manager.queue[3])
|
||||
assertEquals(firstWaiting, manager.queue[5])
|
||||
assertEquals(lastWaiting, manager.queue[6])
|
||||
|
||||
// The queue drains in order and the heap resumes after the interrupted song.
|
||||
holder.advanceToNext()
|
||||
holder.advanceToNext()
|
||||
holder.advanceToNext()
|
||||
assertEquals(heap[4], manager.currentSong)
|
||||
assertEquals(10, manager.queue.size)
|
||||
|
||||
// Out-of-range rows do nothing.
|
||||
manager.gotoDeck(9)
|
||||
assertEquals(heap[4], manager.currentSong)
|
||||
assertEquals(10, manager.queue.size)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clearing the queue drops the waiting deck entries from the timeline; a queue-sourced
|
||||
* current song keeps playing and drains normally afterwards.
|
||||
*/
|
||||
@Test
|
||||
fun `clearing the queue drops the waiting deck entries`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue; deck of two songs.
|
||||
val heap = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Clear: the deck block leaves the timeline.
|
||||
manager.clearQueue()
|
||||
assertEquals(10, manager.queue.size)
|
||||
assertEquals(heap[2], manager.currentSong)
|
||||
|
||||
// Queueing again lands directly behind the current song — no phantom boundary.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
assertEquals(11, manager.queue.size)
|
||||
assertEquals(StateAck.PlayNext(at = 3, size = 1), holder.insertions.last())
|
||||
|
||||
// Enter the deck song; clearing with nothing waiting is a no-op for the playing song.
|
||||
holder.moveTo(3)
|
||||
val deckSong = manager.currentSong
|
||||
manager.clearQueue()
|
||||
assertEquals(11, manager.queue.size)
|
||||
assertEquals(deckSong, manager.currentSong)
|
||||
|
||||
// It drains normally when playback leaves it: the heap resumes.
|
||||
holder.advanceToNext()
|
||||
assertEquals(10, manager.queue.size)
|
||||
assertEquals(heap[3], manager.currentSong)
|
||||
}
|
||||
|
||||
/**
|
||||
* Persistence: a deck song missing from the library on restore drops only itself; the
|
||||
* rest of the deck survives, matching the heap's own realignment.
|
||||
*/
|
||||
@Test
|
||||
fun `a missing deck song drops only itself on restore`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue; deck of two songs.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Save, then restore with the first deck song gone from the library (null in the heap,
|
||||
// as realignment marks missing songs).
|
||||
val savedState = manager.toSavedState()!!
|
||||
val shiftedState =
|
||||
savedState.copy(
|
||||
heap = savedState.heap.map { if (it === savedState.deck[0]) null else it }
|
||||
)
|
||||
val restoredManager = PlaybackStateManagerImpl()
|
||||
val restoredHolder = FakePlaybackStateHolder()
|
||||
restoredHolder.manager = restoredManager
|
||||
restoredManager.registerStateHolder(restoredHolder)
|
||||
restoredManager.applySavedState(shiftedState, destructive = true)
|
||||
|
||||
// The timeline restored without the missing song.
|
||||
assertEquals(11, restoredManager.queue.size)
|
||||
|
||||
// Play after one song: behind the surviving deck song.
|
||||
restoredManager.playAfter(listOf(fakeSong()))
|
||||
assertEquals(StateAck.PlayNext(at = 4, size = 1), restoredHolder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Persistence: the deck survives a save and restore — after a restart, queue actions land
|
||||
* behind the remembered deck.
|
||||
*/
|
||||
@Test
|
||||
fun `the deck survives a save and restore`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue; deck of two songs.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Save, then restore into a fresh manager and holder, as a restart does.
|
||||
val savedState = manager.toSavedState()!!
|
||||
val restoredManager = PlaybackStateManagerImpl()
|
||||
val restoredHolder = FakePlaybackStateHolder()
|
||||
restoredHolder.manager = restoredManager
|
||||
restoredManager.registerStateHolder(restoredHolder)
|
||||
restoredManager.applySavedState(savedState, destructive = true)
|
||||
|
||||
// The timeline survived intact.
|
||||
assertEquals(12, restoredManager.queue.size)
|
||||
|
||||
// Play after one song: behind the remembered deck.
|
||||
restoredManager.playAfter(listOf(fakeSong()))
|
||||
assertEquals(StateAck.PlayNext(at = 5, size = 1), restoredHolder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Reproduction harness (field failure): a deck played through under shuffle, then
|
||||
* unshuffle, must leave the physical heap in playlist order.
|
||||
*/
|
||||
@Test
|
||||
fun `shuffled deck play-through leaves the heap in playlist order after unshuffle`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of two songs (not heap members), then shuffle on.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
manager.shuffled(true)
|
||||
|
||||
// Play through the deck and two songs into the tail.
|
||||
repeat(4) { holder.advanceToNext() }
|
||||
|
||||
// Shuffle off.
|
||||
manager.shuffled(false)
|
||||
|
||||
// The physical heap is the playlist again: the deck songs drained, nothing reordered.
|
||||
assertEquals(queue, holder.rawQueue.heap)
|
||||
assertEquals(queue, manager.queue)
|
||||
}
|
||||
|
||||
/**
|
||||
* Interaction: playNext on an empty deck starts one — the deck is the songs the user
|
||||
* manually lined up, and play-next is such an act.
|
||||
*/
|
||||
@Test
|
||||
fun `playNext on an empty deck starts one`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue; no deck.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Play next one song: inserts at position 3 and starts the deck.
|
||||
manager.playNext(listOf(fakeSong()))
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Receipts: 1 at 3 (play next), then 1 at 4 (behind the play-nexted song).
|
||||
assertEquals(
|
||||
listOf(StateAck.PlayNext(at = 3, size = 1), StateAck.PlayNext(at = 4, size = 1)),
|
||||
holder.insertions,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Interaction: playNext inserts at the deck's top, so on a nonempty deck the boundary
|
||||
* advances by the number of songs play-nexted.
|
||||
*/
|
||||
@Test
|
||||
fun `playNext on a nonempty deck advances the boundary`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4; boundary at 5.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Play next one song: inserts at the deck's top, pushing the deck down one.
|
||||
manager.playNext(listOf(fakeSong()))
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Receipts: 2 at 3 (deck), 1 at 3 (play next), then 1 at 6 (past the pushed deck).
|
||||
assertEquals(
|
||||
listOf(
|
||||
StateAck.PlayNext(at = 3, size = 2),
|
||||
StateAck.PlayNext(at = 3, size = 1),
|
||||
StateAck.PlayNext(at = 6, size = 1),
|
||||
),
|
||||
holder.insertions,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust: removing a song inside the deck shrinks the deck, and the boundary steps down.
|
||||
*/
|
||||
@Test
|
||||
fun `removing a deck song shrinks the deck`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4; boundary at 5.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Swipe the deck's last song out of the queue.
|
||||
manager.removeQueueItem(4)
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 4, past the shrunken deck.
|
||||
assertEquals(StateAck.PlayNext(at = 4, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust: dragging a deck song upward within the deck leaves the boundary unchanged.
|
||||
* Brackets the within-deck case with the downward drag.
|
||||
*/
|
||||
@Test
|
||||
fun `dragging a deck song to the front of the deck keeps the boundary`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4; boundary at 5.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Drag the deck's second song to the deck's front.
|
||||
manager.moveQueueItem(4, 3)
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 5, past the unchanged deck.
|
||||
assertEquals(StateAck.PlayNext(at = 5, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust: dragging a deck song out past the boundary into the tail shrinks the deck, and
|
||||
* the boundary steps down.
|
||||
*/
|
||||
@Test
|
||||
fun `dragging a deck song out to the tail shrinks the deck`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4; boundary at 5.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Drag the deck's front song out to the tail.
|
||||
manager.moveQueueItem(3, 7)
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 4, past the shrunken deck.
|
||||
assertEquals(StateAck.PlayNext(at = 4, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust: dragging a deck song within the deck — including to its last position — leaves
|
||||
* the boundary unchanged. The deck was rearranged, not shrunk.
|
||||
*/
|
||||
@Test
|
||||
fun `dragging a deck song to the end of the deck keeps the boundary`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4; boundary at 5.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Drag the deck's front song to the deck's last position.
|
||||
manager.moveQueueItem(3, 4)
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 5, past the unchanged deck.
|
||||
assertEquals(StateAck.PlayNext(at = 5, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust: dragging a tail song into the deck grows the deck, and the boundary rides along
|
||||
* with the move.
|
||||
*/
|
||||
@Test
|
||||
fun `dragging a tail song into the deck grows it`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4; boundary at 5.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// Drag the tail song at position 7 to the front of the deck.
|
||||
manager.moveQueueItem(7, 3)
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 6, past the grown deck.
|
||||
assertEquals(StateAck.PlayNext(at = 6, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Retention: a reshuffle leaves the deck pinned directly behind the current song, in
|
||||
* order; the heap shuffles beneath it.
|
||||
*/
|
||||
@Test
|
||||
fun `the deck survives a reshuffle pinned in front`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4; boundary at 5.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// The user shuffles. The deck stays in order behind the current song, which lands
|
||||
// at playback position 0; the heap reverses beneath (stand-in shuffle).
|
||||
manager.shuffled(true)
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 3, behind the pinned deck.
|
||||
assertEquals(StateAck.PlayNext(at = 3, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Retention: new playback replaces the heap and retains the queue — the tapped song plays
|
||||
* immediately as the new heap's top, and the deck stays ahead of the new tail.
|
||||
*/
|
||||
@Test
|
||||
fun `the deck persists across new playback`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// The user taps the first song of a 5-song album.
|
||||
val album = List(5) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(album[0], null, album, false))
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 3, behind the retained deck on the new heap.
|
||||
assertEquals(StateAck.PlayNext(at = 3, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Membership: removing a heap entry whose instance is also decked keeps the deck —
|
||||
* membership is the position within the deck block, not the instance.
|
||||
*/
|
||||
@Test
|
||||
fun `removing a heap entry whose instance is decked keeps the deck`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of one song: the same instance that sits at heap position 7 (8 after the
|
||||
// insertion shifts it).
|
||||
val duplicate = queue[7]
|
||||
manager.playAfter(listOf(duplicate))
|
||||
|
||||
// Swipe the heap entry out of the queue.
|
||||
manager.removeQueueItem(8)
|
||||
|
||||
// The deck entry survived at position 3.
|
||||
assertEquals(10, manager.queue.size)
|
||||
assertSame(duplicate, manager.queue[3])
|
||||
|
||||
// Play after one song: behind the surviving deck song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
assertEquals(StateAck.PlayNext(at = 4, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain: a deck song whose instance also lives in the heap drains its deck entry, never
|
||||
* the heap entry.
|
||||
*/
|
||||
@Test
|
||||
fun `draining a duplicated deck song removes the deck entry not the heap entry`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of one song: the same instance that sits at heap position 0.
|
||||
val duplicate = queue[0]
|
||||
manager.playAfter(listOf(duplicate))
|
||||
|
||||
// The current song ends; the deck song starts playing.
|
||||
holder.moveTo(3)
|
||||
|
||||
// The user skips back to the heap cursor.
|
||||
manager.prev()
|
||||
|
||||
// The heap entry survived at position 0; the deck entry drained.
|
||||
assertEquals(10, manager.queue.size)
|
||||
assertSame(duplicate, manager.queue[0])
|
||||
|
||||
// Play after one song: the deck is empty, so it lands behind the current song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
assertEquals(StateAck.PlayNext(at = 3, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain guard: rewinding within the current song (prev past the rewind threshold) is not a
|
||||
* departure — nothing drains, nothing advances.
|
||||
*/
|
||||
@Test
|
||||
fun `rewinding within a deck song does not drain it`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 songs occupies positions 3 and 4.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// The current song ends; the deck head starts playing.
|
||||
holder.moveTo(3)
|
||||
|
||||
// The user presses prev past the rewind threshold: the song restarts in place.
|
||||
holder.rewind()
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 5 — the playing deck song held, the deck intact.
|
||||
assertEquals(StateAck.PlayNext(at = 5, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain: skipping backward out of a deck song drains it from the queue; prev lands on the
|
||||
* heap cursor.
|
||||
*/
|
||||
@Test
|
||||
fun `skipping backward out of a deck song drains it`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 3 songs occupies positions 3 through 5.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||
|
||||
// The current song ends; the deck head starts playing.
|
||||
holder.moveTo(3)
|
||||
|
||||
// The user skips back to the heap cursor.
|
||||
manager.prev()
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 5, behind the two remaining deck songs — the
|
||||
// departed head drained.
|
||||
assertEquals(StateAck.PlayNext(at = 5, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Retention: a track change is the queue doing its job. The deck persists, minus the song
|
||||
* that started playing — it left the upcoming queue by becoming current.
|
||||
*/
|
||||
@Test
|
||||
fun `the deck persists across track changes`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Deck of 2 then 3 songs occupies positions 3 through 7; boundary at 8.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||
|
||||
// The current song ends; the deck head at position 3 starts playing.
|
||||
holder.moveTo(3)
|
||||
|
||||
// Play after one song.
|
||||
manager.playAfter(listOf(fakeSong()))
|
||||
|
||||
// Last receipt: 1 song at position 8, behind the four remaining deck songs.
|
||||
assertEquals(StateAck.PlayNext(at = 8, size = 1), holder.insertions.last())
|
||||
}
|
||||
|
||||
/**
|
||||
* Advancement: with a nonempty deck, playAfter inserts after the last deck song, and the
|
||||
* deck end advances by the number of songs added.
|
||||
*/
|
||||
@Test
|
||||
fun `playAfter with a nonempty deck inserts after the last deck song`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Play after two songs, then three more.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
|
||||
|
||||
// Two receipts: 2 songs at position 3, then 3 songs at position 5.
|
||||
assertEquals(
|
||||
listOf(StateAck.PlayNext(at = 3, size = 2), StateAck.PlayNext(at = 5, size = 3)),
|
||||
holder.insertions,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Base case: with an empty deck, playAfter inserts immediately after the current song
|
||||
* (index + 1), reported to the holder as [StateAck.PlayNext].
|
||||
*/
|
||||
@Test
|
||||
fun `playAfter with an empty deck inserts after the current song`() {
|
||||
val manager = PlaybackStateManagerImpl()
|
||||
val holder = FakePlaybackStateHolder()
|
||||
holder.manager = manager
|
||||
manager.registerStateHolder(holder)
|
||||
|
||||
// Playing index 2 of a 10-song queue.
|
||||
val queue = List(10) { fakeSong() }
|
||||
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(queue[2], null, queue, false))
|
||||
|
||||
// Play-after two songs.
|
||||
manager.playAfter(listOf(fakeSong(), fakeSong()))
|
||||
|
||||
// One insertion receipt: 2 songs at position 3, directly after the current song.
|
||||
assertEquals(listOf(StateAck.PlayNext(at = 3, size = 2)), holder.insertions)
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@
|
||||
#include "JByteArrayRef.h"
|
||||
|
||||
JMetadataBuilder::JMetadataBuilder(JNIEnv *env) : env(env), id3v2(env), xiph(
|
||||
env), mp4(env), cover(), properties(nullptr) {
|
||||
env), mp4(env), ape(env), cover(), properties(nullptr) {
|
||||
}
|
||||
|
||||
void JMetadataBuilder::setMimeType(TagLib::String type) {
|
||||
@@ -94,6 +94,13 @@ void JMetadataBuilder::setId3v2(TagLib::ID3v2::Tag &tag) {
|
||||
}
|
||||
}
|
||||
|
||||
void JMetadataBuilder::setApe(TagLib::APE::Tag &tag) {
|
||||
for (auto item : tag.itemListMap()) {
|
||||
auto key = item.first.upper();
|
||||
ape.add_custom(key, item.second.values());
|
||||
}
|
||||
}
|
||||
|
||||
void JMetadataBuilder::setXiph(TagLib::Ogg::XiphComment &tag) {
|
||||
for (auto field : tag.fieldListMap()) {
|
||||
auto key = field.first.upper();
|
||||
@@ -203,15 +210,16 @@ jobject JMetadataBuilder::build() {
|
||||
|
||||
JClassRef jMetadataClass { env, "org/oxycblt/musikr/metadata/Metadata" };
|
||||
jmethodID jMetadataInitMethod = jMetadataClass.method("<init>",
|
||||
"(Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;[BLorg/"
|
||||
"(Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;[BLorg/"
|
||||
"oxycblt/musikr/metadata/Properties;)V");
|
||||
auto jId3v2Map = id3v2.getObject();
|
||||
auto jXiphMap = xiph.getObject();
|
||||
auto jMp4Map = mp4.getObject();
|
||||
auto jApeMap = ape.getObject();
|
||||
if (cover.has_value()) {
|
||||
JByteArrayRef jCoverArray { env, cover.value() };
|
||||
jobject result = env->NewObject(*jMetadataClass, jMetadataInitMethod,
|
||||
**jId3v2Map, **jXiphMap, **jMp4Map, *jCoverArray, *jProperties);
|
||||
**jId3v2Map, **jXiphMap, **jMp4Map, **jApeMap, *jCoverArray, *jProperties);
|
||||
return result;
|
||||
}
|
||||
return env->NewObject(*jMetadataClass, jMetadataInitMethod, **jId3v2Map,
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
#include "taglib/id3v2tag.h"
|
||||
#include "taglib/xiphcomment.h"
|
||||
#include "taglib/mp4tag.h"
|
||||
#include "taglib/apetag.h"
|
||||
#include "taglib/audioproperties.h"
|
||||
|
||||
#include "JTagMap.h"
|
||||
@@ -40,6 +41,7 @@ public:
|
||||
void setId3v2(TagLib::ID3v2::Tag &tag);
|
||||
void setXiph(TagLib::Ogg::XiphComment &tag);
|
||||
void setMp4(TagLib::MP4::Tag &tag);
|
||||
void setApe(TagLib::APE::Tag &tag);
|
||||
void setFlacPictures(TagLib::List<TagLib::FLAC::Picture*> &pics);
|
||||
void setProperties(TagLib::AudioProperties *properties);
|
||||
|
||||
@@ -56,6 +58,7 @@ private:
|
||||
JTagMap id3v2;
|
||||
JTagMap xiph;
|
||||
JTagMap mp4;
|
||||
JTagMap ape;
|
||||
};
|
||||
|
||||
#endif //AUXIO_JMETADATABUILDER_H
|
||||
|
||||
@@ -28,7 +28,7 @@ build_for_arch() {
|
||||
cmake -B $DST_DIR -DANDROID_NDK_PATH=${NDK_PATH} -DCMAKE_TOOLCHAIN_FILE=${NDK_TOOLCHAIN} \
|
||||
-DANDROID_ABI=$ARCH -DBUILD_SHARED_LIBS=OFF -DVISIBILITY_HIDDEN=ON -DBUILD_TESTING=OFF \
|
||||
-DBUILD_EXAMPLES=OFF -DBUILD_BINDINGS=OFF -DWITH_ZLIB=OFF -DCMAKE_BUILD_TYPE=Release \
|
||||
-DWITH_APE=OFF -DWITH_ASF=OFF -DWITH_ASF=OFF -DWITH_MOD=OFF -DWITH_SHORTEN=OFF \
|
||||
-DWITH_APE=ON -DWITH_ASF=OFF -DWITH_ASF=OFF -DWITH_MOD=OFF -DWITH_SHORTEN=OFF \
|
||||
-DWITH_TRUEAUDIO=OFF -DCMAKE_CXX_FLAGS="-fPIC"
|
||||
# Try to parallelize the build
|
||||
cmake --build $DST_DIR --config Release -j$(nproc)
|
||||
|
||||
@@ -51,6 +51,14 @@ bool parseMpeg(const std::string &name, TagLib::MPEG::File *mpegFile,
|
||||
LOGE("Unable to parse ID3v2 tag in %s: %s", name.c_str(), e.what());
|
||||
}
|
||||
}
|
||||
auto apeTag = mpegFile->APETag();
|
||||
if (apeTag != nullptr) {
|
||||
try {
|
||||
jBuilder.setApe(*apeTag);
|
||||
} catch (std::exception &e) {
|
||||
LOGE("Unable to parse APE tag in %s: %s", name.c_str(), e.what());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -19,9 +19,11 @@
|
||||
package org.oxycblt.musikr
|
||||
|
||||
import android.content.Context
|
||||
import java.util.Collections
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import org.oxycblt.musikr.fs.File
|
||||
import org.oxycblt.musikr.pipeline.EvaluateStep
|
||||
import org.oxycblt.musikr.pipeline.ExploreStep
|
||||
import org.oxycblt.musikr.pipeline.Explored
|
||||
@@ -117,7 +119,8 @@ private class MusikrImpl(
|
||||
var explored = 0
|
||||
var loaded = 0
|
||||
val exploredChannel = Channel<Explored>(Channel.UNLIMITED)
|
||||
val exploredTask = exploreStep.explore(this, exploredChannel)
|
||||
val playlistFiles = Collections.synchronizedList(mutableListOf<File>())
|
||||
val exploredTask = exploreStep.explore(this, exploredChannel, playlistFiles)
|
||||
val trackedExploredChannel = Channel<Explored>(Channel.UNLIMITED)
|
||||
val trackedExploredTask =
|
||||
tryAsyncWith(trackedExploredChannel, Dispatchers.Main) {
|
||||
@@ -139,7 +142,7 @@ private class MusikrImpl(
|
||||
}
|
||||
onProgress(IndexingProgress.Indeterminate)
|
||||
}
|
||||
val library = evaluateStep.evaluate(trackedExtractedChannel)
|
||||
val library = evaluateStep.evaluate(trackedExtractedChannel, playlistFiles)
|
||||
merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await()
|
||||
LibraryResultImpl(config, library)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface FS {
|
||||
/** The roots playlist entries resolve against, in precedence order. May be empty. */
|
||||
val locationRoots: List<Path>
|
||||
|
||||
suspend fun explore(files: Channel<File>): Deferred<Result<Unit>>
|
||||
|
||||
fun track(): Flow<FSUpdate>
|
||||
|
||||
@@ -35,6 +35,7 @@ import org.oxycblt.musikr.fs.FS
|
||||
import org.oxycblt.musikr.fs.FSUpdate
|
||||
import org.oxycblt.musikr.fs.File
|
||||
import org.oxycblt.musikr.fs.Location
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.path.MediaStorePathInterpreter
|
||||
import org.oxycblt.musikr.fs.path.VolumeManager
|
||||
import org.oxycblt.musikr.fs.saf.contentResolverSafe
|
||||
@@ -54,6 +55,15 @@ private constructor(
|
||||
) : FS {
|
||||
private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager)
|
||||
|
||||
// Include-mode filters are the closest thing MediaStore has to configured locations.
|
||||
override val locationRoots: List<Path>
|
||||
get() =
|
||||
if (query.mode == FilterMode.INCLUDE) {
|
||||
query.filtered.map { it.path }
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
|
||||
tryAsyncWith(files, Dispatchers.IO) { channel ->
|
||||
|
||||
@@ -54,6 +54,9 @@ private constructor(
|
||||
private val contentResolver: ContentResolver,
|
||||
private val query: Query,
|
||||
) : FS {
|
||||
override val locationRoots: List<Path>
|
||||
get() = query.source.map { it.path }
|
||||
|
||||
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
|
||||
tryAsyncWith(files, Dispatchers.Main) {
|
||||
query.source
|
||||
|
||||
@@ -22,6 +22,7 @@ data class Metadata(
|
||||
val id3v2: Map<String, List<String>>,
|
||||
val xiph: Map<String, List<String>>,
|
||||
val mp4: Map<String, List<String>>,
|
||||
val ape: Map<String, List<String>>,
|
||||
val cover: ByteArray?,
|
||||
val properties: Properties,
|
||||
) {
|
||||
@@ -34,6 +35,7 @@ data class Metadata(
|
||||
if (id3v2 != other.id3v2) return false
|
||||
if (xiph != other.xiph) return false
|
||||
if (mp4 != other.mp4) return false
|
||||
if (ape != other.ape) return false
|
||||
if (cover != null) {
|
||||
if (other.cover == null) return false
|
||||
if (!cover.contentEquals(other.cover)) return false
|
||||
@@ -47,6 +49,7 @@ data class Metadata(
|
||||
var result = id3v2.hashCode()
|
||||
result = 31 * result + xiph.hashCode()
|
||||
result = 31 * result + mp4.hashCode()
|
||||
result = 31 * result + ape.hashCode()
|
||||
result = 31 * result + (cover?.contentHashCode() ?: 0)
|
||||
result = 31 * result + properties.hashCode()
|
||||
return result
|
||||
|
||||
@@ -19,24 +19,39 @@
|
||||
package org.oxycblt.musikr.pipeline
|
||||
|
||||
import android.content.Context
|
||||
import java.util.zip.CRC32
|
||||
import java.util.zip.CheckedInputStream
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import org.oxycblt.musikr.BuildConfig
|
||||
import org.oxycblt.musikr.Config
|
||||
import org.oxycblt.musikr.Interpretation
|
||||
import org.oxycblt.musikr.MutableLibrary
|
||||
import org.oxycblt.musikr.fs.FS
|
||||
import org.oxycblt.musikr.fs.File
|
||||
import org.oxycblt.musikr.fs.saf.contentResolverSafe
|
||||
import org.oxycblt.musikr.graph.MusicGraph
|
||||
import org.oxycblt.musikr.model.LibraryFactory
|
||||
import org.oxycblt.musikr.playlist.PlaylistPathResolver
|
||||
import org.oxycblt.musikr.playlist.PlaylistReconciler
|
||||
import org.oxycblt.musikr.playlist.db.StoredPlaylists
|
||||
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
|
||||
import org.oxycblt.musikr.playlist.m3u.M3U
|
||||
import org.oxycblt.musikr.playlist.m3u.ParsedM3U
|
||||
import org.oxycblt.musikr.playlist.playlistNameFromFileName
|
||||
import org.oxycblt.musikr.tag.interpret.PreSong
|
||||
import org.oxycblt.musikr.tag.interpret.TagInterpreter
|
||||
|
||||
internal interface EvaluateStep {
|
||||
suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary
|
||||
suspend fun evaluate(
|
||||
extractedMusic: Channel<Extracted>,
|
||||
playlistFiles: List<File>,
|
||||
): MutableLibrary
|
||||
|
||||
companion object {
|
||||
fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep =
|
||||
EvaluateStepImpl(
|
||||
context,
|
||||
config.fs,
|
||||
TagInterpreter.new(interpretation),
|
||||
PlaylistInterpreter.new(interpretation),
|
||||
config.storage.storedPlaylists,
|
||||
@@ -47,21 +62,37 @@ internal interface EvaluateStep {
|
||||
|
||||
private class EvaluateStepImpl(
|
||||
private val context: Context,
|
||||
private val fs: FS,
|
||||
private val tagInterpreter: TagInterpreter,
|
||||
private val playlistInterpreter: PlaylistInterpreter,
|
||||
private val storedPlaylists: StoredPlaylists,
|
||||
private val libraryFactory: LibraryFactory,
|
||||
) : EvaluateStep {
|
||||
override suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary {
|
||||
override suspend fun evaluate(
|
||||
extractedMusic: Channel<Extracted>,
|
||||
playlistFiles: List<File>,
|
||||
): MutableLibrary {
|
||||
val builder = MusicGraph.builder()
|
||||
val preSongs = mutableListOf<PreSong>()
|
||||
for (extracted in extractedMusic) {
|
||||
when (extracted) {
|
||||
is RawSong -> builder.add(tagInterpreter.interpret(extracted))
|
||||
is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file))
|
||||
is RawSong -> {
|
||||
val preSong = tagInterpreter.interpret(extracted)
|
||||
preSongs.add(preSong)
|
||||
builder.add(preSong)
|
||||
}
|
||||
is NotAudio -> {}
|
||||
is InvalidSong -> {}
|
||||
}
|
||||
}
|
||||
if (playlistFiles.isNotEmpty()) {
|
||||
reconcilePlaylists(playlistFiles, preSongs)
|
||||
}
|
||||
// Stored playlists enter the graph after the reconcile pass, so the graph sees the
|
||||
// settled state.
|
||||
for (playlistFile in storedPlaylists.read()) {
|
||||
builder.add(playlistInterpreter.interpret(playlistFile))
|
||||
}
|
||||
val graph = builder.build()
|
||||
|
||||
// Render graph to Graphviz in debug mode
|
||||
@@ -72,4 +103,77 @@ private class EvaluateStepImpl(
|
||||
|
||||
return libraryFactory.create(graph, storedPlaylists, playlistInterpreter)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile the discovered playlist files against the tracked store. Each file is parsed,
|
||||
* signed, and resolved in one pass; the reconciler decides keep/replace/create, and the
|
||||
* actions are applied to the store before stored playlists feed the graph.
|
||||
*/
|
||||
private suspend fun reconcilePlaylists(playlistFiles: List<File>, preSongs: List<PreSong>) {
|
||||
val resolver = PlaylistPathResolver()
|
||||
val m3u = M3U.new()
|
||||
val uidsByPath = preSongs.associate { it.path to it.v363Uid }
|
||||
val roots = fs.locationRoots
|
||||
val discoveredFiles = mutableListOf<DiscoveredFile>()
|
||||
for (file in playlistFiles) {
|
||||
val crc = CRC32()
|
||||
val parsed =
|
||||
context.contentResolverSafe.openInputStream(file.uri)?.use { stream ->
|
||||
m3u.read(CheckedInputStream(stream, crc))
|
||||
}
|
||||
?: continue
|
||||
val paths =
|
||||
resolver.resolve(parsed.entries, listOf(file.path.directory) + roots) { path ->
|
||||
path in uidsByPath
|
||||
}
|
||||
discoveredFiles.add(DiscoveredFile(file, parsed, crc.value, paths ?: emptyList()))
|
||||
}
|
||||
val actions =
|
||||
PlaylistReconciler.reconcile(
|
||||
storedPlaylists.readTracked(),
|
||||
discoveredFiles.map {
|
||||
PlaylistReconciler.Discovered(
|
||||
it.file.uri.toString(),
|
||||
it.signature,
|
||||
it.songPaths.size,
|
||||
)
|
||||
},
|
||||
)
|
||||
for (action in actions) {
|
||||
when (action) {
|
||||
is PlaylistReconciler.Action.Keep -> {}
|
||||
is PlaylistReconciler.Action.Replace -> {
|
||||
val file =
|
||||
discoveredFiles.first { it.file.uri.toString() == action.file.uri }
|
||||
storedPlaylists.replaceTracked(
|
||||
action.tracked.uid,
|
||||
file.name(),
|
||||
file.songPaths.mapNotNull { uidsByPath[it] },
|
||||
action.file.signature,
|
||||
)
|
||||
}
|
||||
is PlaylistReconciler.Action.Create -> {
|
||||
val file =
|
||||
discoveredFiles.first { it.file.uri.toString() == action.file.uri }
|
||||
storedPlaylists.newTracked(
|
||||
file.name(),
|
||||
file.songPaths.mapNotNull { uidsByPath[it] },
|
||||
file.file.uri.toString(),
|
||||
action.file.signature,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class DiscoveredFile(
|
||||
val file: File,
|
||||
val parsed: ParsedM3U,
|
||||
val signature: Long,
|
||||
val songPaths: List<org.oxycblt.musikr.fs.Path>,
|
||||
) {
|
||||
/** The playlist's name: the file's #PLAYLIST entry, else derived from the file name. */
|
||||
fun name() =
|
||||
parsed.name ?: file.path.name?.let { playlistNameFromFileName(it) } ?: "Playlist"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,16 @@ import org.oxycblt.musikr.util.merge
|
||||
import org.oxycblt.musikr.util.tryAsyncWith
|
||||
|
||||
internal interface ExploreStep {
|
||||
suspend fun explore(scope: CoroutineScope, explored: Channel<Explored>): Deferred<Result<Unit>>
|
||||
/**
|
||||
* Explore the file system for music, streaming the results into [explored]. Discovered
|
||||
* playlist files are buffered into [playlistFiles] for reconciliation once the library is
|
||||
* fully extracted.
|
||||
*/
|
||||
suspend fun explore(
|
||||
scope: CoroutineScope,
|
||||
explored: Channel<Explored>,
|
||||
playlistFiles: MutableList<File>,
|
||||
): Deferred<Result<Unit>>
|
||||
|
||||
companion object {
|
||||
fun from(context: Context, config: Config): ExploreStep =
|
||||
@@ -48,6 +57,7 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
|
||||
override suspend fun explore(
|
||||
scope: CoroutineScope,
|
||||
explored: Channel<Explored>,
|
||||
playlistFiles: MutableList<File>,
|
||||
): Deferred<Result<Unit>> {
|
||||
val files = Channel<File>(Channel.UNLIMITED)
|
||||
val filesTask = fs.explore(files)
|
||||
@@ -62,6 +72,10 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
|
||||
file.mimeType != "application/x-ogg" &&
|
||||
file.mimeType != "application/octet-stream")
|
||||
) {
|
||||
if (file.mimeType == M3U.MIME_TYPE) {
|
||||
// Not audio, but still wanted: buffer for the reconcile pass.
|
||||
playlistFiles.add(file)
|
||||
}
|
||||
return@mapParallel Finalized(NotAudio)
|
||||
}
|
||||
when (val cacheResult = storage.cache.read(file)) {
|
||||
@@ -100,26 +114,14 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
|
||||
}
|
||||
}
|
||||
}
|
||||
val playlists = Channel<Explored>(Channel.UNLIMITED)
|
||||
val playlistsTask =
|
||||
scope.tryAsyncWith(playlists, Dispatchers.IO) {
|
||||
for (playlist in storage.storedPlaylists.read()) {
|
||||
val rawPlaylist = RawPlaylist(playlist)
|
||||
it.send(rawPlaylist)
|
||||
}
|
||||
}
|
||||
|
||||
val mergeTask =
|
||||
scope.tryAsyncWith(explored, Dispatchers.Main) {
|
||||
for (item in finalized) {
|
||||
it.send(item.explored)
|
||||
}
|
||||
for (playlist in playlists) {
|
||||
it.send(playlist)
|
||||
}
|
||||
}
|
||||
|
||||
return scope.merge(filesTask, classifiedTask, exploredTask, playlistsTask, mergeTask)
|
||||
return scope.merge(filesTask, classifiedTask, exploredTask, mergeTask)
|
||||
}
|
||||
|
||||
private sealed interface Classified
|
||||
|
||||
@@ -73,7 +73,6 @@ private class ExtractStepImpl(
|
||||
scope.mapParallel(PARALLELISM, explored, extract, Dispatchers.IO) { item ->
|
||||
when (item) {
|
||||
is RawSong -> Finalized(item)
|
||||
is RawPlaylist -> Finalized(item)
|
||||
is NewSong -> {
|
||||
when (val result = metadataExtractor.extract(item.file)) {
|
||||
is MetadataResult.Success ->
|
||||
|
||||
@@ -21,7 +21,6 @@ package org.oxycblt.musikr.pipeline
|
||||
import org.oxycblt.musikr.covers.Cover
|
||||
import org.oxycblt.musikr.fs.File
|
||||
import org.oxycblt.musikr.metadata.Properties
|
||||
import org.oxycblt.musikr.playlist.PlaylistFile
|
||||
import org.oxycblt.musikr.tag.parse.ParsedTags
|
||||
|
||||
internal sealed interface PipelineItem
|
||||
@@ -48,8 +47,6 @@ internal data object InvalidSong : Extracted.Invalid
|
||||
|
||||
internal data object NotAudio : Explored.Known, Extracted.Valid
|
||||
|
||||
internal data class RawPlaylist(val file: PlaylistFile) : Explored.Known, Extracted.Valid
|
||||
|
||||
internal data class RawSong(
|
||||
val file: File,
|
||||
val properties: Properties,
|
||||
|
||||
@@ -20,7 +20,9 @@ package org.oxycblt.musikr.playlist
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import org.oxycblt.musikr.Library
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.Volume
|
||||
@@ -37,13 +39,16 @@ import org.oxycblt.musikr.playlist.m3u.M3U
|
||||
*/
|
||||
interface ExternalPlaylistManager {
|
||||
/**
|
||||
* Import the playli L.d("Unable to extract bit rate field") st file at the given [uri].
|
||||
* Import the playlist file at the given [uri].
|
||||
*
|
||||
* @param uri The [Uri] of the playlist file to import.
|
||||
* @return An [ImportedPlaylist] containing the paths to the files listed in the playlist file,
|
||||
* or null if the playlist could not be imported.
|
||||
* @param roots Candidate roots to resolve entries against after the playlist file's own
|
||||
* directory, in precedence order. Usually the configured music locations.
|
||||
* @param library The [Library] to resolve entries against.
|
||||
* @return An [ImportedPlaylist] containing the resolved songs, or null if the playlist could
|
||||
* not be imported or no entry resolved.
|
||||
*/
|
||||
suspend fun import(uri: Uri): ImportedPlaylist?
|
||||
suspend fun import(uri: Uri, roots: List<Path>, library: Library): ImportedPlaylist?
|
||||
|
||||
/**
|
||||
* Export the given [playlist] to the given [uri].
|
||||
@@ -60,7 +65,7 @@ interface ExternalPlaylistManager {
|
||||
ExternalPlaylistManagerImpl(
|
||||
context,
|
||||
DocumentPathFactory.from(context),
|
||||
M3U.from(context),
|
||||
M3U.new(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -80,40 +85,39 @@ data class ExportConfig(val absolute: Boolean, val windowsPaths: Boolean)
|
||||
* A playlist that has been imported.
|
||||
*
|
||||
* @property name The name of the playlist. May be null if not provided.
|
||||
* @property paths The paths of the files in the playlist.
|
||||
* @property songs The resolved songs of the playlist, in file order. Entries that did not
|
||||
* resolve are dropped.
|
||||
* @see ExternalPlaylistManager
|
||||
* @see M3U
|
||||
*/
|
||||
data class ImportedPlaylist(val name: String?, val paths: List<PossiblePaths>)
|
||||
|
||||
typealias PossiblePaths = List<Path>
|
||||
data class ImportedPlaylist(val name: String?, val songs: List<Song>)
|
||||
|
||||
private class ExternalPlaylistManagerImpl(
|
||||
private val context: Context,
|
||||
private val documentPathFactory: DocumentPathFactory,
|
||||
private val m3u: M3U,
|
||||
) : ExternalPlaylistManager {
|
||||
override suspend fun import(uri: Uri): ImportedPlaylist? {
|
||||
private val resolver = PlaylistPathResolver()
|
||||
override suspend fun import(uri: Uri, roots: List<Path>, library: Library): ImportedPlaylist? {
|
||||
val filePath =
|
||||
documentPathFactory.unpackDocumentUri(uri)
|
||||
?: Path(Volume.ThirdParty(uri), Components.root())
|
||||
|
||||
return try {
|
||||
context.contentResolverSafe.openInputStream(uri)?.use {
|
||||
val imported = m3u.read(it, filePath.directory) ?: return null
|
||||
val name = imported.name
|
||||
val parsed = m3u.read(it) ?: return null
|
||||
val paths =
|
||||
resolver.resolve(parsed.entries, listOf(filePath.directory) + roots) { path ->
|
||||
library.findSongByPath(path) != null
|
||||
}
|
||||
?: return null
|
||||
val songs = paths.mapNotNull(library::findSongByPath)
|
||||
val name = parsed.name
|
||||
if (name != null) {
|
||||
return imported
|
||||
return ImportedPlaylist(name, songs)
|
||||
}
|
||||
// Strip extension
|
||||
val fileName = filePath.name ?: return imported
|
||||
val split = fileName.split(".")
|
||||
var newName = split[0]
|
||||
// Replace delimiters with space
|
||||
newName = newName.replace(Regex("[_-]"), " ")
|
||||
// Replace long stretches of whitespace with one space
|
||||
newName = newName.replace(Regex("\\s+"), " ")
|
||||
return ImportedPlaylist(newName, imported.paths)
|
||||
val fileName = filePath.name ?: return ImportedPlaylist(null, songs)
|
||||
return ImportedPlaylist(playlistNameFromFileName(fileName), songs)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
|
||||
@@ -43,3 +43,13 @@ internal interface PlaylistHandle {
|
||||
|
||||
suspend fun delete()
|
||||
}
|
||||
|
||||
/** Derive a playlist name from a file name: strip the extension, delimiters become spaces. */
|
||||
internal fun playlistNameFromFileName(fileName: String): String {
|
||||
// Strip extension
|
||||
var name = fileName.split(".")[0]
|
||||
// Replace delimiters with space
|
||||
name = name.replace(Regex("[_-]"), " ")
|
||||
// Replace long stretches of whitespace with one space
|
||||
return name.replace(Regex("\\s+"), " ")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* PlaylistPathResolver.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.musikr.playlist
|
||||
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
|
||||
/**
|
||||
* Resolves playlist file entries against the indexed library by probe-and-lock: probe entries
|
||||
* against the candidate roots in order until one resolves, lock that root, then resolve every
|
||||
* entry against it. All entries in a playlist are assumed to share one root. Absolute entries
|
||||
* probe with leading components stripped one at a time, which rescues paths written under
|
||||
* another machine's layout; the locked strip depth then applies to every absolute entry.
|
||||
*
|
||||
* Unresolvable entries drop out of the result. A null result means no entry resolved anywhere —
|
||||
* the only case a playlist fails to resolve.
|
||||
*
|
||||
* @author OxygenCobalt (Fork)
|
||||
*/
|
||||
internal class PlaylistPathResolver {
|
||||
/**
|
||||
* A single playlist entry.
|
||||
*
|
||||
* @property components The path as written in the playlist, split into components.
|
||||
* @property absolute Whether the path was written absolute.
|
||||
*/
|
||||
data class Entry(val components: Components, val absolute: Boolean)
|
||||
|
||||
/**
|
||||
* Resolve [entries] against [roots] (in precedence order), using [exists] to test whether a
|
||||
* resolved path is in the library.
|
||||
*
|
||||
* @return The resolved paths in entry order, or null if no entry resolved under any root.
|
||||
*/
|
||||
fun resolve(entries: List<Entry>, roots: List<Path>, exists: (Path) -> Boolean): List<Path>? {
|
||||
var lockedRoot: Path? = null
|
||||
var lockedStrip = 0
|
||||
probe@ for (entry in entries) {
|
||||
// Never strip the file name itself.
|
||||
val maxStrip = if (entry.absolute) entry.components.components.size - 1 else 0
|
||||
for (strip in 0..maxStrip) {
|
||||
for (root in roots) {
|
||||
val candidate =
|
||||
Path(root.volume, entry.components.depth(strip).joinedTo(root.components))
|
||||
if (exists(candidate)) {
|
||||
lockedRoot = root
|
||||
lockedStrip = strip
|
||||
break@probe
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lockedRoot == null) {
|
||||
return null
|
||||
}
|
||||
return entries.mapNotNull { entry ->
|
||||
val components =
|
||||
if (entry.absolute) entry.components.depth(lockedStrip) else entry.components
|
||||
Path(lockedRoot.volume, components.joinedTo(lockedRoot.components)).takeIf(exists)
|
||||
}
|
||||
}
|
||||
|
||||
/** Join these components onto [base], resolving `.` and `..` segments along the way. */
|
||||
private fun Components.joinedTo(base: Components): Components {
|
||||
var result = base
|
||||
for (component in components) {
|
||||
result =
|
||||
when (component) {
|
||||
".." -> result.parent()
|
||||
"." -> result
|
||||
else -> result.child(component)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* PlaylistReconciler.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.musikr.playlist
|
||||
|
||||
import org.oxycblt.musikr.Music
|
||||
|
||||
/**
|
||||
* Reconciles stored tracked playlists against the playlist files discovered in a scan. The file
|
||||
* on disk wins when it speaks, but never destructively: an unchanged file keeps the stored
|
||||
* playlist (in-app edits survive), a changed file with at least one resolved entry replaces it
|
||||
* (in-app edits are discarded), and a file that is missing or resolves nothing keeps the stored
|
||||
* playlist. Playlists without a source file are unmanaged and never reach this unit.
|
||||
*
|
||||
* @author OxygenCobalt (Fork)
|
||||
*/
|
||||
internal object PlaylistReconciler {
|
||||
/**
|
||||
* A stored playlist's tracking identity.
|
||||
*
|
||||
* @property uid The playlist's UID.
|
||||
* @property sourceUri The document URI of the file the playlist was imported from.
|
||||
* @property signature The content signature of that file at import time.
|
||||
*/
|
||||
data class Tracked(val uid: Music.UID, val sourceUri: String, val signature: Long)
|
||||
|
||||
/**
|
||||
* A playlist file discovered in a scan.
|
||||
*
|
||||
* @property uri The document URI of the file.
|
||||
* @property signature The content signature of the file.
|
||||
* @property resolvedCount How many entries resolved against the library.
|
||||
*/
|
||||
data class Discovered(val uri: String, val signature: Long, val resolvedCount: Int)
|
||||
|
||||
/** What to do with a tracked playlist or discovered file after reconciliation. */
|
||||
sealed interface Action {
|
||||
/** Nothing changes: keep the stored playlist as-is. */
|
||||
data class Keep(val tracked: Tracked) : Action
|
||||
|
||||
/** The file changed and resolves: re-import it, replacing the stored playlist's songs. */
|
||||
data class Replace(val tracked: Tracked, val file: Discovered) : Action
|
||||
|
||||
/** The file has no stored playlist and resolves: import it as a new tracked playlist. */
|
||||
data class Create(val file: Discovered) : Action
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile [tracked] stored playlists against [discovered] files, emitting one [Action] per
|
||||
* input.
|
||||
*/
|
||||
fun reconcile(tracked: List<Tracked>, discovered: List<Discovered>): List<Action> {
|
||||
val filesByUri = discovered.associateBy { it.uri }
|
||||
val trackedActions =
|
||||
tracked.map { item ->
|
||||
val file = filesByUri[item.sourceUri]
|
||||
when {
|
||||
file == null -> Action.Keep(item)
|
||||
file.signature == item.signature -> Action.Keep(item)
|
||||
file.resolvedCount == 0 -> Action.Keep(item)
|
||||
else -> Action.Replace(item, file)
|
||||
}
|
||||
}
|
||||
val trackedUris = tracked.mapTo(mutableSetOf()) { it.sourceUri }
|
||||
val createActions =
|
||||
discovered
|
||||
.filter { it.uri !in trackedUris && it.resolvedCount > 0 }
|
||||
.map { Action.Create(it) }
|
||||
return trackedActions + createActions
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ import org.oxycblt.musikr.Music
|
||||
*/
|
||||
@Database(
|
||||
entities = [PlaylistInfo::class, PlaylistSong::class, PlaylistSongCrossRef::class],
|
||||
version = 75,
|
||||
version = 76,
|
||||
exportSchema = false,
|
||||
)
|
||||
@TypeConverters(Music.UID.TypeConverters::class)
|
||||
@@ -117,7 +117,15 @@ internal abstract class PlaylistDatabase : RoomDatabase() {
|
||||
washUids(db, "PlaylistInfo", "playlistUid")
|
||||
washUids(db, "PlaylistSongCrossRef", "playlistUid")
|
||||
}
|
||||
}
|
||||
},
|
||||
object : Migration(75, 76) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE PlaylistInfo ADD COLUMN sourceUri TEXT")
|
||||
db.execSQL(
|
||||
"ALTER TABLE PlaylistInfo ADD COLUMN sourceSignature INTEGER"
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
.fallbackToDestructiveMigration(true)
|
||||
.build()
|
||||
@@ -143,6 +151,16 @@ internal abstract class PlaylistDao {
|
||||
@Query("SELECT * FROM PlaylistInfo")
|
||||
abstract suspend fun readRawPlaylists(): List<RawPlaylist>
|
||||
|
||||
/** Read the [PlaylistInfo] of playlists with a source file, for reconciliation. */
|
||||
@Query("SELECT * FROM PlaylistInfo WHERE sourceUri IS NOT NULL AND sourceSignature IS NOT NULL")
|
||||
abstract suspend fun readTrackedInfos(): List<PlaylistInfo>
|
||||
|
||||
/** Update the name and source signature of a tracked playlist after a re-import. */
|
||||
@Query(
|
||||
"UPDATE PlaylistInfo SET name = :name, sourceSignature = :signature WHERE playlistUid = :playlistUid"
|
||||
)
|
||||
abstract suspend fun updateTrackedInfo(playlistUid: Music.UID, name: String, signature: Long)
|
||||
|
||||
/**
|
||||
* Create a new playlist.
|
||||
*
|
||||
|
||||
@@ -46,7 +46,15 @@ internal data class RawPlaylist(
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@Entity internal data class PlaylistInfo(@PrimaryKey val playlistUid: Music.UID, val name: String)
|
||||
@Entity
|
||||
internal data class PlaylistInfo(
|
||||
@PrimaryKey val playlistUid: Music.UID,
|
||||
val name: String,
|
||||
/** The document URI of the file this playlist was imported from. Null if unmanaged. */
|
||||
val sourceUri: String? = null,
|
||||
/** The content signature of the source file at import time. Null if unmanaged. */
|
||||
val sourceSignature: Long? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Song information corresponding to a [RawPlaylist] entry.
|
||||
|
||||
@@ -23,11 +23,32 @@ import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.playlist.PlaylistFile
|
||||
import org.oxycblt.musikr.playlist.PlaylistHandle
|
||||
import org.oxycblt.musikr.playlist.PlaylistReconciler
|
||||
import org.oxycblt.musikr.playlist.SongPointer
|
||||
import org.oxycblt.musikr.util.unlikelyToBeNull
|
||||
|
||||
abstract class StoredPlaylists {
|
||||
internal abstract suspend fun new(name: String, songs: List<Song>): PlaylistHandle
|
||||
|
||||
/** Create a playlist tracked against a source file. */
|
||||
internal abstract suspend fun newTracked(
|
||||
name: String,
|
||||
songUids: List<Music.UID>,
|
||||
sourceUri: String,
|
||||
sourceSignature: Long,
|
||||
): PlaylistHandle
|
||||
|
||||
/** Replace a tracked playlist with its re-imported file: new name, songs, and signature. */
|
||||
internal abstract suspend fun replaceTracked(
|
||||
playlistUid: Music.UID,
|
||||
name: String,
|
||||
songUids: List<Music.UID>,
|
||||
sourceSignature: Long,
|
||||
)
|
||||
|
||||
/** Read the tracking identities of playlists with a source file. */
|
||||
internal abstract suspend fun readTracked(): List<PlaylistReconciler.Tracked>
|
||||
|
||||
internal abstract suspend fun read(): List<PlaylistFile>
|
||||
|
||||
companion object {
|
||||
@@ -43,6 +64,42 @@ private class StoredPlaylistsImpl(private val playlistDao: PlaylistDao) : Stored
|
||||
return StoredPlaylistHandle(info, playlistDao)
|
||||
}
|
||||
|
||||
override suspend fun newTracked(
|
||||
name: String,
|
||||
songUids: List<Music.UID>,
|
||||
sourceUri: String,
|
||||
sourceSignature: Long,
|
||||
): PlaylistHandle {
|
||||
val info =
|
||||
PlaylistInfo(
|
||||
Music.UID.auxio(Music.UID.Item.PLAYLIST),
|
||||
name,
|
||||
sourceUri = sourceUri,
|
||||
sourceSignature = sourceSignature,
|
||||
)
|
||||
playlistDao.insertPlaylist(RawPlaylist(info, songUids.map { PlaylistSong(it) }))
|
||||
return StoredPlaylistHandle(info, playlistDao)
|
||||
}
|
||||
|
||||
override suspend fun replaceTracked(
|
||||
playlistUid: Music.UID,
|
||||
name: String,
|
||||
songUids: List<Music.UID>,
|
||||
sourceSignature: Long,
|
||||
) {
|
||||
playlistDao.replacePlaylistSongs(playlistUid, songUids.map { PlaylistSong(it) })
|
||||
playlistDao.updateTrackedInfo(playlistUid, name, sourceSignature)
|
||||
}
|
||||
|
||||
override suspend fun readTracked() =
|
||||
playlistDao.readTrackedInfos().map {
|
||||
PlaylistReconciler.Tracked(
|
||||
it.playlistUid,
|
||||
unlikelyToBeNull(it.sourceUri),
|
||||
unlikelyToBeNull(it.sourceSignature),
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun read() =
|
||||
playlistDao.readRawPlaylists().map {
|
||||
PlaylistFile(
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
package org.oxycblt.musikr.playlist.m3u
|
||||
|
||||
import android.content.Context
|
||||
import java.io.BufferedReader
|
||||
import java.io.BufferedWriter
|
||||
import java.io.InputStream
|
||||
@@ -27,11 +26,8 @@ import java.io.OutputStream
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.Volume
|
||||
import org.oxycblt.musikr.fs.path.VolumeManager
|
||||
import org.oxycblt.musikr.playlist.ExportConfig
|
||||
import org.oxycblt.musikr.playlist.ImportedPlaylist
|
||||
import org.oxycblt.musikr.playlist.PossiblePaths
|
||||
import org.oxycblt.musikr.playlist.PlaylistPathResolver
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import org.oxycblt.musikr.util.correctWhitespace
|
||||
import org.oxycblt.musikr.util.unlikelyToBeNull
|
||||
@@ -43,15 +39,13 @@ import org.oxycblt.musikr.util.unlikelyToBeNull
|
||||
*/
|
||||
abstract class M3U {
|
||||
/**
|
||||
* Reads an M3U file from the given [stream] and returns a [ImportedPlaylist] containing the
|
||||
* paths to the files listed in the M3U file.
|
||||
* Reads an M3U file from the given [stream] and returns the parsed [ParsedM3U]. Entries are
|
||||
* interpreted but not resolved against the library — see [PlaylistPathResolver].
|
||||
*
|
||||
* @param stream The stream to read the M3U file from.
|
||||
* @param workingDirectory The directory that the M3U file is contained in. This is used to
|
||||
* resolve relative paths.
|
||||
* @return An [ImportedPlaylist] containing the paths to the files listed in the M3U file,
|
||||
* @return The [ParsedM3U], or null if the file contained no entries.
|
||||
*/
|
||||
internal abstract fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist?
|
||||
internal abstract fun read(stream: InputStream): ParsedM3U?
|
||||
|
||||
/**
|
||||
* Writes the given [playlist] to the given [outputStream] in the M3U format,.
|
||||
@@ -73,15 +67,22 @@ abstract class M3U {
|
||||
/** The mime type used for M3U files by the android system. */
|
||||
const val MIME_TYPE = "audio/x-mpegurl"
|
||||
|
||||
internal fun from(context: Context): M3U = M3UImpl(VolumeManager.from(context))
|
||||
internal fun new(): M3U = M3UImpl()
|
||||
}
|
||||
}
|
||||
|
||||
private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
|
||||
override fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist? {
|
||||
val volumes = volumeManager.getVolumes()
|
||||
/**
|
||||
* The raw result of parsing an M3U file.
|
||||
*
|
||||
* @property name The playlist name, if a #PLAYLIST entry was present.
|
||||
* @property entries The parsed entries in file order.
|
||||
*/
|
||||
internal data class ParsedM3U(val name: String?, val entries: List<PlaylistPathResolver.Entry>)
|
||||
|
||||
private class M3UImpl : M3U() {
|
||||
override fun read(stream: InputStream): ParsedM3U? {
|
||||
val reader = BufferedReader(InputStreamReader(stream))
|
||||
val paths = mutableListOf<PossiblePaths>()
|
||||
val entries = mutableListOf<PlaylistPathResolver.Entry>()
|
||||
var name: String? = null
|
||||
|
||||
consumeFile@ while (true) {
|
||||
@@ -112,63 +113,43 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
|
||||
}
|
||||
}
|
||||
|
||||
// There is basically no formal specification of file paths in M3U, and it differs
|
||||
// based on the programs that generated it. I more or less have to consider any possible
|
||||
// interpretation as valid.
|
||||
val interpretations = interpretPath(unlikelyToBeNull(path))
|
||||
val possibilities = interpretations.flatMap {
|
||||
expandInterpretation(it, workingDirectory, volumes)
|
||||
}
|
||||
|
||||
paths.add(possibilities)
|
||||
// One interpretation per line: resolution against the library happens later, in
|
||||
// PlaylistPathResolver.
|
||||
entries.add(interpretLine(unlikelyToBeNull(path)))
|
||||
}
|
||||
|
||||
return if (paths.isNotEmpty()) {
|
||||
ImportedPlaylist(name, paths)
|
||||
return if (entries.isNotEmpty()) {
|
||||
ParsedM3U(name, entries)
|
||||
} else {
|
||||
// Couldn't get anything useful out of this file.
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private data class InterpretedPath(val components: Components, val likelyAbsolute: Boolean)
|
||||
|
||||
private fun interpretPath(path: String): List<InterpretedPath> =
|
||||
/**
|
||||
* Interpret a line as an entry. There is no formal specification of M3U paths, so the form
|
||||
* detection is heuristic: unix or windows, absolute or relative. Bare lines parse by
|
||||
* whichever separator they contain.
|
||||
*/
|
||||
private fun interpretLine(path: String): PlaylistPathResolver.Entry =
|
||||
when {
|
||||
path.startsWith('/') -> listOf(InterpretedPath(Components.parseUnix(path), true))
|
||||
path.startsWith("./") -> listOf(InterpretedPath(Components.parseUnix(path), false))
|
||||
path.startsWith('/') ->
|
||||
PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = true)
|
||||
path.startsWith("./") ->
|
||||
PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
|
||||
path.matches(WINDOWS_VOLUME_PREFIX_REGEX) ->
|
||||
listOf(InterpretedPath(Components.parseWindows(path.substring(2)), true))
|
||||
path.startsWith("\\") -> listOf(InterpretedPath(Components.parseWindows(path), true))
|
||||
path.startsWith(".\\") -> listOf(InterpretedPath(Components.parseWindows(path), false))
|
||||
else ->
|
||||
listOf(
|
||||
InterpretedPath(Components.parseUnix(path), false),
|
||||
InterpretedPath(Components.parseWindows(path), true),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseWindows(path.substring(2)), absolute = true
|
||||
)
|
||||
path.startsWith("\\") ->
|
||||
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = true)
|
||||
path.startsWith(".\\") ->
|
||||
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
|
||||
'\\' in path ->
|
||||
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
|
||||
else -> PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
|
||||
}
|
||||
|
||||
private fun expandInterpretation(
|
||||
path: InterpretedPath,
|
||||
workingDirectory: Path,
|
||||
volumes: List<Volume>,
|
||||
): List<Path> {
|
||||
val absoluteInterpretation = Path(workingDirectory.volume, path.components)
|
||||
val relativeInterpretation =
|
||||
Path(workingDirectory.volume, path.components.absoluteTo(workingDirectory.components))
|
||||
val volumeExactMatch = volumes.find { it.components?.contains(path.components) == true }
|
||||
val volumeInterpretation = volumeExactMatch?.let {
|
||||
val components =
|
||||
unlikelyToBeNull(volumeExactMatch.components).containing(path.components)
|
||||
Path(volumeExactMatch, components)
|
||||
}
|
||||
return if (path.likelyAbsolute) {
|
||||
listOfNotNull(volumeInterpretation, absoluteInterpretation, relativeInterpretation)
|
||||
} else {
|
||||
listOfNotNull(relativeInterpretation, volumeInterpretation, absoluteInterpretation)
|
||||
}
|
||||
}
|
||||
|
||||
override fun write(
|
||||
playlist: Playlist,
|
||||
outputStream: OutputStream,
|
||||
@@ -232,22 +213,6 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
|
||||
newLine()
|
||||
}
|
||||
|
||||
private fun Components.absoluteTo(workingDirectory: Components): Components {
|
||||
var absoluteComponents = workingDirectory
|
||||
for (component in components) {
|
||||
when (component) {
|
||||
// Parent specifier, go "back" one directory (in practice cleave off the last
|
||||
// component)
|
||||
".." -> absoluteComponents = absoluteComponents.parent()
|
||||
// Current directory, the components are already there.
|
||||
"." -> {}
|
||||
// New directory, add it
|
||||
else -> absoluteComponents = absoluteComponents.child(component)
|
||||
}
|
||||
}
|
||||
return absoluteComponents
|
||||
}
|
||||
|
||||
private fun Components.relativeTo(workingDirectory: Components): Components {
|
||||
// We want to find the common prefix of the working directory and path, and then
|
||||
// and them combine them with the correct relative elements to make sure they
|
||||
|
||||
@@ -253,15 +253,18 @@ internal fun Metadata.isCompilation() =
|
||||
?: id3v2["TXXX:COMPILATION"]
|
||||
?: id3v2["TXXX:ITUNESCOMPILATION"]) == listOf("1")
|
||||
|
||||
// ReplayGain information
|
||||
// ReplayGain information. APE is preferred over the other tag formats: it is the only ReplayGain
|
||||
// carrier in some libraries, and where it coexists with ID3v2 it is the more deliberate choice.
|
||||
internal fun Metadata.replayGainTrackAdjustment() =
|
||||
(xiph["R128_TRACK_GAIN"]?.parseR128Adjustment()
|
||||
(ape["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
|
||||
?: xiph["R128_TRACK_GAIN"]?.parseR128Adjustment()
|
||||
?: xiph["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
|
||||
?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
|
||||
?: id3v2["TXXX:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment())
|
||||
|
||||
internal fun Metadata.replayGainAlbumAdjustment() =
|
||||
(xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment()
|
||||
(ape["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
|
||||
?: xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment()
|
||||
?: xiph["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
|
||||
?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
|
||||
?: id3v2["TXXX:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment())
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* PlaylistPathResolverTest.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.musikr.playlist
|
||||
|
||||
import android.content.Context
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.Volume
|
||||
|
||||
class PlaylistPathResolverTest {
|
||||
@Test
|
||||
fun resolve_relativeEntries_locksMusicLocationRoot() {
|
||||
val volume = FakeVolume()
|
||||
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
|
||||
val musicRoot = Path(volume, Components.parseUnix("Music"))
|
||||
val library =
|
||||
setOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
)
|
||||
val entries =
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
|
||||
),
|
||||
)
|
||||
|
||||
val resolved =
|
||||
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
|
||||
it in library
|
||||
}
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
),
|
||||
resolved,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolve_dotPrefixedEntries_resolveLikeBareOnes() {
|
||||
val volume = FakeVolume()
|
||||
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
|
||||
val musicRoot = Path(volume, Components.parseUnix("Music"))
|
||||
val library =
|
||||
setOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
)
|
||||
val entries =
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("./Library/Artist/a.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("./Library/Artist/b.mp3"), absolute = false
|
||||
),
|
||||
)
|
||||
|
||||
val resolved =
|
||||
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
|
||||
it in library
|
||||
}
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
),
|
||||
resolved,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolve_dotdotEntries_escapeThePlaylistDirectory() {
|
||||
val volume = FakeVolume()
|
||||
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
|
||||
val musicRoot = Path(volume, Components.parseUnix("Music"))
|
||||
val library =
|
||||
setOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
)
|
||||
val entries =
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("../Library/Artist/a.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("../Library/Artist/b.mp3"), absolute = false
|
||||
),
|
||||
)
|
||||
|
||||
val resolved =
|
||||
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
|
||||
it in library
|
||||
}
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
),
|
||||
resolved,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolve_ambiguousEntries_lockTheFirstRootInOrder() {
|
||||
val volume = FakeVolume()
|
||||
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
|
||||
val musicRoot = Path(volume, Components.parseUnix("Music"))
|
||||
val library =
|
||||
setOf(
|
||||
Path(volume, Components.parseUnix("Music/Playlists/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
)
|
||||
val entries =
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
|
||||
)
|
||||
)
|
||||
|
||||
val resolved =
|
||||
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
|
||||
it in library
|
||||
}
|
||||
|
||||
assertEquals(
|
||||
listOf(Path(volume, Components.parseUnix("Music/Playlists/Library/Artist/a.mp3"))),
|
||||
resolved,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolve_foreignAbsoluteEntries_stripLeadingSegmentsToLock() {
|
||||
val volume = FakeVolume()
|
||||
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
|
||||
val musicRoot = Path(volume, Components.parseUnix("Music"))
|
||||
val library =
|
||||
setOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
)
|
||||
// Written on another machine: C:\Users\me\Music\... with the volume prefix consumed.
|
||||
val entries =
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseWindows("Users\\me\\Music\\Library\\Artist\\a.mp3"),
|
||||
absolute = true,
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseWindows("Users\\me\\Music\\Library\\Artist\\b.mp3"),
|
||||
absolute = true,
|
||||
),
|
||||
)
|
||||
|
||||
val resolved =
|
||||
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
|
||||
it in library
|
||||
}
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
),
|
||||
resolved,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolve_partiallyMissingEntries_resolveTheSurvivors() {
|
||||
val volume = FakeVolume()
|
||||
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
|
||||
val musicRoot = Path(volume, Components.parseUnix("Music"))
|
||||
val library =
|
||||
setOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
|
||||
)
|
||||
val entries =
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/c.mp3"), absolute = false
|
||||
),
|
||||
)
|
||||
|
||||
val resolved =
|
||||
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
|
||||
it in library
|
||||
}
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
|
||||
),
|
||||
resolved,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolve_firstEntryMissing_probeAdvancesAndLocks() {
|
||||
val volume = FakeVolume()
|
||||
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
|
||||
val musicRoot = Path(volume, Components.parseUnix("Music"))
|
||||
val library =
|
||||
setOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
|
||||
)
|
||||
val entries =
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/c.mp3"), absolute = false
|
||||
),
|
||||
)
|
||||
|
||||
val resolved =
|
||||
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
|
||||
it in library
|
||||
}
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
|
||||
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
|
||||
),
|
||||
resolved,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolve_unresolvableEntries_failAsNull() {
|
||||
val volume = FakeVolume()
|
||||
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
|
||||
val musicRoot = Path(volume, Components.parseUnix("Music"))
|
||||
val library =
|
||||
setOf(Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")))
|
||||
val entries =
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Elsewhere/Artist/x.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Elsewhere/Artist/y.mp3"), absolute = false
|
||||
),
|
||||
)
|
||||
|
||||
val resolved =
|
||||
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
|
||||
it in library
|
||||
}
|
||||
|
||||
assertEquals(null, resolved)
|
||||
}
|
||||
|
||||
private class FakeVolume : Volume.External {
|
||||
override val mediaStoreName = "fake"
|
||||
override val id = "fake"
|
||||
override val components = Components.parseUnix("storage/emulated/0")
|
||||
|
||||
override fun resolveName(context: Context) = "fake"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* PlaylistReconcilerTest.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.musikr.playlist
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.oxycblt.musikr.Music
|
||||
|
||||
class PlaylistReconcilerTest {
|
||||
@Test
|
||||
fun reconcile_unchangedFile_keepsTheStoredPlaylist() {
|
||||
val tracked = tracked(42L)
|
||||
val discovered = discovered(42L, resolvedCount = 1)
|
||||
|
||||
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
|
||||
|
||||
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reconcile_changedFile_replacesTheStoredPlaylist() {
|
||||
val tracked = tracked(42L)
|
||||
val discovered = discovered(43L, resolvedCount = 1)
|
||||
|
||||
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
|
||||
|
||||
assertEquals(listOf(PlaylistReconciler.Action.Replace(tracked, discovered)), actions)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reconcile_deletedFile_keepsTheStoredPlaylist() {
|
||||
val tracked = tracked(42L)
|
||||
|
||||
val actions = PlaylistReconciler.reconcile(listOf(tracked), emptyList())
|
||||
|
||||
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reconcile_changedFileWithNothingResolved_keepsTheStoredPlaylist() {
|
||||
val tracked = tracked(42L)
|
||||
val discovered = discovered(43L, resolvedCount = 0)
|
||||
|
||||
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
|
||||
|
||||
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reconcile_newFile_createsATrackedPlaylist() {
|
||||
val discovered = discovered(42L, resolvedCount = 1)
|
||||
|
||||
val actions = PlaylistReconciler.reconcile(emptyList(), listOf(discovered))
|
||||
|
||||
assertEquals(listOf(PlaylistReconciler.Action.Create(discovered)), actions)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reconcile_newFileWithNothingResolved_doesNothing() {
|
||||
val discovered = discovered(42L, resolvedCount = 0)
|
||||
|
||||
val actions = PlaylistReconciler.reconcile(emptyList(), listOf(discovered))
|
||||
|
||||
assertEquals(emptyList<PlaylistReconciler.Action>(), actions)
|
||||
}
|
||||
|
||||
private fun tracked(signature: Long) =
|
||||
PlaylistReconciler.Tracked(
|
||||
Music.UID.auxio(Music.UID.Item.PLAYLIST),
|
||||
"content://tree/playlists/x.m3u",
|
||||
signature,
|
||||
)
|
||||
|
||||
private fun discovered(signature: Long, resolvedCount: Int) =
|
||||
PlaylistReconciler.Discovered("content://tree/playlists/x.m3u", signature, resolvedCount)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* M3UTest.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.musikr.playlist.m3u
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.playlist.PlaylistPathResolver
|
||||
|
||||
class M3UTest {
|
||||
@Test
|
||||
fun read_relativeAndForeignAbsoluteLines_produceEntries() {
|
||||
val text =
|
||||
"""
|
||||
#EXTM3U
|
||||
Library/Artist/a.mp3
|
||||
./Library/Artist/b.mp3
|
||||
C:\Users\me\Music\Library\Artist\c.mp3
|
||||
"""
|
||||
.trimIndent()
|
||||
|
||||
val imported = M3U.new().read(text.byteInputStream())
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("./Library/Artist/b.mp3"), absolute = false
|
||||
),
|
||||
PlaylistPathResolver.Entry(
|
||||
Components.parseUnix("Users/me/Music/Library/Artist/c.mp3"), absolute = true
|
||||
),
|
||||
),
|
||||
imported?.entries,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun read_playlistMetadata_producesName() {
|
||||
val text =
|
||||
"""
|
||||
#EXTM3U
|
||||
#PLAYLIST:My Mix
|
||||
Library/Artist/a.mp3
|
||||
"""
|
||||
.trimIndent()
|
||||
|
||||
val imported = M3U.new().read(text.byteInputStream())
|
||||
|
||||
assertEquals("My Mix", imported?.name)
|
||||
}
|
||||
}
|
||||
@@ -321,10 +321,22 @@ class TagFieldsTest {
|
||||
assertEquals(listOf("Classical", "Ambient"), metadata.genreNames())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun metadata_replayGainTrack_apePreferredOverId3v2() {
|
||||
val metadata =
|
||||
createTestMetadata(
|
||||
id3v2Tags = mapOf("TXXX:REPLAYGAIN_TRACK_GAIN" to listOf("-1.0 dB")),
|
||||
apeTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("-5.175 dB")),
|
||||
)
|
||||
|
||||
assertEquals(-5.175f, metadata.replayGainTrackAdjustment()!!, 0.0001f)
|
||||
}
|
||||
|
||||
private fun createTestMetadata(
|
||||
id3v2Tags: Map<String, List<String>> = emptyMap(),
|
||||
xiphTags: Map<String, List<String>> = emptyMap(),
|
||||
mp4Tags: Map<String, List<String>> = emptyMap(),
|
||||
apeTags: Map<String, List<String>> = emptyMap(),
|
||||
cover: ByteArray? = null,
|
||||
durationMs: Long = 1000,
|
||||
bitrateKbps: Int = 320,
|
||||
@@ -332,6 +344,6 @@ class TagFieldsTest {
|
||||
mimeType: String = "audio/mpeg",
|
||||
): Metadata {
|
||||
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
|
||||
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties)
|
||||
return Metadata(id3v2Tags, xiphTags, mp4Tags, apeTags, cover, properties)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,6 +185,6 @@ class TagParserTest {
|
||||
mimeType: String = "audio/mpeg",
|
||||
): Metadata {
|
||||
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
|
||||
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties)
|
||||
return Metadata(id3v2Tags, xiphTags, mp4Tags, emptyMap(), cover, properties)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,6 +243,6 @@ class TagParsingEdgeCasesTest {
|
||||
mimeType: String = "audio/mpeg",
|
||||
): Metadata {
|
||||
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
|
||||
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties)
|
||||
return Metadata(id3v2Tags, xiphTags, mp4Tags, emptyMap(), cover, properties)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user