diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/data/DailyMixManager.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/data/DailyMixManager.kt index ac67faf52..867fb9555 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/data/DailyMixManager.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/data/DailyMixManager.kt @@ -326,7 +326,8 @@ class DailyMixManager @Inject constructor( val noveltyScore = computeNoveltyScore(song.dateAdded, now) val favoriteScore = if (favoriteSongIds.contains(song.id)) 1.0 else 0.0 val baselineScore = if (stats == null) 0.1 else 0.0 - val noise = random.nextDouble() * 0.005 + // Large enough to rotate songs with similar scores day to day; the seed is per day. + val noise = random.nextDouble() * DAILY_VARIETY_NOISE val finalScore = (preferenceScore * 0.45) + (affinityScore * 0.25) + @@ -356,13 +357,13 @@ class DailyMixManager @Inject constructor( suspend fun generateDailyMix( allSongs: List, favoriteSongIds: Set = emptySet(), - limit: Int = 30 + limit: Int = 30, + calendar: Calendar = Calendar.getInstance() ): List { if (allSongs.isEmpty()) { return emptyList() } - val calendar = Calendar.getInstance() val seed = calendar.get(Calendar.YEAR) * 1000 + calendar.get(Calendar.DAY_OF_YEAR) val random = java.util.Random(seed.toLong()) @@ -605,5 +606,6 @@ class DailyMixManager @Inject constructor( companion object { private const val TAG = "DailyMixManager" private val SCORE_KEY_CANDIDATES = listOf("score", "count", "value") + private const val DAILY_VARIETY_NOISE = 0.25 } } diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/data/media/AudioMetadataReader.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/data/media/AudioMetadataReader.kt index 5a8d55237..7d3316456 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/data/media/AudioMetadataReader.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/data/media/AudioMetadataReader.kt @@ -37,9 +37,28 @@ data class AudioMetadata( val replayGainTrackGainDb: Float? = null, val replayGainAlbumGainDb: Float? = null, val rating: Int? = null, - val customFields: List = emptyList() + val customFields: List = emptyList(), + val mbRecordingId: String? = null, + val mbReleaseId: String? = null, + val mbArtistId: String? = null ) +private val MBID_REGEX = + Regex("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", RegexOption.IGNORE_CASE) + +/** + * Returns the first well-formed MusicBrainz identifier among tag values. Some taggers join + * multiple artist IDs into one value ("id1; id2" or "id1/id2"), so each value is split first. + * Malformed IDs are dropped because ListenBrainz rejects listens carrying an invalid MBID. + */ +internal fun firstMusicBrainzId(values: Iterable?): String? = + values?.asSequence().orEmpty() + .filterNotNull() + .flatMap { it.split(';', '/', ',').asSequence() } + .map { it.trim() } + .firstOrNull { MBID_REGEX.matches(it) } + ?.lowercase() + /** * Normalizes values read from repeated metadata fields without changing their source order. * @@ -146,6 +165,10 @@ object AudioMetadataReader { propertyMap = propertyMap, keys = listOf("REPLAYGAIN_ALBUM_GAIN", "REPLAYGAIN_ALBUM_GAIN_DB", "R128_ALBUM_GAIN") ) + // TagLib maps ID3 UFID/TXXX, MP4 freeform atoms and Vorbis comments to these keys. + val mbRecordingId = firstMusicBrainzId(propertyMap["MUSICBRAINZ_TRACKID"]?.asIterable()) + val mbReleaseId = firstMusicBrainzId(propertyMap["MUSICBRAINZ_ALBUMID"]?.asIterable()) + val mbArtistId = firstMusicBrainzId(propertyMap["MUSICBRAINZ_ARTISTID"]?.asIterable()) val tagFamily = metadataTagFamily(file.extension) val propertyMapRating = if (readCustomMetadata) { listOf("RATING", "POPULARIMETER") @@ -216,7 +239,10 @@ object AudioMetadataReader { replayGainTrackGainDb = replayGainTrackGainDb ?: fallback?.replayGainTrackGainDb, replayGainAlbumGainDb = replayGainAlbumGainDb ?: fallback?.replayGainAlbumGainDb, rating = fallback?.rating ?: propertyMapRating, - customFields = customFields.ifEmpty { fallback?.customFields.orEmpty() } + customFields = customFields.ifEmpty { fallback?.customFields.orEmpty() }, + mbRecordingId = mbRecordingId ?: fallback?.mbRecordingId, + mbReleaseId = mbReleaseId ?: fallback?.mbReleaseId, + mbArtistId = mbArtistId ?: fallback?.mbArtistId ) } } catch (error: Exception) { @@ -296,6 +322,8 @@ object AudioMetadataReader { null } + fun mbid(key: FieldKey) = firstMusicBrainzId(runCatching { tag?.getAll(key) }.getOrNull()) + val durationMs = header?.trackLength?.takeIf { it > 0 }?.let { it * 1000L } val bitrate = header?.bitRateAsNumber?.takeIf { it > 0 }?.toInt()?.let { it * 1000 } val sampleRate = header?.sampleRateAsNumber?.takeIf { it > 0 } @@ -334,7 +362,10 @@ object AudioMetadataReader { bitrate = bitrate, sampleRate = sampleRate, artwork = artwork, - rating = rating + rating = rating, + mbRecordingId = mbid(FieldKey.MUSICBRAINZ_TRACK_ID), + mbReleaseId = mbid(FieldKey.MUSICBRAINZ_RELEASEID), + mbArtistId = mbid(FieldKey.MUSICBRAINZ_ARTISTID) ) } catch (e: Exception) { Timber.tag(TAG).e(e, "JAudioTagger fallback FAILED for: ${file.name}") diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/data/preferences/SwipeToQueueAction.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/data/preferences/SwipeToQueueAction.kt new file mode 100644 index 000000000..1989f8551 --- /dev/null +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/data/preferences/SwipeToQueueAction.kt @@ -0,0 +1,19 @@ +package com.lostf1sh.pixelplayeross.data.preferences + +/** What swiping a song row to the right does in playlist, album, artist, genre and mix lists. */ +enum class SwipeToQueueAction(val storageKey: String) { + OFF("off"), + + /** Append the song to the end of the queue. */ + ADD_TO_QUEUE("add_to_queue"), + + /** Insert the song right after the one playing. */ + PLAY_NEXT("play_next"); + + companion object { + val DEFAULT = ADD_TO_QUEUE + + fun fromStorageKey(value: String?): SwipeToQueueAction = + entries.firstOrNull { it.storageKey == value } ?: DEFAULT + } +} diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/data/preferences/UserPreferencesRepository.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/data/preferences/UserPreferencesRepository.kt index d4cf98e02..f5525a85f 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/data/preferences/UserPreferencesRepository.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/data/preferences/UserPreferencesRepository.kt @@ -240,6 +240,7 @@ constructor( val MINI_PLAYER_SWIPE_TO_SKIP = booleanPreferencesKey("mini_player_swipe_to_skip") val AUTOPLAY_ON_SKIP = booleanPreferencesKey("autoplay_on_skip") val PREVIOUS_BUTTON_BEHAVIOR = stringPreferencesKey("previous_button_behavior") + val SWIPE_TO_QUEUE_ACTION = stringPreferencesKey("swipe_to_queue_action") val HAPTICS_ENABLED = booleanPreferencesKey("haptics_enabled") val ADVANCED_PERFORMANCE_DIAGNOSTICS_ENABLED = booleanPreferencesKey("advanced_performance_diagnostics_enabled") @@ -1998,6 +1999,17 @@ constructor( } } + val swipeToQueueActionFlow: Flow = + dataStore.data.map { preferences -> + SwipeToQueueAction.fromStorageKey(preferences[PreferencesKeys.SWIPE_TO_QUEUE_ACTION]) + }.distinctUntilChanged() + + suspend fun setSwipeToQueueAction(action: SwipeToQueueAction) { + dataStore.edit { preferences -> + preferences[PreferencesKeys.SWIPE_TO_QUEUE_ACTION] = action.storageKey + } + } + val hapticsEnabledFlow: Flow = dataStore.data.map { preferences -> preferences[PreferencesKeys.HAPTICS_ENABLED] ?: true diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/data/service/player/FadingPlayer.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/data/service/player/FadingPlayer.kt index c07fdce72..fdaf368e0 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/data/service/player/FadingPlayer.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/data/service/player/FadingPlayer.kt @@ -20,6 +20,11 @@ import kotlinx.coroutines.launch * tracking only wrapper-side [setVolume] calls would make every fade end at full volume and * defeat the normalization. [getVolume] reports the logical volume during a fade rather * than the transient mid-ramp value. + * + * A pause is reported as soon as its fade starts, not when the engine player stops at the + * end of it. Controllers show a pause optimistically; a session that went on reporting + * "playing" for the length of the fade overwrote that, so the pause button answered half a + * second late and a second tap inside the fade paused again instead of resuming. */ @OptIn(UnstableApi::class) class FadingPlayer( @@ -30,6 +35,59 @@ class FadingPlayer( private var fadeJob: Job? = null // Volume the player should sit at when no fade is running. private var logicalVolume = innerPlayer.volume + // True while a pause fade ramps down: the pause is decided, only the audio trails it. + private var isFadingToPause = false + private val listeners = LinkedHashSet() + + override fun addListener(listener: Player.Listener) { + listeners.add(listener) + super.addListener(listener) + } + + override fun removeListener(listener: Player.Listener) { + listeners.remove(listener) + super.removeListener(listener) + } + + override fun getPlayWhenReady(): Boolean = !isFadingToPause && super.getPlayWhenReady() + + override fun isPlaying(): Boolean = !isFadingToPause && super.isPlaying() + + override fun setPlayWhenReady(playWhenReady: Boolean) { + if (playWhenReady && isFadingToPause) { + // The engine player is still playing, so it would ignore this and the fade + // would go on to pause it. + play() + } else { + super.setPlayWhenReady(playWhenReady) + } + } + + /** + * Enters or leaves the pause fade and tells listeners what that changes in the reported + * state. The engine player emits nothing here: it keeps playing until the fade ends, and + * never stopped if the fade is cut short. + */ + private fun setFadingToPause(fading: Boolean) { + if (isFadingToPause == fading) return + val playWhenReadyBefore = playWhenReady + val isPlayingBefore = isPlaying + isFadingToPause = fading + val playWhenReadyNow = playWhenReady + val isPlayingNow = isPlaying + if (playWhenReadyBefore == playWhenReadyNow && isPlayingBefore == isPlayingNow) return + for (listener in listeners.toList()) { + if (playWhenReadyBefore != playWhenReadyNow) { + listener.onPlayWhenReadyChanged( + playWhenReadyNow, + Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST + ) + } + if (isPlayingBefore != isPlayingNow) { + listener.onIsPlayingChanged(isPlayingNow) + } + } + } override fun setVolume(volume: Float) { logicalVolume = volume @@ -54,13 +112,15 @@ class FadingPlayer( val targetVolume = settledVolume() fadeJob?.cancel() logicalVolume = targetVolume - if (isPlaying) { + if (innerPlayer.isPlaying) { // A pause fade cut short here has left the volume partway down. super.setVolume(targetVolume) + setFadingToPause(false) super.play() return } + setFadingToPause(false) super.setVolume(0f) super.play() @@ -80,13 +140,16 @@ class FadingPlayer( val settledVolume = settledVolume() fadeJob?.cancel() logicalVolume = settledVolume - if (!isPlaying) { + if (!innerPlayer.isPlaying) { super.pause() // A play fade cut short while buffering has left the volume partway up. super.setVolume(settledVolume) + setFadingToPause(false) return } + setFadingToPause(true) + // Ramp down from where the volume is now, which is below the settled level when // this cuts a play fade short. val startVolume = innerPlayer.volume @@ -102,6 +165,7 @@ class FadingPlayer( super.pause() // Restore the logical volume so the paused player resumes from the right level. super.setVolume(logicalVolume) + setFadingToPause(false) } } diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/data/worker/SyncWorker.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/data/worker/SyncWorker.kt index 442f07827..8b9192c83 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/data/worker/SyncWorker.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/data/worker/SyncWorker.kt @@ -88,6 +88,22 @@ internal fun shouldReadEmbeddedMetadata( isDefaultMetadata(rawAlbum) } +/** + * Embedded MusicBrainz tags win; otherwise IDs stored earlier (a previous scan or a manual + * lookup) survive a rescan that did not read tags. The three IDs move together so a recording + * is never paired with another match's release or artist. + */ +internal fun SongEntity.withMusicBrainzIdsFallback(stored: SongEntity): SongEntity = + if (mbRecordingId != null) { + this + } else { + copy( + mbRecordingId = stored.mbRecordingId, + mbReleaseId = stored.mbReleaseId, + mbArtistId = stored.mbArtistId + ) + } + private fun isDefaultMetadata(value: String): Boolean { val lower = value.trim().lowercase(Locale.ROOT) return lower.isEmpty() || @@ -1092,7 +1108,7 @@ constructor( artistUserEdited = localSong.artistUserEdited, albumUserEdited = localSong.albumUserEdited, genreUserEdited = localSong.genreUserEdited - ) + ).withMusicBrainzIdsFallback(localSong) } else { scannedMediaStoreSong.entity } @@ -1157,6 +1173,9 @@ constructor( var discNumber = raw.discNumber var year = raw.year var genre: String? = genreMap[raw.id] ?: raw.genre + var mbRecordingId: String? = null + var mbReleaseId: String? = null + var mbArtistId: String? = null val shouldAugmentMetadata = shouldReadEmbeddedMetadata( filePath = raw.filePath, @@ -1190,6 +1209,11 @@ constructor( if (meta.trackNumber != null) trackNumber = meta.trackNumber if (meta.discNumber != null) discNumber = meta.discNumber if (meta.year != null) year = meta.year + if (meta.mbRecordingId != null) { + mbRecordingId = meta.mbRecordingId + mbReleaseId = meta.mbReleaseId + mbArtistId = meta.mbArtistId + } } } catch (e: Exception) { Timber.tag(TAG).w(e, "Failed to read metadata via TagLib for ${raw.filePath}") @@ -1225,7 +1249,10 @@ constructor( bitrate = audioMetadata?.bitrate, sourceType = SourceType.LOCAL, mediaStoreDateAdded = raw.dateAdded, - mediaStoreDateModified = raw.dateModified + mediaStoreDateModified = raw.dateModified, + mbRecordingId = mbRecordingId, + mbReleaseId = mbReleaseId, + mbArtistId = mbArtistId ), artistValues = artistValues ) diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/AlbumArtCollage.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/AlbumArtCollage.kt index 317214276..aea1164e2 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/AlbumArtCollage.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/AlbumArtCollage.kt @@ -1,7 +1,7 @@ package com.lostf1sh.pixelplayeross.presentation.components import androidx.compose.foundation.background -import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.material3.Icon @@ -19,6 +19,7 @@ import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import coil.request.ImageRequest @@ -47,9 +48,11 @@ fun AlbumArtCollage( height: Dp = 400.dp, padding: Dp = 0.dp, pattern: CollagePattern = CollagePattern.default, + onSongLongClick: ((Song) -> Unit)? = null, onSongClick: (Song) -> Unit, ) { val context = LocalContext.current + val moreOptionsLabel = stringResource(R.string.presentation_batch_b_more_options) val songsToShow = remember(songs) { (songs.take(6) + List(6 - songs.size.coerceAtMost(6)) { null }).toImmutableList() } @@ -97,10 +100,13 @@ fun AlbumArtCollage( .align(cfg.align) .offset(cfg.offsetX, cfg.offsetY) .graphicsLayer { rotationZ = cfg.rot } - .clickable( + .combinedClickable( interactionSource = remember { MutableInteractionSource() }, - indication = null - ) { onSongClick(song) } + indication = null, + onLongClickLabel = moreOptionsLabel, + onLongClick = onSongLongClick?.let { { it(song) } }, + onClick = { onSongClick(song) } + ) .background(shape = cfg.shape, color = MaterialTheme.colorScheme.surfaceContainerHigh) .clip(cfg.shape) ) @@ -119,10 +125,13 @@ fun AlbumArtCollage( .align(cfg.align) .offset(cfg.offsetX, cfg.offsetY) .graphicsLayer { rotationZ = cfg.rot } - .clickable( + .combinedClickable( interactionSource = remember { MutableInteractionSource() }, - indication = null - ) { onSongClick(song) } + indication = null, + onLongClickLabel = moreOptionsLabel, + onLongClick = onSongLongClick?.let { { it(song) } }, + onClick = { onSongClick(song) } + ) .clip(cfg.shape) ) } diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/DailyMixSection.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/DailyMixSection.kt index 2da51c100..5d26283a9 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/DailyMixSection.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/DailyMixSection.kt @@ -358,6 +358,7 @@ private fun DailyMixSongList( isPlaying = stablePlayerState.isPlaying && stablePlayerState.currentSong?.id == song.id, containerColorOverride = itemContainerColor, onMoreOptionsClick = onMoreOptionsClick, + onLongPress = { onMoreOptionsClick(song) }, customShape = RoundedCornerShape(10.dp), showAlbumArt = false, onClick = { diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/RecentlyPlayedSongOptionsSheet.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/RecentlyPlayedSongOptionsSheet.kt index cdac2175d..f95f0a773 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/RecentlyPlayedSongOptionsSheet.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/RecentlyPlayedSongOptionsSheet.kt @@ -21,9 +21,9 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf /** - * Song options for a Home "Recently played" pill. The pills have no more-options button, so a - * long press opens this sheet instead. Playing from here keeps the recently played queue, the - * same as tapping the pill. + * Song options for a Home "Recently played" pill or "Your Mix" cover. Neither has a + * more-options button, so a long press opens this sheet instead. Playing from here keeps the + * section's queue, the same as tapping the song. */ @androidx.annotation.OptIn(UnstableApi::class) @Composable @@ -31,6 +31,7 @@ fun RecentlyPlayedSongOptionsSheet( song: Song, queueSongs: ImmutableList, queueName: String, + playFromLibrary: Boolean = false, playerViewModel: PlayerViewModel, onDismiss: () -> Unit, onSongDeleted: (Song) -> Unit, @@ -60,7 +61,9 @@ fun RecentlyPlayedSongOptionsSheet( onDismiss() }, onPlaySong = { - if (queueSongs.any { it.id == sheetSong.id }) { + if (playFromLibrary) { + playerViewModel.showAndPlaySongFromLibrary(sheetSong, queueName = queueName) + } else if (queueSongs.any { it.id == sheetSong.id }) { playerViewModel.playSongs( songsToPlay = queueSongs, startSong = sheetSong, diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/SongInfoBottomSheet.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/SongInfoBottomSheet.kt index 3cbb69761..f5e2649ba 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/SongInfoBottomSheet.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/SongInfoBottomSheet.kt @@ -18,6 +18,7 @@ import androidx.compose.animation.core.tween import androidx.compose.foundation.LocalOverscrollFactory import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.text.TextAutoSize import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items @@ -75,6 +76,7 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import androidx.core.content.FileProvider import com.lostf1sh.pixelplayeross.R import com.lostf1sh.pixelplayeross.data.model.Song @@ -455,9 +457,15 @@ fun SongInfoBottomSheet( Icon(Icons.Rounded.PlayArrow, contentDescription = stringResource(R.string.cd_play_song_action)) }, text = { + // Long translations (e.g. Italian) shrink to fit on one line. Text( modifier = Modifier.padding(end = 10.dp), - text = stringResource(R.string.play_playback) + text = stringResource(R.string.play_playback), + maxLines = 1, + autoSize = TextAutoSize.StepBased( + minFontSize = 10.sp, + maxFontSize = LocalTextStyle.current.fontSize + ) ) } ) diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/SwipeToQueueBox.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/SwipeToQueueBox.kt new file mode 100644 index 000000000..e101a529e --- /dev/null +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/SwipeToQueueBox.kt @@ -0,0 +1,112 @@ +package com.lostf1sh.pixelplayeross.presentation.components + +import androidx.compose.animation.core.Animatable +import androidx.compose.foundation.gestures.detectHorizontalDragGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.media3.common.util.UnstableApi +import com.lostf1sh.pixelplayeross.R +import com.lostf1sh.pixelplayeross.data.model.Song +import com.lostf1sh.pixelplayeross.data.preferences.SwipeToQueueAction +import com.lostf1sh.pixelplayeross.presentation.viewmodel.PlayerViewModel +import kotlinx.coroutines.launch + +private val SwipeToQueueThreshold = 72.dp + +/** The swipe-to-queue action for song rows, or null while the setting turns the swipe off. */ +@androidx.annotation.OptIn(UnstableApi::class) +@Composable +fun rememberSwipeToQueue(playerViewModel: PlayerViewModel): ((Song) -> Unit)? { + val action by playerViewModel.swipeToQueueAction.collectAsStateWithLifecycle() + return remember(action, playerViewModel) { + if (action == SwipeToQueueAction.OFF) null else playerViewModel::queueSongFromSwipe + } +} + +/** + * Lets a song row slide towards the end edge; letting go past the threshold calls [onSwipe]. + * With a null [onSwipe], [content] gets [modifier] as is and no gesture is added. + */ +@Composable +fun SwipeToQueueBox( + onSwipe: (() -> Unit)?, + modifier: Modifier = Modifier, + content: @Composable (Modifier) -> Unit +) { + if (onSwipe == null) { + content(modifier) + return + } + + val currentOnSwipe by rememberUpdatedState(onSwipe) + val haptics = LocalHapticFeedback.current + val scope = rememberCoroutineScope() + val offset = remember { Animatable(0f) } + val thresholdPx = with(LocalDensity.current) { SwipeToQueueThreshold.toPx() } + // Offsets are kept towards the end edge, which is left in right-to-left layouts. + val direction = if (LocalLayoutDirection.current == LayoutDirection.Rtl) -1f else 1f + + Box(modifier) { + Icon( + painter = painterResource(R.drawable.rounded_queue_music_24), + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier + .align(Alignment.CenterStart) + .padding(start = 20.dp) + .graphicsLayer { + val progress = (offset.value / thresholdPx).coerceIn(0f, 1f) + alpha = progress + scaleX = 0.6f + 0.4f * progress + scaleY = scaleX + } + ) + content( + Modifier + .graphicsLayer { translationX = offset.value * direction } + .pointerInput(direction, thresholdPx) { + var dragged = 0f + fun settle() { + dragged = 0f + scope.launch { offset.animateTo(0f) } + } + detectHorizontalDragGestures( + onDragStart = { dragged = 0f }, + onDragEnd = { + if (dragged >= thresholdPx) currentOnSwipe() + settle() + }, + onDragCancel = { settle() } + ) { change, dragAmount -> + change.consume() + val wasArmed = dragged >= thresholdPx + dragged = (dragged + dragAmount * direction).coerceIn(0f, thresholdPx * 1.5f) + if (!wasArmed && dragged >= thresholdPx) { + haptics.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate) + } + val target = dragged + scope.launch { offset.snapTo(target) } + } + } + ) + } +} diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/subcomps/EnhancedSongListItem.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/subcomps/EnhancedSongListItem.kt index eeca16aee..6014fd718 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/subcomps/EnhancedSongListItem.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/components/subcomps/EnhancedSongListItem.kt @@ -65,6 +65,7 @@ import com.lostf1sh.pixelplayeross.presentation.components.ShimmerBox import androidx.compose.ui.res.stringResource import com.lostf1sh.pixelplayeross.R import com.lostf1sh.pixelplayeross.presentation.components.SmartImage +import com.lostf1sh.pixelplayeross.presentation.components.SwipeToQueueBox @Immutable private data class EnhancedSongAnimationTarget( @@ -115,6 +116,7 @@ private class HighlightMorphShape( * @param isSelected Whether this item is selected in multi-selection mode * @param isSelectionMode Whether multi-selection mode is active * @param onLongPress Callback for long press gesture (activates selection) + * @param onSwipeToQueue Called when the row is swiped towards the end edge; null disables the swipe * @param onMoreOptionsClick Callback for more options button * @param onClick Callback for tap gesture */ @@ -135,6 +137,7 @@ fun EnhancedSongListItem( isSelectionMode: Boolean = false, showMoreOptionsButton: Boolean = true, onLongPress: () -> Unit = {}, + onSwipeToQueue: (() -> Unit)? = null, onMoreOptionsClick: (Song) -> Unit, onClick: () -> Unit ) { @@ -275,9 +278,13 @@ fun EnhancedSongListItem( ) } } - } else { + } else SwipeToQueueBox( + // A swipe would fight the selection gestures. + onSwipe = onSwipeToQueue?.takeUnless { isSelectionMode }, + modifier = modifier + ) { rowModifier -> Surface( - modifier = modifier + modifier = rowModifier .fillMaxWidth() .scale(selectionScale) .clip(surfaceShape) diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/AlbumDetailScreen.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/AlbumDetailScreen.kt index a8bcf5225..97bfdcb66 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/AlbumDetailScreen.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/AlbumDetailScreen.kt @@ -2,6 +2,7 @@ package com.lostf1sh.pixelplayeross.presentation.screens +import com.lostf1sh.pixelplayeross.presentation.components.rememberSwipeToQueue import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafely import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafelyReplacing import com.lostf1sh.pixelplayeross.presentation.components.DetailHeroArtistChip @@ -142,6 +143,7 @@ fun AlbumDetailScreen( } val favoriteIds by playerViewModel.favoriteSongIds.collectAsStateWithLifecycle() val navBarCompactMode by playerViewModel.navBarCompactMode.collectAsStateWithLifecycle() + val swipeToQueue = rememberSwipeToQueue(playerViewModel) val completedOfflineUris by viewModel.completedOfflineUris.collectAsStateWithLifecycle() val allArtists by playerViewModel.artistsFlow.collectAsStateWithLifecycle() var showAlbumPlaylistSheet by remember { mutableStateOf(false) } @@ -527,6 +529,7 @@ fun AlbumDetailScreen( playerViewModel = playerViewModel, customShape = getSegmentedItemShape(index, discSongs.size), showAlbumArt = false, + onSwipeToQueue = swipeToQueue?.let { { it(song) } }, onMoreOptionsClick = { playerViewModel.selectSongForInfo(song) showSongInfoBottomSheet = true diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/ArtistDetailScreen.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/ArtistDetailScreen.kt index 3b1d228b7..3ded91e2e 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/ArtistDetailScreen.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/ArtistDetailScreen.kt @@ -2,6 +2,7 @@ package com.lostf1sh.pixelplayeross.presentation.screens +import com.lostf1sh.pixelplayeross.presentation.components.rememberSwipeToQueue import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafely import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafelyReplacing import com.lostf1sh.pixelplayeross.presentation.components.DetailHeroFloatingLayer @@ -150,6 +151,7 @@ fun ArtistDetailScreen( val lazyListState = rememberLazyListState() val favoriteIds by playerViewModel.favoriteSongIds.collectAsStateWithLifecycle() val navBarCompactMode by playerViewModel.navBarCompactMode.collectAsStateWithLifecycle() + val swipeToQueue = rememberSwipeToQueue(playerViewModel) var showSongInfoBottomSheet by remember { mutableStateOf(false) } val selectedSongForInfo by playerViewModel.selectedSongForInfo.collectAsStateWithLifecycle() val systemNavBarInset = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() @@ -544,6 +546,7 @@ fun ArtistDetailScreen( onSongClick = { playerViewModel.showAndPlaySong(song, section.songs) }, + onSwipeToQueue = swipeToQueue?.let { { it(song) } }, onMoreOptionsClick = { playerViewModel.selectSongForInfo(song) showSongInfoBottomSheet = true @@ -890,6 +893,7 @@ private fun ArtistAlbumSectionSongItem( isCurrentSong: Boolean, isPlaying: Boolean, onSongClick: () -> Unit, + onSwipeToQueue: (() -> Unit)?, onMoreOptionsClick: () -> Unit ) { val isLastSong = songIndex == songCount - 1 @@ -932,6 +936,7 @@ private fun ArtistAlbumSectionSongItem( isPlaying = isPlaying, showAlbumArt = false, customShape = songItemShape, + onSwipeToQueue = onSwipeToQueue, onMoreOptionsClick = { onMoreOptionsClick() }, onClick = onSongClick ) diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/DailyMixScreen.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/DailyMixScreen.kt index 747d8f17d..ab03eaea6 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/DailyMixScreen.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/DailyMixScreen.kt @@ -1,5 +1,6 @@ package com.lostf1sh.pixelplayeross.presentation.screens +import com.lostf1sh.pixelplayeross.presentation.components.rememberSwipeToQueue import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafely import androidx.compose.foundation.background @@ -114,6 +115,7 @@ fun DailyMixScreen( val isPlaying by remember { playerViewModel.stablePlayerState.map { it.isPlaying }.distinctUntilChanged() }.collectAsStateWithLifecycle(initialValue = false) val isShuffleEnabled by remember { playerViewModel.stablePlayerState.map { it.isShuffleEnabled }.distinctUntilChanged() }.collectAsStateWithLifecycle(initialValue = false) val navBarCompactMode by playerViewModel.navBarCompactMode.collectAsStateWithLifecycle() + val swipeToQueue = rememberSwipeToQueue(playerViewModel) val systemNavBarInset = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() val useNavigationRail = currentWindowAdaptiveInfo().windowSizeClass .isWidthAtLeastBreakpoint(WindowSizeClass.WIDTH_DP_MEDIUM_LOWER_BOUND) @@ -320,6 +322,7 @@ fun DailyMixScreen( isCurrentSong = currentSongId == song.id, isPlaying = currentSongId == song.id && isPlaying, onClick = { playerViewModel.showAndPlaySong(song, dailyMixSongs, dailyMixTitle, isVoluntaryPlay = false) }, + onSwipeToQueue = swipeToQueue?.let { { it(song) } }, onMoreOptionsClick = { playerViewModel.selectSongForInfo(song) showSongInfoSheet = true diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/GenreDetailScreen.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/GenreDetailScreen.kt index a912e5349..b597b23da 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/GenreDetailScreen.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/GenreDetailScreen.kt @@ -1,5 +1,6 @@ package com.lostf1sh.pixelplayeross.presentation.screens +import com.lostf1sh.pixelplayeross.presentation.components.rememberSwipeToQueue import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafely import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafelyReplacing import androidx.lifecycle.compose.collectAsStateWithLifecycle @@ -115,6 +116,7 @@ fun GenreDetailScreen( val uiState by viewModel.uiState.collectAsStateWithLifecycle() val stablePlayerState by playerViewModel.stablePlayerState.collectAsStateWithLifecycle() val favoriteSongIds by playerViewModel.favoriteSongIds.collectAsStateWithLifecycle() + val swipeToQueue = rememberSwipeToQueue(playerViewModel) val playlistUiState by playlistViewModel.uiState.collectAsStateWithLifecycle() val libraryGenres by playerViewModel.genres.collectAsStateWithLifecycle() @@ -410,6 +412,7 @@ fun GenreDetailScreen( playerViewModel.showAndPlaySong(song, uiState.sortedSongs, genreDisplayName) }, onMoreOptionsClick = { song -> showSongOptionsSheet = song }, + onSwipeToQueue = swipeToQueue, isSelectionMode = isSelectionMode, isSelected = item.song.id in selectedSongIds, selectionIndex = multiSelectionState.getSelectionIndex(item.song.id), @@ -1060,6 +1063,7 @@ fun GenreSongItemWrapper( stablePlayerState: StablePlayerState, onSongClick: (Song) -> Unit, onMoreOptionsClick: (Song) -> Unit, + onSwipeToQueue: ((Song) -> Unit)? = null, isSelectionMode: Boolean = false, isSelected: Boolean = false, selectionIndex: Int? = null, @@ -1114,6 +1118,7 @@ fun GenreSongItemWrapper( customShape = songItemShape, onClick = { onSongClick(song) }, onMoreOptionsClick = onMoreOptionsClick, + onSwipeToQueue = onSwipeToQueue?.let { { it(song) } }, isSelected = isSelected, selectionIndex = selectionIndex, isSelectionMode = isSelectionMode, diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/HomeScreen.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/HomeScreen.kt index 98f045eae..9a81eeb68 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/HomeScreen.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/HomeScreen.kt @@ -113,6 +113,7 @@ import com.lostf1sh.pixelplayeross.presentation.viewmodel.StatsViewModel import com.lostf1sh.pixelplayeross.presentation.viewmodel.StreamingProviderLoginViewModel import com.lostf1sh.pixelplayeross.presentation.viewmodel.sharedPlayerViewModel import com.lostf1sh.pixelplayeross.ui.theme.ExpTitleTypography +import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.delay @@ -129,6 +130,15 @@ import com.lostf1sh.pixelplayeross.presentation.components.rememberModalSheetSta private const val HomeLoadingPlaceholderMinDurationMillis = 1200L private const val HomeScrollRestoreGraceMillis = 1_500L +/** A Home song a long press opened options for, with the queue that playing it from there uses. */ +private data class HomeSongOptions( + val song: Song, + val queueSongs: ImmutableList, + val queueName: String, + /** Play builds the full library queue, as tapping a Home library preview does. */ + val playFromLibrary: Boolean = false +) + @androidx.annotation.OptIn(UnstableApi::class) @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -264,7 +274,7 @@ fun HomeScreen( var showChangelogBottomSheet by remember { mutableStateOf(false) } var showBetaInfoBottomSheet by remember { mutableStateOf(false) } var showStreamingProviderSheet by remember { mutableStateOf(false) } - var recentSongForOptions by remember { mutableStateOf(null) } + var songForOptions by remember { mutableStateOf(null) } val sheetState = rememberModalSheetState() val betaSheetState = rememberModalSheetState() val scope = rememberCoroutineScope() @@ -442,6 +452,11 @@ fun HomeScreen( padding = 12.dp, height = 290.dp, pattern = activePattern, + onSongLongClick = { song -> + songForOptions = HomeSongOptions( + song, yourMixSongs, yourMixQueueName, playFromLibrary = usesFallbackHomeMix + ) + }, onSongClick = { song -> if (usesFallbackHomeMix) { playerViewModel.showAndPlaySongFromLibrary(song, queueName = yourMixQueueName) @@ -498,6 +513,11 @@ fun HomeScreen( padding = 14.dp, height = 400.dp, pattern = activePattern, + onSongLongClick = { song -> + songForOptions = HomeSongOptions( + song, yourMixSongs, yourMixQueueName, playFromLibrary = usesFallbackHomeMix + ) + }, onSongClick = { song -> if (usesFallbackHomeMix) { playerViewModel.showAndPlaySongFromLibrary(song, queueName = yourMixQueueName) @@ -542,7 +562,7 @@ fun HomeScreen( } }, onSongLongClick = { song -> - recentSongForOptions = song + songForOptions = HomeSongOptions(song, recentlyPlayedQueue, recentlyPlayedQueueName) }, onOpenAllClick = { navController.navigateSafely(Screen.RecentlyPlayed.route) @@ -647,7 +667,7 @@ fun HomeScreen( } }, onSongLongClick = { song -> - recentSongForOptions = song + songForOptions = HomeSongOptions(song, recentlyPlayedQueue, recentlyPlayedQueueName) }, onOpenAllClick = { navController.navigateSafely(Screen.RecentlyPlayed.route) @@ -741,13 +761,14 @@ fun HomeScreen( } ) } - recentSongForOptions?.let { song -> + songForOptions?.let { (song, queueSongs, queueName, playFromLibrary) -> RecentlyPlayedSongOptionsSheet( song = song, - queueSongs = recentlyPlayedQueue, - queueName = recentlyPlayedQueueName, + queueSongs = queueSongs, + queueName = queueName, + playFromLibrary = playFromLibrary, playerViewModel = playerViewModel, - onDismiss = { recentSongForOptions = null }, + onDismiss = { songForOptions = null }, onSongDeleted = { deletedSong -> recentlyPlayedSongs = recentlyPlayedSongs.withoutSong(deletedSong.id) }, diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/LibraryPlaybackAwareSongItem.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/LibraryPlaybackAwareSongItem.kt index a4f04fe34..8620d733f 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/LibraryPlaybackAwareSongItem.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/LibraryPlaybackAwareSongItem.kt @@ -36,6 +36,7 @@ internal fun LibraryPlaybackAwareSongItem( selectionIndex: Int? = null, isSelectionMode: Boolean = false, onLongPress: () -> Unit = {}, + onSwipeToQueue: (() -> Unit)? = null, onMoreOptionsClick: (Song) -> Unit, onClick: () -> Unit ) { @@ -64,6 +65,7 @@ internal fun LibraryPlaybackAwareSongItem( selectionIndex = selectionIndex, isSelectionMode = isSelectionMode, onLongPress = onLongPress, + onSwipeToQueue = onSwipeToQueue, onMoreOptionsClick = onMoreOptionsClick, onClick = onClick ) diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/PlaylistDetailScreen.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/PlaylistDetailScreen.kt index 8e6c107b9..a346b1d37 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/PlaylistDetailScreen.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/PlaylistDetailScreen.kt @@ -1,5 +1,7 @@ package com.lostf1sh.pixelplayeross.presentation.screens +import com.lostf1sh.pixelplayeross.presentation.components.SwipeToQueueBox +import com.lostf1sh.pixelplayeross.presentation.components.rememberSwipeToQueue import android.widget.Toast import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafely import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafelyReplacing @@ -243,6 +245,7 @@ fun PlaylistDetailScreen( val selectedSongForInfo by playerViewModel.selectedSongForInfo.collectAsStateWithLifecycle() val favoriteIds by playerViewModel.favoriteSongIds.collectAsStateWithLifecycle() + val swipeToQueue = rememberSwipeToQueue(playerViewModel) val stableOnMoreOptionsClick: (Song) -> Unit = remember { { song -> playerViewModel.selectSongForInfo(song) @@ -801,68 +804,76 @@ fun PlaylistDetailScreen( label = "scale" ) - QueuePlaylistSongItem( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 0.dp) - .graphicsLayer { - scaleX = scale - scaleY = scale + SwipeToQueueBox( + // Swipes would fight reordering and removal. + onSwipe = swipeToQueue + ?.takeUnless { isReorderModeEnabled || isRemoveModeEnabled } + ?.let { { it(song) } }, + modifier = Modifier.fillMaxWidth() + ) { rowModifier -> + QueuePlaylistSongItem( + modifier = rowModifier + .fillMaxWidth() + .padding(horizontal = 0.dp) + .graphicsLayer { + scaleX = scale + scaleY = scale + }, + onClick = { + playerViewModel.playSongs( + localReorderableSongs, + song, + currentPlaylist.name, + currentPlaylist.id + ) }, - onClick = { - playerViewModel.playSongs( - localReorderableSongs, - song, - currentPlaylist.name, - currentPlaylist.id - ) - }, - song = song, - isCurrentSong = playbackUiState.isCurrentSong, - isPlaying = playbackUiState.isPlaying, - isDragging = isDragging, - onRemoveClick = { - if (isEditablePlaylist) { - currentPlaylist.let { - playlistViewModel.removeSongFromPlaylist(it.id, song.id) + song = song, + isCurrentSong = playbackUiState.isCurrentSong, + isPlaying = playbackUiState.isPlaying, + isDragging = isDragging, + onRemoveClick = { + if (isEditablePlaylist) { + currentPlaylist.let { + playlistViewModel.removeSongFromPlaylist(it.id, song.id) + } } - } - }, - isFromPlaylist = true, - isReorderModeEnabled = isReorderModeEnabled, - isDragHandleVisible = isReorderModeEnabled && isEditablePlaylist, - isRemoveButtonVisible = isRemoveModeEnabled && isEditablePlaylist, - onMoreOptionsClick = stableOnMoreOptionsClick, - dragHandle = { - IconButton( - onClick = {}, - modifier = Modifier - .draggableHandle( - onDragStarted = { - performAppCompatHapticFeedback( - view, - appHapticsConfig, - HapticFeedbackConstantsCompat.GESTURE_START - ) - }, - onDragStopped = { - performAppCompatHapticFeedback( - view, - appHapticsConfig, - HapticFeedbackConstantsCompat.GESTURE_END - ) - } + }, + isFromPlaylist = true, + isReorderModeEnabled = isReorderModeEnabled, + isDragHandleVisible = isReorderModeEnabled && isEditablePlaylist, + isRemoveButtonVisible = isRemoveModeEnabled && isEditablePlaylist, + onMoreOptionsClick = stableOnMoreOptionsClick, + dragHandle = { + IconButton( + onClick = {}, + modifier = Modifier + .draggableHandle( + onDragStarted = { + performAppCompatHapticFeedback( + view, + appHapticsConfig, + HapticFeedbackConstantsCompat.GESTURE_START + ) + }, + onDragStopped = { + performAppCompatHapticFeedback( + view, + appHapticsConfig, + HapticFeedbackConstantsCompat.GESTURE_END + ) + } + ) + .size(40.dp) + ) { + Icon( + imageVector = Icons.Rounded.DragIndicator, + contentDescription = reorderSongCd, + tint = MaterialTheme.colorScheme.onSurfaceVariant ) - .size(40.dp) - ) { - Icon( - imageVector = Icons.Rounded.DragIndicator, - contentDescription = reorderSongCd, - tint = MaterialTheme.colorScheme.onSurfaceVariant - ) + } } - } - ) + ) + } } } } diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/RecentlyPlayedScreen.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/RecentlyPlayedScreen.kt index 01779fe89..26e9c0cda 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/RecentlyPlayedScreen.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/RecentlyPlayedScreen.kt @@ -1,5 +1,6 @@ package com.lostf1sh.pixelplayeross.presentation.screens +import com.lostf1sh.pixelplayeross.presentation.components.rememberSwipeToQueue import com.lostf1sh.pixelplayeross.presentation.navigation.navigateSafely import com.lostf1sh.pixelplayeross.utils.traceSection @@ -115,6 +116,7 @@ fun RecentlyPlayedScreen( playerViewModel.stablePlayerState.map { it.isPlaying }.distinctUntilChanged() }.collectAsStateWithLifecycle(initialValue = false) val favoriteSongIds by playerViewModel.favoriteSongIds.collectAsStateWithLifecycle() + val swipeToQueue = rememberSwipeToQueue(playerViewModel) val selectedSongForInfo by playerViewModel.selectedSongForInfo.collectAsStateWithLifecycle() val playlistUiState by playlistViewModel.uiState.collectAsStateWithLifecycle() @@ -259,6 +261,7 @@ fun RecentlyPlayedScreen( queueName = queueRecentlyPlayed ) }, + onSwipeToQueue = swipeToQueue?.let { { it(item.song) } }, onMoreOptionsClick = { song -> playerViewModel.selectSongForInfo(song) showSongInfoBottomSheet = true diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/SettingsCategoryScreen.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/SettingsCategoryScreen.kt index 063c09320..8803fbdf9 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/SettingsCategoryScreen.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/screens/SettingsCategoryScreen.kt @@ -175,6 +175,7 @@ import com.lostf1sh.pixelplayeross.data.preferences.LaunchTab import com.lostf1sh.pixelplayeross.data.preferences.LibraryNavigationMode import com.lostf1sh.pixelplayeross.data.preferences.NavBarStyle import com.lostf1sh.pixelplayeross.data.preferences.PreviousButtonBehavior +import com.lostf1sh.pixelplayeross.data.preferences.SwipeToQueueAction import com.lostf1sh.pixelplayeross.data.preferences.ThemePreference import com.lostf1sh.pixelplayeross.data.preferences.ThemePreset import com.lostf1sh.pixelplayeross.utils.isIgnoringBatteryOptimizations @@ -1130,6 +1131,38 @@ fun SettingsCategoryScreen( modifier = Modifier.settingHighlight("item_behavior_mini_swipe_skip", highlightKey) ) } + SettingsSubsection( + title = stringResource(R.string.setcat_song_lists) + ) { + ThemeSelectorItem( + label = stringResource(R.string.setcat_swipe_to_queue_title), + description = stringResource(R.string.setcat_swipe_to_queue_description), + options = linkedMapOf( + SwipeToQueueAction.ADD_TO_QUEUE.storageKey to + stringResource(R.string.setcat_swipe_to_queue_add), + SwipeToQueueAction.PLAY_NEXT.storageKey to + stringResource(R.string.setcat_swipe_to_queue_next), + SwipeToQueueAction.OFF.storageKey to + stringResource(R.string.setcat_swipe_to_queue_off) + ), + optionDescriptions = mapOf( + SwipeToQueueAction.ADD_TO_QUEUE.storageKey to + stringResource(R.string.setcat_swipe_to_queue_add_description), + SwipeToQueueAction.PLAY_NEXT.storageKey to + stringResource(R.string.setcat_swipe_to_queue_next_description), + SwipeToQueueAction.OFF.storageKey to + stringResource(R.string.setcat_swipe_to_queue_off_description) + ), + selectedKey = uiState.swipeToQueueAction.storageKey, + onSelectionChanged = { key -> + settingsViewModel.setSwipeToQueueAction( + SwipeToQueueAction.fromStorageKey(key) + ) + }, + leadingIcon = { Icon(painterResource(R.drawable.rounded_queue_music_24), null, tint = MaterialTheme.colorScheme.secondary) }, + modifier = Modifier.settingHighlight("item_behavior_swipe_to_queue", highlightKey) + ) + } SettingsSubsection( title = stringResource(R.string.setcat_playback_behavior) ) { diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/settings/search/SettingsRegistry.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/settings/search/SettingsRegistry.kt index 281a79439..d26b41787 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/settings/search/SettingsRegistry.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/settings/search/SettingsRegistry.kt @@ -782,6 +782,18 @@ object SettingsRegistry { "restart", "replay", "button" ) ), + SettingSpec( + id = "behavior_swipe_to_queue", + itemKey = "item_behavior_swipe_to_queue", + titleRes = R.string.setcat_swipe_to_queue_title, + subtitleRes = R.string.setcat_swipe_to_queue_description, + category = SettingsCategory.BEHAVIOR, + subscreenRoute = Screen.SettingsCategory.createRoute("behavior"), + type = SettingType.NAVIGABLE_CARD, + keywordsStatic = listOf( + "swipe", "gesture", "queue", "add to queue", "play next", "song list", "playlist" + ) + ), SettingSpec( id = "behavior_haptics", itemKey = "item_behavior_haptics", diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlaybackStateHolder.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlaybackStateHolder.kt index 3e0b37995..b87a728b2 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlaybackStateHolder.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlaybackStateHolder.kt @@ -869,92 +869,7 @@ class PlaybackStateHolder @Inject constructor( val isCurrentlyShuffled = _stablePlayerState.value.isShuffleEnabled if (!isCurrentlyShuffled) { - val playlistTags = playlistTagsOf(player) - if (!queueStateHolder.hasOriginalQueue()) { - // With no original order, for example after a cold start restored - // the queue, only the player knows which playlist each entry came - // from. The order keeps that so shuffle off can put each tag back. - queueStateHolder.setOriginalQueueOrder( - currentSongs, - playlistIdsLinedUpWith(currentSongs, playlistTags) - ) - } - - val currentMediaId = player.currentMediaItem?.mediaId ?: currentSong?.id - val playerCurrentIndex = player.currentMediaItemIndex - .takeIf { it in currentSongs.indices } - val currentIndex = when { - playerCurrentIndex != null && currentMediaId != null && - currentSongs.getOrNull(playerCurrentIndex)?.id == currentMediaId -> playerCurrentIndex - playerCurrentIndex != null && currentMediaId == null -> playerCurrentIndex - currentMediaId != null -> - currentSongs.indexOfFirst { it.id == currentMediaId }.takeIf { it >= 0 } - else -> null - } ?: 0 - val currentPosition = player.currentPosition - val wasPlaying = player.isPlaying - val currentMediaItem = player.currentMediaItem - - val shuffledQueue = withContext(Dispatchers.Default) { - QueueUtils.buildAnchoredShuffleQueueSuspending(currentSongs, currentIndex) - } - - if (currentSongs.size > BULK_REPLACE_THRESHOLD) { - val preservedReplacement = buildQueueSegments( - newQueue = shuffledQueue, - currentIndex = currentIndex, - currentMediaItem = currentMediaItem, - playlistTags = playlistTags - ) - val replacedInPlace = preservedReplacement?.let { preparedSegments -> - replacePlayerQueuePreservingCurrent(player, currentIndex, preparedSegments) - } == true - - if (!replacedInPlace) { - val preparedQueue = buildQueueReplacement( - newQueue = shuffledQueue, - targetIndex = currentIndex, - currentMediaItem = currentMediaItem, - playlistTags = playlistTags - ) - replacePlayerQueue(player, preparedQueue, currentPosition) - } - } else { - val reordered = reorderQueueInPlace(player, shuffledQueue) - if (!reordered) { - val preservedReplacement = buildQueueSegments( - newQueue = shuffledQueue, - currentIndex = currentIndex, - currentMediaItem = currentMediaItem, - playlistTags = playlistTags - ) - val replacedInPlace = preservedReplacement?.let { preparedSegments -> - replacePlayerQueuePreservingCurrent(player, currentIndex, preparedSegments) - } == true - - if (!replacedInPlace) { - val preparedQueue = buildQueueReplacement( - newQueue = shuffledQueue, - targetIndex = currentIndex, - currentMediaItem = currentMediaItem, - playlistTags = playlistTags - ) - replacePlayerQueue(player, preparedQueue, currentPosition) - } - } - } - - updateQueueCallback(shuffledQueue) - _stablePlayerState.update { it.copy(isShuffleEnabled = true) } - if (wasPlaying && !player.isPlaying) { - player.play() - } - - scope?.launch { - if (userPreferencesRepository.persistentShuffleEnabledFlow.first()) { - userPreferencesRepository.setShuffleOn(true) - } - } + shuffleQueue(player, currentSongs, currentSong, updateQueueCallback) } else { scope?.launch { if (userPreferencesRepository.persistentShuffleEnabledFlow.first()) { @@ -1052,6 +967,142 @@ class PlaybackStateHolder @Inject constructor( } } + /** + * Shuffles [currentSongs] with the playing song first and applies it to the player without + * interrupting playback. The pre-shuffle order is saved once so shuffle off can restore it. + */ + private suspend fun shuffleQueue( + player: Player, + currentSongs: List, + currentSong: Song?, + updateQueueCallback: (List) -> Unit + ) { + var playlistTags = playlistTagsOf(player) + if (!queueStateHolder.hasOriginalQueue()) { + // With no original order, for example after a cold start restored + // the queue, only the player knows which playlist each entry came + // from. The order keeps that so shuffle off can put each tag back. + queueStateHolder.setOriginalQueueOrder( + currentSongs, + playlistIdsLinedUpWith(currentSongs, playlistTags) + ) + } + + val currentMediaId = player.currentMediaItem?.mediaId ?: currentSong?.id + val playerCurrentIndex = player.currentMediaItemIndex + .takeIf { it in currentSongs.indices } + var currentIndex = when { + playerCurrentIndex != null && currentMediaId != null && + currentSongs.getOrNull(playerCurrentIndex)?.id == currentMediaId -> playerCurrentIndex + playerCurrentIndex != null && currentMediaId == null -> playerCurrentIndex + currentMediaId != null -> + currentSongs.indexOfFirst { it.id == currentMediaId }.takeIf { it >= 0 } + else -> null + } ?: 0 + var songs = currentSongs + // Like other players, the playing song leads the shuffled order, so no song is left + // behind it until the queue repeats. Moving the playing item keeps playback going. + if ( + currentIndex > 0 && + player.mediaItemCount == currentSongs.size && + player.currentMediaItemIndex == currentIndex + ) { + player.moveMediaItem(currentIndex, 0) + songs = listOf(currentSongs[currentIndex]) + + currentSongs.filterIndexed { index, _ -> index != currentIndex } + currentIndex = 0 + playlistTags = playlistTagsOf(player) + } + val currentPosition = player.currentPosition + val wasPlaying = player.isPlaying + val currentMediaItem = player.currentMediaItem + + val shuffledQueue = withContext(Dispatchers.Default) { + QueueUtils.buildAnchoredShuffleQueueSuspending(songs, currentIndex) + } + + if (currentSongs.size > BULK_REPLACE_THRESHOLD) { + val preservedReplacement = buildQueueSegments( + newQueue = shuffledQueue, + currentIndex = currentIndex, + currentMediaItem = currentMediaItem, + playlistTags = playlistTags + ) + val replacedInPlace = preservedReplacement?.let { preparedSegments -> + replacePlayerQueuePreservingCurrent(player, currentIndex, preparedSegments) + } == true + + if (!replacedInPlace) { + val preparedQueue = buildQueueReplacement( + newQueue = shuffledQueue, + targetIndex = currentIndex, + currentMediaItem = currentMediaItem, + playlistTags = playlistTags + ) + replacePlayerQueue(player, preparedQueue, currentPosition) + } + } else { + val reordered = reorderQueueInPlace(player, shuffledQueue) + if (!reordered) { + val preservedReplacement = buildQueueSegments( + newQueue = shuffledQueue, + currentIndex = currentIndex, + currentMediaItem = currentMediaItem, + playlistTags = playlistTags + ) + val replacedInPlace = preservedReplacement?.let { preparedSegments -> + replacePlayerQueuePreservingCurrent(player, currentIndex, preparedSegments) + } == true + + if (!replacedInPlace) { + val preparedQueue = buildQueueReplacement( + newQueue = shuffledQueue, + targetIndex = currentIndex, + currentMediaItem = currentMediaItem, + playlistTags = playlistTags + ) + replacePlayerQueue(player, preparedQueue, currentPosition) + } + } + } + + updateQueueCallback(shuffledQueue) + _stablePlayerState.update { it.copy(isShuffleEnabled = true) } + if (wasPlaying && !player.isPlaying) { + player.play() + } + + scope?.launch { + if (userPreferencesRepository.persistentShuffleEnabledFlow.first()) { + userPreferencesRepository.setShuffleOn(true) + } + } + } + + /** + * Draws a new shuffled order once a repeat-all queue starts over, so every pass plays in a + * fresh order instead of looping the same one. + */ + fun reshuffleForRepeat( + currentSongs: List, + currentSong: Song?, + updateQueueCallback: (List) -> Unit + ) { + if (shuffleToggleJob?.isActive == true || currentSongs.size < 2) return + if (!_stablePlayerState.value.isShuffleEnabled) return + val coroutineScope = scope ?: return + shuffleToggleJob = coroutineScope.launch { + _stablePlayerState.update { it.copy(isShuffleTransitionInProgress = true) } + try { + val player = mediaController ?: return@launch + shuffleQueue(player, currentSongs, currentSong, updateQueueCallback) + } finally { + _stablePlayerState.update { it.copy(isShuffleTransitionInProgress = false) } + shuffleToggleJob = null + } + } + } + fun onCleared(owner: CoroutineScope) { // A stale PlayerViewModel clearing leaves the newer binding alone; the current one // (e.g. ExternalPlayerActivity's) clearing hands the holder back to the previous live diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlayerViewModel.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlayerViewModel.kt index c13023f1c..d1849a825 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlayerViewModel.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlayerViewModel.kt @@ -60,6 +60,7 @@ import com.lostf1sh.pixelplayeross.data.preferences.UserPreferencesRepository import com.lostf1sh.pixelplayeross.data.preferences.AlbumArtQuality import com.lostf1sh.pixelplayeross.data.preferences.ThemePreference import com.lostf1sh.pixelplayeross.data.preferences.restartsAtPosition +import com.lostf1sh.pixelplayeross.data.preferences.SwipeToQueueAction import com.lostf1sh.pixelplayeross.data.repository.LyricsSearchResult import com.lostf1sh.pixelplayeross.data.repository.MusicRepository import com.lostf1sh.pixelplayeross.data.service.MusicNotificationProvider @@ -444,6 +445,13 @@ class PlayerViewModel @Inject constructor( initialValue = NavBarStyle.DEFAULT ) + val swipeToQueueAction: StateFlow = userPreferencesRepository.swipeToQueueActionFlow + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = SwipeToQueueAction.OFF + ) + val navBarCompactMode: StateFlow = userPreferencesRepository.navBarCompactModeFlow .stateIn( scope = viewModelScope, @@ -2704,6 +2712,15 @@ class PlayerViewModel @Inject constructor( override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) { playbackStateHolder.onPlaybackOccurrenceTransition(mediaItem?.mediaId) + // An automatic move to the first entry means a repeat-all queue started over. + if ( + reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO && + playerCtrl.repeatMode == Player.REPEAT_MODE_ALL && + playerCtrl.currentMediaItemIndex == 0 && + !dualPlayerEngine.isUsingWindowedQueue() + ) { + reshuffleForRepeat() + } preparePlaybackAudioMetadataForMedia(mediaItem?.mediaId) transitionSchedulerJob?.cancel() lyricsStateHolder.cancelLoading() @@ -3207,6 +3224,16 @@ class PlayerViewModel @Inject constructor( ) } + private fun reshuffleForRepeat() { + playbackStateHolder.reshuffleForRepeat( + currentSongs = _playerUiState.value.currentPlaybackQueue.toList(), + currentSong = playbackStateHolder.stablePlayerState.value.currentSong, + updateQueueCallback = { newQueue -> + _playerUiState.update { it.copy(currentPlaybackQueue = newQueue.toPlaybackQueue()) } + } + ) + } + fun toggleShuffle(currentSongOverride: Song? = null) { cancelPendingFullQueuePlayback() val currentQueue = _playerUiState.value.currentPlaybackQueue.toList() @@ -3301,6 +3328,21 @@ class PlayerViewModel @Inject constructor( return uri.takeIf { it.scheme == "file" }?.path?.takeIf { it.isNotBlank() } } + /** Queues [song] the way the swipe-to-queue setting says, and confirms it with a toast. */ + fun queueSongFromSwipe(song: Song) { + when (swipeToQueueAction.value) { + SwipeToQueueAction.OFF -> return + SwipeToQueueAction.ADD_TO_QUEUE -> { + addSongToQueue(song) + sendToast(context.getString(R.string.toast_added_to_queue)) + } + SwipeToQueueAction.PLAY_NEXT -> { + addSongNextToQueue(song) + sendToast(context.getString(R.string.toast_playing_next)) + } + } + } + fun addSongToQueue(song: Song) { mediaController?.let { controller -> val mediaItem = buildPlaybackMediaItem(song) diff --git a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/SettingsViewModel.kt b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/SettingsViewModel.kt index 5c4059239..e81afbf01 100644 --- a/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/SettingsViewModel.kt +++ b/app/src/main/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/SettingsViewModel.kt @@ -20,6 +20,7 @@ import com.lostf1sh.pixelplayeross.data.preferences.AppThemeMode import com.lostf1sh.pixelplayeross.data.preferences.CarouselStyle import com.lostf1sh.pixelplayeross.data.preferences.LibraryNavigationMode import com.lostf1sh.pixelplayeross.data.preferences.PreviousButtonBehavior +import com.lostf1sh.pixelplayeross.data.preferences.SwipeToQueueAction import com.lostf1sh.pixelplayeross.data.preferences.DEFAULT_LYRICS_DUET_LAYOUT_ENABLED import com.lostf1sh.pixelplayeross.data.preferences.DEFAULT_LYRICS_FONT_SIZE_SP import com.lostf1sh.pixelplayeross.data.preferences.DEFAULT_SHOW_LYRICS_BACKGROUND_VOCALS @@ -105,6 +106,7 @@ data class SettingsUiState( val miniPlayerSwipeToSkip: Boolean = false, val autoplayOnSkip: Boolean = true, val previousButtonBehavior: PreviousButtonBehavior = PreviousButtonBehavior.DEFAULT, + val swipeToQueueAction: SwipeToQueueAction = SwipeToQueueAction.DEFAULT, val hapticsEnabled: Boolean = true, val immersiveLyricsEnabled: Boolean = false, val immersiveLyricsTimeout: Long = 4000L, @@ -511,6 +513,12 @@ class SettingsViewModel @Inject constructor( } } + viewModelScope.launch { + userPreferencesRepository.swipeToQueueActionFlow.collect { action -> + _uiState.update { it.copy(swipeToQueueAction = action) } + } + } + viewModelScope.launch { userPreferencesRepository.minSongDurationFlow.collect { duration -> _uiState.update { it.copy(minSongDuration = duration) } @@ -1082,6 +1090,12 @@ class SettingsViewModel @Inject constructor( } } + fun setSwipeToQueueAction(action: SwipeToQueueAction) { + viewModelScope.launch { + userPreferencesRepository.setSwipeToQueueAction(action) + } + } + fun setTapBackgroundClosesPlayer(enabled: Boolean) { viewModelScope.launch { userPreferencesRepository.setTapBackgroundClosesPlayer(enabled) diff --git a/app/src/main/res/values-ar/strings_swipe_to_queue.xml b/app/src/main/res/values-ar/strings_swipe_to_queue.xml new file mode 100644 index 000000000..862126985 --- /dev/null +++ b/app/src/main/res/values-ar/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + قوائم الأغاني + اسحب أغنية + اسحب صف الأغنية نحو نهاية الشاشة في قوائم التشغيل والألبومات والفنانين والأنواع والمزيج. + إضافة إلى قائمة الانتظار + يضيف الأغنية إلى نهاية قائمة الانتظار. + تشغيل التالي + يضيف الأغنية بعد الأغنية الحالية مباشرة. + إيقاف + سحب الأغنية لا يفعل شيئًا. + diff --git a/app/src/main/res/values-de/strings_swipe_to_queue.xml b/app/src/main/res/values-de/strings_swipe_to_queue.xml new file mode 100644 index 000000000..45018d63b --- /dev/null +++ b/app/src/main/res/values-de/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Titellisten + Titel wischen + Wische in Playlists, Alben, Künstlern, Genres und Mixes eine Titelzeile zum Bildschirmende. + Zur Warteschlange hinzufügen + Fügt den Titel am Ende der Warteschlange hinzu. + Als Nächstes abspielen + Fügt den Titel direkt nach dem aktuellen ein. + Aus + Wischen über einen Titel bewirkt nichts. + diff --git a/app/src/main/res/values-es/strings_swipe_to_queue.xml b/app/src/main/res/values-es/strings_swipe_to_queue.xml new file mode 100644 index 000000000..70bc8fe0f --- /dev/null +++ b/app/src/main/res/values-es/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Listas de canciones + Deslizar una canción + Desliza la fila de una canción hacia el final de la pantalla en listas, álbumes, artistas, géneros y mixes. + Añadir a la cola + Añade la canción al final de la cola. + Reproducir a continuación + Añade la canción justo después de la que suena. + Desactivado + Deslizar una canción no hace nada. + diff --git a/app/src/main/res/values-fr/strings_swipe_to_queue.xml b/app/src/main/res/values-fr/strings_swipe_to_queue.xml new file mode 100644 index 000000000..cab37b751 --- /dev/null +++ b/app/src/main/res/values-fr/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Listes de titres + Balayer un titre + Balayez la ligne d’un titre vers la fin de l’écran dans les playlists, albums, artistes, genres et mixes. + Ajouter à la file d’attente + Ajoute le titre à la fin de la file d’attente. + Lire ensuite + Ajoute le titre juste après celui en cours. + Désactivé + Balayer un titre ne fait rien. + diff --git a/app/src/main/res/values-in/strings_swipe_to_queue.xml b/app/src/main/res/values-in/strings_swipe_to_queue.xml new file mode 100644 index 000000000..1621942e9 --- /dev/null +++ b/app/src/main/res/values-in/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Daftar lagu + Geser lagu + Geser baris lagu ke arah ujung layar di playlist, album, artis, genre, dan mix. + Tambahkan ke antrean + Menambahkan lagu ke akhir antrean. + Putar berikutnya + Menambahkan lagu tepat setelah lagu yang diputar. + Nonaktif + Menggeser lagu tidak melakukan apa pun. + diff --git a/app/src/main/res/values-it/strings_swipe_to_queue.xml b/app/src/main/res/values-it/strings_swipe_to_queue.xml new file mode 100644 index 000000000..78790b0fc --- /dev/null +++ b/app/src/main/res/values-it/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Elenchi di brani + Scorri un brano + Scorri la riga di un brano verso il bordo finale dello schermo in playlist, album, artisti, generi e mix. + Aggiungi alla coda + Aggiunge il brano alla fine della coda. + Riproduci dopo + Aggiunge il brano subito dopo quello in riproduzione. + Disattivato + Scorrere un brano non fa nulla. + diff --git a/app/src/main/res/values-ko/strings_swipe_to_queue.xml b/app/src/main/res/values-ko/strings_swipe_to_queue.xml new file mode 100644 index 000000000..a79997bbf --- /dev/null +++ b/app/src/main/res/values-ko/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + 노래 목록 + 노래 스와이프 + 재생목록, 앨범, 아티스트, 장르, 믹스에서 노래 행을 화면 끝쪽으로 스와이프합니다. + 대기열에 추가 + 노래를 대기열 끝에 추가합니다. + 다음에 재생 + 재생 중인 노래 바로 다음에 추가합니다. + 끄기 + 노래를 스와이프해도 아무 일도 일어나지 않습니다. + diff --git a/app/src/main/res/values-nb/strings_swipe_to_queue.xml b/app/src/main/res/values-nb/strings_swipe_to_queue.xml new file mode 100644 index 000000000..e8df235ac --- /dev/null +++ b/app/src/main/res/values-nb/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Sanglister + Sveip en sang + Sveip en sangrad mot enden av skjermen i spillelister, album, artister, sjangre og mikser. + Legg til i køen + Legger sangen til på slutten av køen. + Spill neste + Legger sangen rett etter den som spilles. + Av + Å sveipe en sang gjør ingenting. + diff --git a/app/src/main/res/values-pt-rBR/strings_swipe_to_queue.xml b/app/src/main/res/values-pt-rBR/strings_swipe_to_queue.xml new file mode 100644 index 000000000..9993b1bf8 --- /dev/null +++ b/app/src/main/res/values-pt-rBR/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Listas de músicas + Deslizar uma música + Deslize a linha de uma música em direção ao fim da tela em playlists, álbuns, artistas, gêneros e mixes. + Adicionar à fila + Adiciona a música ao fim da fila. + Tocar em seguida + Adiciona a música logo após a que está tocando. + Desativado + Deslizar uma música não faz nada. + diff --git a/app/src/main/res/values-ru/strings_swipe_to_queue.xml b/app/src/main/res/values-ru/strings_swipe_to_queue.xml new file mode 100644 index 000000000..1fc16481c --- /dev/null +++ b/app/src/main/res/values-ru/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Списки треков + Свайп по треку + Проведите строку трека к концу экрана в плейлистах, альбомах, исполнителях, жанрах и миксах. + Добавить в очередь + Добавляет трек в конец очереди. + Воспроизвести следующим + Добавляет трек сразу после текущего. + Выкл. + Свайп по треку ничего не делает. + diff --git a/app/src/main/res/values-tr/strings_swipe_to_queue.xml b/app/src/main/res/values-tr/strings_swipe_to_queue.xml new file mode 100644 index 000000000..bf3b979d8 --- /dev/null +++ b/app/src/main/res/values-tr/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Şarkı listeleri + Şarkıyı kaydır + Çalma listeleri, albümler, sanatçılar, türler ve mikslerde bir şarkı satırını ekranın sonuna doğru kaydırın. + Sıraya ekle + Şarkıyı sıranın sonuna ekler. + Sıradaki + Şarkıyı çalanın hemen arkasına ekler. + Kapalı + Şarkıyı kaydırmak hiçbir şey yapmaz. + diff --git a/app/src/main/res/values-vi/strings_swipe_to_queue.xml b/app/src/main/res/values-vi/strings_swipe_to_queue.xml new file mode 100644 index 000000000..3337d1250 --- /dev/null +++ b/app/src/main/res/values-vi/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Danh sách bài hát + Vuốt bài hát + Vuốt một dòng bài hát về phía cuối màn hình trong danh sách phát, album, nghệ sĩ, thể loại và mix. + Thêm vào hàng đợi + Thêm bài hát vào cuối hàng đợi. + Phát tiếp theo + Thêm bài hát ngay sau bài đang phát. + Tắt + Vuốt bài hát không làm gì cả. + diff --git a/app/src/main/res/values-zh-rCN/strings_swipe_to_queue.xml b/app/src/main/res/values-zh-rCN/strings_swipe_to_queue.xml new file mode 100644 index 000000000..94b279e09 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + 歌曲列表 + 滑动歌曲 + 在播放列表、专辑、艺术家、流派和混音中,将歌曲行向屏幕末端滑动。 + 添加到队列 + 将歌曲添加到队列末尾。 + 下一首播放 + 将歌曲添加到当前歌曲之后。 + 关闭 + 滑动歌曲不执行任何操作。 + diff --git a/app/src/main/res/values/strings_swipe_to_queue.xml b/app/src/main/res/values/strings_swipe_to_queue.xml new file mode 100644 index 000000000..f3ec0982a --- /dev/null +++ b/app/src/main/res/values/strings_swipe_to_queue.xml @@ -0,0 +1,12 @@ + + + Song lists + Swipe a song + Swipe a song row toward the end of the screen in playlists, albums, artists, genres and mixes. + Add to queue + Adds the song to the end of the queue. + Play next + Adds the song right after the one playing. + Off + Swiping a song does nothing. + diff --git a/app/src/test/java/com/lostf1sh/pixelplayeross/data/DailyMixManagerTest.kt b/app/src/test/java/com/lostf1sh/pixelplayeross/data/DailyMixManagerTest.kt new file mode 100644 index 000000000..9a6c20ebd --- /dev/null +++ b/app/src/test/java/com/lostf1sh/pixelplayeross/data/DailyMixManagerTest.kt @@ -0,0 +1,60 @@ +package com.lostf1sh.pixelplayeross.data + +import android.content.Context +import com.lostf1sh.pixelplayeross.data.database.EngagementDao +import com.lostf1sh.pixelplayeross.data.model.Song +import io.mockk.coEvery +import io.mockk.every +import io.mockk.mockk +import java.io.File +import java.util.Calendar +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir + +class DailyMixManagerTest { + + @TempDir + lateinit var tempDir: File + + @Test + fun `daily mix rotates between days when nothing has been played`() = runTest { + val context = mockk { every { filesDir } returns tempDir } + val dao = mockk { coEvery { getAllEngagements() } returns emptyList() } + val manager = DailyMixManager(context, dao) + // Distinct artists and genres so diversity caps do not decide the pick. + val songs = (1..300).map { song(it) } + + val monday = manager.generateDailyMix(songs, calendar = day(2025, Calendar.MARCH, 3)).map { it.id } + val mondayAgain = manager.generateDailyMix(songs, calendar = day(2025, Calendar.MARCH, 3)).map { it.id } + val tuesday = manager.generateDailyMix(songs, calendar = day(2025, Calendar.MARCH, 4)).map { it.id } + + assertEquals(monday, mondayAgain) + val overlap = monday.intersect(tuesday.toSet()).size + assertTrue(overlap < monday.size / 2, "expected a mostly new mix, overlap=$overlap") + } + + private fun day(year: Int, month: Int, dayOfMonth: Int) = + Calendar.getInstance().apply { set(year, month, dayOfMonth) } + + private fun song(index: Int) = Song( + id = index.toString(), + title = "Song $index", + artist = "Artist $index", + artistId = index.toLong(), + album = "Album", + albumId = 1L, + path = "/music/$index.mp3", + contentUriString = "content://media/external/audio/media/$index", + albumArtUriString = null, + duration = 180_000L, + genre = "Genre $index", + // Newest songs used to win every day through the novelty score alone. + dateAdded = System.currentTimeMillis() - index * 86_400_000L, + mimeType = "audio/mpeg", + bitrate = 320_000, + sampleRate = 44_100 + ) +} diff --git a/app/src/test/java/com/lostf1sh/pixelplayeross/data/media/AudioMetadataReaderTest.kt b/app/src/test/java/com/lostf1sh/pixelplayeross/data/media/AudioMetadataReaderTest.kt index 502b7f9d4..2b9da55e9 100644 --- a/app/src/test/java/com/lostf1sh/pixelplayeross/data/media/AudioMetadataReaderTest.kt +++ b/app/src/test/java/com/lostf1sh/pixelplayeross/data/media/AudioMetadataReaderTest.kt @@ -86,6 +86,34 @@ class AudioMetadataReaderTest { assertEquals("image/png", artwork.mimeType) } + @Test + fun `firstMusicBrainzId returns the first well-formed id and drops malformed values`() { + val recording = "a1b2c3d4-0000-4000-8000-123456789ABC" + + assertEquals(recording.lowercase(), firstMusicBrainzId(listOf(null, "not-an-id", " $recording "))) + assertEquals( + "11111111-2222-3333-4444-555555555555", + firstMusicBrainzId(listOf("11111111-2222-3333-4444-555555555555; 66666666-7777-8888-9999-000000000000")) + ) + assertNull(firstMusicBrainzId(listOf("", "12345"))) + assertNull(firstMusicBrainzId(null)) + } + + @Test + fun `JAudioTagger fallback reads embedded MusicBrainz ids`() { + val file = writeTaggedWav() + val audioFile = AudioFileIO.read(file) + audioFile.tag.setField(FieldKey.MUSICBRAINZ_TRACK_ID, RECORDING_MBID) + audioFile.tag.setField(FieldKey.MUSICBRAINZ_RELEASEID, RELEASE_MBID) + audioFile.commit() + + val metadata = AudioMetadataReader.readWithJAudioTagger(file, readArtwork = false) + + assertEquals(RECORDING_MBID, metadata?.mbRecordingId) + assertEquals(RELEASE_MBID, metadata?.mbReleaseId) + assertNull(metadata?.mbArtistId) + } + @Test fun `read records a metadata timing even when the file cannot be read`() { // ParcelFileDescriptor is stubbed on the JVM, so the TagLib path fails and the read @@ -146,6 +174,8 @@ class AudioMetadataReaderTest { private companion object { const val TITLE = "Scan Title" + const val RECORDING_MBID = "0f4a1b2c-3d4e-4f50-8a6b-7c8d9e0f1a2b" + const val RELEASE_MBID = "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d" val PNG_SIGNATURE = byteArrayOf( 0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A diff --git a/app/src/test/java/com/lostf1sh/pixelplayeross/data/service/player/FadingPlayerTest.kt b/app/src/test/java/com/lostf1sh/pixelplayeross/data/service/player/FadingPlayerTest.kt index 274b87ddd..58aa10f91 100644 --- a/app/src/test/java/com/lostf1sh/pixelplayeross/data/service/player/FadingPlayerTest.kt +++ b/app/src/test/java/com/lostf1sh/pixelplayeross/data/service/player/FadingPlayerTest.kt @@ -3,6 +3,7 @@ package com.lostf1sh.pixelplayeross.data.service.player import androidx.media3.common.Player import io.mockk.every import io.mockk.mockk +import io.mockk.verify import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.StandardTestDispatcher @@ -39,14 +40,22 @@ class FadingPlayerTest { Dispatchers.resetMain() } - private class InnerState(var volume: Float, var isPlaying: Boolean) + private class InnerState( + var volume: Float, + var isPlaying: Boolean, + var playWhenReady: Boolean = isPlaying, + ) private fun innerPlayer(state: InnerState): Player = mockk(relaxed = true).also { player -> every { player.volume } answers { state.volume } every { player.setVolume(any()) } answers { state.volume = firstArg() } every { player.isPlaying } answers { state.isPlaying } - every { player.pause() } answers { state.isPlaying = false } + every { player.playWhenReady } answers { state.playWhenReady } + every { player.pause() } answers { + state.isPlaying = false + state.playWhenReady = false + } } @Test @@ -129,4 +138,124 @@ class FadingPlayerTest { assertEquals(1f, state.volume) } + + @Test + fun `pause is reported when its fade starts, before the engine player stops`() = + runTest(dispatcher) { + val state = InnerState(volume = 1f, isPlaying = true) + val inner = innerPlayer(state) + val player = FadingPlayer(inner, TestScope(dispatcher)) + val listener = mockk(relaxed = true) + player.addListener(listener) + + player.pause() + runCurrent() + + assertFalse(player.isPlaying) + assertFalse(player.playWhenReady) + assertTrue(state.isPlaying) + verify(exactly = 1) { + listener.onPlayWhenReadyChanged( + false, + Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST + ) + } + verify(exactly = 1) { listener.onIsPlayingChanged(false) } + verify(exactly = 0) { inner.pause() } + + advanceUntilIdle() + + verify(exactly = 1) { inner.pause() } + assertFalse(player.isPlaying) + // The end of the fade changes nothing a listener has not already been told. + verify(exactly = 1) { listener.onIsPlayingChanged(any()) } + verify(exactly = 1) { listener.onPlayWhenReadyChanged(any(), any()) } + } + + @Test + fun `play during the pause fade reports playing again and never pauses the engine player`() = + runTest(dispatcher) { + val state = InnerState(volume = 1f, isPlaying = true) + val inner = innerPlayer(state) + val player = FadingPlayer(inner, TestScope(dispatcher)) + val listener = mockk(relaxed = true) + player.addListener(listener) + + player.pause() + advanceTimeBy(250) + player.play() + + assertTrue(player.isPlaying) + assertTrue(player.playWhenReady) + verify(exactly = 1) { + listener.onPlayWhenReadyChanged( + true, + Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST + ) + } + verify(exactly = 1) { listener.onIsPlayingChanged(true) } + + advanceUntilIdle() + + verify(exactly = 0) { inner.pause() } + assertEquals(1f, state.volume) + } + + @Test + fun `setting play when ready during the pause fade resumes instead of letting it pause`() = + runTest(dispatcher) { + val state = InnerState(volume = 1f, isPlaying = true) + val inner = innerPlayer(state) + val player = FadingPlayer(inner, TestScope(dispatcher)) + + player.pause() + advanceTimeBy(250) + player.playWhenReady = true + advanceUntilIdle() + + assertTrue(player.isPlaying) + verify(exactly = 0) { inner.pause() } + assertEquals(1f, state.volume) + } + + @Test + fun `second pause during the pause fade keeps ramping down and is reported once`() = + runTest(dispatcher) { + val state = InnerState(volume = 1f, isPlaying = true) + val inner = innerPlayer(state) + val player = FadingPlayer(inner, TestScope(dispatcher)) + val listener = mockk(relaxed = true) + player.addListener(listener) + + player.pause() + advanceTimeBy(250) + val midFadeVolume = state.volume + player.pause() + runCurrent() + + // Still fading rather than cut off, and not back up to full volume. + assertTrue(state.isPlaying) + assertTrue(state.volume > 0f && state.volume <= midFadeVolume) + verify(exactly = 0) { inner.pause() } + + advanceUntilIdle() + + verify(exactly = 1) { inner.pause() } + verify(exactly = 1) { listener.onIsPlayingChanged(false) } + assertEquals(1f, state.volume) + } + + @Test + fun `removed listener is not told about a pause fade`() = runTest(dispatcher) { + val state = InnerState(volume = 1f, isPlaying = true) + val player = FadingPlayer(innerPlayer(state), TestScope(dispatcher)) + val listener = mockk(relaxed = true) + player.addListener(listener) + player.removeListener(listener) + + player.pause() + advanceUntilIdle() + + verify(exactly = 0) { listener.onIsPlayingChanged(any()) } + } } diff --git a/app/src/test/java/com/lostf1sh/pixelplayeross/data/worker/SyncWorkerMusicBrainzIdsTest.kt b/app/src/test/java/com/lostf1sh/pixelplayeross/data/worker/SyncWorkerMusicBrainzIdsTest.kt new file mode 100644 index 000000000..e873206ea --- /dev/null +++ b/app/src/test/java/com/lostf1sh/pixelplayeross/data/worker/SyncWorkerMusicBrainzIdsTest.kt @@ -0,0 +1,44 @@ +package com.lostf1sh.pixelplayeross.data.worker + +import com.lostf1sh.pixelplayeross.data.database.SongEntity +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class SyncWorkerMusicBrainzIdsTest { + + private fun song(recording: String?, release: String?, artist: String?) = SongEntity( + id = 1L, + title = "Title", + artistName = "Artist", + artistId = 1L, + albumName = "Album", + albumId = 1L, + contentUriString = "content://media/external/audio/media/1", + albumArtUriString = null, + duration = 1_000L, + genre = null, + filePath = "/music/a.opus", + parentDirectoryPath = "/music", + mbRecordingId = recording, + mbReleaseId = release, + mbArtistId = artist + ) + + @Test + fun `rescan without embedded ids keeps the stored ids`() { + val stored = song("rec", "rel", "art") + + val merged = song(null, null, null).withMusicBrainzIdsFallback(stored) + + assertEquals(Triple("rec", "rel", "art"), Triple(merged.mbRecordingId, merged.mbReleaseId, merged.mbArtistId)) + } + + @Test + fun `embedded ids replace stored ids as a group`() { + val stored = song("old-rec", "old-rel", "old-art") + + val merged = song("new-rec", null, null).withMusicBrainzIdsFallback(stored) + + assertEquals(Triple("new-rec", null, null), Triple(merged.mbRecordingId, merged.mbReleaseId, merged.mbArtistId)) + } +} diff --git a/app/src/test/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/DailyMixStateHolderTest.kt b/app/src/test/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/DailyMixStateHolderTest.kt index c53adb871..e6946191f 100644 --- a/app/src/test/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/DailyMixStateHolderTest.kt +++ b/app/src/test/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/DailyMixStateHolderTest.kt @@ -173,7 +173,7 @@ class DailyMixStateHolderTest { songsStillInLibrary = listOf(song("smart"), song("other")) ) coEvery { musicRepository.getAllSongsOnce() } returns listOf(song("smart"), song("other")) - coEvery { dailyMixManager.generateDailyMix(any(), any(), any()) } returns listOf(song("other")) + coEvery { dailyMixManager.generateDailyMix(any(), any(), any(), any()) } returns listOf(song("other")) coEvery { dailyMixManager.generateYourMix(any(), any(), any()) } returns listOf(song("other")) holder.initialize(owner) @@ -199,7 +199,7 @@ class DailyMixStateHolderTest { savedReplacedAtMillis = System.currentTimeMillis() ) coEvery { musicRepository.getAllSongsOnce() } returns listOf(song("smart"), song("other")) - coEvery { dailyMixManager.generateDailyMix(any(), any(), any()) } returns listOf(song("other")) + coEvery { dailyMixManager.generateDailyMix(any(), any(), any(), any()) } returns listOf(song("other")) coEvery { dailyMixManager.generateYourMix(any(), any(), any()) } returns listOf(song("other")) holder.initialize(owner) @@ -220,7 +220,7 @@ class DailyMixStateHolderTest { savedReplacedAtMillis = System.currentTimeMillis() ) coEvery { musicRepository.getAllSongsOnce() } returns listOf(song("other")) - coEvery { dailyMixManager.generateDailyMix(any(), any(), any()) } returns listOf(song("other")) + coEvery { dailyMixManager.generateDailyMix(any(), any(), any(), any()) } returns listOf(song("other")) coEvery { dailyMixManager.generateYourMix(any(), any(), any()) } returns listOf(song("other")) holder.initialize(owner) // A Smart Mix applied earlier today whose only song a sync has since removed @@ -245,7 +245,7 @@ class DailyMixStateHolderTest { coEvery { musicRepository.getAllSongsOnce() } returns listOf(song("smart"), song("other")) val generating = CompletableDeferred() val finishGenerating = CompletableDeferred() - coEvery { dailyMixManager.generateDailyMix(any(), any(), any()) } coAnswers { + coEvery { dailyMixManager.generateDailyMix(any(), any(), any(), any()) } coAnswers { generating.complete(Unit) finishGenerating.await() listOf(song("other")) @@ -276,7 +276,7 @@ class DailyMixStateHolderTest { savedReplacedAtMillis = System.currentTimeMillis() ) coEvery { musicRepository.getAllSongsOnce() } returns listOf(song("smart"), song("other")) - coEvery { dailyMixManager.generateDailyMix(any(), any(), any()) } returns listOf(song("other")) + coEvery { dailyMixManager.generateDailyMix(any(), any(), any(), any()) } returns listOf(song("other")) coEvery { dailyMixManager.generateYourMix(any(), any(), any()) } returns listOf(song("other")) val lookups = AtomicInteger() val keepCheckLooking = CompletableDeferred() diff --git a/app/src/test/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlaybackStateHolderTest.kt b/app/src/test/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlaybackStateHolderTest.kt index c1202593c..a0af7518d 100644 --- a/app/src/test/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlaybackStateHolderTest.kt +++ b/app/src/test/java/com/lostf1sh/pixelplayeross/presentation/viewmodel/PlaybackStateHolderTest.kt @@ -653,8 +653,8 @@ class PlaybackStateHolderTest { val playlistSongs = playlistOf(81) val duplicated = playlistSongs[5] val songs = playlistSongs + duplicated - // The playlist's own copy plays and keeps its tag in place, so the copy added through - // Play next must not be handed that tag as well. + // The playlist's own copy plays and keeps its tag as it moves to the front, so the copy + // added through Play next must not be handed that tag as well. val queue = TaggedQueue(songs, playlistSongs.map { "playlist" } + null, currentIndex = 5) val playing = queue.playing @@ -663,8 +663,8 @@ class PlaybackStateHolderTest { holder.toggleShuffleAndWait(songs, duplicated) - assertSame(playing, queue.items[5]) - val rebuilt = queue.entries().filterIndexed { index, _ -> index != 5 } + assertSame(playing, queue.items[0]) + val rebuilt = queue.entries().drop(1) assertEquals(listOf(null), rebuilt.filter { it.first == duplicated.id }.map { it.second }) assertEquals(playlistSongs.size - 1, rebuilt.count { it.second != null }) verify(exactly = 0) { queue.controller.setMediaItems(any(), any(), any()) } @@ -678,10 +678,10 @@ class PlaybackStateHolderTest { val songs = playlistSongs + duplicated val queue = TaggedQueue(songs, playlistSongs.map { "playlist" } + null, currentIndex = 5) val playing = queue.playing - // The player reports another current index once the entries around the playing one are + // The player reports another current index once the entries after the playing one are // replaced, so the shuffle replaces the whole queue in one call instead. every { queue.controller.currentMediaItemIndex } answers { - if (queue.segmentReplaceCount > 0) 0 else 5 + if (queue.segmentReplaceCount > 0) 3 else 5 } withPlaylistTagsIn(queue.tags) { @@ -689,14 +689,33 @@ class PlaybackStateHolderTest { holder.toggleShuffleAndWait(songs, duplicated) - verify(exactly = 1) { queue.controller.setMediaItems(any(), 5, any()) } - assertSame(playing, queue.items[5]) - val rebuilt = queue.entries().filterIndexed { index, _ -> index != 5 } + verify(exactly = 1) { queue.controller.setMediaItems(any(), 0, any()) } + assertSame(playing, queue.items[0]) + val rebuilt = queue.entries().drop(1) assertEquals(listOf(null), rebuilt.filter { it.first == duplicated.id }.map { it.second }) assertEquals(playlistSongs.size - 1, rebuilt.count { it.second != null }) } } + @Test + fun `turning shuffle on moves the playing song to the front without restarting it`() = runTest { + val songs = playlistOf(10) + val queue = TaggedQueue(songs, songs.map { null }, currentIndex = 4) + val playing = queue.playing + + withPlaylistTagsIn(queue.tags) { + val holder = holderFor(queue.controller) + + val shuffled = holder.toggleShuffleAndWait(songs, songs[4]) + + assertEquals(songs[4], shuffled.first()) + assertEquals(songs.toSet(), shuffled.toSet()) + assertSame(playing, queue.items[0]) + assertEquals(shuffled.map { it.id }, queue.items.map { it.mediaId }) + verify(exactly = 0) { queue.controller.setMediaItems(any(), any(), any()) } + } + } + @Test fun `turning shuffle off after a cold start puts each copy's tag back at its own place`() = runTest { // A restored queue: the playlist plays at song-2 and song-50 was added again through