Author SHA1 Message Date
jay 442a066136 chore: release v4.1.5-fork.3
Build / build (push) Successful in 5m42s
Release / release (push) Successful in 6m41s
2026-11-12 16:57:53 -05:00
jay 1f3e319552 list: let the swipe reveal stretch to three cell widths 2026-11-12 16:52:51 -05:00
jay 7efa7bff59 list: keep the swipe underlay visible through the spring-back 2026-11-12 16:50:07 -05:00
jay 037c5b1382 list: commit swipes on spring-back instead of flying off 2026-11-12 16:48:02 -05:00
jay 93c8f8f05f list: zero change-animation duration on swipeable lists instead 2026-11-12 16:44:06 -05:00
jay a251d5fc2d list: disable change cross-fades on swipeable lists 2026-11-12 16:39:27 -05:00
jay 9f2b8894df list: restore swipe recovery by dropping the payload rebind 2026-11-12 16:36:43 -05:00
jay 18332d8478 list: rubber-band the swipe reveal, mute swipes while playlist-editing 2026-11-12 16:32:39 -05:00
jay 94170a8079 list: square swipe reveal with resistance, Lucide action icons 2026-11-12 16:21:35 -05:00
jay a1615f3c1b list: swipe song rows right to queue, left to play next 2026-11-12 16:08:59 -05:00
jay f1e999effc queue: pad the sheet's below-screen overflow so the empty hint centers 2026-11-12 15:58:19 -05:00
jay 9c6380489c queue: hide the drag handle on the playing row 2026-11-12 15:52:20 -05:00
jay 1b5134f854 playback: never lose pager commands to event overwrite 2026-11-12 15:43:43 -05:00
jay 642a3add27 playback: instrument the cover pager's command path 2026-11-12 15:33:45 -05:00
jay 6e2a260df9 queue: update the drawer with precise per-change instructions 2026-11-12 15:32:04 -05:00
jay 0d6a3240ad playback: navigate to the parent deterministically from the header 2026-11-12 14:58:44 -05:00
jay 23135fe80d playback: notify listeners only after deck bookkeeping settles 2026-11-12 14:55:17 -05:00
jay a8e898d5e9 playback: navigate via the now-playing header tap 2026-11-12 14:51:20 -05:00
jay c784b4cebd queue: render the deck only, with clear button and Now Playing header 2026-11-12 13:54:55 -05:00
jay ecc6f34a02 playback: publish the deck to the queue drawer 2026-11-12 13:40:00 -05:00
jay b7c425b410 playback: add moveDeckItems for queue-drawer drags 2026-11-12 13:34:34 -05:00
jay 7c130ac6c3 playback: add removeDeckItem for queue-drawer swipes 2026-11-12 13:31:53 -05:00
jay d17f789dd2 playback: add gotoDeck for queue-drawer taps 2026-11-12 13:28:48 -05:00
jay a19bfbaddf playback: add clearQueue for the drawer's clear button 2026-11-12 13:11:01 -05:00
23 changed files with 1111 additions and 133 deletions
+2 -2
View File
@@ -16,8 +16,8 @@ android {
defaultConfig { defaultConfig {
applicationId namespace applicationId namespace
versionName "4.1.5-fork.2" versionName "4.1.5-fork.3"
versionCode 77 versionCode 78
minSdk min_sdk minSdk min_sdk
// randomly flickers between deprecated and required depending on what mood my gradle is in // randomly flickers between deprecated and required depending on what mood my gradle is in
@@ -29,6 +29,7 @@ import androidx.core.view.ViewCompat
import androidx.core.view.isInvisible import androidx.core.view.isInvisible
import androidx.core.view.isVisible import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.findNavController import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import com.google.android.material.R as MR 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.PlaybackBottomSheetBehavior
import org.oxycblt.auxio.playback.PlaybackViewModel import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.queue.QueueBottomSheetBehavior 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.DialogAwareNavigationListener
import org.oxycblt.auxio.ui.UISettings import org.oxycblt.auxio.ui.UISettings
import org.oxycblt.auxio.ui.ViewBindingFragment 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.auxio.util.unlikelyToBeNull
import org.oxycblt.musikr.Music import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song 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 import timber.log.Timber as L
/** /**
@@ -88,6 +95,7 @@ class MainFragment :
private val homeModel: HomeViewModel by activityViewModels() private val homeModel: HomeViewModel by activityViewModels()
private val listModel: ListViewModel by activityViewModels() private val listModel: ListViewModel by activityViewModels()
private val playbackModel: PlaybackViewModel by activityViewModels() private val playbackModel: PlaybackViewModel by activityViewModels()
private val queueModel: QueueViewModel by activityViewModels()
private var sheetBackCallback: SheetBackPressedCallback? = null private var sheetBackCallback: SheetBackPressedCallback? = null
private var detailBackCallback: DetailBackPressedCallback? = null private var detailBackCallback: DetailBackPressedCallback? = null
private var selectionBackCallback: SelectionBackPressedCallback? = null private var selectionBackCallback: SelectionBackPressedCallback? = null
@@ -121,6 +129,9 @@ class MainFragment :
binding.queueSheet.coordinatorLayoutBehavior as QueueBottomSheetBehavior? binding.queueSheet.coordinatorLayoutBehavior as QueueBottomSheetBehavior?
queueSheetBehavior?.uiSettings = uiSettings queueSheetBehavior?.uiSettings = uiSettings
// --- QUEUE SHEET SETUP ---
binding.queueClear.setOnClickListener { queueModel.clearQueue() }
elevationNormal = binding.context.getDimen(MR.dimen.m3_sys_elevation_level1) elevationNormal = binding.context.getDimen(MR.dimen.m3_sys_elevation_level1)
// Currently all back press callbacks are handled in MainFragment, as it's not guaranteed // 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 // FIXME: This is a consequence of sharing events across several consumers. There has to be
// a better way of doing this. // a better way of doing this.
collect(detailModel.toShow.flow, ::handleShow) collect(detailModel.toShow.flow, ::handleShow)
collect(playbackModel.parentNavigation.flow, ::handleParentNavigation)
collectImmediately(detailModel.editedPlaylist, detailBackCallback::invalidateEnabled) collectImmediately(detailModel.editedPlaylist, detailBackCallback::invalidateEnabled)
collectImmediately(homeModel.showOuter.flow, ::handleShowOuter) collectImmediately(homeModel.showOuter.flow, ::handleShowOuter)
collectImmediately(homeModel.currentTabType, ::updateCurrentTab) collectImmediately(homeModel.currentTabType, ::updateCurrentTab)
@@ -222,6 +234,7 @@ class MainFragment :
collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled) collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled)
collectImmediately(playbackModel.song, ::updateSong) collectImmediately(playbackModel.song, ::updateSong)
collectImmediately(playbackModel.openPanel.flow, ::handlePanel) collectImmediately(playbackModel.openPanel.flow, ::handlePanel)
collectImmediately(queueModel.queue, ::updateQueueClearButton)
} }
override fun onStart() { override fun onStart() {
@@ -555,6 +568,25 @@ class MainFragment :
binding.sheetScrim.isInvisible = !open 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?) { private fun handleShow(show: Show?) {
when (show) { when (show) {
is Show.SongAlbumDetails, is Show.SongAlbumDetails,
@@ -624,6 +656,10 @@ class MainFragment :
} }
} }
private fun updateQueueClearButton(queue: List<Song>) {
requireBinding().queueClear.isVisible = queue.isNotEmpty()
}
private fun tryClosePlaybackPanel() { private fun tryClosePlaybackPanel() {
val binding = requireBinding() val binding = requireBinding()
val playbackSheetBehavior = val playbackSheetBehavior =
@@ -25,6 +25,7 @@ import android.view.View
import androidx.core.view.updatePadding import androidx.core.view.updatePadding
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.navigation.findNavController import androidx.navigation.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import com.google.android.material.appbar.AppBarLayout import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.transition.MaterialSharedAxis import com.google.android.material.transition.MaterialSharedAxis
import kotlin.math.abs 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.detail.list.DetailListAdapter
import org.oxycblt.auxio.list.ListFragment import org.oxycblt.auxio.list.ListFragment
import org.oxycblt.auxio.list.ListViewModel import org.oxycblt.auxio.list.ListViewModel
import org.oxycblt.auxio.list.recycler.SwipeActionsCallback
import org.oxycblt.auxio.music.MusicViewModel import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.playback.PlaybackViewModel import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.util.getDimenPixels import org.oxycblt.auxio.util.getDimenPixels
@@ -122,6 +124,24 @@ abstract class DetailFragment<P : MusicParent, C : Music> :
binding.detailRecycler.apply { adapter = getDetailListAdapter() } 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) 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 { binding.playbackToolbar.apply {
setNavigationOnClickListener { playbackModel.openMain() } setNavigationOnClickListener { playbackModel.openMain() }
setOnMenuItemClickListener(this@PlaybackPanelFragment) setOnMenuItemClickListener(this@PlaybackPanelFragment)
// Tapping the Now Playing header navigates to the parent (album, playlist, etc.).
setOnClickListener { playbackModel.navigateToParent() }
} }
binding.playbackPager?.apply { binding.playbackPager?.apply {
@@ -119,7 +121,7 @@ class PlaybackPanelFragment :
UserAwarePagerCallback(this) { UserAwarePagerCallback(this) {
// Posting the queue goto command prevents the seekbar pos from desyncing // Posting the queue goto command prevents the seekbar pos from desyncing
// from the song's duration, which creates a visual flicker in the seekbar. // from the song's duration, which creates a visual flicker in the seekbar.
post { queueModel.goto(it) } post { queueModel.gotoTimelinePosition(it) }
} }
.also { it.attach() } .also { it.attach() }
setPageTransformer(CarouselTransformer()) setPageTransformer(CarouselTransformer())
@@ -275,8 +277,9 @@ class PlaybackPanelFragment :
private fun updateParent(parent: MusicParent?) { private fun updateParent(parent: MusicParent?) {
val binding = requireBinding() val binding = requireBinding()
val context = requireContext() val context = requireContext()
binding.playbackToolbar.subtitle = // No subtitle without a parent: the header carries a tap action, so it must not name
parent?.run { name.resolve(context) } ?: context.getString(R.string.lbl_all_songs) // a destination it cannot navigate to.
binding.playbackToolbar.subtitle = parent?.run { name.resolve(context) }
} }
private fun updatePosition(positionDs: Long) { private fun updatePosition(positionDs: Long) {
@@ -344,8 +347,9 @@ class PlaybackPanelFragment :
// but only on some devices. // but only on some devices.
val binding = binding ?: return val binding = binding ?: return
val command = playbackModel.pagerCommand.consume() val commands = playbackModel.drainPagerCommands()
if (command == null) { 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 // This probably shouldn't happen in practice, as QueueViewModel directly
// attaches to PlaybackStateManager and will basically always initialize // attaches to PlaybackStateManager and will basically always initialize
// with a command as a result. // with a command as a result.
@@ -357,24 +361,28 @@ class PlaybackPanelFragment :
return return
} }
if (command.update != null) { // Apply every command in order; each carries the queue state it was made against, so a
// queue needs to be updated. // burst (like a drain's removal plus scroll) cannot lose its intermediate step.
coverPagerAdapter.update(queue.queue, command.update) for ((commandQueue, command) in commands) {
} if (command.update != null) {
// queue needs to be updated.
if (command.scroll != null) { coverPagerAdapter.update(commandQueue.queue, command.update)
// 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
} }
if (command.update == null && abs(delta) == 1) {
binding.playbackPager.smoothScrollByPageTo(command.scroll) if (command.scroll != null) {
} else { // we need to scroll, however the smooth scroll only really looks best
binding.playbackPager.setCurrentItem(command.scroll, false) // 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> val openPanel: Event<OpenPanel>
field = MutableEvent<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)) private val _pagerQueue = MutableStateFlow(PagerQueue(listOf(), 0))
/** The current queue in a special bundled format suitable for the cover ViewPager2. */ /** The current queue in a special bundled format suitable for the cover ViewPager2. */
val pagerQueue: StateFlow<PagerQueue> = _pagerQueue val pagerQueue: StateFlow<PagerQueue> = _pagerQueue
/** Specialized ViewPager2-friendly queue commands */ // Manager callbacks can arrive on any thread; the panel drains on the main thread.
val pagerCommand: Event<PagerCommand> private val pagerLock = Any()
field = MutableEvent<PagerCommand>() 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 * 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() positionDs.value = playbackManager.progression.calculateElapsedPositionMs().msToDs()
song.value = playbackManager.currentSong song.value = playbackManager.currentSong
pagerCommand.put(PagerCommand(update = null, scroll = index)) updatePagerQueue(_pagerQueue.value.queue, index, PagerCommand(update = null, scroll = index))
_pagerQueue.value = _pagerQueue.value.copy(index = index)
} }
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) { override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
@@ -148,21 +171,21 @@ constructor(
song.value = playbackManager.currentSong song.value = playbackManager.currentSong
} }
pagerCommand.put( updatePagerQueue(
queue,
index,
PagerCommand( PagerCommand(
update = change.instructions, update = change.instructions,
scroll = index.takeIf { change.type != QueueChange.Type.MAPPING }, 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) { override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) {
L.d("Queue completely changed, updating current song") L.d("Queue completely changed, updating current song")
this.isShuffled.value = isShuffled this.isShuffled.value = isShuffled
pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index)) updatePagerQueue(queue, index, PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
_pagerQueue.value = PagerQueue(queue = queue, index = index)
} }
override fun onNewPlayback( override fun onNewPlayback(
@@ -176,8 +199,7 @@ constructor(
_parent.value = parent _parent.value = parent
this.isShuffled.value = isShuffled this.isShuffled.value = isShuffled
pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index)) updatePagerQueue(queue, index, PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
_pagerQueue.value = PagerQueue(queue = queue, index = index)
} }
override fun onProgressionChanged(progression: Progression) { override fun onProgressionChanged(progression: Progression) {
@@ -632,6 +654,12 @@ constructor(
/** Open the main panel, closing all other panels. */ /** Open the main panel, closing all other panels. */
fun openMain() = openImpl(OpenPanel.MAIN) 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. */ /** Open the playback panel, closing the queue panel if needed. */
fun openPlayback() = openImpl(OpenPanel.PLAYBACK) fun openPlayback() = openImpl(OpenPanel.PLAYBACK)
@@ -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 // 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 // adapter, as one item can appear at several points in the UI. Use a similar implementation
// with an index value instead. // with an index value instead.
private var currentIndex = 0 private var currentIndex = -1
private var isPlaying = false private var isPlaying = false
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
@@ -69,7 +69,6 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
viewHolder.bind(getItem(position), listener) viewHolder.bind(getItem(position), listener)
} }
viewHolder.isFuture = position > currentIndex
viewHolder.updatePlayingIndicator(position == currentIndex, isPlaying) 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. // TODO: Don't update when the index has not moved.
if (currentIndex < lastIndex) { if (currentIndex < lastIndex) {
L.d("Moved backwards, must update items above last index") 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( notifyItemRangeChanged(
since, since,
lastIndex - since + 1, lastIndex - since + 1,
@@ -99,17 +98,20 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
) )
} else if (currentIndex > lastIndex) { } else if (currentIndex > lastIndex) {
L.d("Moved forwards, update items after index") 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( notifyItemRangeChanged(
since, since,
currentIndex - since + 1, currentIndex - since + 1,
PAYLOAD_UPDATE_POSITION, 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 val lastIsPlaying = this.isPlaying
this.isPlaying = isPlaying this.isPlaying = isPlaying
if (this.isPlaying != lastIsPlaying) { if (currentIndex >= 0 && this.isPlaying != lastIsPlaying) {
L.d("Changed play state") L.d("Changed play state")
notifyItemChanged(currentIndex) notifyItemChanged(currentIndex)
} }
@@ -128,7 +130,11 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
*/ */
class QueueSongViewHolder private constructor(private val binding: ItemEditableSongBinding) : class QueueSongViewHolder private constructor(private val binding: ItemEditableSongBinding) :
PlayingIndicatorAdapter.ViewHolder(binding.root), MaterialDragCallback.ViewHolder { 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 root = binding.root
override val body = binding.body override val body = binding.body
override val delete = binding.background override val delete = binding.background
@@ -143,18 +149,6 @@ class QueueSongViewHolder private constructor(private val binding: ItemEditableS
fillColor = binding.context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh) 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 { init {
binding.body.background = LayerDrawable(arrayOf(roundableBackground, liftableBackground)) 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) { override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) {
isActiveRow = isActive
binding.interactBody.isSelected = isActive binding.interactBody.isSelected = isActive
binding.songAlbumCover.setPlaying(isPlaying) binding.songAlbumCover.setPlaying(isPlaying)
// The playing row is neither draggable nor swipeable; hide the drag affordance.
binding.songDragHandle.isInvisible = isActive
} }
companion object { companion object {
@@ -23,6 +23,7 @@ import android.util.AttributeSet
import android.view.View import android.view.View
import android.view.WindowInsets import android.view.WindowInsets
import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.updatePadding
import com.google.android.material.R as MR import com.google.android.material.R as MR
import com.google.android.material.shape.MaterialShapeDrawable import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.ShapeAppearanceModel import com.google.android.material.shape.ShapeAppearanceModel
@@ -106,6 +107,10 @@ class QueueBottomSheetBehavior<V : View>(context: Context, attributeSet: Attribu
val bars = insets.systemBarInsetsCompat val bars = insets.systemBarInsetsCompat
val effectiveBarHeight = if (barHeight > 0) barHeight else getIdealBarHeight(child.context) val effectiveBarHeight = if (barHeight > 0) barHeight else getIdealBarHeight(child.context)
expandedOffset = effectiveBarHeight + barSpacing 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( return insets.replaceSystemBarInsetsCompat(
bars.left, bars.left,
bars.top, bars.top,
@@ -21,6 +21,7 @@ package org.oxycblt.auxio.playback.queue
import android.os.Bundle import android.os.Bundle
import android.view.LayoutInflater import android.view.LayoutInflater
import androidx.core.view.isInvisible import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
@@ -88,9 +89,9 @@ class QueueFragment : ViewBindingFragment<FragmentQueueBinding>(), EditClickList
super.onDestroyBinding(binding) super.onDestroyBinding(binding)
touchHelper = null touchHelper = null
binding.queueRecycler.adapter = null binding.queueRecycler.adapter = null
// Avoid possible race conditions that could cause a bad instruction to be consumed // Discard any updates accumulated while the view was gone; a recreated view rebuilds
// during list initialization and crash the app. Could happen if the user is fast enough. // from the current rows.
queueModel.queueInstructions.consume() queueModel.drainQueueUpdates()
} }
override fun onClick(item: Song, viewHolder: RecyclerView.ViewHolder) { 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) { private fun updateQueue(queue: List<Song>, index: Int, isPlaying: Boolean) {
val binding = requireBinding() val binding = requireBinding()
val instructions = queueModel.queueInstructions.consume() val updates = queueModel.drainQueueUpdates()
queueAdapter.update(queue, instructions) updates.forEach { (rows, instructions) -> queueAdapter.update(rows, instructions) }
queueAdapter.setPosition(index, isPlaying, instructions == null) queueAdapter.setPosition(index, isPlaying, updates.isEmpty())
binding.queueEmpty.isVisible = queue.isEmpty()
// If requested, scroll to a new item (occurs when the index moves) // If requested, scroll to a new item (occurs when the index moves)
val scrollTo = queueModel.scrollTo.consume() val scrollTo = queueModel.scrollTo.consume()
@@ -33,7 +33,8 @@ import org.oxycblt.musikr.Song
import timber.log.Timber as L 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) * @author Alexander Capehart (OxygenCobalt)
*/ */
@@ -42,49 +43,53 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
ViewModel(), PlaybackStateManager.Listener { ViewModel(), PlaybackStateManager.Listener {
private val _queue = MutableStateFlow(listOf<Song>()) 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 val queue: StateFlow<List<Song>> = _queue
private val _queueInstructions = MutableEvent<UpdateInstructions>()
/** Instructions for how to update [queue] in the UI. */ // Manager callbacks can arrive on any thread; the fragment drains on the main thread.
val queueInstructions: Event<UpdateInstructions> = _queueInstructions 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. */ /** Controls whether the queue should be force-scrolled to a particular location. */
val scrollTo: Event<Int> val scrollTo: Event<Int>
field = MutableEvent<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> val index: StateFlow<Int>
field = MutableStateFlow(playbackManager.index) field = MutableStateFlow(-1)
init { init {
playbackManager.addListener(this) playbackManager.addListener(this)
republish()
} }
override fun onIndexMoved(index: Int) { override fun onIndexMoved(index: Int) {
L.d("Index moved, synchronizing and scrolling to new position") val hadPlayingDeckSong = this.index.value == 0
scrollTo.put(index) republish()
this.index.value = index 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) {
// 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
} }
} }
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
republish()
}
override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) { override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) {
// Queue changed completely -> Replace queue, update index republish()
L.d("Queue changed completely, replacing queue and position")
_queueInstructions.put(UpdateInstructions.Replace(0))
scrollTo.put(index)
_queue.value = queue
this.index.value = index
} }
override fun onNewPlayback( override fun onNewPlayback(
@@ -93,12 +98,7 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
index: Int, index: Int,
isShuffled: Boolean, isShuffled: Boolean,
) { ) {
// Entirely new queue -> Replace queue, update index republish()
L.d("New playback, replacing queue and position")
_queueInstructions.put(UpdateInstructions.Replace(0))
scrollTo.put(index)
_queue.value = queue
this.index.value = index
} }
override fun onCleared() { 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 * @param adapterIndex The deck row to play. Does nothing if the row is out of range.
* range.
*/ */
fun goto(adapterIndex: Int) { fun goto(adapterIndex: Int) {
if (adapterIndex !in queue.value.indices) { if (adapterIndex !in queue.value.indices) {
return return
} }
L.d("Going to position $adapterIndex in queue") L.d("Going to deck row $adapterIndex")
playbackManager.goto(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 * @param timelineIndex The timeline position to play. Does nothing if out of range.
* 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) { fun removeQueueDataItem(adapterIndex: Int) {
if (adapterIndex !in queue.value.indices) { if (adapterIndex !in queue.value.indices) {
return return
} }
L.d("Removing item $adapterIndex in queue") L.d("Removing deck row $adapterIndex")
playbackManager.removeQueueItem(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 adapterFrom The deck row to move.
* @param adapterTo The destination index for the queue item. * @param adapterTo The destination deck row.
* @return true if the items were moved, false otherwise. * @return true if the rows were moved, false otherwise.
*/ */
fun moveQueueDataItems(adapterFrom: Int, adapterTo: Int): Boolean { fun moveQueueDataItems(adapterFrom: Int, adapterTo: Int): Boolean {
if (adapterFrom !in queue.value.indices || adapterTo !in queue.value.indices) { if (adapterFrom !in queue.value.indices || adapterTo !in queue.value.indices) {
return false return false
} }
L.d("Moving $adapterFrom to $adapterFrom in queue") L.d("Moving deck row $adapterFrom to row $adapterTo")
playbackManager.moveQueueItem(adapterFrom, adapterTo) playbackManager.moveDeckItems(adapterFrom, adapterTo)
return true 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
}
} }
@@ -60,6 +60,12 @@ interface PlaybackStateManager {
/** The current queue of [Song]s. */ /** The current queue of [Song]s. */
val queue: List<Song> 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. */ /** The index of the currently playing [Song] in the queue. */
val index: Int val index: Int
@@ -192,6 +198,41 @@ interface PlaybackStateManager {
*/ */
fun removeQueueItem(at: Int) 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. * (Re)shuffle or (Re)order this instance.
* *
@@ -382,10 +423,12 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
@Volatile private var isInitialized = false @Volatile private var isInitialized = false
/** The upcoming deck songs, in order. The deck sits directly behind the current song. */ /** The upcoming deck songs, in order. The deck sits directly behind the current song. */
private var deck = emptyList<Song>() override var deck = emptyList<Song>()
private set
/** The current song when it came from the deck. Null when the heap is playing. */ /** The current song when it came from the deck. Null when the heap is playing. */
private var deckCurrent: Song? = null override var deckCurrent: Song? = null
private set
override val progression override val progression
get() = stateMirror.progression get() = stateMirror.progression
@@ -513,9 +556,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
} else { } else {
val stateHolder = stateHolder ?: return val stateHolder = stateHolder ?: return
L.d("Adding ${songs.size} songs to start of queue") 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)) stateHolder.playNext(songs, StateAck.PlayNext(stateMirror.index + 1, songs.size))
// Play-next joins the front of the deck.
deck = songs + deck
} }
} }
@@ -540,8 +582,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
val stateHolder = stateHolder ?: return val stateHolder = stateHolder ?: return
val at = stateMirror.index + 1 + deck.size val at = stateMirror.index + 1 + deck.size
L.d("Adding ${songs.size} songs at deck end $at") 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)) stateHolder.playAfter(songs, StateAck.PlayNext(at, songs.size))
deck = deck + songs
} }
} }
@@ -565,6 +607,70 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
stateHolder.remove(at, StateAck.Remove(at)) 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 @Synchronized
override fun shuffled(shuffled: Boolean) { override fun shuffled(shuffled: Boolean) {
val stateHolder = stateHolder ?: return val stateHolder = stateHolder ?: return
@@ -638,7 +744,6 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
val departedAt = stateMirror.index val departedAt = stateMirror.index
val rawQueue = stateHolder.resolveQueue() val rawQueue = stateHolder.resolveQueue()
stateMirror = stateMirror.copy(index = rawQueue.resolveIndex(), rawQueue = rawQueue) stateMirror = stateMirror.copy(index = rawQueue.resolveIndex(), rawQueue = rawQueue)
listeners.forEach { it.onIndexMoved(stateMirror.index) }
// Leaving a deck song drains it: a different song is playing now. A rewind // Leaving a deck song drains it: a different song is playing now. A rewind
// acks without departing and drains nothing. // acks without departing and drains nothing.
if (departed != null && departed !== currentSong && departed === deckCurrent) { if (departed != null && departed !== currentSong && departed === deckCurrent) {
@@ -650,12 +755,21 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
deckCurrent = deck[0] deckCurrent = deck[0]
deck = deck.drop(1) 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 -> { is StateAck.PlayNext -> {
val rawQueue = stateHolder.resolveQueue() val rawQueue = stateHolder.resolveQueue()
val change = val change =
QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size)) QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size))
stateMirror = stateMirror.copy(queue = rawQueue.resolveSongs(), rawQueue = rawQueue) 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 { listeners.forEach {
it.onQueueChanged(stateMirror.queue, stateMirror.index, change) it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
} }
@@ -917,5 +1031,16 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
deckCurrent = if (savedState.deckCurrent) currentSong else null deckCurrent = if (savedState.deckCurrent) currentSong else null
isInitialized = true 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.fragment.app.viewModels
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import com.google.android.material.transition.MaterialSharedAxis import com.google.android.material.transition.MaterialSharedAxis
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import org.oxycblt.auxio.R import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.FragmentSearchBinding import org.oxycblt.auxio.databinding.FragmentSearchBinding
import org.oxycblt.auxio.list.recycler.SwipeActionsCallback
import org.oxycblt.auxio.detail.DetailViewModel import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.detail.Show import org.oxycblt.auxio.detail.Show
import org.oxycblt.auxio.list.Item 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 --- // --- VIEWMODEL SETUP ---
collectImmediately(searchModel.searchResults, ::updateSearchResults) collectImmediately(searchModel.searchResults, ::updateSearchResults)
@@ -1,11 +1,15 @@
<?xml version="1.0" encoding="utf-8"?> <?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" <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:width="24dp"
android:height="24dp" android:height="24dp"
android:tint="?attr/colorControlNormal" android:tint="?attr/colorControlNormal"
android:viewportWidth="960" android:viewportWidth="24"
android:viewportHeight="960"> android:viewportHeight="24">
<path <path
android:fillColor="@android:color/white" android:strokeColor="@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: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> </vector>
@@ -1,11 +1,15 @@
<?xml version="1.0" encoding="utf-8"?> <?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" <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:width="24dp"
android:height="24dp" android:height="24dp"
android:tint="?attr/colorControlNormal" android:tint="?attr/colorControlNormal"
android:viewportWidth="960" android:viewportWidth="24"
android:viewportHeight="960"> android:viewportHeight="24">
<path <path
android:fillColor="@android:color/white" android:strokeColor="@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: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> </vector>
@@ -108,16 +108,30 @@
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/playback_panel_fragment"> app:layout_constraintStart_toEndOf="@+id/playback_panel_fragment">
<TextView <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="64dp" android:layout_height="wrap_content"
android:gravity="center" android:gravity="center_vertical"
android:text="@string/lbl_queue" android:orientation="horizontal">
android:textAppearance="?attr/textAppearanceLabelLargeEmphasized"
android:textColor="?attr/colorOnSurfaceVariant" <TextView
app:layout_constraintBottom_toBottomOf="@+id/handle" android:layout_width="0dp"
app:layout_constraintEnd_toEndOf="@+id/handle" android:layout_height="64dp"
app:layout_constraintStart_toStartOf="parent" /> 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 <androidx.fragment.app.FragmentContainerView
android:id="@+id/queue_fragment" android:id="@+id/queue_fragment"
+11
View File
@@ -126,6 +126,17 @@
app:layout_constraintEnd_toEndOf="@+id/queue_handle" app:layout_constraintEnd_toEndOf="@+id/queue_handle"
app:layout_constraintStart_toStartOf="parent" /> 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.constraintlayout.widget.ConstraintLayout>
<androidx.fragment.app.FragmentContainerView <androidx.fragment.app.FragmentContainerView
@@ -17,4 +17,14 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" /> 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> </FrameLayout>
+16
View File
@@ -2,8 +2,24 @@
<navigation xmlns:android="http://schemas.android.com/apk/res/android" <navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/inner"
app:startDestination="@id/home_fragment"> 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 <fragment
android:id="@+id/home_fragment" android:id="@+id/home_fragment"
android:name="org.oxycblt.auxio.home.HomeFragment" android:name="org.oxycblt.auxio.home.HomeFragment"
+2
View File
@@ -123,6 +123,8 @@
<string name="lbl_shuffle">Shuffle</string> <string name="lbl_shuffle">Shuffle</string>
<string name="lbl_queue">Queue</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_play_next">Play next</string>
<string name="lbl_queue_add">Add to queue</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))
}
}
@@ -155,7 +155,10 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
} }
} }
override fun goto(index: Int) {} 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) { override fun addToQueue(songs: List<Song>, ack: StateAck.AddToQueue) {
insertAt(ack.at, songs) insertAt(ack.at, songs)
@@ -19,10 +19,242 @@
package org.oxycblt.auxio.playback.state package org.oxycblt.auxio.playback.state
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.oxycblt.musikr.Song
import org.junit.Assert.assertSame import org.junit.Assert.assertSame
import org.junit.Test import org.junit.Test
class PlaybackStateManagerImplTest { 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 * 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. * rest of the deck survives, matching the heap's own realignment.