Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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.3"
|
||||
versionCode 78
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user