diff --git a/app/src/main/java/org/oxycblt/auxio/Auxio.kt b/app/src/main/java/org/oxycblt/auxio/Auxio.kt index 2304a626b..9f138e99e 100644 --- a/app/src/main/java/org/oxycblt/auxio/Auxio.kt +++ b/app/src/main/java/org/oxycblt/auxio/Auxio.kt @@ -47,8 +47,10 @@ class Auxio : Application() { override fun onCreate() { super.onCreate() @Suppress("KotlinConstantConditions") - if (BuildConfig.APPLICATION_ID != "org.oxycblt.auxio" && - BuildConfig.APPLICATION_ID != "org.oxycblt.auxio.debug") { + if ( + BuildConfig.APPLICATION_ID != "org.oxycblt.auxio" && + BuildConfig.APPLICATION_ID != "org.oxycblt.auxio.debug" + ) { Timber.plant(CopyleftNoticeTree()) } else if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) @@ -72,8 +74,11 @@ class Auxio : Application() { .setIcon(IconCompat.createWithResource(this, R.drawable.ic_shortcut_shuffle_24)) .setIntent( Intent(this, MainActivity::class.java) - .setAction(INTENT_KEY_SHORTCUT_SHUFFLE)) - .build())) + .setAction(INTENT_KEY_SHORTCUT_SHUFFLE) + ) + .build() + ), + ) } companion object { diff --git a/app/src/main/java/org/oxycblt/auxio/AuxioService.kt b/app/src/main/java/org/oxycblt/auxio/AuxioService.kt index bb2d7b1af..40a218fa0 100644 --- a/app/src/main/java/org/oxycblt/auxio/AuxioService.kt +++ b/app/src/main/java/org/oxycblt/auxio/AuxioService.kt @@ -94,7 +94,7 @@ class AuxioService : override fun onGetRoot( clientPackageName: String, clientUid: Int, - rootHints: Bundle? + rootHints: Bundle?, ): BrowserRoot { return musicFragment.getRoot() } @@ -111,7 +111,7 @@ class AuxioService : override fun onLoadChildren( parentId: String, result: Result>, - options: Bundle + options: Bundle, ) { val maximumRootChildLimit = getRootChildrenLimit() musicFragment.getChildren(parentId, maximumRootChildLimit, result, options.getPage()) @@ -123,7 +123,9 @@ class AuxioService : private fun getRootChildrenLimit(): Int { return browserRootHints?.getInt( - MediaConstants.BROWSER_ROOT_HINTS_KEY_ROOT_CHILDREN_LIMIT, 4) ?: 4 + MediaConstants.BROWSER_ROOT_HINTS_KEY_ROOT_CHILDREN_LIMIT, + 4, + ) ?: 4 } private fun Bundle.getPage(): MusicServiceFragment.Page? { @@ -175,7 +177,7 @@ interface ForegroundListener { enum class Change { MEDIA_SESSION, - INDEXER + INDEXER, } } diff --git a/app/src/main/java/org/oxycblt/auxio/MainActivity.kt b/app/src/main/java/org/oxycblt/auxio/MainActivity.kt index 9430e6fd6..e7287c1b5 100644 --- a/app/src/main/java/org/oxycblt/auxio/MainActivity.kt +++ b/app/src/main/java/org/oxycblt/auxio/MainActivity.kt @@ -71,7 +71,8 @@ class MainActivity : AppCompatActivity() { startService( Intent(this, AuxioService::class.java) .setAction(AuxioService.ACTION_START) - .putExtra(AuxioService.INTENT_KEY_START_ID, IntegerTable.START_ID_ACTIVITY)) + .putExtra(AuxioService.INTENT_KEY_START_ID, IntegerTable.START_ID_ACTIVITY) + ) if (!startIntentAction(intent)) { // No intent action to do, just restore the previously saved state. diff --git a/app/src/main/java/org/oxycblt/auxio/MainFragment.kt b/app/src/main/java/org/oxycblt/auxio/MainFragment.kt index 10342f1d1..0c51e1c5a 100644 --- a/app/src/main/java/org/oxycblt/auxio/MainFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/MainFragment.kt @@ -126,7 +126,8 @@ class MainFragment : sheetBackCallback = SheetBackPressedCallback( playbackSheetBehavior = playbackSheetBehavior, - queueSheetBehavior = queueSheetBehavior) + queueSheetBehavior = queueSheetBehavior, + ) val detailBackCallback = DetailBackPressedCallback(detailModel).also { detailBackCallback = it } val selectionBackCallback = @@ -145,9 +146,13 @@ class MainFragment : // Send meaningful accessibility events for bottom sheets ViewCompat.setAccessibilityPaneTitle( - binding.playbackSheet, context.getString(R.string.lbl_playback)) + binding.playbackSheet, + context.getString(R.string.lbl_playback), + ) ViewCompat.setAccessibilityPaneTitle( - binding.queueSheet, context.getString(R.string.lbl_queue)) + binding.queueSheet, + context.getString(R.string.lbl_queue), + ) if (queueSheetBehavior != null) { // In portrait mode, set up click listeners on the stacked sheets. @@ -166,7 +171,8 @@ class MainFragment : ShapeAppearanceModel.builder( context, MR.style.ShapeAppearance_Material3_Corner_ExtraLarge, - MR.style.ShapeAppearanceOverlay_Material3_Corner_Top) + MR.style.ShapeAppearanceOverlay_Material3_Corner_Top, + ) .build() fillColor = context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh) } @@ -194,7 +200,8 @@ class MainFragment : binding, homeModel.songList.value, homeModel.isFastScrolling.value, - homeModel.currentTabType.value) + homeModel.currentTabType.value, + ) // --- VIEWMODEL SETUP --- // This has to be done here instead of the playback panel to make sure that it's prioritized @@ -281,7 +288,8 @@ class MainFragment : binding, homeModel.songList.value, homeModel.isFastScrolling.value, - homeModel.currentTabType.value) + homeModel.currentTabType.value, + ) } val playbackOutRatio = 1 - min(playbackRatio * 2, 1f) @@ -295,7 +303,8 @@ class MainFragment : binding.mainSheetScrim.alpha = playbackLastStretchRatio playbackSheetBehavior.sheetBackgroundDrawable.setCornerSize( - normalCornerSize * (1 - playbackLastStretchRatio)) + normalCornerSize * (1 - playbackLastStretchRatio) + ) binding.exploreNavHost.isInvisible = playbackLastStretchRatio == 1f binding.playbackSheet.translationZ = (1 - playbackLastStretchRatio) * elevationNormal @@ -398,13 +407,18 @@ class MainFragment : requireBinding(), homeModel.songList.value, homeModel.isFastScrolling.value, - homeModel.currentTabType.value) + homeModel.currentTabType.value, + ) } private fun updateCurrentTab(tabType: MusicType) { val binding = requireBinding() updateFabVisibility( - binding, homeModel.songList.value, homeModel.isFastScrolling.value, tabType) + binding, + homeModel.songList.value, + homeModel.isFastScrolling.value, + tabType, + ) } private fun updateIndexerState(state: IndexingState?) { @@ -415,7 +429,8 @@ class MainFragment : binding, homeModel.songList.value, homeModel.isFastScrolling.value, - homeModel.currentTabType.value) + homeModel.currentTabType.value, + ) } } @@ -428,7 +443,7 @@ class MainFragment : binding: FragmentMainBinding, songs: List, isFastScrolling: Boolean, - tabType: MusicType + tabType: MusicType, ) { // If there are no songs, it's likely that the library has not been loaded, so // displaying the shuffle FAB makes no sense. We also don't want the fast scroll @@ -448,15 +463,19 @@ class MainFragment : object : FloatingActionButton.OnVisibilityChangedListener() { override fun onHidden(fab: FloatingActionButton) { super.onHidden(fab) - if (shouldHideAllFabs( - binding, - homeModel.songList.value, - homeModel.isFastScrolling.value)) { + if ( + shouldHideAllFabs( + binding, + homeModel.songList.value, + homeModel.isFastScrolling.value, + ) + ) { return } binding.homeShuffleFab.show() } - }) + } + ) } else { L.d("Showing immediately") binding.homeShuffleFab.show() @@ -473,15 +492,19 @@ class MainFragment : object : FloatingActionButton.OnVisibilityChangedListener() { override fun onHidden(fab: FloatingActionButton) { super.onHidden(fab) - if (shouldHideAllFabs( - binding, - homeModel.songList.value, - homeModel.isFastScrolling.value)) { + if ( + shouldHideAllFabs( + binding, + homeModel.songList.value, + homeModel.isFastScrolling.value, + ) + ) { return } binding.homeNewPlaylistFab.show() } - }) + } + ) } else { L.d("Showing immediately") binding.homeNewPlaylistFab.show() @@ -493,7 +516,7 @@ class MainFragment : private fun shouldHideAllFabs( binding: FragmentMainBinding, songs: List, - isFastScrolling: Boolean + isFastScrolling: Boolean, ) = binding.exploreNavHost.findNavController().currentDestination?.id != R.id.home_fragment || sheetRising == true || @@ -579,8 +602,10 @@ class MainFragment : val queueSheetBehavior = (binding.queueSheet.coordinatorLayoutBehavior ?: return) as QueueBottomSheetBehavior - if (playbackSheetBehavior.state == BackportBottomSheetBehavior.STATE_EXPANDED && - queueSheetBehavior.targetState == BackportBottomSheetBehavior.STATE_EXPANDED) { + if ( + playbackSheetBehavior.state == BackportBottomSheetBehavior.STATE_EXPANDED && + queueSheetBehavior.targetState == BackportBottomSheetBehavior.STATE_EXPANDED + ) { // Queue sheet and playback sheet is expanded, close the queue sheet so the // playback panel can shown. L.d("Collapsing queue sheet") @@ -608,8 +633,10 @@ class MainFragment : binding.playbackSheet.coordinatorLayoutBehavior as PlaybackBottomSheetBehavior val queueSheetBehavior = (binding.queueSheet.coordinatorLayoutBehavior ?: return) as QueueBottomSheetBehavior - if (playbackSheetBehavior.state == BackportBottomSheetBehavior.STATE_EXPANDED && - queueSheetBehavior.targetState == BackportBottomSheetBehavior.STATE_COLLAPSED) { + if ( + playbackSheetBehavior.state == BackportBottomSheetBehavior.STATE_EXPANDED && + queueSheetBehavior.targetState == BackportBottomSheetBehavior.STATE_COLLAPSED + ) { // Playback sheet is expanded and queue sheet is collapsed, we can expand it. queueSheetBehavior.state = BackportBottomSheetBehavior.STATE_EXPANDED } @@ -658,7 +685,7 @@ class MainFragment : private class SheetBackPressedCallback( private val playbackSheetBehavior: PlaybackBottomSheetBehavior<*>, - private val queueSheetBehavior: QueueBottomSheetBehavior<*>? + private val queueSheetBehavior: QueueBottomSheetBehavior<*>?, ) : OnBackPressedCallback(false) { override fun handleOnBackStarted(backEvent: BackEventCompat) { if (queueSheetShown()) { @@ -766,6 +793,7 @@ class MainFragment : FloatingActionButton::class, "hide", FloatingActionButton.OnVisibilityChangedListener::class, - Boolean::class) + Boolean::class, + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/detail/AlbumDetailFragment.kt b/app/src/main/java/org/oxycblt/auxio/detail/AlbumDetailFragment.kt index 48785f276..414ccd574 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/AlbumDetailFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/AlbumDetailFragment.kt @@ -76,7 +76,11 @@ class AlbumDetailFragment : DetailFragment() { collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) } @@ -152,7 +156,10 @@ class AlbumDetailFragment : DetailFragment() { playbackModel.shuffle(unlikelyToBeNull(detailModel.currentAlbum.value)) } updatePlayback( - playbackModel.song.value, playbackModel.parent.value, playbackModel.isPlaying.value) + playbackModel.song.value, + playbackModel.parent.value, + playbackModel.isPlaying.value, + ) } private fun updateList(list: List) { @@ -251,7 +258,8 @@ class AlbumDetailFragment : DetailFragment() { is PlaylistDecision.Add -> { L.d("Adding ${decision.songs.size} songs to a playlist") AlbumDetailFragmentDirections.addToPlaylist( - decision.songs.map { it.uid }.toTypedArray()) + decision.songs.map { it.uid }.toTypedArray() + ) } is PlaylistDecision.New, is PlaylistDecision.Import, @@ -270,7 +278,9 @@ class AlbumDetailFragment : DetailFragment() { private fun updatePlayback(song: Song?, parent: MusicParent?, isPlaying: Boolean) { albumListAdapter.setPlaying( - song.takeIf { parent == detailModel.currentAlbum.value }, isPlaying) + song.takeIf { parent == detailModel.currentAlbum.value }, + isPlaying, + ) } private fun handlePlaybackDecision(decision: PlaybackDecision?) { @@ -318,7 +328,7 @@ class AlbumDetailFragment : DetailFragment() { viewEnd: Int, boxStart: Int, boxEnd: Int, - snapPreference: Int + snapPreference: Int, ) = (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2) diff --git a/app/src/main/java/org/oxycblt/auxio/detail/ArtistDetailFragment.kt b/app/src/main/java/org/oxycblt/auxio/detail/ArtistDetailFragment.kt index 8f672344f..1b4beed14 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/ArtistDetailFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/ArtistDetailFragment.kt @@ -75,7 +75,11 @@ class ArtistDetailFragment : DetailFragment() { collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) } @@ -138,7 +142,8 @@ class ArtistDetailFragment : DetailFragment() { context.getPlural(R.plurals.fmt_song_count, artist.songs.size) } else { context.getString(R.string.def_song_count) - }) + }, + ) if (artist.songs.isNotEmpty()) { // Information about the artist's genre(s) map to the sub-head text @@ -178,7 +183,10 @@ class ArtistDetailFragment : DetailFragment() { playbackModel.shuffle(unlikelyToBeNull(detailModel.currentArtist.value)) } updatePlayback( - playbackModel.song.value, playbackModel.parent.value, playbackModel.isPlaying.value) + playbackModel.song.value, + playbackModel.parent.value, + playbackModel.isPlaying.value, + ) } private fun updateList(list: List) { @@ -274,7 +282,8 @@ class ArtistDetailFragment : DetailFragment() { is PlaylistDecision.Add -> { L.d("Adding ${decision.songs.size} songs to a playlist") ArtistDetailFragmentDirections.addToPlaylist( - decision.songs.map { it.uid }.toTypedArray()) + decision.songs.map { it.uid }.toTypedArray() + ) } is PlaylistDecision.New, is PlaylistDecision.Import, diff --git a/app/src/main/java/org/oxycblt/auxio/detail/ContinuousAppBarLayoutBehavior.kt b/app/src/main/java/org/oxycblt/auxio/detail/ContinuousAppBarLayoutBehavior.kt index d2e074d8f..d02ddf65c 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/ContinuousAppBarLayoutBehavior.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/ContinuousAppBarLayoutBehavior.kt @@ -38,7 +38,7 @@ constructor(context: Context? = null, attrs: AttributeSet? = null) : override fun onInterceptTouchEvent( parent: CoordinatorLayout, child: AppBarLayout, - ev: MotionEvent + ev: MotionEvent, ): Boolean { val consumed = super.onInterceptTouchEvent(parent, child, ev) when (ev.actionMasked) { @@ -60,7 +60,7 @@ constructor(context: Context? = null, attrs: AttributeSet? = null) : override fun onTouchEvent( parent: CoordinatorLayout, child: AppBarLayout, - ev: MotionEvent + ev: MotionEvent, ): Boolean { val consumed = super.onTouchEvent(parent, child, ev) when (ev.actionMasked) { diff --git a/app/src/main/java/org/oxycblt/auxio/detail/DetailGenerator.kt b/app/src/main/java/org/oxycblt/auxio/detail/DetailGenerator.kt index 8ba06b5f7..83a533afe 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/DetailGenerator.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/DetailGenerator.kt @@ -71,7 +71,7 @@ constructor(private val listSettings: ListSettings, private val musicRepository: private class DetailGeneratorImpl( private val invalidator: DetailGenerator.Invalidator, private val listSettings: ListSettings, - private val musicRepository: MusicRepository + private val musicRepository: MusicRepository, ) : DetailGenerator, MusicRepository.UpdateListener, ListSettings.Listener { override fun attach() { listSettings.registerListener(this) @@ -225,7 +225,7 @@ sealed interface DetailSection { DEMOS(R.string.lbl_demos), APPEARANCES(R.string.lbl_appears_on), LIVE(R.string.lbl_live_group), - REMIXES(R.string.lbl_remix_group) + REMIXES(R.string.lbl_remix_group), } } diff --git a/app/src/main/java/org/oxycblt/auxio/detail/DetailViewModel.kt b/app/src/main/java/org/oxycblt/auxio/detail/DetailViewModel.kt index 4bdb7d3f3..c9996f65c 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/DetailViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/DetailViewModel.kt @@ -67,7 +67,7 @@ constructor( private val listSettings: ListSettings, private val musicRepository: MusicRepository, private val playbackSettings: PlaybackSettings, - detailGeneratorFactory: DetailGenerator.Factory + detailGeneratorFactory: DetailGenerator.Factory, ) : ViewModel(), DetailGenerator.Invalidator { private val _toShow = MutableEvent() @@ -226,7 +226,12 @@ constructor( MusicType.ARTISTS -> { val artist = detailGenerator.artist(currentArtist.value?.uid ?: return) refreshDetail( - artist, _currentArtist, _artistSongList, _artistSongInstructions, replace) + artist, + _currentArtist, + _artistSongList, + _artistSongInstructions, + replace, + ) } MusicType.GENRES -> { val genre = detailGenerator.genre(currentGenre.value?.uid ?: return) @@ -272,7 +277,8 @@ constructor( Show.SongArtistDecision(song) } else { Show.ArtistDetails(song.artists.first()) - }) + } + ) /** * Navigate to the details of one of the [Artist]s of an [Album] using the corresponding choice @@ -286,7 +292,8 @@ constructor( Show.AlbumArtistDecision(album) } else { Show.ArtistDetails(album.artists.first()) - }) + } + ) /** * Navigate to the details of an [Artist]. @@ -518,7 +525,8 @@ constructor( } else { L.d("Playlist will be empty after removal, removing header") UpdateInstructions.Remove(at - 1, 3) - }) + }, + ) } private fun refreshAudioInfo(song: Song) { @@ -541,7 +549,10 @@ constructor( add(SongProperty(R.string.lbl_bitrate, SongProperty.Value.Bitrate(song.bitrateKbps))) add( SongProperty( - R.string.lbl_sample_rate, SongProperty.Value.SampleRate(song.sampleRateHz))) + R.string.lbl_sample_rate, + SongProperty.Value.SampleRate(song.sampleRateHz), + ) + ) song.replayGainAdjustment.track?.let { add(SongProperty(R.string.lbl_replaygain_track, SongProperty.Value.Decibels(it))) } @@ -557,7 +568,7 @@ constructor( list: MutableStateFlow>, instructions: MutableEvent, replace: Int?, - songHeader: (Int) -> PlainHeader = { SortHeader(it) } + songHeader: (Int) -> PlainHeader = { SortHeader(it) }, ) { if (detail == null) { parent.value = null @@ -611,16 +622,21 @@ constructor( private fun refreshPlaylist( uid: Music.UID, - instructions: UpdateInstructions = UpdateInstructions.Diff + instructions: UpdateInstructions = UpdateInstructions.Diff, ) { L.d("Refreshing playlist list") val edited = editedPlaylist.value if (edited == null) { val playlist = detailGenerator.playlist(uid) refreshDetail( - playlist, _currentPlaylist, _playlistSongList, _playlistSongInstructions, null) { - EditHeader(it) - } + playlist, + _currentPlaylist, + _playlistSongList, + _playlistSongInstructions, + null, + ) { + EditHeader(it) + } return } val list = mutableListOf() diff --git a/app/src/main/java/org/oxycblt/auxio/detail/GenreDetailFragment.kt b/app/src/main/java/org/oxycblt/auxio/detail/GenreDetailFragment.kt index fdc40cc17..47e058882 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/GenreDetailFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/GenreDetailFragment.kt @@ -74,7 +74,11 @@ class GenreDetailFragment : DetailFragment() { collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) } @@ -129,7 +133,8 @@ class GenreDetailFragment : DetailFragment() { context.getString( R.string.fmt_two, context.getPlural(R.plurals.fmt_artist_count, genre.artists.size), - context.getPlural(R.plurals.fmt_song_count, genre.songs.size)) + context.getPlural(R.plurals.fmt_song_count, genre.songs.size), + ) binding.detailPlayButton?.setOnClickListener { playbackModel.play(unlikelyToBeNull(detailModel.currentGenre.value)) } @@ -143,7 +148,10 @@ class GenreDetailFragment : DetailFragment() { playbackModel.shuffle(unlikelyToBeNull(detailModel.currentGenre.value)) } updatePlayback( - playbackModel.song.value, playbackModel.parent.value, playbackModel.isPlaying.value) + playbackModel.song.value, + playbackModel.parent.value, + playbackModel.isPlaying.value, + ) } private fun updateList(list: List) { @@ -234,7 +242,8 @@ class GenreDetailFragment : DetailFragment() { is PlaylistDecision.Add -> { L.d("Adding ${decision.songs.size} songs to a playlist") GenreDetailFragmentDirections.addToPlaylist( - decision.songs.map { it.uid }.toTypedArray()) + decision.songs.map { it.uid }.toTypedArray() + ) } is PlaylistDecision.New, is PlaylistDecision.Import, diff --git a/app/src/main/java/org/oxycblt/auxio/detail/PlaylistDetailFragment.kt b/app/src/main/java/org/oxycblt/auxio/detail/PlaylistDetailFragment.kt index b29ca2bd9..36a2fe84e 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/PlaylistDetailFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/PlaylistDetailFragment.kt @@ -106,7 +106,10 @@ class PlaylistDetailFragment : // DetailViewModel handles most initialization from the navigation argument. detailModel.setPlaylist(args.playlistUid) collectImmediately( - detailModel.currentPlaylist, detailModel.editedPlaylist, ::updatePlaylist) + detailModel.currentPlaylist, + detailModel.editedPlaylist, + ::updatePlaylist, + ) collectImmediately(detailModel.playlistSongList, ::updateList) collectImmediately(detailModel.editedPlaylist, ::updateEditedList) collect(detailModel.toShow.flow, ::handleShow) @@ -115,7 +118,11 @@ class PlaylistDetailFragment : collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) } @@ -171,7 +178,9 @@ class PlaylistDetailFragment : override fun onOpenParentMenu() { listModel.openMenu( - R.menu.detail_playlist, unlikelyToBeNull(detailModel.currentPlaylist.value)) + R.menu.detail_playlist, + unlikelyToBeNull(detailModel.currentPlaylist.value), + ) } override fun onOpenMenu(item: Song) { @@ -198,7 +207,8 @@ class PlaylistDetailFragment : binding.detailCover.bind( editedPlaylist, binding.context.getString(R.string.desc_playlist_image, playlist.name), - R.drawable.ic_playlist_24) + R.drawable.ic_playlist_24, + ) } else { binding.detailCover.bind(playlist) } @@ -216,7 +226,8 @@ class PlaylistDetailFragment : binding.context.getString( R.string.fmt_two, binding.context.getPlural(R.plurals.fmt_song_count, songs.size), - durationMs.formatDurationMs(true)) + durationMs.formatDurationMs(true), + ) } else { binding.context.getString(R.string.def_song_count) } @@ -251,7 +262,10 @@ class PlaylistDetailFragment : } } updatePlayback( - playbackModel.song.value, playbackModel.parent.value, playbackModel.isPlaying.value) + playbackModel.song.value, + playbackModel.parent.value, + playbackModel.isPlaying.value, + ) } private fun updateList(list: List) { @@ -303,7 +317,8 @@ class PlaylistDetailFragment : L.d("Navigating to artist choices for ${show.album}") findNavController() .navigateSafe( - PlaylistDetailFragmentDirections.showArtistChoices(show.album.uid)) + PlaylistDetailFragmentDirections.showArtistChoices(show.album.uid) + ) } is Show.PlaylistDetails -> { L.d("Navigated to this playlist") @@ -362,7 +377,8 @@ class PlaylistDetailFragment : decision.playlist.uid, decision.template, decision.applySongs.map { it.uid }.toTypedArray(), - decision.reason) + decision.reason, + ) } is PlaylistDecision.Export -> { L.d("Exporting ${decision.playlist}") @@ -375,7 +391,8 @@ class PlaylistDetailFragment : is PlaylistDecision.Add -> { L.d("Adding ${decision.songs.size} songs to a playlist") PlaylistDetailFragmentDirections.addToPlaylist( - decision.songs.map { it.uid }.toTypedArray()) + decision.songs.map { it.uid }.toTypedArray() + ) } is PlaylistDecision.New -> error("Unexpected playlist decision $decision") } @@ -391,7 +408,9 @@ class PlaylistDetailFragment : private fun updatePlayback(song: Song?, parent: MusicParent?, isPlaying: Boolean) { // Prefer songs that are playing from this playlist. playlistListAdapter.setPlaying( - song.takeIf { parent == detailModel.currentPlaylist.value }, isPlaying) + song.takeIf { parent == detailModel.currentPlaylist.value }, + isPlaying, + ) } private fun handlePlaybackDecision(decision: PlaybackDecision?) { diff --git a/app/src/main/java/org/oxycblt/auxio/detail/ReadOnlyTextInput.kt b/app/src/main/java/org/oxycblt/auxio/detail/ReadOnlyTextInput.kt index 716d70c60..928cd0f16 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/ReadOnlyTextInput.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/ReadOnlyTextInput.kt @@ -38,7 +38,7 @@ class ReadOnlyTextInput constructor( context: Context, attrs: AttributeSet? = null, - defStyleAttr: Int = R.attr.editTextStyle + defStyleAttr: Int = R.attr.editTextStyle, ) : TextInputEditText(context, attrs, defStyleAttr) { init { // Enable selection, but still disable focus (i.e Keyboard opening) @@ -50,8 +50,10 @@ constructor( // Make text immutable override fun getFreezesText() = false + // Prevent editing by default override fun getDefaultEditable() = false + // Remove the movement method that allows cursor scrolling override fun getDefaultMovementMethod() = null } diff --git a/app/src/main/java/org/oxycblt/auxio/detail/decision/ArtistShowChoice.kt b/app/src/main/java/org/oxycblt/auxio/detail/decision/ArtistShowChoice.kt index 1749a22ab..6dfb5eb8e 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/decision/ArtistShowChoice.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/decision/ArtistShowChoice.kt @@ -38,7 +38,8 @@ import org.oxycblt.musikr.Artist */ class ArtistShowChoice(private val listener: ClickableListListener) : FlexibleListAdapter( - ArtistNavigationChoiceViewHolder.DIFF_CALLBACK) { + ArtistNavigationChoiceViewHolder.DIFF_CALLBACK + ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ArtistNavigationChoiceViewHolder.from(parent) @@ -78,7 +79,8 @@ private constructor(private val binding: ItemPickerChoiceBinding) : */ fun from(parent: View) = ArtistNavigationChoiceViewHolder( - ItemPickerChoiceBinding.inflate(parent.context.inflater)) + ItemPickerChoiceBinding.inflate(parent.context.inflater) + ) /** A comparator that can be used with DiffUtil. */ val DIFF_CALLBACK = diff --git a/app/src/main/java/org/oxycblt/auxio/detail/decision/DetailDecisionViewModel.kt b/app/src/main/java/org/oxycblt/auxio/detail/decision/DetailDecisionViewModel.kt index b3286983c..cd31361d5 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/decision/DetailDecisionViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/decision/DetailDecisionViewModel.kt @@ -98,6 +98,7 @@ sealed interface ArtistShowChoices { val uid: Music.UID /** The current [Artist] choices. */ val choices: List + /** Sanitize this instance with a [Library]. */ fun sanitize(newLibrary: Library): ArtistShowChoices? diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/DetailListAdapter.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/DetailListAdapter.kt index 8feee699b..ecb56fdd9 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/DetailListAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/DetailListAdapter.kt @@ -49,7 +49,7 @@ import org.oxycblt.musikr.Music */ abstract class DetailListAdapter( private val listener: Listener<*>, - private val diffCallback: DiffUtil.ItemCallback + private val diffCallback: DiffUtil.ItemCallback, ) : SelectionIndicatorAdapter(diffCallback) { override fun getItemViewType(position: Int) = diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDetailListAdapter.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDetailListAdapter.kt index b125ed558..eeb878048 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDetailListAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDetailListAdapter.kt @@ -77,7 +77,7 @@ class PlaylistDetailListAdapter(private val listener: Listener) : override fun onBindViewHolder( holder: RecyclerView.ViewHolder, position: Int, - payloads: List + payloads: List, ) { super.onBindViewHolder(holder, position, payloads) @@ -131,7 +131,9 @@ class PlaylistDetailListAdapter(private val listener: Listener) : when { oldItem is Song && newItem is Song -> PlaylistSongViewHolder.DIFF_CALLBACK.areContentsTheSame( - oldItem, newItem) + oldItem, + newItem, + ) oldItem is EditHeader && newItem is EditHeader -> EditHeaderViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem) else -> DetailListAdapter.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem) @@ -242,7 +244,9 @@ private constructor(private val binding: ItemEditableSongBinding) : MaterialShapeDrawable.createWithElevationOverlay(binding.context).apply { fillColor = binding.context.getAttrColorCompat(MR.attr.colorSurface) }, - background)) + background, + ) + ) } /** diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDragCallback.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDragCallback.kt index c93514e14..f33e3b521 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDragCallback.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/PlaylistDragCallback.kt @@ -31,10 +31,12 @@ class PlaylistDragCallback(private val detailModel: DetailViewModel) : MaterialD override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, - target: RecyclerView.ViewHolder + target: RecyclerView.ViewHolder, ) = detailModel.movePlaylistSongs( - viewHolder.bindingAdapterPosition, target.bindingAdapterPosition) + viewHolder.bindingAdapterPosition, + target.bindingAdapterPosition, + ) override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { detailModel.removePlaylistSong(viewHolder.bindingAdapterPosition) diff --git a/app/src/main/java/org/oxycblt/auxio/detail/list/SongPropertyAdapter.kt b/app/src/main/java/org/oxycblt/auxio/detail/list/SongPropertyAdapter.kt index eef657286..c1a8e857d 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/list/SongPropertyAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/list/SongPropertyAdapter.kt @@ -46,7 +46,8 @@ import org.oxycblt.musikr.tag.Date */ class SongPropertyAdapter : FlexibleListAdapter( - SongPropertyViewHolder.DIFF_CALLBACK) { + SongPropertyViewHolder.DIFF_CALLBACK + ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = SongPropertyViewHolder.from(parent) @@ -115,7 +116,8 @@ class SongPropertyViewHolder private constructor(private val binding: ItemSongPr context.getString(R.string.fmt_zipped_names, value, subtitle) } else { value - }) + } + ) } is SongProperty.Value.ItemDate -> { val date = property.value.date diff --git a/app/src/main/java/org/oxycblt/auxio/detail/sort/GenreSongSortDialog.kt b/app/src/main/java/org/oxycblt/auxio/detail/sort/GenreSongSortDialog.kt index b996c71f4..c578162c6 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/sort/GenreSongSortDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/sort/GenreSongSortDialog.kt @@ -58,7 +58,8 @@ class GenreSongSortDialog : SortDialog() { Sort.Mode.ByArtist, Sort.Mode.ByAlbum, Sort.Mode.ByDate, - Sort.Mode.ByDuration) + Sort.Mode.ByDuration, + ) private fun updateGenre(genre: Genre?) { if (genre == null) { diff --git a/app/src/main/java/org/oxycblt/auxio/detail/sort/PlaylistSongSortDialog.kt b/app/src/main/java/org/oxycblt/auxio/detail/sort/PlaylistSongSortDialog.kt index 090428035..75b6c50db 100644 --- a/app/src/main/java/org/oxycblt/auxio/detail/sort/PlaylistSongSortDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/detail/sort/PlaylistSongSortDialog.kt @@ -58,7 +58,8 @@ class PlaylistSongSortDialog : SortDialog() { Sort.Mode.ByArtist, Sort.Mode.ByAlbum, Sort.Mode.ByDate, - Sort.Mode.ByDuration) + Sort.Mode.ByDuration, + ) private fun updatePlaylist(genre: Playlist?) { if (genre == null) { diff --git a/app/src/main/java/org/oxycblt/auxio/home/ErrorDetailsDialog.kt b/app/src/main/java/org/oxycblt/auxio/home/ErrorDetailsDialog.kt index 933ee6848..35daab67d 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/ErrorDetailsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/ErrorDetailsDialog.kt @@ -77,7 +77,8 @@ class ErrorDetailsDialog : ViewBindingMaterialDialogFragment { L.d("Importing playlist") @@ -371,7 +377,8 @@ class HomeFragment : decision.playlist.uid, decision.template, decision.applySongs.map { it.uid }.toTypedArray(), - decision.reason) + decision.reason, + ) } is PlaylistDecision.Export -> { L.d("Exporting ${decision.playlist}") @@ -384,7 +391,8 @@ class HomeFragment : is PlaylistDecision.Add -> { L.d("Adding ${decision.songs.size} to a playlist") HomeFragmentDirections.addToPlaylist( - decision.songs.map { it.uid }.toTypedArray()) + decision.songs.map { it.uid }.toTypedArray() + ) } } findNavController().navigateSafe(directions) @@ -491,7 +499,7 @@ class HomeFragment : private class HomePagerAdapter( private val tabs: List, fragmentManager: FragmentManager, - lifecycleOwner: LifecycleOwner + lifecycleOwner: LifecycleOwner, ) : FragmentStateAdapter(fragmentManager, lifecycleOwner.lifecycle) { override fun getItemCount() = tabs.size diff --git a/app/src/main/java/org/oxycblt/auxio/home/HomeSettings.kt b/app/src/main/java/org/oxycblt/auxio/home/HomeSettings.kt index aadacc21d..96d6e3455 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/HomeSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/HomeSettings.kt @@ -43,6 +43,7 @@ interface HomeSettings : Settings { interface Listener { /** Called when the [homeTabs] configuration changes. */ fun onTabsChanged() {} + /** Called when the [shouldHideCollaborators] configuration changes. */ fun onHideCollaboratorsChanged() {} } @@ -54,8 +55,10 @@ class HomeSettingsImpl @Inject constructor(@ApplicationContext context: Context) get() = Tab.fromIntCode( sharedPreferences.getInt( - getString(R.string.set_key_home_tabs), Tab.SEQUENCE_DEFAULT)) - ?: unlikelyToBeNull(Tab.fromIntCode(Tab.SEQUENCE_DEFAULT)) + getString(R.string.set_key_home_tabs), + Tab.SEQUENCE_DEFAULT, + ) + ) ?: unlikelyToBeNull(Tab.fromIntCode(Tab.SEQUENCE_DEFAULT)) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_home_tabs), Tab.toIntCode(value)) diff --git a/app/src/main/java/org/oxycblt/auxio/home/HomeViewModel.kt b/app/src/main/java/org/oxycblt/auxio/home/HomeViewModel.kt index a140a4dff..1402de7b1 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/HomeViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/HomeViewModel.kt @@ -50,7 +50,7 @@ class HomeViewModel constructor( private val listSettings: ListSettings, private val playbackSettings: PlaybackSettings, - homeGeneratorFactory: HomeGenerator.Factory + homeGeneratorFactory: HomeGenerator.Factory, ) : ViewModel(), HomeGenerator.Invalidator { private val _songList = MutableStateFlow(listOf()) /** A list of [Song]s, sorted by the preferred [Sort], to be shown in the home view. */ diff --git a/app/src/main/java/org/oxycblt/auxio/home/ThemedSpeedDialView.kt b/app/src/main/java/org/oxycblt/auxio/home/ThemedSpeedDialView.kt index 7f686dec3..7e813b38b 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/ThemedSpeedDialView.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/ThemedSpeedDialView.kt @@ -75,7 +75,7 @@ class ThemedSpeedDialView : SpeedDialView { constructor( context: Context, attrs: AttributeSet?, - @AttrRes defStyleAttr: Int + @AttrRes defStyleAttr: Int, ) : super(context, attrs, defStyleAttr) private val stationaryConfig = AnimConfig.of(context, AnimConfig.STANDARD, AnimConfig.MEDIUM2) @@ -121,10 +121,12 @@ class ThemedSpeedDialView : SpeedDialView { mainFab.backgroundTintList = ColorStateList.valueOf( if (isOpen) mainFabClosedBackgroundColor - else mainFabOpenedBackgroundColor) + else mainFabOpenedBackgroundColor + ) mainFab.imageTintList = ColorStateList.valueOf( - if (isOpen) mainFabClosedIconColor else mainFabOpenedIconColor) + if (isOpen) mainFabClosedIconColor else mainFabOpenedIconColor + ) mainFabAnimator?.cancel() mainFabAnimator = createMainFabAnimator(isOpen).apply { @@ -133,12 +135,14 @@ class ThemedSpeedDialView : SpeedDialView { override fun onAnimationEnd(animation: Animator) { mainFabAnimator = null } - }) + } + ) start() } innerChangeListener?.invoke(isOpen) } - }) + } + ) } private fun createMainFabAnimator(isOpen: Boolean): Animator { @@ -150,7 +154,8 @@ class ThemedSpeedDialView : SpeedDialView { ObjectAnimator.ofArgb( mainFab, VIEW_PROPERTY_BACKGROUND_TINT, - if (isOpen) mainFabOpenedBackgroundColor else mainFabClosedBackgroundColor) + if (isOpen) mainFabOpenedBackgroundColor else mainFabClosedBackgroundColor, + ) .apply { startDelay = delay duration = partialDuration @@ -160,7 +165,8 @@ class ThemedSpeedDialView : SpeedDialView { ObjectAnimator.ofArgb( mainFab, IMAGE_VIEW_PROPERTY_IMAGE_TINT, - if (isOpen) mainFabOpenedIconColor else mainFabClosedIconColor) + if (isOpen) mainFabOpenedIconColor else mainFabClosedIconColor, + ) .apply { startDelay = delay duration = partialDuration @@ -168,7 +174,10 @@ class ThemedSpeedDialView : SpeedDialView { val levelAnimator = ObjectAnimator.ofInt( - mainFab.drawable, DRAWABLE_PROPERTY_LEVEL, if (isOpen) 10000 else 0) + mainFab.drawable, + DRAWABLE_PROPERTY_LEVEL, + if (isOpen) 10000 else 0, + ) .apply { duration = totalDuration } val animatorSet = @@ -204,7 +213,7 @@ class ThemedSpeedDialView : SpeedDialView { override fun addActionItem( actionItem: SpeedDialActionItem, position: Int, - animate: Boolean + animate: Boolean, ): FabWithLabelView? { val context = context val fabImageTintColor = context.getAttrColorCompat(androidx.appcompat.R.attr.colorPrimary) @@ -220,7 +229,8 @@ class ThemedSpeedDialView : SpeedDialView { SpeedDialActionItem.Builder( actionItem.id, // Should not be a resource, pass null to fail fast. - actionItem.getFabImageDrawable(null)) + actionItem.getFabImageDrawable(null), + ) .setLabel(actionItem.getLabel(context)) .setFabImageTintColor(fabImageTintColor.defaultColor) .setFabBackgroundColor(fabBackgroundColor.defaultColor) @@ -269,7 +279,10 @@ class ThemedSpeedDialView : SpeedDialView { override fun onSaveInstanceState(): Parcelable { val superState = BundleCompat.getParcelable( - super.onSaveInstanceState() as Bundle, "superState", Parcelable::class.java) + super.onSaveInstanceState() as Bundle, + "superState", + Parcelable::class.java, + ) return State(superState, isOpen) } diff --git a/app/src/main/java/org/oxycblt/auxio/home/list/AlbumListFragment.kt b/app/src/main/java/org/oxycblt/auxio/home/list/AlbumListFragment.kt index 23a031c21..6bda9dd9b 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/list/AlbumListFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/list/AlbumListFragment.kt @@ -94,7 +94,11 @@ class AlbumListFragment : collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator) collectImmediately(listModel.selected, ::updateSelection) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) } override fun onDestroyBinding(binding: FragmentHomeListBinding) { @@ -134,7 +138,8 @@ class AlbumListFragment : formatter, dateAddedMillis, dateAddedMillis, - DateUtils.FORMAT_ABBREV_ALL) + DateUtils.FORMAT_ABBREV_ALL, + ) .toString() } diff --git a/app/src/main/java/org/oxycblt/auxio/home/list/ArtistListFragment.kt b/app/src/main/java/org/oxycblt/auxio/home/list/ArtistListFragment.kt index addf0ff62..5951c2900 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/list/ArtistListFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/list/ArtistListFragment.kt @@ -89,7 +89,11 @@ class ArtistListFragment : collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator) collectImmediately(listModel.selected, ::updateSelection) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) } override fun onDestroyBinding(binding: FragmentHomeListBinding) { diff --git a/app/src/main/java/org/oxycblt/auxio/home/list/GenreListFragment.kt b/app/src/main/java/org/oxycblt/auxio/home/list/GenreListFragment.kt index e2a2142b3..69621541c 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/list/GenreListFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/list/GenreListFragment.kt @@ -88,7 +88,11 @@ class GenreListFragment : collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator) collectImmediately(listModel.selected, ::updateSelection) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) } override fun onDestroyBinding(binding: FragmentHomeListBinding) { diff --git a/app/src/main/java/org/oxycblt/auxio/home/list/PlaylistListFragment.kt b/app/src/main/java/org/oxycblt/auxio/home/list/PlaylistListFragment.kt index eb8de750c..e453bbaa8 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/list/PlaylistListFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/list/PlaylistListFragment.kt @@ -85,10 +85,15 @@ class PlaylistListFragment : homeModel.empty, homeModel.playlistList, musicModel.indexingState, - ::updateNoMusicIndicator) + ::updateNoMusicIndicator, + ) collectImmediately(listModel.selected, ::updateSelection) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) } override fun onDestroyBinding(binding: FragmentHomeListBinding) { @@ -137,7 +142,7 @@ class PlaylistListFragment : private fun updateNoMusicIndicator( empty: Boolean, playlists: List, - indexingState: IndexingState? + indexingState: IndexingState?, ) { val binding = requireBinding() binding.homeRecycler.isInvisible = empty diff --git a/app/src/main/java/org/oxycblt/auxio/home/list/SongListFragment.kt b/app/src/main/java/org/oxycblt/auxio/home/list/SongListFragment.kt index 08700b6a8..3e03623f0 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/list/SongListFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/list/SongListFragment.kt @@ -92,7 +92,11 @@ class SongListFragment : collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator) collectImmediately(listModel.selected, ::updateSelection) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) } override fun onDestroyBinding(binding: FragmentHomeListBinding) { @@ -134,7 +138,8 @@ class SongListFragment : formatter, dateAddedMillis, dateAddedMillis, - DateUtils.FORMAT_ABBREV_ALL) + DateUtils.FORMAT_ABBREV_ALL, + ) .toString() } diff --git a/app/src/main/java/org/oxycblt/auxio/home/sort/AlbumSortDialog.kt b/app/src/main/java/org/oxycblt/auxio/home/sort/AlbumSortDialog.kt index 39efb1ca1..ad33d35df 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/sort/AlbumSortDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/sort/AlbumSortDialog.kt @@ -46,5 +46,6 @@ class AlbumSortDialog : SortDialog() { Sort.Mode.ByDate, Sort.Mode.ByDuration, Sort.Mode.ByCount, - Sort.Mode.ByDateAdded) + Sort.Mode.ByDateAdded, + ) } diff --git a/app/src/main/java/org/oxycblt/auxio/home/sort/SongSortDialog.kt b/app/src/main/java/org/oxycblt/auxio/home/sort/SongSortDialog.kt index a961a39c4..5112e2d71 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/sort/SongSortDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/sort/SongSortDialog.kt @@ -46,5 +46,6 @@ class SongSortDialog : SortDialog() { Sort.Mode.ByAlbum, Sort.Mode.ByDate, Sort.Mode.ByDuration, - Sort.Mode.ByDateAdded) + Sort.Mode.ByDateAdded, + ) } diff --git a/app/src/main/java/org/oxycblt/auxio/home/tabs/Tab.kt b/app/src/main/java/org/oxycblt/auxio/home/tabs/Tab.kt index 5f741bad2..14e936f5f 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/tabs/Tab.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/tabs/Tab.kt @@ -73,7 +73,8 @@ sealed class Tab(open val type: MusicType) { MusicType.ALBUMS, MusicType.ARTISTS, MusicType.GENRES, - MusicType.PLAYLISTS) + MusicType.PLAYLISTS, + ) /** * Convert an array of [Tab]s into it's integer representation. @@ -86,7 +87,8 @@ sealed class Tab(open val type: MusicType) { val distinct = tabs.distinctBy { it.type } if (tabs.size != distinct.size) { L.w( - "Tab sequences should not have duplicates [old: ${tabs.size} new: ${distinct.size}]") + "Tab sequences should not have duplicates [old: ${tabs.size} new: ${distinct.size}]" + ) } var sequence = 0 @@ -133,7 +135,8 @@ sealed class Tab(open val type: MusicType) { val distinct = tabs.distinctBy { it.type } if (tabs.size != distinct.size) { L.w( - "Tab sequences should not have duplicates [old: ${tabs.size} new: ${distinct.size}]") + "Tab sequences should not have duplicates [old: ${tabs.size} new: ${distinct.size}]" + ) } // For safety, return null if we have an empty or larger-than-expected tab array. diff --git a/app/src/main/java/org/oxycblt/auxio/home/tabs/TabAdapter.kt b/app/src/main/java/org/oxycblt/auxio/home/tabs/TabAdapter.kt index 592b808b7..e178f8ab8 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/tabs/TabAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/tabs/TabAdapter.kt @@ -117,7 +117,8 @@ class TabViewHolder private constructor(private val binding: ItemTabBinding) : MusicType.ARTISTS -> R.string.lbl_artists MusicType.GENRES -> R.string.lbl_genres MusicType.PLAYLISTS -> R.string.lbl_playlists - }) + } + ) // Unlike in other adapters, we update the checked state alongside // the tab data since they are in the same data structure (Tab) diff --git a/app/src/main/java/org/oxycblt/auxio/home/tabs/TabDragCallback.kt b/app/src/main/java/org/oxycblt/auxio/home/tabs/TabDragCallback.kt index 49af3b57b..8d0b45a9f 100644 --- a/app/src/main/java/org/oxycblt/auxio/home/tabs/TabDragCallback.kt +++ b/app/src/main/java/org/oxycblt/auxio/home/tabs/TabDragCallback.kt @@ -30,7 +30,7 @@ import androidx.recyclerview.widget.RecyclerView class TabDragCallback(private val adapter: TabAdapter) : ItemTouchHelper.Callback() { override fun getMovementFlags( recyclerView: RecyclerView, - viewHolder: RecyclerView.ViewHolder + viewHolder: RecyclerView.ViewHolder, ) = // Allow dragging up and down only makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.UP or ItemTouchHelper.DOWN) @@ -41,7 +41,7 @@ class TabDragCallback(private val adapter: TabAdapter) : ItemTouchHelper.Callbac dX: Float, dY: Float, actionState: Int, - isCurrentlyActive: Boolean + isCurrentlyActive: Boolean, ) { viewHolder.itemView.translationX = dX viewHolder.itemView.translationY = dY @@ -55,7 +55,7 @@ class TabDragCallback(private val adapter: TabAdapter) : ItemTouchHelper.Callbac override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, - target: RecyclerView.ViewHolder + target: RecyclerView.ViewHolder, ): Boolean { // I don't think it's possible to jump more than one position at a time, so a swap // will work just fine. diff --git a/app/src/main/java/org/oxycblt/auxio/image/BitmapProvider.kt b/app/src/main/java/org/oxycblt/auxio/image/BitmapProvider.kt index ac77b5d7a..77b1a6f68 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/BitmapProvider.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/BitmapProvider.kt @@ -44,7 +44,7 @@ class BitmapProvider @Inject constructor( @ApplicationContext private val context: Context, - private val imageLoader: ImageLoader + private val imageLoader: ImageLoader, ) { /** * An extension of [Disposable] with an additional [Target] to deliver the final [Bitmap] to. @@ -96,7 +96,8 @@ constructor( ImageRequest.Builder(context) .data(song.cover) // Use ORIGINAL sizing, as we are not loading into any View-like component. - .size(Size.ORIGINAL)) + .size(Size.ORIGINAL) + ) .target( onSuccess = { synchronized(this) { @@ -111,7 +112,8 @@ constructor( target.onCompleted(null) } } - }) + }, + ) currentRequest = Request(imageLoader.enqueue(imageRequest.build()), target) } diff --git a/app/src/main/java/org/oxycblt/auxio/image/CoverProvider.kt b/app/src/main/java/org/oxycblt/auxio/image/CoverProvider.kt index 286d820a7..b4e23e220 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/CoverProvider.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/CoverProvider.kt @@ -56,7 +56,7 @@ class CoverProvider : ContentProvider() { projection: Array?, selection: String?, selectionArgs: Array?, - sortOrder: String? + sortOrder: String?, ): Cursor = throw UnsupportedOperationException() override fun insert(uri: Uri, values: ContentValues?): Uri? = null @@ -67,7 +67,7 @@ class CoverProvider : ContentProvider() { uri: Uri, values: ContentValues?, selection: String?, - selectionArgs: Array? + selectionArgs: Array?, ): Int = 0 companion object { diff --git a/app/src/main/java/org/oxycblt/auxio/image/CoverView.kt b/app/src/main/java/org/oxycblt/auxio/image/CoverView.kt index 962dc549b..fa68e91e0 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/CoverView.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/CoverView.kt @@ -90,7 +90,7 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr private data class PlaybackIndicator( val view: ImageView, val playingDrawable: AnimationDrawable, - val pausedDrawable: Drawable + val pausedDrawable: Drawable, ) private val playbackIndicator: PlaybackIndicator? @@ -120,7 +120,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr context, com.google.android.material.R.style .ShapeAppearance_Material3_Corner_Medium, - -1) + -1, + ) .build() } } else { @@ -147,11 +148,14 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr ImageView(context).apply { scaleType = ImageView.ScaleType.MATRIX ImageViewCompat.setImageTintList( - this, context.getColorCompat(R.color.sel_on_cover_bg)) + this, + context.getColorCompat(R.color.sel_on_cover_bg), + ) }, context.getDrawableCompat(R.drawable.ic_playing_indicator_24) as AnimationDrawable, - context.getDrawableCompat(R.drawable.ic_paused_indicator_24)) + context.getDrawableCompat(R.drawable.ic_paused_indicator_24), + ) } else { null } @@ -193,7 +197,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr gravity = Gravity.BOTTOM or Gravity.END val spacing = context.getDimenPixels(R.dimen.spacing_tiny) updateMarginsRelative(bottom = spacing, end = spacing) - }) + }, + ) } } @@ -214,14 +219,20 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr 0f, 0f, drawable.intrinsicWidth.toFloat(), - drawable.intrinsicHeight.toFloat()) + drawable.intrinsicHeight.toFloat(), + ) indicatorMatrixDst.set(0f, 0f, iconSize.toFloat(), iconSize.toFloat()) indicatorMatrix.setRectToRect( - indicatorMatrixSrc, indicatorMatrixDst, Matrix.ScaleToFit.CENTER) + indicatorMatrixSrc, + indicatorMatrixDst, + Matrix.ScaleToFit.CENTER, + ) // Then actually center it into the icon. indicatorMatrix.postTranslate( - (measuredWidth - iconSize) / 2f, (measuredHeight - iconSize) / 2f) + (measuredWidth - iconSize) / 2f, + (measuredHeight - iconSize) / 2f, + ) } } } @@ -319,7 +330,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr bindImpl( song.cover, context.getString(R.string.desc_album_cover, song.album.name), - R.drawable.ic_album_24) + R.drawable.ic_album_24, + ) /** * Bind an [Album]'s image to this view. @@ -341,7 +353,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr bindImpl( mostProminentCover, context.getString(R.string.desc_album_cover, album.name), - R.drawable.ic_album_24) + R.drawable.ic_album_24, + ) } /** @@ -353,7 +366,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr bindImpl( artist.covers, context.getString(R.string.desc_artist_image, artist.name), - R.drawable.ic_artist_24) + R.drawable.ic_artist_24, + ) /** * Bind a [Genre]'s image to this view. @@ -364,7 +378,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr bindImpl( genre.covers, context.getString(R.string.desc_genre_image, genre.name), - R.drawable.ic_genre_24) + R.drawable.ic_genre_24, + ) /** * Bind a [Playlist]'s image to this view. @@ -375,7 +390,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr bindImpl( playlist.covers, context.getString(R.string.desc_playlist_image, playlist.name), - R.drawable.ic_playlist_24) + R.drawable.ic_playlist_24, + ) /** * Bind the covers of a generic list of [Song]s. @@ -392,14 +408,16 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr ImageRequest.Builder(context) .data(cover) .error( - StyledDrawable(context, context.getDrawableCompat(errorRes), iconSize) - .asImage()) + StyledDrawable(context, context.getDrawableCompat(errorRes), iconSize).asImage() + ) .target(image) val cornersTransformation = RoundedRectTransformation( shapeAppearance.topLeftCornerSize.getCornerSize( - RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat()))) + RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat()) + ) + ) if (imageSettings.forceSquareCovers) { request.transformations(SquareCropTransformation.INSTANCE, cornersTransformation) } else { @@ -419,7 +437,7 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr private class StyledDrawable( context: Context, private val inner: Drawable, - @Px val iconSize: Int? + @Px val iconSize: Int?, ) : Drawable() { init { // Re-tint the drawable to use the analogous "on surface" color for diff --git a/app/src/main/java/org/oxycblt/auxio/image/ImageSettings.kt b/app/src/main/java/org/oxycblt/auxio/image/ImageSettings.kt index 12671f822..f220825c0 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/ImageSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/ImageSettings.kt @@ -48,16 +48,18 @@ class ImageSettingsImpl @Inject constructor(@ApplicationContext context: Context override val coverMode: CoverMode get() = CoverMode.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_cover_mode), Int.MIN_VALUE)) - ?: CoverMode.BALANCED + sharedPreferences.getInt(getString(R.string.set_key_cover_mode), Int.MIN_VALUE) + ) ?: CoverMode.BALANCED override val forceSquareCovers: Boolean get() = sharedPreferences.getBoolean(getString(R.string.set_key_square_covers), false) override fun migrate() { // Show album covers and Ignore MediaStore covers were unified in 3.0.0 - if (sharedPreferences.contains(OLD_KEY_SHOW_COVERS) || - sharedPreferences.contains(OLD_KEY_QUALITY_COVERS)) { + if ( + sharedPreferences.contains(OLD_KEY_SHOW_COVERS) || + sharedPreferences.contains(OLD_KEY_QUALITY_COVERS) + ) { L.d("Migrating cover settings") val mode = @@ -95,8 +97,10 @@ class ImageSettingsImpl @Inject constructor(@ApplicationContext context: Context } override fun onSettingChanged(key: String, listener: ImageSettings.Listener) { - if (key == getString(R.string.set_key_cover_mode) || - key == getString(R.string.set_key_square_covers)) { + if ( + key == getString(R.string.set_key_cover_mode) || + key == getString(R.string.set_key_square_covers) + ) { L.d("Dispatching image setting change") listener.onImageSettingsChanged() } diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/CoilModule.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/CoilModule.kt index 59f904d66..8f80d12e0 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/coil/CoilModule.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/CoilModule.kt @@ -39,7 +39,7 @@ class CoilModule { coverKeyer: CoverKeyer, coverFactory: CoverFetcher.Factory, coverCollectionKeyer: CoverCollectionKeyer, - coverCollectionFactory: CoverCollectionFetcher.Factory + coverCollectionFactory: CoverCollectionFetcher.Factory, ) = ImageLoader.Builder(context) .components { diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/CoverCollectionFetcher.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/CoverCollectionFetcher.kt index 286e59a93..0246a0532 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/coil/CoverCollectionFetcher.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/CoverCollectionFetcher.kt @@ -80,7 +80,8 @@ private constructor( return SourceFetchResult( source = ImageSource(first.source().buffer(), FileSystem.SYSTEM, null), mimeType = null, - dataSource = DataSource.DISK) + dataSource = DataSource.DISK, + ) } /** Derived from phonograph: https://github.com/kabouzeid/Phonograph */ @@ -107,7 +108,9 @@ private constructor( // TODO: Work around this val bitmap = SquareCropTransformation.INSTANCE.transform( - BitmapFactory.decodeStream(stream), mosaicFrameSize) + BitmapFactory.decodeStream(stream), + mosaicFrameSize, + ) canvas.drawBitmap(bitmap, x.toFloat(), y.toFloat(), null) x += bitmap.width @@ -123,7 +126,8 @@ private constructor( return ImageFetchResult( image = mosaicBitmap.toDrawable(context.resources).asImage(), isSampled = true, - dataSource = DataSource.DISK) + dataSource = DataSource.DISK, + ) } private fun Dimension.mosaicSize(): Int { diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/CoverFetcher.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/CoverFetcher.kt index bc6284ee5..843f1b206 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/coil/CoverFetcher.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/CoverFetcher.kt @@ -37,7 +37,8 @@ class CoverFetcher private constructor(private val cover: Cover) : Fetcher { return SourceFetchResult( source = ImageSource(stream.source().buffer(), FileSystem.SYSTEM, null), mimeType = null, - dataSource = DataSource.DISK) + dataSource = DataSource.DISK, + ) } class Factory @Inject constructor() : Fetcher.Factory { diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/RoundedRectTransformation.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/RoundedRectTransformation.kt index 6220f3bd7..79fc7e842 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/coil/RoundedRectTransformation.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/RoundedRectTransformation.kt @@ -47,7 +47,7 @@ class RoundedRectTransformation( @Px private val topLeft: Float = 0f, @Px private val topRight: Float = 0f, @Px private val bottomLeft: Float = 0f, - @Px private val bottomRight: Float = 0f + @Px private val bottomRight: Float = 0f, ) : Transformation() { constructor(@Px radius: Float) : this(radius, radius, radius, radius) @@ -69,7 +69,8 @@ class RoundedRectTransformation( createBitmap( outputWidth, outputHeight, - requireNotNull(input.config) { "unsupported bitmap format" }) + requireNotNull(input.config) { "unsupported bitmap format" }, + ) output.applyCanvas { drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) @@ -80,7 +81,8 @@ class RoundedRectTransformation( srcHeight = input.height, dstWidth = outputWidth, dstHeight = outputHeight, - scale = Scale.FILL) + scale = Scale.FILL, + ) .toFloat() val dx = (outputWidth - multiplier * input.width) / 2 val dy = (outputHeight - multiplier * input.height) / 2 @@ -121,7 +123,8 @@ class RoundedRectTransformation( srcHeight = input.height, dstWidth = size.width.pxOrElse { Int.MIN_VALUE }, dstHeight = size.height.pxOrElse { Int.MIN_VALUE }, - scale = Scale.FIT) + scale = Scale.FIT, + ) val outputWidth = (multiplier * input.width).roundToInt() val outputHeight = (multiplier * input.height).roundToInt() return outputWidth to outputHeight diff --git a/app/src/main/java/org/oxycblt/auxio/image/covers/SettingCovers.kt b/app/src/main/java/org/oxycblt/auxio/image/covers/SettingCovers.kt index 9f1d244cb..6b6494d0b 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/covers/SettingCovers.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/covers/SettingCovers.kt @@ -64,7 +64,10 @@ class SettingCoversImpl @Inject constructor(private val imageSettings: ImageSett val revisionedTranscoding = RevisionedTranscoding(revision, transcoding) val storedCovers = MutableStoredCovers( - EmbeddedCovers(CoverIdentifier.md5()), coverStorage, revisionedTranscoding) + EmbeddedCovers(CoverIdentifier.md5()), + coverStorage, + revisionedTranscoding, + ) val fsCovers = MutableFSCovers(context) return MutableChainedCovers(storedCovers, fsCovers) } diff --git a/app/src/main/java/org/oxycblt/auxio/list/ListSettings.kt b/app/src/main/java/org/oxycblt/auxio/list/ListSettings.kt index 7dcbfa13f..7fe5d6afe 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/ListSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/ListSettings.kt @@ -68,8 +68,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont override var songSort: Sort get() = Sort.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_songs_sort), Int.MIN_VALUE)) - ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) + sharedPreferences.getInt(getString(R.string.set_key_songs_sort), Int.MIN_VALUE) + ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_songs_sort), value.intCode) @@ -80,8 +80,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont override var albumSort: Sort get() = Sort.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_albums_sort), Int.MIN_VALUE)) - ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) + sharedPreferences.getInt(getString(R.string.set_key_albums_sort), Int.MIN_VALUE) + ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_albums_sort), value.intCode) @@ -92,8 +92,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont override var artistSort: Sort get() = Sort.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_artists_sort), Int.MIN_VALUE)) - ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) + sharedPreferences.getInt(getString(R.string.set_key_artists_sort), Int.MIN_VALUE) + ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_artists_sort), value.intCode) @@ -104,8 +104,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont override var genreSort: Sort get() = Sort.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_genres_sort), Int.MIN_VALUE)) - ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) + sharedPreferences.getInt(getString(R.string.set_key_genres_sort), Int.MIN_VALUE) + ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_genres_sort), value.intCode) @@ -116,8 +116,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont override var playlistSort: Sort get() = Sort.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_playlists_sort), Int.MIN_VALUE)) - ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) + sharedPreferences.getInt(getString(R.string.set_key_playlists_sort), Int.MIN_VALUE) + ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_playlists_sort), value.intCode) @@ -129,8 +129,10 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont get() = Sort.fromIntCode( sharedPreferences.getInt( - getString(R.string.set_key_album_songs_sort), Int.MIN_VALUE)) - ?: Sort(Sort.Mode.ByDisc, Sort.Direction.ASCENDING) + getString(R.string.set_key_album_songs_sort), + Int.MIN_VALUE, + ) + ) ?: Sort(Sort.Mode.ByDisc, Sort.Direction.ASCENDING) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_album_songs_sort), value.intCode) @@ -142,8 +144,10 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont get() = Sort.fromIntCode( sharedPreferences.getInt( - getString(R.string.set_key_artist_songs_sort), Int.MIN_VALUE)) - ?: Sort(Sort.Mode.ByDate, Sort.Direction.DESCENDING) + getString(R.string.set_key_artist_songs_sort), + Int.MIN_VALUE, + ) + ) ?: Sort(Sort.Mode.ByDate, Sort.Direction.DESCENDING) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_artist_songs_sort), value.intCode) @@ -155,8 +159,10 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont get() = Sort.fromIntCode( sharedPreferences.getInt( - getString(R.string.set_key_genre_songs_sort), Int.MIN_VALUE)) - ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) + getString(R.string.set_key_genre_songs_sort), + Int.MIN_VALUE, + ) + ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_genre_songs_sort), value.intCode) diff --git a/app/src/main/java/org/oxycblt/auxio/list/Listeners.kt b/app/src/main/java/org/oxycblt/auxio/list/Listeners.kt index c7704e503..987e1da78 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/Listeners.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/Listeners.kt @@ -98,7 +98,7 @@ interface EditClickListListener : ClickableListListener, EditableListLi item: T, viewHolder: RecyclerView.ViewHolder, bodyView: View = viewHolder.itemView, - dragHandle: View + dragHandle: View, ) { bind(item, viewHolder, bodyView) bind(viewHolder, dragHandle) @@ -138,7 +138,7 @@ interface SelectableListListener : ClickableListListener { item: T, viewHolder: RecyclerView.ViewHolder, bodyView: View = viewHolder.itemView, - menuButton: View + menuButton: View, ) { bind(item, viewHolder, bodyView) // Map long clicks to the selection listener. diff --git a/app/src/main/java/org/oxycblt/auxio/list/adapter/FlexibleListAdapter.kt b/app/src/main/java/org/oxycblt/auxio/list/adapter/FlexibleListAdapter.kt index 4a5da90ca..99943822c 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/adapter/FlexibleListAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/adapter/FlexibleListAdapter.kt @@ -39,9 +39,11 @@ abstract class FlexibleListAdapter( @Suppress("LeakingThis") private val differ = FlexibleListDiffer(this, diffCallback) final override fun getItemCount() = differ.currentList.size + /** The current list stored by the adapter's differ instance. */ val currentList: List get() = differ.currentList + /** @see currentList */ fun getItem(at: Int) = differ.currentList[at] @@ -55,7 +57,7 @@ abstract class FlexibleListAdapter( fun update( newList: List, instructions: UpdateInstructions?, - callback: (() -> Unit)? = null + callback: (() -> Unit)? = null, ) { L.d("Updating list to ${newList.size} items with $instructions") differ.update(newList, instructions, callback) @@ -111,7 +113,7 @@ sealed interface UpdateInstructions { */ private class FlexibleListDiffer( adapter: RecyclerView.Adapter<*>, - diffCallback: DiffUtil.ItemCallback + diffCallback: DiffUtil.ItemCallback, ) { private val updateCallback = AdapterListUpdateCallback(adapter) private val config = AsyncDifferConfig.Builder(diffCallback).build() @@ -167,7 +169,7 @@ private class FlexibleListDiffer( oldList: List, newList: List, runGeneration: Int, - callback: (() -> Unit)? + callback: (() -> Unit)?, ) { // fast simple remove all if (newList.isEmpty()) { @@ -204,7 +206,7 @@ private class FlexibleListDiffer( override fun areItemsTheSame( oldItemPosition: Int, - newItemPosition: Int + newItemPosition: Int, ): Boolean { val oldItem: T? = oldList[oldItemPosition] val newItem: T? = newList[newItemPosition] @@ -216,7 +218,7 @@ private class FlexibleListDiffer( override fun areContentsTheSame( oldItemPosition: Int, - newItemPosition: Int + newItemPosition: Int, ): Boolean { val oldItem: T? = oldList[oldItemPosition] val newItem: T? = newList[newItemPosition] @@ -231,7 +233,7 @@ private class FlexibleListDiffer( override fun getChangePayload( oldItemPosition: Int, - newItemPosition: Int + newItemPosition: Int, ): Any? { val oldItem: T? = oldList[oldItemPosition] val newItem: T? = newList[newItemPosition] @@ -240,7 +242,8 @@ private class FlexibleListDiffer( } throw AssertionError() } - }) + } + ) mainThreadExecutor.execute { if (maxScheduledGeneration == runGeneration) { diff --git a/app/src/main/java/org/oxycblt/auxio/list/adapter/PlayingIndicatorAdapter.kt b/app/src/main/java/org/oxycblt/auxio/list/adapter/PlayingIndicatorAdapter.kt index 8d1721b46..b30a88fbf 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/adapter/PlayingIndicatorAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/adapter/PlayingIndicatorAdapter.kt @@ -51,6 +51,7 @@ abstract class PlayingIndicatorAdapter( onBindViewHolder(holder, position) } } + /** * Update the currently playing item in the list. * diff --git a/app/src/main/java/org/oxycblt/auxio/list/menu/Menu.kt b/app/src/main/java/org/oxycblt/auxio/list/menu/Menu.kt index 3413e03f0..b3c9549c6 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/menu/Menu.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/menu/Menu.kt @@ -64,7 +64,7 @@ sealed interface Menu { val res: Int, val songUid: Music.UID, val playWithCode: Int, - val playWithUid: Music.UID? + val playWithUid: Music.UID?, ) : Menu.Parcel } diff --git a/app/src/main/java/org/oxycblt/auxio/list/menu/MenuDialogFragmentImpl.kt b/app/src/main/java/org/oxycblt/auxio/list/menu/MenuDialogFragmentImpl.kt index 709cd7e08..2c196a68b 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/menu/MenuDialogFragmentImpl.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/menu/MenuDialogFragmentImpl.kt @@ -166,7 +166,8 @@ class ArtistMenuDialogFragment : MenuDialogFragment() { R.id.action_play_next, R.id.action_queue_add, R.id.action_playlist_add, - R.id.action_share) + R.id.action_share, + ) } else { setOf() } @@ -188,7 +189,8 @@ class ArtistMenuDialogFragment : MenuDialogFragment() { context.getPlural(R.plurals.fmt_song_count, menu.artist.songs.size) } else { getString(R.string.def_song_count) - }) + }, + ) } override fun onClick(item: MenuItem, menu: Menu.ForArtist) { @@ -239,7 +241,8 @@ class GenreMenuDialogFragment : MenuDialogFragment() { getString( R.string.fmt_two, context.getPlural(R.plurals.fmt_artist_count, menu.genre.artists.size), - context.getPlural(R.plurals.fmt_song_count, menu.genre.songs.size)) + context.getPlural(R.plurals.fmt_song_count, menu.genre.songs.size), + ) } override fun onClick(item: MenuItem, menu: Menu.ForGenre) { @@ -290,7 +293,8 @@ class PlaylistMenuDialogFragment : MenuDialogFragment() { R.id.action_queue_add, R.id.action_playlist_add, R.id.action_export, - R.id.action_share) + R.id.action_share, + ) } else { setOf() } @@ -352,7 +356,10 @@ class SelectionMenuDialogFragment : MenuDialogFragment() { override fun updateMenu(binding: DialogMenuBinding, menu: Menu.ForSelection) { binding.menuCover.bind( - menu.songs, getString(R.string.desc_selection_image), R.drawable.ic_song_24) + menu.songs, + getString(R.string.desc_selection_image), + R.drawable.ic_song_24, + ) binding.menuType.text = getString(R.string.lbl_selection) binding.menuName.text = requireContext().getPlural(R.plurals.fmt_song_count, menu.songs.size) diff --git a/app/src/main/java/org/oxycblt/auxio/list/recycler/DialogRecyclerView.kt b/app/src/main/java/org/oxycblt/auxio/list/recycler/DialogRecyclerView.kt index 9fc255ce1..01c3caa7b 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/recycler/DialogRecyclerView.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/recycler/DialogRecyclerView.kt @@ -85,12 +85,14 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr ViewGroup.getChildMeasureSpec( MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), 0, - divider.layoutParams.width) + divider.layoutParams.width, + ) val heightMeasureSpec = ViewGroup.getChildMeasureSpec( MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY), 0, - divider.layoutParams.height) + divider.layoutParams.height, + ) divider.measure(widthMeasureSpec, heightMeasureSpec) } diff --git a/app/src/main/java/org/oxycblt/auxio/list/recycler/FastScrollRecyclerView.kt b/app/src/main/java/org/oxycblt/auxio/list/recycler/FastScrollRecyclerView.kt index 18e8f9e7a..f6f17e29e 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/recycler/FastScrollRecyclerView.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/recycler/FastScrollRecyclerView.kt @@ -114,7 +114,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr TextViewCompat.setTextAppearance(this, R.style.TextAppearance_Auxio_HeadlineMedium) setTextColor( - context.getAttrColorCompat(com.google.android.material.R.attr.colorOnSecondary)) + context.getAttrColorCompat(com.google.android.material.R.attr.colorOnSecondary) + ) ellipsize = TextUtils.TruncateAt.MIDDLE gravity = Gravity.CENTER includeFontPadding = false @@ -129,7 +130,9 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr updatePaddingRelative(start = paddingStart, end = paddingEnd) layoutParams = FrameLayout.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ) .apply { marginEnd = context.getDimenPixels(R.dimen.size_touchable_small) gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP @@ -208,7 +211,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr override fun onDraw(canvas: Canvas, parent: RecyclerView, state: State) { onPreDraw() } - }) + } + ) // We use a listener instead of overriding onTouchEvent so that we don't conflict with // RecyclerView touch events. @@ -220,11 +224,12 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr override fun onInterceptTouchEvent( recyclerView: RecyclerView, - event: MotionEvent + event: MotionEvent, ): Boolean { return onItemTouch(event) } - }) + } + ) } // --- RECYCLERVIEW EVENT MANAGEMENT --- @@ -235,7 +240,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr thumbView.layoutDirection = layoutDirection thumbView.measure( MeasureSpec.makeMeasureSpec(thumbWidth, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(thumbHeight, MeasureSpec.EXACTLY)) + MeasureSpec.makeMeasureSpec(thumbHeight, MeasureSpec.EXACTLY), + ) val thumbTop = thumbPadding.top + thumbOffset val thumbLeft = if (isRtl) { @@ -278,7 +284,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr thumbWidth + popupLayoutParams.leftMargin + popupLayoutParams.rightMargin, - popupLayoutParams.width) + popupLayoutParams.width, + ) val heightMeasureSpec = ViewGroup.getChildMeasureSpec( @@ -287,7 +294,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr thumbPadding.bottom + popupLayoutParams.topMargin + popupLayoutParams.bottomMargin, - popupLayoutParams.height) + popupLayoutParams.height, + ) popupView.measure(widthMeasureSpec, heightMeasureSpec) if (showingPopup) { @@ -311,7 +319,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr (thumbTop + thumbAnchorY - popupAnchorY) .coerceAtLeast(thumbPadding.top + popupLayoutParams.topMargin) .coerceAtMost( - height - thumbPadding.bottom - popupLayoutParams.bottomMargin - popupHeight) + height - thumbPadding.bottom - popupLayoutParams.bottomMargin - popupHeight + ) popupView.layout(popupLeft, popupTop, popupLeft + popupWidth, popupTop + popupHeight) } @@ -383,9 +392,11 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr } } MotionEvent.ACTION_MOVE -> { - if (!dragging && - thumbView.isUnder(downX, thumbView.top.toFloat(), minTouchTargetSize) && - abs(eventY - downY) > touchSlop) { + if ( + !dragging && + thumbView.isUnder(downX, thumbView.top.toFloat(), minTouchTargetSize) && + abs(eventY - downY) > touchSlop + ) { if (thumbView.isUnder(downX, downY, minTouchTargetSize)) { dragStartY = lastY dragStartThumbOffset = thumbOffset @@ -487,7 +498,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr HapticFeedbackConstants.TEXT_HANDLE_MOVE } else { HapticFeedbackConstants.KEYBOARD_TAP - }) + } + ) } // --- LAYOUT STATE --- diff --git a/app/src/main/java/org/oxycblt/auxio/list/recycler/MaterialDragCallback.kt b/app/src/main/java/org/oxycblt/auxio/list/recycler/MaterialDragCallback.kt index af81d7629..b955ed6eb 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/recycler/MaterialDragCallback.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/recycler/MaterialDragCallback.kt @@ -48,12 +48,13 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() { final override fun getMovementFlags( recyclerView: RecyclerView, - viewHolder: RecyclerView.ViewHolder + viewHolder: RecyclerView.ViewHolder, ) = if (viewHolder is ViewHolder && viewHolder.enabled) { makeFlag( - ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.UP or ItemTouchHelper.DOWN) or - makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.START) + ItemTouchHelper.ACTION_STATE_DRAG, + ItemTouchHelper.UP or ItemTouchHelper.DOWN, + ) or makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.START) } else { 0 } @@ -63,18 +64,24 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() { viewSize: Int, viewSizeOutOfBounds: Int, totalSize: Int, - msSinceStartScroll: Long + msSinceStartScroll: Long, ): Int { // Clamp the scroll speed to prevent the lists from freaking out // Adapted from NewPipe: https://github.com/TeamNewPipe/NewPipe val standardSpeed = super.interpolateOutOfBoundsScroll( - recyclerView, viewSize, viewSizeOutOfBounds, totalSize, msSinceStartScroll) + recyclerView, + viewSize, + viewSizeOutOfBounds, + totalSize, + msSinceStartScroll, + ) val clampedAbsVelocity = max( MINIMUM_INITIAL_DRAG_VELOCITY, - min(abs(standardSpeed), MAXIMUM_INITIAL_DRAG_VELOCITY)) + min(abs(standardSpeed), MAXIMUM_INITIAL_DRAG_VELOCITY), + ) return clampedAbsVelocity * sign(viewSizeOutOfBounds.toDouble()).toInt() } @@ -86,7 +93,7 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() { dX: Float, dY: Float, actionState: Int, - isCurrentlyActive: Boolean + isCurrentlyActive: Boolean, ) { val holder = viewHolder as ViewHolder @@ -101,7 +108,8 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() { .animate() .translationZ(elevation) .setDuration( - recyclerView.context.getInteger(R.integer.anim_fade_exit_duration).toLong()) + recyclerView.context.getInteger(R.integer.anim_fade_exit_duration).toLong() + ) .setUpdateListener { bg.alpha = ((holder.root.translationZ / elevation) * 255).toInt() } @@ -143,7 +151,8 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() { .animate() .translationZ(0f) .setDuration( - recyclerView.context.getInteger(R.integer.anim_fade_exit_duration).toLong()) + recyclerView.context.getInteger(R.integer.anim_fade_exit_duration).toLong() + ) .setUpdateListener { bg.alpha = ((holder.root.translationZ / elevation) * 255).toInt() } diff --git a/app/src/main/java/org/oxycblt/auxio/list/recycler/ViewHolders.kt b/app/src/main/java/org/oxycblt/auxio/list/recycler/ViewHolders.kt index 51c247f85..c7721a303 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/recycler/ViewHolders.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/recycler/ViewHolders.kt @@ -175,7 +175,8 @@ class ArtistViewHolder private constructor(private val binding: ItemParentBindin binding.context.getPlural(R.plurals.fmt_song_count, artist.songs.size) } else { binding.context.getString(R.string.def_song_count) - }) + }, + ) } override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) { @@ -232,7 +233,8 @@ class GenreViewHolder private constructor(private val binding: ItemParentBinding binding.context.getString( R.string.fmt_two, binding.context.getPlural(R.plurals.fmt_artist_count, genre.artists.size), - binding.context.getPlural(R.plurals.fmt_song_count, genre.songs.size)) + binding.context.getPlural(R.plurals.fmt_song_count, genre.songs.size), + ) } override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) { diff --git a/app/src/main/java/org/oxycblt/auxio/list/sort/Sort.kt b/app/src/main/java/org/oxycblt/auxio/list/sort/Sort.kt index 64b033218..b881a0253 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/sort/Sort.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/sort/Sort.kt @@ -394,7 +394,7 @@ data class Sort(val mode: Mode, val direction: Direction) { /** The direction to sort items in. */ enum class Direction { ASCENDING, - DESCENDING + DESCENDING, } companion object { diff --git a/app/src/main/java/org/oxycblt/auxio/list/sort/SortDialog.kt b/app/src/main/java/org/oxycblt/auxio/list/sort/SortDialog.kt index 0072dd4ad..67b146e65 100644 --- a/app/src/main/java/org/oxycblt/auxio/list/sort/SortDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/list/sort/SortDialog.kt @@ -89,7 +89,7 @@ abstract class SortDialog : override fun onButtonChecked( group: MaterialButtonToggleGroup?, checkedId: Int, - isChecked: Boolean + isChecked: Boolean, ) { updateButtons() } diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index ecc8cec63..2728456b1 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -244,7 +244,7 @@ constructor( private val cache: MutableCache, private val storedPlaylists: StoredPlaylists, private val settingCovers: SettingCovers, - private val musicSettings: MusicSettings + private val musicSettings: MusicSettings, ) : MusicRepository { private val updateListeners = mutableListOf() private val indexingListeners = mutableListOf() diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 3e5b98512..372630dcb 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -117,7 +117,9 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont get() { val mode = sharedPreferences.getInt( - getString(R.string.set_key_locations_mode), IntegerTable.LOCATION_MODE_SAF) + getString(R.string.set_key_locations_mode), + IntegerTable.LOCATION_MODE_SAF, + ) return LocationMode.fromInt(mode) ?: LocationMode.SAF } set(value) { @@ -131,18 +133,24 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont get() { val locations = unlikelyToBeNull( - sharedPreferences.getString( - getString(R.string.set_key_music_locations), "")) + sharedPreferences.getString(getString(R.string.set_key_music_locations), "") + ) .toOpenedLocations() val excludedLocations = unlikelyToBeNull( sharedPreferences.getString( - getString(R.string.set_key_excluded_locations), "")) + getString(R.string.set_key_excluded_locations), + "", + ) + ) .toUnopenedLocations() val withHidden = sharedPreferences.getBoolean(getString(R.string.set_key_with_hidden), false) return SAF.Query( - source = locations, exclude = excludedLocations, withHidden = withHidden) + source = locations, + exclude = excludedLocations, + withHidden = withHidden, + ) } set(value) { sharedPreferences.edit { @@ -157,11 +165,16 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont get() { val filterMode = sharedPreferences.getInt( - getString(R.string.set_key_filter_mode), IntegerTable.FILTER_MODE_EXCLUDE) + getString(R.string.set_key_filter_mode), + IntegerTable.FILTER_MODE_EXCLUDE, + ) val filteredLocations = unlikelyToBeNull( sharedPreferences.getString( - getString(R.string.set_key_filtered_locations), "")) + getString(R.string.set_key_filtered_locations), + "", + ) + ) .toUnopenedLocations() val excludeNonMusic = sharedPreferences.getBoolean(getString(R.string.set_key_exclude_non_music), true) @@ -173,7 +186,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont else -> MediaStore.FilterMode.EXCLUDE }, filtered = filteredLocations, - excludeNonMusic = excludeNonMusic) + excludeNonMusic = excludeNonMusic, + ) } set(value) { sharedPreferences.edit { @@ -184,7 +198,9 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } putInt(getString(R.string.set_key_filter_mode), filterMode) putString( - getString(R.string.set_key_filtered_locations), value.filtered.stringify()) + getString(R.string.set_key_filtered_locations), + value.filtered.stringify(), + ) putBoolean(getString(R.string.set_key_exclude_non_music), value.excludeNonMusic) apply() } @@ -215,7 +231,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont getString(R.string.set_key_filtered_locations), getString(R.string.set_key_exclude_non_music), getString(R.string.set_key_separators), - getString(R.string.set_key_auto_sort_names), -> { + getString(R.string.set_key_auto_sort_names) -> { L.d("Dispatching indexing setting change for $key") listener.onIndexingSettingChanged() } diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt index a5977fc2c..4ec8656cb 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicViewModel.kt @@ -53,7 +53,7 @@ class MusicViewModel constructor( @ApplicationContext context: Context, private val listSettings: ListSettings, - private val musicRepository: MusicRepository + private val musicRepository: MusicRepository, ) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener { private val externalPlaylistManager = ExternalPlaylistManager.from(context) @@ -102,6 +102,7 @@ constructor( library.genres.size, library.songs.sumOf { it.durationMs }, library.songs.sumOf { it.size }) + ) L.d("Updated statistics: ${_statistics.value}") } @@ -132,7 +133,7 @@ constructor( fun createPlaylist( name: String? = null, songs: List = listOf(), - reason: PlaylistDecision.New.Reason = PlaylistDecision.New.Reason.NEW + reason: PlaylistDecision.New.Reason = PlaylistDecision.New.Reason.NEW, ) { if (name != null) { L.d("Creating $name with ${songs.size} songs]") @@ -190,7 +191,9 @@ constructor( target, importedPlaylist.name, songs, - PlaylistDecision.Rename.Reason.IMPORT)) + PlaylistDecision.Rename.Reason.IMPORT, + ) + ) } else { musicRepository.rewritePlaylist(target, songs) _playlistMessage.put(PlaylistMessage.ImportSuccess) @@ -198,7 +201,11 @@ constructor( } else { _playlistDecision.put( PlaylistDecision.New( - songs, importedPlaylist.name, PlaylistDecision.New.Reason.IMPORT)) + songs, + importedPlaylist.name, + PlaylistDecision.New.Reason.IMPORT, + ) + ) } } } else { @@ -243,7 +250,7 @@ constructor( playlist: Playlist, name: String? = null, applySongs: List = listOf(), - reason: PlaylistDecision.Rename.Reason = PlaylistDecision.Rename.Reason.ACTION + reason: PlaylistDecision.Rename.Reason = PlaylistDecision.Rename.Reason.ACTION, ) { if (name != null) { L.d("Renaming $playlist to $name") @@ -388,7 +395,7 @@ sealed interface PlaylistDecision { enum class Reason { NEW, ADD, - IMPORT + IMPORT, } } @@ -409,11 +416,11 @@ sealed interface PlaylistDecision { val playlist: Playlist, val template: String?, val applySongs: List, - val reason: Reason + val reason: Reason, ) : PlaylistDecision { enum class Reason { ACTION, - IMPORT + IMPORT, } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/decision/AddToPlaylistDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/decision/AddToPlaylistDialog.kt index 321dd87ff..bdad13ef5 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/decision/AddToPlaylistDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/decision/AddToPlaylistDialog.kt @@ -100,7 +100,11 @@ class AddToPlaylistDialog : findNavController() .navigateSafe( AddToPlaylistDialogDirections.newPlaylist( - songs.map { it.uid }.toTypedArray(), null, PlaylistDecision.New.Reason.ADD)) + songs.map { it.uid }.toTypedArray(), + null, + PlaylistDecision.New.Reason.ADD, + ) + ) } private fun updatePendingSongs(songs: List?) { diff --git a/app/src/main/java/org/oxycblt/auxio/music/decision/DeletePlaylistDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/decision/DeletePlaylistDialog.kt index 75b360451..39203f247 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/decision/DeletePlaylistDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/decision/DeletePlaylistDialog.kt @@ -58,7 +58,9 @@ class DeletePlaylistDialog : ViewBindingMaterialDialogFragment @@ -142,7 +143,8 @@ class ExportPlaylistDialog : ViewBindingMaterialDialogFragment R.string.lbl_new_playlist PlaylistDecision.New.Reason.IMPORT -> R.string.lbl_import_playlist - }) + } + ) .setPositiveButton(R.string.lbl_ok) { _, _ -> val pendingPlaylist = unlikelyToBeNull(pickerModel.currentPendingNewPlaylist.value) val name = diff --git a/app/src/main/java/org/oxycblt/auxio/music/decision/NewPlaylistFooterAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/decision/NewPlaylistFooterAdapter.kt index 2eee93bda..226544da5 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/decision/NewPlaylistFooterAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/decision/NewPlaylistFooterAdapter.kt @@ -78,6 +78,7 @@ private constructor(private val binding: ItemNewPlaylistChoiceBinding) : */ fun from(parent: View) = NewPlaylistFooterViewHolder( - ItemNewPlaylistChoiceBinding.inflate(parent.context.inflater)) + ItemNewPlaylistChoiceBinding.inflate(parent.context.inflater) + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistChoiceAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistChoiceAdapter.kt index f40137935..c3c527489 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistChoiceAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistChoiceAdapter.kt @@ -37,7 +37,8 @@ import org.oxycblt.auxio.util.inflater */ class PlaylistChoiceAdapter(val listener: ClickableListListener) : FlexibleListAdapter( - PlaylistChoiceViewHolder.DIFF_CALLBACK) { + PlaylistChoiceViewHolder.DIFF_CALLBACK + ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = PlaylistChoiceViewHolder.from(parent) diff --git a/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistPickerViewModel.kt b/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistPickerViewModel.kt index 799ca1667..d5a3f44ea 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistPickerViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/decision/PlaylistPickerViewModel.kt @@ -97,7 +97,8 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M pendingPlaylist.preferredName, pendingPlaylist.songs.mapNotNull { library.findSong(it.uid) }, pendingPlaylist.template, - pendingPlaylist.reason) + pendingPlaylist.reason, + ) } L.d("Updated pending playlist: ${_currentPendingNewPlaylist.value?.preferredName}") @@ -150,7 +151,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M context: Context, songUids: Array, template: String?, - reason: PlaylistDecision.New.Reason + reason: PlaylistDecision.New.Reason, ) { L.d("Opening ${songUids.size} songs to create a playlist from") val library = musicRepository.library ?: return @@ -191,7 +192,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M playlistUid: Music.UID, applySongUids: Array, template: String?, - reason: PlaylistDecision.Rename.Reason + reason: PlaylistDecision.Rename.Reason, ) { L.d("Opening playlist $playlistUid to rename") val playlist = musicRepository.library?.findPlaylist(playlistUid) @@ -320,14 +321,14 @@ data class PendingNewPlaylist( val preferredName: String, val songs: List, val template: String?, - val reason: PlaylistDecision.New.Reason + val reason: PlaylistDecision.New.Reason, ) data class PendingRenamePlaylist( val playlist: Playlist, val applySongs: List, val template: String?, - val reason: PlaylistDecision.Rename.Reason + val reason: PlaylistDecision.Rename.Reason, ) /** @@ -338,10 +339,13 @@ data class PendingRenamePlaylist( sealed interface ChosenName { /** The current name is valid. */ data class Valid(val value: String) : ChosenName + /** The current name already exists. */ data class AlreadyExists(val prior: String) : ChosenName + /** The current name is empty. */ data object Empty : ChosenName + /** The current name only consists of whitespace. */ data object Blank : ChosenName } diff --git a/app/src/main/java/org/oxycblt/auxio/music/decision/RenamePlaylistDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/decision/RenamePlaylistDialog.kt index bc0da2b65..9c08db61f 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/decision/RenamePlaylistDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/decision/RenamePlaylistDialog.kt @@ -61,7 +61,8 @@ class RenamePlaylistDialog : ViewBindingMaterialDialogFragment(private val binding: ItemMusicLocationBin */ fun from(parent: ViewGroup) = LocationViewHolder( - ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false) + ) } } @@ -154,6 +155,7 @@ class EmptyLocationViewHolder(private val binding: ItemNoLocationsBinding) : */ fun from(parent: ViewGroup) = EmptyLocationViewHolder( - ItemNoLocationsBinding.inflate(parent.context.inflater, parent, false)) + ItemNoLocationsBinding.inflate(parent.context.inflater, parent, false) + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt index 76ad21f23..3d1368100 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt @@ -100,7 +100,7 @@ class LocationsDialog : ViewBindingMaterialDialogFragment @@ -257,7 +257,8 @@ class LocationsDialog : ViewBindingMaterialDialogFragment song?.let { library.findSong(it.uid) } }), - true) + heap = savedState.heap.map { song -> song?.let { library.findSong(it.uid) } }, + ), + true, + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/MediaItemTranslation.kt b/app/src/main/java/org/oxycblt/auxio/music/service/MediaItemTranslation.kt index d3e117ec6..ea0ef6f81 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/MediaItemTranslation.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/MediaItemTranslation.kt @@ -72,7 +72,9 @@ typealias Sugar = Bundle.(Context) -> Unit fun header(@StringRes nameRes: Int): Sugar = { putString( - MediaConstants.DESCRIPTION_EXTRAS_KEY_CONTENT_STYLE_GROUP_TITLE, it.getString(nameRes)) + MediaConstants.DESCRIPTION_EXTRAS_KEY_CONTENT_STYLE_GROUP_TITLE, + it.getString(nameRes), + ) } fun header(name: String): Sugar = { @@ -95,7 +97,8 @@ fun TabNode.toMediaItem(context: Context): MediaItem { val extras = makeExtras( context, - style(MediaConstants.DESCRIPTION_EXTRAS_VALUE_CONTENT_STYLE_CATEGORY_LIST_ITEM)) + style(MediaConstants.DESCRIPTION_EXTRAS_VALUE_CONTENT_STYLE_CATEGORY_LIST_ITEM), + ) val mediaSessionUID = MediaSessionUID.Tab(this) val description = MediaDescriptionCompat.Builder() @@ -140,7 +143,8 @@ fun Album.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem { .setIconUri( covers.covers.firstOrNull()?.let { Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id) - }) + } + ) .setExtras(extras) .build() return MediaItem(description, MediaItem.FLAG_BROWSABLE) @@ -160,7 +164,8 @@ fun Artist.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem { context.getPlural(R.plurals.fmt_song_count, songs.size) } else { context.getString(R.string.def_song_count) - }) + }, + ) val extras = makeExtras(context, *sugar) val description = MediaDescriptionCompat.Builder() @@ -171,7 +176,8 @@ fun Artist.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem { .setIconUri( covers.covers.firstOrNull()?.let { Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id) - }) + } + ) .setExtras(extras) .build() return MediaItem(description, MediaItem.FLAG_BROWSABLE) @@ -194,7 +200,8 @@ fun Genre.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem { .setIconUri( covers.covers.firstOrNull()?.let { Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id) - }) + } + ) .setExtras(extras) .build() return MediaItem(description, MediaItem.FLAG_BROWSABLE) @@ -218,7 +225,8 @@ fun Playlist.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem { .setIconUri( covers.covers.firstOrNull()?.let { Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id) - }) + } + ) .setExtras(extras) .build() return MediaItem(description, MediaItem.FLAG_BROWSABLE) diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/MusicBrowser.kt b/app/src/main/java/org/oxycblt/auxio/music/service/MusicBrowser.kt index cc5245795..8522738cb 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/MusicBrowser.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/MusicBrowser.kt @@ -45,7 +45,7 @@ private constructor( private val musicRepository: MusicRepository, private val searchEngine: SearchEngine, homeGeneratorFactory: HomeGenerator.Factory, - detailGeneratorFactory: DetailGenerator.Factory + detailGeneratorFactory: DetailGenerator.Factory, ) : HomeGenerator.Invalidator, DetailGenerator.Invalidator { class Factory @@ -54,7 +54,7 @@ private constructor( private val musicRepository: MusicRepository, private val searchEngine: SearchEngine, private val homeGeneratorFactory: HomeGenerator.Factory, - private val detailGeneratorFactory: DetailGenerator.Factory + private val detailGeneratorFactory: DetailGenerator.Factory, ) { fun create(context: Context, invalidator: Invalidator): MusicBrowser = MusicBrowser( @@ -63,7 +63,8 @@ private constructor( musicRepository, searchEngine, homeGeneratorFactory, - detailGeneratorFactory) + detailGeneratorFactory, + ) } interface Invalidator { @@ -143,7 +144,12 @@ private constructor( val library = musicRepository.library ?: return mutableListOf() val items = SearchEngine.Items( - library.songs, library.albums, library.artists, library.genres, library.playlists) + library.songs, + library.albums, + library.artists, + library.genres, + library.playlists, + ) return searchEngine.search(items, query).toMediaItems() } diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/MusicServiceFragment.kt b/app/src/main/java/org/oxycblt/auxio/music/service/MusicServiceFragment.kt index 9105f5617..0c4286e92 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/MusicServiceFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/MusicServiceFragment.kt @@ -41,7 +41,7 @@ constructor( private val invalidator: Invalidator, indexingHolderFactory: IndexingHolder.Factory, musicBrowserFactory: MusicBrowser.Factory, - private val musicRepository: MusicRepository + private val musicRepository: MusicRepository, ) : MusicBrowser.Invalidator { private val indexer = indexingHolderFactory.create(context, foregroundListener) private val musicBrowser = musicBrowserFactory.create(context, this) @@ -55,12 +55,12 @@ constructor( constructor( private val indexingHolderFactory: IndexingHolder.Factory, private val musicBrowserFactory: MusicBrowser.Factory, - private val musicRepository: MusicRepository + private val musicRepository: MusicRepository, ) { fun create( context: Context, foregroundListener: ForegroundListener, - invalidator: Invalidator + invalidator: Invalidator, ): MusicServiceFragment = MusicServiceFragment( context, @@ -68,7 +68,8 @@ constructor( invalidator, indexingHolderFactory, musicBrowserFactory, - musicRepository) + musicRepository, + ) } interface Invalidator { @@ -104,17 +105,13 @@ constructor( fun getRoot() = BrowserRoot(MediaSessionUID.Tab(TabNode.Root).toString(), Bundle()) fun getItem(mediaId: String, result: Result) = - result.dispatch { - musicBrowser.getItem( - mediaId, - ) - } + result.dispatch { musicBrowser.getItem(mediaId) } fun getChildren( mediaId: String, maxTabs: Int, result: Result>, - page: Page? + page: Page?, ) = result.dispatch { musicBrowser.getChildren(mediaId, maxTabs)?.expose(page) } fun search(query: String, result: Result>, page: Page?) = diff --git a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBarFragment.kt b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBarFragment.kt index 6e488f6b5..3821debcd 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBarFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBarFragment.kt @@ -51,7 +51,7 @@ class PlaybackBarFragment : ViewBindingFragment() { override fun onBindingCreated( binding: FragmentPlaybackBarBinding, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ) { super.onBindingCreated(binding, savedInstanceState) val context = requireContext() @@ -84,7 +84,8 @@ class PlaybackBarFragment : ViewBindingFragment() { playbackModel.currentBarAction, playbackModel.repeatMode, playbackModel.isShuffled, - ::updateBarAction) + ::updateBarAction, + ) } override fun onDestroyBinding(binding: FragmentPlaybackBarBinding) { @@ -119,7 +120,7 @@ class PlaybackBarFragment : ViewBindingFragment() { private fun updateBarAction( actionMode: ActionMode, repeatMode: RepeatMode, - isShuffled: Boolean + isShuffled: Boolean, ) { val binding = requireBinding() when (actionMode) { diff --git a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBottomSheetBehavior.kt b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBottomSheetBehavior.kt index 49cef16f3..304b839b4 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBottomSheetBehavior.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackBottomSheetBehavior.kt @@ -54,7 +54,8 @@ class PlaybackBottomSheetBehavior(context: Context, attributeSet: Attr ShapeAppearanceModel.builder( context, R.style.ShapeAppearance_Auxio_BottomSheet, - MR.style.ShapeAppearanceOverlay_Material3_Corner_Top) + MR.style.ShapeAppearanceOverlay_Material3_Corner_Top, + ) .build() } else { ShapeAppearanceModel.Builder().build() @@ -85,7 +86,9 @@ class PlaybackBottomSheetBehavior(context: Context, attributeSet: Attr MaterialShapeDrawable(sheetBackgroundDrawable.shapeAppearanceModel).apply { fillColor = sheetBackgroundDrawable.fillColor }, - sheetBackgroundDrawable)) + sheetBackgroundDrawable, + ) + ) override fun applyWindowInsets(child: View, insets: WindowInsets): WindowInsets { super.applyWindowInsets(child, insets) @@ -94,6 +97,10 @@ class PlaybackBottomSheetBehavior(context: Context, attributeSet: Attr val bars = insets.systemBarInsetsCompat expandedOffset = bars.top return insets.replaceSystemBarInsetsCompat( - bars.left, bars.top, bars.right, expandedOffset + bars.bottom) + bars.left, + bars.top, + bars.right, + expandedOffset + bars.bottom, + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackPanelFragment.kt b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackPanelFragment.kt index 64f75751f..c3373ffc3 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackPanelFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackPanelFragment.kt @@ -75,7 +75,7 @@ class PlaybackPanelFragment : override fun onBindingCreated( binding: FragmentPlaybackPanelBinding, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ) { super.onBindingCreated(binding, savedInstanceState) diff --git a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackSettings.kt b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackSettings.kt index a86fbee47..f7444fd3c 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackSettings.kt @@ -64,10 +64,13 @@ interface PlaybackSettings : Settings { interface Listener { /** Called when one of the ReplayGain configurations have changed. */ fun onReplayGainSettingsChanged() {} + /** Called when [notificationAction] has changed. */ fun onNotificationActionChanged() {} + /** Called when [barAction] has changed. */ fun onBarActionChanged() {} + /** Called when [pauseOnRepeat] has changed. */ fun onPauseOnRepeatChanged() {} } @@ -79,26 +82,31 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont get() = PlaySong.fromIntCode( sharedPreferences.getInt( - getString(R.string.set_key_play_in_list_with), Int.MIN_VALUE)) - ?: PlaySong.FromAll + getString(R.string.set_key_play_in_list_with), + Int.MIN_VALUE, + ) + ) ?: PlaySong.FromAll override val inParentPlaybackMode: PlaySong? get() = PlaySong.fromIntCode( sharedPreferences.getInt( - getString(R.string.set_key_play_in_parent_with), Int.MIN_VALUE)) + getString(R.string.set_key_play_in_parent_with), + Int.MIN_VALUE, + ) + ) override val barAction: ActionMode get() = ActionMode.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_bar_action), Int.MIN_VALUE)) - ?: ActionMode.NEXT + sharedPreferences.getInt(getString(R.string.set_key_bar_action), Int.MIN_VALUE) + ) ?: ActionMode.NEXT override val notificationAction: ActionMode get() = ActionMode.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_notif_action), Int.MIN_VALUE)) - ?: ActionMode.REPEAT + sharedPreferences.getInt(getString(R.string.set_key_notif_action), Int.MIN_VALUE) + ) ?: ActionMode.REPEAT override val headsetAutoplay: Boolean get() = sharedPreferences.getBoolean(getString(R.string.set_key_headset_autoplay), false) @@ -106,14 +114,15 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont override val replayGainMode: ReplayGainMode get() = ReplayGainMode.fromIntCode( - sharedPreferences.getInt(getString(R.string.set_key_replay_gain), Int.MIN_VALUE)) - ?: ReplayGainMode.DYNAMIC + sharedPreferences.getInt(getString(R.string.set_key_replay_gain), Int.MIN_VALUE) + ) ?: ReplayGainMode.DYNAMIC override var replayGainPreAmp: ReplayGainPreAmp get() = ReplayGainPreAmp( sharedPreferences.getFloat(getString(R.string.set_key_pre_amp_with), 0f), - sharedPreferences.getFloat(getString(R.string.set_key_pre_amp_without), 0f)) + sharedPreferences.getFloat(getString(R.string.set_key_pre_amp_without), 0f), + ) set(value) { sharedPreferences.edit { putFloat(getString(R.string.set_key_pre_amp_with), value.with) @@ -155,7 +164,9 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont sharedPreferences.edit { putInt( - getString(R.string.set_key_play_in_list_with), mode?.intCode ?: Int.MIN_VALUE) + getString(R.string.set_key_play_in_list_with), + mode?.intCode ?: Int.MIN_VALUE, + ) remove(OLD_KEY_LIB_MUSIC_PLAYBACK_MODE) apply() } @@ -171,7 +182,9 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont sharedPreferences.edit { putInt( - getString(R.string.set_key_play_in_parent_with), mode?.intCode ?: Int.MIN_VALUE) + getString(R.string.set_key_play_in_parent_with), + mode?.intCode ?: Int.MIN_VALUE, + ) remove(OLD_KEY_DETAIL_MUSIC_PLAYBACK_MODE) apply() } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackViewModel.kt b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackViewModel.kt index a2ba95279..b8b5653f3 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/PlaybackViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/PlaybackViewModel.kt @@ -150,7 +150,7 @@ constructor( parent: MusicParent?, queue: List, index: Int, - isShuffled: Boolean + isShuffled: Boolean, ) { L.d("New playback started, updating playback information") _song.value = playbackManager.currentSong @@ -242,7 +242,8 @@ constructor( playbackManager.play( requireNotNull(commandFactory.song(song, shuffle)) { "Invalid playback parameters [$song $shuffle]" - }) + } + ) } private fun playFromAllImpl(song: Song?, shuffle: ShuffleMode) { @@ -268,7 +269,8 @@ constructor( return } L.d( - "Cannot use given artist parameter for $song [$artist from ${song.artists}], showing choice dialog") + "Cannot use given artist parameter for $song [$artist from ${song.artists}], showing choice dialog" + ) startPlaybackDecision(PlaybackDecision.PlayFromArtist(song)) } @@ -279,7 +281,8 @@ constructor( return } L.d( - "Cannot use given genre parameter for $song [$genre from ${song.genres}], showing choice dialog") + "Cannot use given genre parameter for $song [$genre from ${song.genres}], showing choice dialog" + ) startPlaybackDecision(PlaybackDecision.PlayFromArtist(song)) } @@ -639,7 +642,7 @@ enum class OpenPanel { * Open the queue panel, assuming that it exists in the current layout, is collapsed, and with * the playback panel already being expanded. Do nothing if these conditions are not met. */ - QUEUE + QUEUE, } /** @@ -650,8 +653,10 @@ enum class OpenPanel { sealed interface PlaybackDecision { /** The [Song] currently attempting to be played from. */ val song: Song + /** Navigate to a dialog to determine which [Artist] a [Song] should be played from. */ class PlayFromArtist(override val song: Song) : PlaybackDecision + /** Navigate to a dialog to determine which [Genre] a [Song] should be played from. */ class PlayFromGenre(override val song: Song) : PlaybackDecision } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/decision/ArtistPlaybackChoiceAdapter.kt b/app/src/main/java/org/oxycblt/auxio/playback/decision/ArtistPlaybackChoiceAdapter.kt index 2d1f785f4..0fef9dfbf 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/decision/ArtistPlaybackChoiceAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/decision/ArtistPlaybackChoiceAdapter.kt @@ -38,7 +38,8 @@ import org.oxycblt.musikr.Artist */ class ArtistPlaybackChoiceAdapter(private val listener: ClickableListListener) : FlexibleListAdapter( - ArtistPlaybackChoiceViewHolder.DIFF_CALLBACK) { + ArtistPlaybackChoiceViewHolder.DIFF_CALLBACK + ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ArtistPlaybackChoiceViewHolder.from(parent) diff --git a/app/src/main/java/org/oxycblt/auxio/playback/decision/GenrePlaybackChoiceAdapter.kt b/app/src/main/java/org/oxycblt/auxio/playback/decision/GenrePlaybackChoiceAdapter.kt index 7eb31fd06..e96938c34 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/decision/GenrePlaybackChoiceAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/decision/GenrePlaybackChoiceAdapter.kt @@ -38,7 +38,8 @@ import org.oxycblt.musikr.Genre */ class GenrePlaybackChoiceAdapter(private val listener: ClickableListListener) : FlexibleListAdapter( - GenrePlaybackChoiceViewHolder.DIFF_CALLBACK) { + GenrePlaybackChoiceViewHolder.DIFF_CALLBACK + ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = GenrePlaybackChoiceViewHolder.from(parent) diff --git a/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceDatabase.kt b/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceDatabase.kt index 99805a0d5..90f4e5bdf 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceDatabase.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceDatabase.kt @@ -39,7 +39,8 @@ import org.oxycblt.musikr.Music @Database( entities = [PlaybackState::class, QueueHeapItem::class, QueueShuffledMappingItem::class], version = 38, - exportSchema = false) + exportSchema = false, +) @TypeConverters(Music.UID.TypeConverters::class) abstract class PersistenceDatabase : RoomDatabase() { /** @@ -144,7 +145,7 @@ data class PlaybackState( val positionMs: Long, val repeatMode: RepeatMode, val songUid: Music.UID, - val parentUid: Music.UID? + val parentUid: Music.UID?, ) @Entity data class QueueHeapItem(@PrimaryKey val id: Int, val uid: Music.UID) diff --git a/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceModule.kt b/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceModule.kt index fd82e75d4..5b3123a10 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceModule.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceModule.kt @@ -43,7 +43,8 @@ class PersistenceRoomModule { Room.databaseBuilder( context.applicationContext, PersistenceDatabase::class.java, - "playback_persistence.db") + "playback_persistence.db", + ) .fallbackToDestructiveMigration() .addMigrations(PersistenceDatabase.MIGRATION_27_32) .build() diff --git a/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceRepository.kt b/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceRepository.kt index 5dc48852d..14029d9a8 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/persist/PersistenceRepository.kt @@ -46,7 +46,7 @@ class PersistenceRepositoryImpl constructor( private val playbackStateDao: PlaybackStateDao, private val queueDao: QueueDao, - private val musicRepository: MusicRepository + private val musicRepository: MusicRepository, ) : PersistenceRepository { override suspend fun readState(): PlaybackStateManager.SavedState? { @@ -75,7 +75,8 @@ constructor( heap = heap, shuffledMapping = shuffledMapping, index = playbackState.index, - songUid = playbackState.songUid) + songUid = playbackState.songUid, + ) } override suspend fun saveState(state: PlaybackStateManager.SavedState?): Boolean { @@ -99,7 +100,8 @@ constructor( positionMs = state.positionMs, repeatMode = state.repeatMode, songUid = state.songUid, - parentUid = state.parent?.uid) + parentUid = state.parent?.uid, + ) // Convert the remaining queue information do their database-specific counterparts. val heap = diff --git a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueAdapter.kt b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueAdapter.kt index d1b630c7f..02ea29f09 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueAdapter.kt @@ -63,7 +63,7 @@ class QueueAdapter(private val listener: EditClickListListener) : override fun onBindViewHolder( viewHolder: QueueSongViewHolder, position: Int, - payload: List + payload: List, ) { if (payload.isEmpty()) { viewHolder.bind(getItem(position), listener) @@ -143,7 +143,9 @@ class QueueSongViewHolder private constructor(private val binding: ItemEditableS fillColor = binding.context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh) }, - background)) + background, + ) + ) } /** diff --git a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueBottomSheetBehavior.kt b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueBottomSheetBehavior.kt index 10608aa6e..71e2b5299 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueBottomSheetBehavior.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueBottomSheetBehavior.kt @@ -59,7 +59,7 @@ class QueueBottomSheetBehavior(context: Context, attributeSet: Attribu override fun onDependentViewChanged( parent: CoordinatorLayout, child: V, - dependency: View + dependency: View, ): Boolean { barHeight = dependency.height // No change, just grabbed the height @@ -75,7 +75,8 @@ class QueueBottomSheetBehavior(context: Context, attributeSet: Attribu ShapeAppearanceModel.builder( context, R.style.ShapeAppearance_Auxio_BottomSheet, - MR.style.ShapeAppearanceOverlay_Material3_Corner_Top) + MR.style.ShapeAppearanceOverlay_Material3_Corner_Top, + ) .build() } } @@ -89,6 +90,10 @@ class QueueBottomSheetBehavior(context: Context, attributeSet: Attribu val effectiveBarHeight = if (barHeight > 0) barHeight else getIdealBarHeight(child.context) expandedOffset = effectiveBarHeight + barSpacing return insets.replaceSystemBarInsetsCompat( - bars.left, bars.top, bars.right, expandedOffset + bars.bottom) + bars.left, + bars.top, + bars.right, + expandedOffset + bars.bottom, + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueDragCallback.kt b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueDragCallback.kt index 23d45f62a..e15d2ed2b 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueDragCallback.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueDragCallback.kt @@ -32,10 +32,12 @@ class QueueDragCallback(private val queueModel: QueueViewModel) : MaterialDragCa override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, - target: RecyclerView.ViewHolder + target: RecyclerView.ViewHolder, ) = queueModel.moveQueueDataItems( - viewHolder.bindingAdapterPosition, target.bindingAdapterPosition) + viewHolder.bindingAdapterPosition, + target.bindingAdapterPosition, + ) override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { queueModel.removeQueueDataItem(viewHolder.bindingAdapterPosition) diff --git a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueFragment.kt b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueFragment.kt index ede1313e0..614f7142e 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueFragment.kt @@ -71,12 +71,17 @@ class QueueFragment : ViewBindingFragment(), EditClickList override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { updateDivider() } - }) + } + ) } // --- VIEWMODEL SETUP ---- collectImmediately( - queueModel.queue, queueModel.index, playbackModel.isPlaying, ::updateQueue) + queueModel.queue, + queueModel.index, + playbackModel.isPlaying, + ::updateQueue, + ) } override fun onDestroyBinding(binding: FragmentQueueBinding) { diff --git a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueViewModel.kt b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueViewModel.kt index 5e1e2aa64..20abf7881 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/queue/QueueViewModel.kt @@ -92,7 +92,7 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt parent: MusicParent?, queue: List, index: Int, - isShuffled: Boolean + isShuffled: Boolean, ) { // Entirely new queue -> Replace queue, update index L.d("New playback, replacing queue and position") diff --git a/app/src/main/java/org/oxycblt/auxio/playback/replaygain/ReplayGainAudioProcessor.kt b/app/src/main/java/org/oxycblt/auxio/playback/replaygain/ReplayGainAudioProcessor.kt index 5c2e27c41..c41e98e48 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/replaygain/ReplayGainAudioProcessor.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/replaygain/ReplayGainAudioProcessor.kt @@ -48,7 +48,7 @@ class ReplayGainAudioProcessor @Inject constructor( private val playbackManager: PlaybackStateManager, - private val playbackSettings: PlaybackSettings + private val playbackSettings: PlaybackSettings, ) : BaseAudioProcessor(), PlaybackStateManager.Listener, PlaybackSettings.Listener { private var volume = 1f set(value) { @@ -86,7 +86,7 @@ constructor( parent: MusicParent?, queue: List, index: Int, - isShuffled: Boolean + isShuffled: Boolean, ) { L.d("New playback started, updating playback information") applyReplayGain(playbackManager.currentSong) diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/BluetoothHeadsetReceiver.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/BluetoothHeadsetReceiver.kt index 11df166f2..c2f301df5 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/BluetoothHeadsetReceiver.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/BluetoothHeadsetReceiver.kt @@ -33,7 +33,9 @@ class BluetoothHeadsetReceiver : BroadcastReceiver() { if (intent.action == android.bluetooth.BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) { val newState = intent.getIntExtra( - BluetoothProfile.EXTRA_STATE, BluetoothProfile.STATE_DISCONNECTED) + BluetoothProfile.EXTRA_STATE, + BluetoothProfile.STATE_DISCONNECTED, + ) if (newState == BluetoothProfile.STATE_CONNECTED) { // TODO: Initialize the service (Permission workflow must be figured out) // Perhaps move this to the internal receivers? diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/ExoPlaybackStateHolder.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/ExoPlaybackStateHolder.kt index 32bd40ad8..4b64e5848 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/ExoPlaybackStateHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/ExoPlaybackStateHolder.kt @@ -74,7 +74,7 @@ class ExoPlaybackStateHolder( private val commandFactory: PlaybackCommand.Factory, private val replayGainProcessor: ReplayGainAudioProcessor, private val musicRepository: MusicRepository, - private val imageSettings: ImageSettings + private val imageSettings: ImageSettings, ) : PlaybackStateHolder, Player.Listener, @@ -180,7 +180,8 @@ class ExoPlaybackStateHolder( playbackManager.play( requireNotNull(commandFactory.all(ShuffleMode.ON)) { "Invalid playback parameters" - }) + } + ) } // Open -> Try to find the Song for the given file and then play it from all songs is DeferredPlayback.Open -> { @@ -191,7 +192,8 @@ class ExoPlaybackStateHolder( arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, - null) + null, + ) ?.use { cursor -> val displayNameIndex = cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME) @@ -206,9 +208,10 @@ class ExoPlaybackStateHolder( if (song != null) { val command = requireNotNull( - commandFactory.songFromAll(song, ShuffleMode.IMPLICIT)) { - "Invalid playback command" - } + commandFactory.songFromAll(song, ShuffleMode.IMPLICIT) + ) { + "Invalid playback command" + } playbackManager.play(command) } } @@ -265,7 +268,8 @@ class ExoPlaybackStateHolder( if (player.shuffleModeEnabled) { // Have to manually refresh the shuffle seed and anchor it to the new current songs player.setShuffleOrder( - BetterShuffleOrder(player.mediaItemCount, player.currentMediaItemIndex)) + BetterShuffleOrder(player.mediaItemCount, player.currentMediaItemIndex) + ) } playbackManager.ack(this, StateAck.QueueReordered) deferSave() @@ -282,7 +286,9 @@ class ExoPlaybackStateHolder( } } else { player.seekTo( - player.currentTimeline.getFirstWindowIndex(player.shuffleModeEnabled), C.TIME_UNSET) + player.currentTimeline.getFirstWindowIndex(player.shuffleModeEnabled), + C.TIME_UNSET, + ) // TODO: Dislike the UX implications of this, I feel should I bite the bullet // and switch to dynamic skip enable/disable? if (!playbackSettings.rememberPause) { @@ -330,7 +336,10 @@ class ExoPlaybackStateHolder( C.INDEX_UNSET } else { currTimeline.getNextWindowIndex( - player.currentMediaItemIndex, Player.REPEAT_MODE_OFF, player.shuffleModeEnabled) + player.currentMediaItemIndex, + Player.REPEAT_MODE_OFF, + player.shuffleModeEnabled, + ) } if (nextIndex == C.INDEX_UNSET) { @@ -393,7 +402,7 @@ class ExoPlaybackStateHolder( rawQueue: RawQueue, positionMs: Long, repeatMode: RepeatMode, - ack: StateAck.NewPlayback? + ack: StateAck.NewPlayback?, ) { var sendNewPlaybackEvent = false var shouldSeek = false @@ -498,10 +507,13 @@ class ExoPlaybackStateHolder( // So many actions trigger progression changes that it becomes easier just to handle it // in an ExoPlayer callback anyway. This doesn't really cause issues anywhere. - if (events.containsAny( - Player.EVENT_PLAY_WHEN_READY_CHANGED, - Player.EVENT_IS_PLAYING_CHANGED, - Player.EVENT_POSITION_DISCONTINUITY)) { + if ( + events.containsAny( + Player.EVENT_PLAY_WHEN_READY_CHANGED, + Player.EVENT_IS_PLAYING_CHANGED, + Player.EVENT_POSITION_DISCONTINUITY, + ) + ) { L.d("Player state changed, must synchronize state") playbackManager.ack(this, StateAck.ProgressionChanged) } @@ -521,7 +533,8 @@ class ExoPlaybackStateHolder( Intent(event) .putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.packageName) .putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId) - .putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC)) + .putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC) + ) } // --- MUSICREPOSITORY METHODS --- @@ -601,7 +614,10 @@ class ExoPlaybackStateHolder( if (lastMediaItemIndex != C.INDEX_UNSET) { lastMediaItemIndex = timeline.getNextWindowIndex( - lastMediaItemIndex, Player.REPEAT_MODE_OFF, shuffleModeEnabled) + lastMediaItemIndex, + Player.REPEAT_MODE_OFF, + shuffleModeEnabled, + ) if (lastMediaItemIndex != C.INDEX_UNSET) { queue.add(lastMediaItemIndex) } @@ -609,7 +625,10 @@ class ExoPlaybackStateHolder( if (firstMediaItemIndex != C.INDEX_UNSET) { firstMediaItemIndex = timeline.getPreviousWindowIndex( - firstMediaItemIndex, Player.REPEAT_MODE_OFF, shuffleModeEnabled) + firstMediaItemIndex, + Player.REPEAT_MODE_OFF, + shuffleModeEnabled, + ) if (firstMediaItemIndex != C.INDEX_UNSET) { queue.add(0, firstMediaItemIndex) } @@ -645,7 +664,9 @@ class ExoPlaybackStateHolder( audioListener, DefaultAudioSink.Builder(context) .setAudioProcessors(arrayOf(replayGainProcessor)) - .build())) + .build(), + ), + ) } val exoPlayer = @@ -659,7 +680,8 @@ class ExoPlaybackStateHolder( .setUsage(C.USAGE_MEDIA) .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC) .build(), - true) + true, + ) .build() return ExoPlaybackStateHolder( @@ -671,7 +693,8 @@ class ExoPlaybackStateHolder( commandFactory, replayGainProcessor, musicRepository, - imageSettings) + imageSettings, + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionHolder.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionHolder.kt index d90ddb8b7..02529afe1 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionHolder.kt @@ -68,7 +68,7 @@ private constructor( private val playbackSettings: PlaybackSettings, private val bitmapProvider: BitmapProvider, private val imageSettings: ImageSettings, - private val mediaSessionInterface: MediaSessionInterface + private val mediaSessionInterface: MediaSessionInterface, ) : PlaybackStateManager.Listener, ImageSettings.Listener, PlaybackSettings.Listener { class Factory @@ -78,7 +78,7 @@ private constructor( private val playbackSettings: PlaybackSettings, private val bitmapProvider: BitmapProvider, private val imageSettings: ImageSettings, - private val mediaSessionInterface: MediaSessionInterface + private val mediaSessionInterface: MediaSessionInterface, ) { fun create(context: Context, foregroundListener: ForegroundListener) = MediaSessionHolder( @@ -88,7 +88,8 @@ private constructor( playbackSettings, bitmapProvider, imageSettings, - mediaSessionInterface) + mediaSessionInterface, + ) } private val mediaSession = MediaSessionCompat(context, context.packageName) @@ -156,7 +157,8 @@ private constructor( PlaybackStateCompat.SHUFFLE_MODE_ALL } else { PlaybackStateCompat.SHUFFLE_MODE_NONE - }) + } + ) invalidateSecondaryAction() } @@ -164,7 +166,7 @@ private constructor( parent: MusicParent?, queue: List, index: Int, - isShuffled: Boolean + isShuffled: Boolean, ) { updateMediaMetadata(playbackManager.currentSong, parent) updateQueue(queue) @@ -185,7 +187,8 @@ private constructor( RepeatMode.NONE -> PlaybackStateCompat.REPEAT_MODE_NONE RepeatMode.TRACK -> PlaybackStateCompat.REPEAT_MODE_ONE RepeatMode.ALL -> PlaybackStateCompat.REPEAT_MODE_ALL - }) + } + ) invalidateSecondaryAction() } @@ -238,7 +241,8 @@ private constructor( .putText(MediaMetadataCompat.METADATA_KEY_ARTIST, artist) .putText( MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, - song.album.artists.resolveNames(context)) + song.album.artists.resolveNames(context), + ) .putText(MediaMetadataCompat.METADATA_KEY_AUTHOR, artist) .putText(MediaMetadataCompat.METADATA_KEY_COMPOSER, artist) .putText(MediaMetadataCompat.METADATA_KEY_WRITER, artist) @@ -249,13 +253,16 @@ private constructor( .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, song.durationMs) .putText( PlaybackNotification.KEY_PARENT, - parent?.name?.resolve(context) ?: context.getString(R.string.lbl_all_songs)) + parent?.name?.resolve(context) ?: context.getString(R.string.lbl_all_songs), + ) .putText( MetadataExtras.KEY_SUBTITLE_LINK_MEDIA_ID, - MediaSessionUID.SingleItem(song.artists[0].uid).toString()) + MediaSessionUID.SingleItem(song.artists[0].uid).toString(), + ) .putText( MetadataExtras.KEY_DESCRIPTION_LINK_MEDIA_ID, - MediaSessionUID.SingleItem(song.album.uid).toString()) + MediaSessionUID.SingleItem(song.album.uid).toString(), + ) // These fields are nullable and so we must check first before adding them to the fields. song.track?.let { L.d("Adding track information") @@ -288,7 +295,8 @@ private constructor( _notification.updateMetadata(metadata) foregroundListener.updateForeground(ForegroundListener.Change.MEDIA_SESSION) } - }) + }, + ) } /** @@ -301,7 +309,9 @@ private constructor( queue.mapIndexed { i, song -> val description = song.toMediaDescription( - context, { putInt(MediaSessionInterface.KEY_QUEUE_POS, i) }) + context, + { putInt(MediaSessionInterface.KEY_QUEUE_POS, i) }, + ) // Store the item index so we can then use the analogous index in the // playback state. MediaSessionCompat.QueueItem(description, i.toLong()) @@ -336,14 +346,16 @@ private constructor( R.drawable.ic_shuffle_on_24 } else { R.drawable.ic_shuffle_off_24 - }) + }, + ) } else -> { L.d("Using repeat mode MediaSession action") PlaybackStateCompat.CustomAction.Builder( PlaybackActions.ACTION_INC_REPEAT_MODE, context.getString(R.string.desc_change_repeat), - playbackManager.repeatMode.icon) + playbackManager.repeatMode.icon, + ) } } state.addCustomAction(secondaryAction.build()) @@ -353,7 +365,8 @@ private constructor( PlaybackStateCompat.CustomAction.Builder( PlaybackActions.ACTION_EXIT, context.getString(R.string.desc_exit), - R.drawable.ic_close_24) + R.drawable.ic_close_24, + ) .build() state.addCustomAction(exitAction) @@ -396,7 +409,7 @@ private constructor( @SuppressLint("RestrictedApi") private class PlaybackNotification( private val context: Context, - sessionToken: MediaSessionCompat.Token + sessionToken: MediaSessionCompat.Token, ) : ForegroundServiceNotification(context, CHANNEL_INFO) { init { setSmallIcon(R.drawable.ic_auxio_24) @@ -408,14 +421,17 @@ private class PlaybackNotification( addAction(buildRepeatAction(context, RepeatMode.NONE)) addAction( - buildAction(context, PlaybackActions.ACTION_SKIP_PREV, R.drawable.ic_skip_prev_24)) + buildAction(context, PlaybackActions.ACTION_SKIP_PREV, R.drawable.ic_skip_prev_24) + ) addAction(buildPlayPauseAction(context, true)) addAction( - buildAction(context, PlaybackActions.ACTION_SKIP_NEXT, R.drawable.ic_skip_next_24)) + buildAction(context, PlaybackActions.ACTION_SKIP_NEXT, R.drawable.ic_skip_next_24) + ) addAction(buildAction(context, PlaybackActions.ACTION_EXIT, R.drawable.ic_close_24)) setStyle( - MediaStyle(this).setMediaSession(sessionToken).setShowActionsInCompactView(1, 2, 3)) + MediaStyle(this).setMediaSession(sessionToken).setShowActionsInCompactView(1, 2, 3) + ) } override val code: Int @@ -470,7 +486,7 @@ private class PlaybackNotification( private fun buildPlayPauseAction( context: Context, - isPlaying: Boolean + isPlaying: Boolean, ): NotificationCompat.Action { val drawableRes = if (isPlaying) { @@ -483,14 +499,14 @@ private class PlaybackNotification( private fun buildRepeatAction( context: Context, - repeatMode: RepeatMode + repeatMode: RepeatMode, ): NotificationCompat.Action { return buildAction(context, PlaybackActions.ACTION_INC_REPEAT_MODE, repeatMode.icon) } private fun buildShuffleAction( context: Context, - isShuffled: Boolean + isShuffled: Boolean, ): NotificationCompat.Action { val drawableRes = if (isShuffled) { @@ -503,7 +519,10 @@ private class PlaybackNotification( private fun buildAction(context: Context, actionName: String, @DrawableRes iconRes: Int) = NotificationCompat.Action.Builder( - iconRes, actionName, context.newBroadcastPendingIntent(actionName)) + iconRes, + actionName, + context.newBroadcastPendingIntent(actionName), + ) .build() companion object { @@ -513,6 +532,7 @@ private class PlaybackNotification( private val CHANNEL_INFO = ChannelInfo( id = BuildConfig.APPLICATION_ID + ".channel.PLAYBACK", - nameRes = R.string.lbl_playback) + nameRes = R.string.lbl_playback, + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionInterface.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionInterface.kt index abe600479..b1246b2fb 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionInterface.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/MediaSessionInterface.kt @@ -168,13 +168,15 @@ constructor( PlaybackStateCompat.REPEAT_MODE_GROUP -> RepeatMode.ALL PlaybackStateCompat.REPEAT_MODE_ONE -> RepeatMode.TRACK else -> RepeatMode.NONE - }) + } + ) } override fun onSetShuffleMode(shuffleMode: Int) { playbackManager.shuffled( shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_ALL || - shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_GROUP) + shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_GROUP + ) } override fun onStop() { @@ -191,7 +193,7 @@ constructor( private fun expandUidIntoCommand( uid: MediaSessionUID, - parentUid: MediaSessionUID? + parentUid: MediaSessionUID?, ): PlaybackCommand? { val unwrappedUid = (uid as? MediaSessionUID.SingleItem)?.uid ?: return null val unwrappedParentUid = (parentUid as? MediaSessionUID.SingleItem)?.uid @@ -204,7 +206,7 @@ constructor( private fun expandSearchInfoCommand( query: String?, extras: Bundle, - library: Library + library: Library, ): PlaybackCommand? { if (query == null) { // User just wanted to 'play some music', shuffle all diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/PlaybackServiceFragment.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/PlaybackServiceFragment.kt index 2b90f2f38..44ede3eb1 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/PlaybackServiceFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/PlaybackServiceFragment.kt @@ -59,7 +59,8 @@ private constructor( exoHolderFactory, sessionHolderFactory, widgetComponentFactory, - systemReceiverFactory) + systemReceiverFactory, + ) } private val waitJob = Job() @@ -94,12 +95,16 @@ private constructor( IntegerTable.START_ID_ACTIVITY -> null IntegerTable.START_ID_TASKER -> DeferredPlayback.RestoreState( - play = true, fallback = DeferredPlayback.ShuffleAll) + play = true, + fallback = DeferredPlayback.ShuffleAll, + ) IntegerTable.START_ID_MEDIA_BUTTON -> { if (!sessionHolder.tryMediaButtonIntent(intent)) { // Malformed intent, need to restore state immediately DeferredPlayback.RestoreState( - play = true, fallback = DeferredPlayback.ShuffleAll) + play = true, + fallback = DeferredPlayback.ShuffleAll, + ) } else { null } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/SystemModule.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/SystemModule.kt index 2854d4873..dacb2e94c 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/SystemModule.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/SystemModule.kt @@ -48,7 +48,7 @@ class SystemModule { @Provides fun mediaSourceFactory( dataSourceFactory: DataSource.Factory, - extractorsFactory: ExtractorsFactory + extractorsFactory: ExtractorsFactory, ): MediaSource.Factory = ProgressiveMediaSource.Factory(dataSourceFactory, extractorsFactory) @Provides @@ -70,6 +70,7 @@ class SystemModule { MatroskaExtractor(DefaultSubtitleParserFactory.UNSUPPORTED), // Enable constant bitrate seeking so that certain MP3s/AACs are seekable AdtsExtractor(AdtsExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING), - Mp3Extractor(Mp3Extractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING)) + Mp3Extractor(Mp3Extractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING), + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/service/SystemPlaybackReceiver.kt b/app/src/main/java/org/oxycblt/auxio/playback/service/SystemPlaybackReceiver.kt index 0ff4b83e3..50792f99d 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/service/SystemPlaybackReceiver.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/service/SystemPlaybackReceiver.kt @@ -40,7 +40,7 @@ private constructor( private val context: Context, private val playbackManager: PlaybackStateManager, private val playbackSettings: PlaybackSettings, - private val widgetComponent: WidgetComponent + private val widgetComponent: WidgetComponent, ) : BroadcastReceiver() { private var initialHeadsetPlugEventHandled = false @@ -48,7 +48,7 @@ private constructor( @Inject constructor( private val playbackManager: PlaybackStateManager, - private val playbackSettings: PlaybackSettings + private val playbackSettings: PlaybackSettings, ) { fun create(context: Context, widgetComponent: WidgetComponent) = SystemPlaybackReceiver(context, playbackManager, playbackSettings, widgetComponent) @@ -57,7 +57,11 @@ private constructor( @Suppress("WrongConstant") fun attach() { ContextCompat.registerReceiver( - context, this, INTENT_FILTER, ContextCompat.RECEIVER_EXPORTED) + context, + this, + INTENT_FILTER, + ContextCompat.RECEIVER_EXPORTED, + ) } fun release() { @@ -125,9 +129,11 @@ private constructor( // ACTION_HEADSET_PLUG will fire when this BroadcastReceiver is initially attached, // which would result in unexpected playback. Work around it by dropping the first // call to this function, which should come from that Intent. - if (playbackSettings.headsetAutoplay && - playbackManager.currentSong != null && - initialHeadsetPlugEventHandled) { + if ( + playbackSettings.headsetAutoplay && + playbackManager.currentSong != null && + initialHeadsetPlugEventHandled + ) { L.d("Device connected, resuming") playbackManager.playing(true) } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackCommand.kt b/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackCommand.kt index d4aedf3db..99b8a67d0 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackCommand.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackCommand.kt @@ -78,7 +78,7 @@ interface PlaybackCommand { enum class ShuffleMode { ON, OFF, - IMPLICIT + IMPLICIT, } class PlaybackCommandFactoryImpl @@ -87,13 +87,13 @@ constructor( val playbackManager: PlaybackStateManager, val playbackSettings: PlaybackSettings, val listSettings: ListSettings, - val musicRepository: MusicRepository + val musicRepository: MusicRepository, ) : PlaybackCommand.Factory { data class PlaybackCommandImpl( override val song: Song?, override val parent: MusicParent?, override val queue: List, - override val shuffled: Boolean + override val shuffled: Boolean, ) : PlaybackCommand { // Only show queue count to reduce memory use override fun toString() = @@ -139,7 +139,7 @@ constructor( parent: T?, parents: List, sort: Sort, - shuffle: ShuffleMode + shuffle: ShuffleMode, ): PlaybackCommand? { return if (parent != null) { newCommand(song, parent, sort, shuffle) @@ -159,7 +159,7 @@ constructor( song: Song?, parent: MusicParent, sort: Sort, - shuffle: ShuffleMode + shuffle: ShuffleMode, ): PlaybackCommand? { val songs = sort.songs(parent.songs) return newCommand(song, parent, songs, sort, shuffle) @@ -170,7 +170,7 @@ constructor( parent: MusicParent?, queue: Collection, sort: Sort, - shuffle: ShuffleMode + shuffle: ShuffleMode, ): PlaybackCommand? { if (queue.isEmpty() || (song != null && song !in queue)) { return null @@ -182,7 +182,7 @@ constructor( song: Song?, parent: MusicParent?, queue: List, - shuffle: ShuffleMode + shuffle: ShuffleMode, ): PlaybackCommand { return PlaybackCommandImpl(song, parent, queue, isShuffled(shuffle)) } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackStateHolder.kt b/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackStateHolder.kt index 11f5f2938..4b96af070 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackStateHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackStateHolder.kt @@ -150,7 +150,7 @@ interface PlaybackStateHolder { rawQueue: RawQueue, positionMs: Long, repeatMode: RepeatMode, - ack: StateAck.NewPlayback? + ack: StateAck.NewPlayback?, ) /** End whatever ongoing playback session may be going on */ @@ -219,11 +219,7 @@ sealed interface StateAck { * nonsensical value that cannot be used to obtain next and last songs without first resolving the * queue. */ -data class RawQueue( - val heap: List, - val shuffledMapping: List, - val heapIndex: Int, -) { +data class RawQueue(val heap: List, val shuffledMapping: List, val heapIndex: Int) { /** Whether the queue is currently shuffled. */ val isShuffled = shuffledMapping.isNotEmpty() @@ -275,7 +271,7 @@ data class QueueChange(val type: Type, val instructions: UpdateInstructions) { * The current song has changed, possibly alongside the mapping and index depending on the * context. */ - SONG + SONG, } } @@ -308,7 +304,7 @@ private constructor( /** The position when this instance was created, in milliseconds. */ private val initPositionMs: Long, /** The time this instance was created, as a unix epoch timestamp. */ - private val creationTime: Long + private val creationTime: Long, ) { /** * Calculate the "real" playback position this instance contains, in milliseconds. @@ -347,7 +343,8 @@ private constructor( // Not advancing, so don't move the position. 0f }, - creationTime) + creationTime, + ) // Equality ignores the creation time to prevent functionally identical states // from being non-equal. @@ -380,13 +377,15 @@ private constructor( // Minor sanity check: Make sure that advancing can't occur if already paused. isPlaying && isAdvancing, positionMs, - SystemClock.elapsedRealtime()) + SystemClock.elapsedRealtime(), + ) fun nil() = Progression( isPlaying = false, isAdvancing = false, initPositionMs = 0, - creationTime = SystemClock.elapsedRealtime()) + creationTime = SystemClock.elapsedRealtime(), + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackStateManager.kt b/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackStateManager.kt index e0aede3ab..2dfc07c5f 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackStateManager.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/state/PlaybackStateManager.kt @@ -296,7 +296,7 @@ interface PlaybackStateManager { parent: MusicParent?, queue: List, index: Int, - isShuffled: Boolean + isShuffled: Boolean, ) {} /** @@ -342,7 +342,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { val queue: List, val index: Int, val isShuffled: Boolean, - val rawQueue: RawQueue + val rawQueue: RawQueue, ) private val listeners = mutableListOf() @@ -356,7 +356,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { queue = emptyList(), index = -1, isShuffled = false, - rawQueue = RawQueue.nil()) + rawQueue = RawQueue.nil(), + ) @Volatile private var stateHolder: PlaybackStateHolder? = null @Volatile private var pendingDeferredPlayback: DeferredPlayback? = null @Volatile private var isInitialized = false @@ -393,7 +394,11 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { if (isInitialized) { L.d("Sending initial state to $listener") listener.onNewPlayback( - stateMirror.parent, stateMirror.queue, stateMirror.index, stateMirror.isShuffled) + stateMirror.parent, + stateMirror.queue, + stateMirror.index, + stateMirror.isShuffled, + ) listener.onProgressionChanged(stateMirror.progression) listener.onRepeatModeChanged(stateMirror.repeatMode) } @@ -421,7 +426,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { stateMirror.rawQueue, stateMirror.progression.calculateElapsedPositionMs(), stateMirror.repeatMode, - null) + null, + ) } pendingDeferredPlayback?.let(stateHolder::handleDeferred) } @@ -592,11 +598,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { val rawQueue = stateHolder.resolveQueue() val change = 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) listeners.forEach { it.onQueueChanged(stateMirror.queue, stateMirror.index, change) } @@ -605,11 +607,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { val rawQueue = stateHolder.resolveQueue() val change = 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) listeners.forEach { it.onQueueChanged(stateMirror.queue, stateMirror.index, change) } @@ -621,7 +619,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { QueueChange( if (stateMirror.index != newIndex) QueueChange.Type.INDEX else QueueChange.Type.MAPPING, - UpdateInstructions.Move(ack.from, ack.to)) + UpdateInstructions.Move(ack.from, ack.to), + ) stateMirror = stateMirror.copy( @@ -644,7 +643,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { stateMirror.index != newIndex -> QueueChange.Type.INDEX else -> QueueChange.Type.MAPPING }, - UpdateInstructions.Remove(ack.index, 1)) + UpdateInstructions.Remove(ack.index, 1), + ) stateMirror = stateMirror.copy( @@ -664,10 +664,14 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { queue = rawQueue.resolveSongs(), index = rawQueue.resolveIndex(), isShuffled = rawQueue.isShuffled, - rawQueue = rawQueue) + rawQueue = rawQueue, + ) listeners.forEach { it.onQueueReordered( - stateMirror.queue, stateMirror.index, stateMirror.isShuffled) + stateMirror.queue, + stateMirror.index, + stateMirror.isShuffled, + ) } } is StateAck.NewPlayback -> { @@ -678,27 +682,23 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { queue = rawQueue.resolveSongs(), index = rawQueue.resolveIndex(), isShuffled = rawQueue.isShuffled, - rawQueue = rawQueue) + rawQueue = rawQueue, + ) listeners.forEach { it.onNewPlayback( stateMirror.parent, stateMirror.queue, stateMirror.index, - stateMirror.isShuffled) + stateMirror.isShuffled, + ) } } is StateAck.ProgressionChanged -> { - stateMirror = - stateMirror.copy( - progression = stateHolder.progression, - ) + stateMirror = stateMirror.copy(progression = stateHolder.progression) listeners.forEach { it.onProgressionChanged(stateMirror.progression) } } is StateAck.RepeatModeChanged -> { - stateMirror = - stateMirror.copy( - repeatMode = stateHolder.repeatMode, - ) + stateMirror = stateMirror.copy(repeatMode = stateHolder.repeatMode) listeners.forEach { it.onRepeatModeChanged(stateMirror.repeatMode) } } is StateAck.SessionEnded -> { @@ -726,7 +726,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { @Synchronized override fun applySavedState( savedState: PlaybackStateManager.SavedState, - destructive: Boolean + destructive: Boolean, ) { if (isInitialized && !destructive) { L.w("Already initialized, cannot apply saved state") @@ -795,14 +795,16 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager { shuffledMapping[index] } else { index - }) + }, + ) stateHolder.applySavedState( savedState.parent, rawQueue, savedState.positionMs, savedState.repeatMode, - StateAck.NewPlayback) + StateAck.NewPlayback, + ) isInitialized = true } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/AnimatedMaterialButton.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/AnimatedMaterialButton.kt index 29accb6f0..b13686c75 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/ui/AnimatedMaterialButton.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/AnimatedMaterialButton.kt @@ -40,7 +40,7 @@ class AnimatedMaterialButton : RippleFixMaterialButton { constructor( context: Context, attrs: AttributeSet, - defStyleAttr: Int + defStyleAttr: Int, ) : super(context, attrs, defStyleAttr) private var animator: Animator? = null diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/ControlledCoverView.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/ControlledCoverView.kt index 216755c37..677292261 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/ui/ControlledCoverView.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/ControlledCoverView.kt @@ -65,21 +65,23 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr e1: MotionEvent?, e2: MotionEvent, velocityX: Float, - velocityY: Float + velocityY: Float, ): Boolean = false override fun onFling( e1: MotionEvent?, e2: MotionEvent, velocityX: Float, - velocityY: Float + velocityY: Float, ): Boolean { e1 ?: return false val diffY = e2.y - e1.y val diffX = e2.x - e1.x - if (abs(diffX) > abs(diffY) && - abs(diffX) > viewConfig.scaledTouchSlop && - abs(velocityX) > viewConfig.scaledMinimumFlingVelocity) { + if ( + abs(diffX) > abs(diffY) && + abs(diffX) > viewConfig.scaledTouchSlop && + abs(velocityX) > viewConfig.scaledMinimumFlingVelocity + ) { if (diffX > 0) { onSwipeRight() } else { diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/ForcedLTRFrameLayout.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/ForcedLTRFrameLayout.kt index 7d5a6da19..2df5c7a8b 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/ui/ForcedLTRFrameLayout.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/ForcedLTRFrameLayout.kt @@ -36,7 +36,7 @@ constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, - defStyleRes: Int = 0 + defStyleRes: Int = 0, ) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) { override fun onFinishInflate() { super.onFinishInflate() diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/CircleClipTapView.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/CircleClipTapView.kt index f307a15e7..df6e0d565 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/CircleClipTapView.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/CircleClipTapView.kt @@ -83,7 +83,8 @@ class CircleClipTapView(context: Context?, attrs: AttributeSet) : View(context, f * (halfWidth + arcSize) + w, heightPx.toFloat() / 2, f * (halfWidth - arcSize) + w, - heightPx.toFloat()) + heightPx.toFloat(), + ) shapePath.lineTo(w, heightPx.toFloat()) shapePath.close() diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/PlayerFastSeekOverlay.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/PlayerFastSeekOverlay.kt index 366a9b704..7f5348a3b 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/PlayerFastSeekOverlay.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/PlayerFastSeekOverlay.kt @@ -38,7 +38,7 @@ enum class DisplayPortion { MIDDLE, RIGHT, LEFT_HALF, - RIGHT_HALF + RIGHT_HALF, } interface DoubleTapListener { @@ -81,7 +81,8 @@ class PlayerFastSeekOverlay(context: Context, attrs: AttributeSet?) : context, com.google.android.material.R.style .ShapeAppearance_Material3_Corner_Medium, - -1) + -1, + ) .build() } } else { @@ -122,7 +123,8 @@ class PlayerFastSeekOverlay(context: Context, attrs: AttributeSet?) : context, object : GestureDetector.SimpleOnGestureListener() { override fun onDown(e: MotionEvent) = true - }) + }, + ) gestureDetector.setOnDoubleTapListener(this) addOnLayoutChangeListener { view, _, _, _, _, _, _, _, _ -> @@ -333,6 +335,7 @@ class PlayerFastSeekOverlay(context: Context, attrs: AttributeSet?) : fun onDoubleTap() fun onDoubleTapEnd() + /** Determines if the playback should forward/rewind or do nothing. */ fun getFastSeekDirection(portion: DisplayPortion): FastSeekDirection @@ -341,7 +344,7 @@ class PlayerFastSeekOverlay(context: Context, attrs: AttributeSet?) : enum class FastSeekDirection(val directionAsBoolean: Boolean?) { NONE(null), FORWARD(true), - BACKWARD(false) + BACKWARD(false), } } diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/SecondsView.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/SecondsView.kt index e81d319df..276937e00 100644 --- a/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/SecondsView.kt +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/stepper/SecondsView.kt @@ -54,7 +54,10 @@ class SecondsView(context: Context, attrs: AttributeSet?) : LinearLayout(context // Done as a field so that we don't have to compute on each tab if animations are enabled private val animationsEnabled = Settings.System.getFloat( - context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1F) != 0F + context.contentResolver, + Settings.Global.ANIMATOR_DURATION_SCALE, + 1F, + ) != 0F val binding = PlayerFastSeekSecondsViewBinding.inflate(LayoutInflater.from(context), this) @@ -108,7 +111,8 @@ class SecondsView(context: Context, attrs: AttributeSet?) : LinearLayout(context binding.icon3.alpha = 0f }, { binding.icon1.alpha = it }, - { secondAnimator.start() }) + { secondAnimator.start() }, + ) private val secondAnimator: ValueAnimator = CustomValueAnimator( @@ -118,7 +122,8 @@ class SecondsView(context: Context, attrs: AttributeSet?) : LinearLayout(context binding.icon3.alpha = 0f }, { binding.icon2.alpha = it }, - { thirdAnimator.start() }) + { thirdAnimator.start() }, + ) private val thirdAnimator: ValueAnimator = CustomValueAnimator( @@ -131,7 +136,8 @@ class SecondsView(context: Context, attrs: AttributeSet?) : LinearLayout(context binding.icon1.alpha = 1f - binding.icon3.alpha binding.icon3.alpha = it }, - { fourthAnimator.start() }) + { fourthAnimator.start() }, + ) private val fourthAnimator: ValueAnimator = CustomValueAnimator( @@ -141,7 +147,8 @@ class SecondsView(context: Context, attrs: AttributeSet?) : LinearLayout(context binding.icon3.alpha = 1f }, { binding.icon2.alpha = 1f - it }, - { fifthAnimator.start() }) + { fifthAnimator.start() }, + ) private val fifthAnimator: ValueAnimator = CustomValueAnimator( @@ -151,12 +158,13 @@ class SecondsView(context: Context, attrs: AttributeSet?) : LinearLayout(context binding.icon3.alpha = 1f }, { binding.icon3.alpha = 1f - it }, - { firstAnimator.start() }) + { firstAnimator.start() }, + ) private inner class CustomValueAnimator( start: () -> Unit, update: (value: Float) -> Unit, - end: () -> Unit + end: () -> Unit, ) : ValueAnimator() { init { diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/PlayerSwipeIndicatorOverlay.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/PlayerSwipeIndicatorOverlay.kt new file mode 100644 index 000000000..d2b162848 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/PlayerSwipeIndicatorOverlay.kt @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2025 Auxio Project + * PlayerSwipeIndicatorOverlay.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 . + */ + +package org.oxycblt.auxio.playback.ui.swipe + +import android.content.Context +import android.util.AttributeSet +import android.view.LayoutInflater +import android.view.View +import androidx.constraintlayout.widget.ConstraintLayout +import com.google.android.material.shape.MaterialShapeDrawable +import com.google.android.material.shape.ShapeAppearanceModel +import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject +import org.oxycblt.auxio.R +import org.oxycblt.auxio.ui.UISettings +import org.oxycblt.auxio.util.isRtl + +@AndroidEntryPoint +class PlayerSwipeIndicatorOverlay(context: Context, attrs: AttributeSet?) : + ConstraintLayout(context, attrs) { + + @Inject lateinit var uiSettings: UISettings + + private var leftSwipeIndicator: SwipeIndicatorView + private var rightSwipeIndicator: SwipeIndicatorView + private var leftSwipeClipView: SwipeClipView + private var rightSwipeClipView: SwipeClipView + private var rootConstraintLayout: ConstraintLayout + + private val shapeAppearance: ShapeAppearanceModel + + /** The width used for calculating full slide translation */ + private var indicatorSlideDistance = 100f + + /** Current swipe direction, null if no swipe in progress */ + private var currentSwipeDirection: SwipeDirection? = null + + init { + LayoutInflater.from(context).inflate(R.layout.player_swipe_indicator_overlay, this, true) + + // Set up shape appearance based on UISettings similar to CoverView + val styledAttrs = + context.obtainStyledAttributes(attrs, R.styleable.PlayerSwipeIndicatorOverlay) + val shapeAppearanceRes = + styledAttrs.getResourceId(R.styleable.PlayerSwipeIndicatorOverlay_shapeAppearance, 0) + + shapeAppearance = + if (uiSettings.roundMode) { + if (shapeAppearanceRes != 0) { + ShapeAppearanceModel.builder(context, shapeAppearanceRes, -1).build() + } else { + ShapeAppearanceModel.builder( + context, + com.google.android.material.R.style + .ShapeAppearance_Material3_Corner_Medium, + -1, + ) + .build() + } + } else { + ShapeAppearanceModel.builder().build() + } + + styledAttrs.recycle() + + leftSwipeIndicator = findViewById(R.id.left_swipe_indicator) + rightSwipeIndicator = findViewById(R.id.right_swipe_indicator) + leftSwipeClipView = findViewById(R.id.left_swipe_clip_view) + rightSwipeClipView = findViewById(R.id.right_swipe_clip_view) + rootConstraintLayout = findViewById(R.id.root_constraint_layout) + + // Apply shape clipping to the overlay + clipToOutline = true + background = + MaterialShapeDrawable().apply { + shapeAppearanceModel = shapeAppearance + fillColor = + android.content.res.ColorStateList.valueOf(android.graphics.Color.TRANSPARENT) + } + + // Hide overlay elements by default + leftSwipeIndicator.alpha = 0f + rightSwipeIndicator.alpha = 0f + leftSwipeClipView.alpha = 0f + rightSwipeClipView.alpha = 0f + leftSwipeIndicator.visibility = INVISIBLE + rightSwipeIndicator.visibility = INVISIBLE + leftSwipeClipView.visibility = INVISIBLE + rightSwipeClipView.visibility = INVISIBLE + + addOnLayoutChangeListener { view, _, _, _, _, _, _, _, _ -> + leftSwipeClipView.updateArcSize(view) + rightSwipeClipView.updateArcSize(view) + // Set slide distance based on indicator width plus some padding + indicatorSlideDistance = view.width * 0.3f + } + + // Initialize directions for each side + // In LTR: left side = previous, right side = next + // In RTL: left side = next, right side = previous + leftSwipeClipView.updatePosition(true) + rightSwipeClipView.updatePosition(false) + updateIndicatorDirections() + } + + private fun updateIndicatorDirections() { + val isRtl = isRtl + // Left indicator: previous in LTR, next in RTL + leftSwipeIndicator.setIsNext(isRtl) + // Right indicator: next in LTR, previous in RTL + rightSwipeIndicator.setIsNext(!isRtl) + } + + /** + * Called when a swipe gesture starts. + * + * @param direction The direction of the swipe (LEFT for swiping left, RIGHT for swiping right) + */ + fun onSwipeStarted(direction: SwipeDirection) { + // Cancel any pending animations on ALL indicators (in case previous swipe + // was in a different direction and its fade-out animation is still running) + cancelAllAnimations() + + currentSwipeDirection = direction + + val indicatorView = getIndicatorForDirection(direction) + val clipView = getClipViewForDirection(direction) + + indicatorView.visibility = VISIBLE + clipView.visibility = VISIBLE + } + + private fun cancelAllAnimations() { + // Cancel animations and reset state for both indicators + leftSwipeIndicator.animate().cancel() + rightSwipeIndicator.animate().cancel() + leftSwipeClipView.animate().cancel() + rightSwipeClipView.animate().cancel() + + // Reset the non-active indicator to hidden state + leftSwipeIndicator.alpha = 0f + leftSwipeIndicator.translationX = 0f + leftSwipeIndicator.visibility = INVISIBLE + leftSwipeClipView.alpha = 0f + leftSwipeClipView.swipeProgress = 0f + leftSwipeClipView.visibility = INVISIBLE + + rightSwipeIndicator.alpha = 0f + rightSwipeIndicator.translationX = 0f + rightSwipeIndicator.visibility = INVISIBLE + rightSwipeClipView.alpha = 0f + rightSwipeClipView.swipeProgress = 0f + rightSwipeClipView.visibility = INVISIBLE + } + + /** + * Called as the user swipes to update the visual progress. + * + * @param progress Normalized progress of the swipe (0 to 1+, where 1 is the commit threshold) + * @param direction The direction of the swipe + */ + fun onSwipeProgress(progress: Float, direction: SwipeDirection) { + val indicatorView = getIndicatorForDirection(direction) + val clipView = getClipViewForDirection(direction) + + // Clamp progress for visual calculations (allow slight overshoot) + val visualProgress = progress.coerceIn(0f, 1.2f) + + // Alpha: fade in from 0 to 1 as progress goes from 0 to 1 + val alpha = (visualProgress).coerceIn(0f, 1f) + indicatorView.alpha = alpha + clipView.alpha = alpha + + // Translation: slide in from the edge + // At progress 0: fully translated off screen + // At progress 1: at final position (translation = 0) + val translationFactor = 1f - visualProgress.coerceIn(0f, 1f) + val translation = + when (direction) { + SwipeDirection.LEFT -> indicatorSlideDistance * translationFactor + SwipeDirection.RIGHT -> -indicatorSlideDistance * translationFactor + } + indicatorView.translationX = translation + + // Update clip view progress + clipView.swipeProgress = visualProgress.coerceIn(0f, 1f) + } + + /** + * Called when the swipe gesture is released. + * + * @param committed True if the swipe passed the commit threshold and the action should execute + * @param direction The direction of the swipe + */ + fun onSwipeReleased(committed: Boolean, direction: SwipeDirection) { + val indicatorView = getIndicatorForDirection(direction) + val clipView = getClipViewForDirection(direction) + + if (committed) { + // Committed: fade out immediately without sliding + indicatorView + .animate() + .alpha(0f) + .setDuration(200) + .withEndAction { indicatorView.visibility = INVISIBLE } + .start() + clipView + .animate() + .alpha(0f) + .setDuration(200) + .withEndAction { + clipView.visibility = INVISIBLE + clipView.swipeProgress = 0f + } + .start() + } else { + // Not committed: slide back out and fade out + val slideOutTranslation = + when (direction) { + SwipeDirection.LEFT -> indicatorSlideDistance + SwipeDirection.RIGHT -> -indicatorSlideDistance + } + indicatorView + .animate() + .alpha(0f) + .translationX(slideOutTranslation) + .setDuration(200) + .withEndAction { + indicatorView.visibility = INVISIBLE + indicatorView.translationX = 0f + } + .start() + // Animate clip view progress back to 0 + val startProgress = clipView.swipeProgress + clipView + .animate() + .alpha(0f) + .setDuration(200) + .setUpdateListener { animator -> + val fraction = animator.animatedFraction + clipView.swipeProgress = startProgress * (1f - fraction) + } + .withEndAction { + clipView.visibility = INVISIBLE + clipView.swipeProgress = 0f + } + .start() + } + + currentSwipeDirection = null + } + + /** Cancels any in-progress swipe indicator without animation. */ + fun cancelSwipe() { + cancelAllAnimations() + currentSwipeDirection = null + } + + private fun getIndicatorForDirection(direction: SwipeDirection): View { + // When swiping left, we show the right indicator (next) + // When swiping right, we show the left indicator (previous) + return when (direction) { + SwipeDirection.LEFT -> rightSwipeIndicator + SwipeDirection.RIGHT -> leftSwipeIndicator + } + } + + private fun getClipViewForDirection(direction: SwipeDirection): SwipeClipView { + return when (direction) { + SwipeDirection.LEFT -> rightSwipeClipView + SwipeDirection.RIGHT -> leftSwipeClipView + } + } + + enum class SwipeDirection { + LEFT, + RIGHT, + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/SwipeClipView.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/SwipeClipView.kt new file mode 100644 index 000000000..6a56716ba --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/SwipeClipView.kt @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2025 Auxio Project + * SwipeClipView.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 . + */ + +package org.oxycblt.auxio.playback.ui.swipe + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Path +import android.util.AttributeSet +import android.view.View + +class SwipeClipView(context: Context?, attrs: AttributeSet) : View(context, attrs) { + + private var backgroundPaint = Paint() + + private var widthPx = 0 + private var heightPx = 0 + + private var shapePath = Path() + private var arcSize: Float = 80f + private var isLeft = true + + /** Progress from 0.0 to 1.0 indicating how much of the swipe area to show */ + var swipeProgress: Float = 0f + set(value) { + field = value.coerceIn(0f, 1f) + updatePathShape() + } + + init { + requireNotNull(context) { "Context is null." } + + backgroundPaint.apply { + style = Paint.Style.FILL + isAntiAlias = true + color = 0x30000000 + } + + val dm = context.resources.displayMetrics + widthPx = dm.widthPixels + heightPx = dm.heightPixels + + updatePathShape() + } + + fun updateArcSize(baseView: View) { + val newArcSize = baseView.height / 11.4f + if (arcSize != newArcSize) { + arcSize = newArcSize + updatePathShape() + } + } + + fun updatePosition(newIsLeft: Boolean) { + if (isLeft != newIsLeft) { + isLeft = newIsLeft + updatePathShape() + } + } + + private fun updatePathShape() { + // The maximum width the swipe area can take (half of the view) + val maxSwipeWidth = widthPx * 0.5f + // The current swipe width based on progress + val currentSwipeWidth = maxSwipeWidth * swipeProgress + + shapePath.reset() + + if (currentSwipeWidth <= 0) { + invalidate() + return + } + + if (isLeft) { + // Draw from left edge + shapePath.moveTo(0f, 0f) + shapePath.lineTo(currentSwipeWidth - arcSize.coerceAtMost(currentSwipeWidth), 0f) + shapePath.quadTo( + currentSwipeWidth + arcSize.coerceAtMost(currentSwipeWidth), + heightPx.toFloat() / 2, + currentSwipeWidth - arcSize.coerceAtMost(currentSwipeWidth), + heightPx.toFloat(), + ) + shapePath.lineTo(0f, heightPx.toFloat()) + } else { + // Draw from right edge + val rightEdge = widthPx.toFloat() + shapePath.moveTo(rightEdge, 0f) + shapePath.lineTo( + rightEdge - currentSwipeWidth + arcSize.coerceAtMost(currentSwipeWidth), + 0f, + ) + shapePath.quadTo( + rightEdge - currentSwipeWidth - arcSize.coerceAtMost(currentSwipeWidth), + heightPx.toFloat() / 2, + rightEdge - currentSwipeWidth + arcSize.coerceAtMost(currentSwipeWidth), + heightPx.toFloat(), + ) + shapePath.lineTo(rightEdge, heightPx.toFloat()) + } + + shapePath.close() + invalidate() + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + widthPx = w + heightPx = h + updatePathShape() + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + + if (swipeProgress > 0) { + canvas.clipPath(shapePath) + canvas.drawPath(shapePath, backgroundPaint) + } + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/SwipeIndicatorView.kt b/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/SwipeIndicatorView.kt new file mode 100644 index 000000000..9a887a8d6 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/playback/ui/swipe/SwipeIndicatorView.kt @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2025 Auxio Project + * SwipeIndicatorView.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 . + */ + +package org.oxycblt.auxio.playback.ui.swipe + +import android.content.Context +import android.util.AttributeSet +import android.view.LayoutInflater +import android.widget.LinearLayout +import org.oxycblt.auxio.R +import org.oxycblt.auxio.databinding.PlayerSwipeIndicatorViewBinding + +class SwipeIndicatorView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) { + + val binding = PlayerSwipeIndicatorViewBinding.inflate(LayoutInflater.from(context), this) + + init { + orientation = HORIZONTAL + layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) + } + + fun setIsNext(isNext: Boolean) { + if (isNext) { + // For "next": Text on left, icon on right + binding.swipeIcon.setImageResource(R.drawable.ic_skip_next_24) + binding.swipeText.setText(R.string.desc_skip_next) + // Reorder views: text first, then icon + removeAllViews() + addView(binding.swipeText) + addView(binding.swipeIcon) + } else { + // For "previous": Icon on left, text on right + binding.swipeIcon.setImageResource(R.drawable.ic_skip_prev_24) + binding.swipeText.setText(R.string.desc_skip_prev) + // Reorder views: icon first, then text + removeAllViews() + addView(binding.swipeIcon) + addView(binding.swipeText) + } + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/search/SearchEngine.kt b/app/src/main/java/org/oxycblt/auxio/search/SearchEngine.kt index c107a5c99..cf0e353b1 100644 --- a/app/src/main/java/org/oxycblt/auxio/search/SearchEngine.kt +++ b/app/src/main/java/org/oxycblt/auxio/search/SearchEngine.kt @@ -61,7 +61,7 @@ interface SearchEngine { val albums: Collection? = null, val artists: Collection? = null, val genres: Collection? = null, - val playlists: Collection? = null + val playlists: Collection? = null, ) } @@ -77,7 +77,8 @@ class SearchEngineImpl @Inject constructor(@ApplicationContext private val conte albums = items.albums?.searchListImpl(query), artists = items.artists?.searchListImpl(query), genres = items.genres?.searchListImpl(query), - playlists = items.playlists?.searchListImpl(query)) + playlists = items.playlists?.searchListImpl(query), + ) } /** @@ -91,7 +92,7 @@ class SearchEngineImpl @Inject constructor(@ApplicationContext private val conte */ private inline fun Collection.searchListImpl( query: String, - fallback: (String, T) -> Boolean = { _, _ -> false } + fallback: (String, T) -> Boolean = { _, _ -> false }, ) = filter { // See if the plain resolved name matches the query. This works for most @@ -119,7 +120,9 @@ class SearchEngineImpl @Inject constructor(@ApplicationContext private val conte // could make it match the query. val normalizedName = NORMALIZE_POST_PROCESSING_REGEX.replace( - Normalizer.normalize(resolvedName, Normalizer.Form.NFKD), "") + Normalizer.normalize(resolvedName, Normalizer.Form.NFKD), + "", + ) if (normalizedName.contains(query, ignoreCase = true)) { return@filter true } diff --git a/app/src/main/java/org/oxycblt/auxio/search/SearchFragment.kt b/app/src/main/java/org/oxycblt/auxio/search/SearchFragment.kt index e6f39872d..0dd36f97d 100644 --- a/app/src/main/java/org/oxycblt/auxio/search/SearchFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/search/SearchFragment.kt @@ -164,7 +164,11 @@ class SearchFragment : ListFragment() { collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collectImmediately( - playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) + playbackModel.song, + playbackModel.parent, + playbackModel.isPlaying, + ::updatePlayback, + ) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) collect(detailModel.toShow.flow, ::handleShow) } @@ -324,7 +328,8 @@ class SearchFragment : ListFragment() { decision.playlist.uid, decision.template, decision.applySongs.map { it.uid }.toTypedArray(), - decision.reason) + decision.reason, + ) } is PlaylistDecision.Delete -> { L.d("Deleting ${decision.playlist}") @@ -337,7 +342,8 @@ class SearchFragment : ListFragment() { is PlaylistDecision.Add -> { L.d("Adding ${decision.songs.size} to a playlist") SearchFragmentDirections.addToPlaylist( - decision.songs.map { it.uid }.toTypedArray()) + decision.songs.map { it.uid }.toTypedArray() + ) } is PlaylistDecision.New -> { error("Unexpected decision $decision") diff --git a/app/src/main/java/org/oxycblt/auxio/search/SearchSettings.kt b/app/src/main/java/org/oxycblt/auxio/search/SearchSettings.kt index 71fd94583..b789feb6e 100644 --- a/app/src/main/java/org/oxycblt/auxio/search/SearchSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/search/SearchSettings.kt @@ -42,11 +42,16 @@ class SearchSettingsImpl @Inject constructor(@ApplicationContext context: Contex get() = MusicType.fromIntCode( sharedPreferences.getInt( - getString(R.string.set_key_search_filter_to), Int.MIN_VALUE)) + getString(R.string.set_key_search_filter_to), + Int.MIN_VALUE, + ) + ) set(value) { sharedPreferences.edit { putInt( - getString(R.string.set_key_search_filter_to), value?.intCode ?: Int.MIN_VALUE) + getString(R.string.set_key_search_filter_to), + value?.intCode ?: Int.MIN_VALUE, + ) apply() } } diff --git a/app/src/main/java/org/oxycblt/auxio/search/SearchViewModel.kt b/app/src/main/java/org/oxycblt/auxio/search/SearchViewModel.kt index ec835c912..060f7c72c 100644 --- a/app/src/main/java/org/oxycblt/auxio/search/SearchViewModel.kt +++ b/app/src/main/java/org/oxycblt/auxio/search/SearchViewModel.kt @@ -121,7 +121,8 @@ constructor( library.albums, library.artists, library.genres, - library.playlists) + library.playlists, + ) } else { L.d("Filter specified, reducing library") SearchEngine.Items( @@ -129,7 +130,8 @@ constructor( albums = if (filter == MusicType.ALBUMS) library.albums else null, artists = if (filter == MusicType.ARTISTS) library.artists else null, genres = if (filter == MusicType.GENRES) library.genres else null, - playlists = if (filter == MusicType.PLAYLISTS) library.playlists else null) + playlists = if (filter == MusicType.PLAYLISTS) library.playlists else null, + ) } val results = searchEngine.search(items, query) diff --git a/app/src/main/java/org/oxycblt/auxio/settings/BasePreferenceFragment.kt b/app/src/main/java/org/oxycblt/auxio/settings/BasePreferenceFragment.kt index b8cd75c7f..708ff595a 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/BasePreferenceFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/BasePreferenceFragment.kt @@ -88,7 +88,7 @@ abstract class BasePreferenceFragment(@XmlRes private val screen: Int) : override fun onCreateRecyclerView( inflater: LayoutInflater, parent: ViewGroup, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ) = super.onCreateRecyclerView(inflater, parent, savedInstanceState).apply { clipToPadding = false diff --git a/app/src/main/java/org/oxycblt/auxio/settings/Settings.kt b/app/src/main/java/org/oxycblt/auxio/settings/Settings.kt index 2128d6db4..a8916f1ba 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/Settings.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/Settings.kt @@ -93,7 +93,7 @@ interface Settings { final override fun onSharedPreferenceChanged( sharedPreferences: SharedPreferences, - key: String? + key: String?, ) { // FIXME: Settings initialization firing the listener. L.d("Dispatching settings change $key") diff --git a/app/src/main/java/org/oxycblt/auxio/settings/ui/IntListPreference.kt b/app/src/main/java/org/oxycblt/auxio/settings/ui/IntListPreference.kt index bffb5f746..8dbd67b40 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/ui/IntListPreference.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/ui/IntListPreference.kt @@ -46,7 +46,7 @@ constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = androidx.preference.R.attr.dialogPreferenceStyle, - defStyleRes: Int = 0 + defStyleRes: Int = 0, ) : DialogPreference(context, attrs, defStyleAttr, defStyleRes) { /** The names of each entry. */ val entries: Array @@ -60,14 +60,19 @@ constructor( init { val prefAttrs = context.obtainStyledAttributes( - attrs, R.styleable.IntListPreference, defStyleAttr, defStyleRes) + attrs, + R.styleable.IntListPreference, + defStyleAttr, + defStyleRes, + ) // Can't depend on ListPreference due to it working with strings we have to instead // define our own attributes for entries/values. entries = prefAttrs.getTextArrayOrThrow(R.styleable.IntListPreference_entries) values = context.resources.getIntArray( - prefAttrs.getResourceIdOrThrow(R.styleable.IntListPreference_entryValues)) + prefAttrs.getResourceIdOrThrow(R.styleable.IntListPreference_entryValues) + ) // entryIcons defines an additional set of icons to use for each entry. val iconsId = prefAttrs.getResourceId(R.styleable.IntListPreference_entryIcons, -1) diff --git a/app/src/main/java/org/oxycblt/auxio/settings/ui/PreferenceHeaderItemDecoration.kt b/app/src/main/java/org/oxycblt/auxio/settings/ui/PreferenceHeaderItemDecoration.kt index c959d0b3e..514a03317 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/ui/PreferenceHeaderItemDecoration.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/ui/PreferenceHeaderItemDecoration.kt @@ -40,7 +40,7 @@ constructor( context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = R.attr.materialDividerStyle, - orientation: Int = LinearLayoutManager.VERTICAL + orientation: Int = LinearLayoutManager.VERTICAL, ) : MaterialDividerItemDecoration(context, attributeSet, defStyleAttr, orientation) { @SuppressLint("RestrictedApi") override fun shouldDrawDivider(position: Int, adapter: RecyclerView.Adapter<*>?) = diff --git a/app/src/main/java/org/oxycblt/auxio/settings/ui/WrappedDialogPreference.kt b/app/src/main/java/org/oxycblt/auxio/settings/ui/WrappedDialogPreference.kt index f73e10245..76e52e966 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/ui/WrappedDialogPreference.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/ui/WrappedDialogPreference.kt @@ -34,5 +34,5 @@ constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = androidx.preference.R.attr.dialogPreferenceStyle, - defStyleRes: Int = 0 + defStyleRes: Int = 0, ) : DialogPreference(context, attrs, defStyleAttr, defStyleRes) diff --git a/app/src/main/java/org/oxycblt/auxio/tasker/Start.kt b/app/src/main/java/org/oxycblt/auxio/tasker/Start.kt index 7372bde56..9fb714520 100644 --- a/app/src/main/java/org/oxycblt/auxio/tasker/Start.kt +++ b/app/src/main/java/org/oxycblt/auxio/tasker/Start.kt @@ -62,7 +62,8 @@ class StartActionRunner : TaskerPluginRunnerActionNoOutputOrInput() { context, Intent(context, AuxioService::class.java) .setAction(AuxioService.ACTION_START) - .putExtra(AuxioService.INTENT_KEY_START_ID, IntegerTable.START_ID_TASKER)) + .putExtra(AuxioService.INTENT_KEY_START_ID, IntegerTable.START_ID_TASKER), + ) while (!AuxioService.isForeground) { Thread.sleep(100) } diff --git a/app/src/main/java/org/oxycblt/auxio/ui/Animations.kt b/app/src/main/java/org/oxycblt/auxio/ui/Animations.kt index 986893cc3..c507df698 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/Animations.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/Animations.kt @@ -37,7 +37,7 @@ class AnimConfig( context: Context, @AttrRes interpolatorRes: Int, @AttrRes durationRes: Int, - defaultDuration: Int + defaultDuration: Int, ) { val interpolator: TimeInterpolator = MotionUtils.resolveThemeInterpolator(context, interpolatorRes, FastOutSlowInInterpolator()) @@ -56,6 +56,7 @@ class AnimConfig( val MEDIUM1 = MR.attr.motionDurationMedium1 to 250 val MEDIUM2 = MR.attr.motionDurationMedium2 to 300 val MEDIUM3 = MR.attr.motionDurationMedium3 to 350 + // val MEDIUM4 = MR.attr.motionDurationMedium4 to 400 // val LONG1 = MR.attr.motionDurationLong1 to 450 // val LONG2 = MR.attr.motionDurationLong2 to 500 @@ -74,7 +75,7 @@ class AnimConfig( from: Float, to: Float, delayMs: Long = 0, - crossinline update: (Float) -> Unit + crossinline update: (Float) -> Unit, ): ValueAnimator = ValueAnimator.ofFloat(from, to).apply { startDelay = delayMs @@ -106,7 +107,7 @@ private constructor( scaleOutDuration: Pair, inInterpolator: Int, alphaInDuration: Pair, - scaleInDuration: Pair + scaleInDuration: Pair, ) { private val alphaOutConfig = AnimConfig.of(context, outInterpolator, alphaOutDuration) private val scaleOutConfig = AnimConfig.of(context, outInterpolator, scaleOutDuration) @@ -172,7 +173,8 @@ private constructor( AnimConfig.SHORT3, AnimConfig.EMPHASIZED_DECELERATE, AnimConfig.SHORT1, - AnimConfig.MEDIUM3) + AnimConfig.MEDIUM3, + ) fun symmetric(context: Context) = MaterialFader( @@ -183,7 +185,8 @@ private constructor( AnimConfig.MEDIUM1, AnimConfig.EMPHASIZED_DECELERATE, AnimConfig.SHORT3, - AnimConfig.MEDIUM1) + AnimConfig.MEDIUM1, + ) } } @@ -206,7 +209,7 @@ private constructor( context: Context, private val x: Int?, inDuration: Pair, - outDuration: Pair + outDuration: Pair, ) { private val outConfig = AnimConfig.of(context, AnimConfig.EMPHASIZED_ACCELERATE, outDuration) private val inConfig = AnimConfig.of(context, AnimConfig.EMPHASIZED_DECELERATE, inDuration) diff --git a/app/src/main/java/org/oxycblt/auxio/ui/BottomSheetContentBehavior.kt b/app/src/main/java/org/oxycblt/auxio/ui/BottomSheetContentBehavior.kt index 96d494a47..aed8ea316 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/BottomSheetContentBehavior.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/BottomSheetContentBehavior.kt @@ -56,7 +56,7 @@ class BottomSheetContentBehavior(context: Context, attributeSet: Attri override fun onDependentViewChanged( parent: CoordinatorLayout, child: V, - dependency: View + dependency: View, ): Boolean { val behavior = dependency.coordinatorLayoutBehavior as BackportBottomSheetBehavior val consumed = behavior.calculateConsumedByBar() @@ -83,7 +83,7 @@ class BottomSheetContentBehavior(context: Context, attributeSet: Attri parentWidthMeasureSpec: Int, widthUsed: Int, parentHeightMeasureSpec: Int, - heightUsed: Int + heightUsed: Int, ): Boolean { measureContent(parent, child) return true @@ -106,7 +106,11 @@ class BottomSheetContentBehavior(context: Context, attributeSet: Attri val bars = insets.systemBarInsetsCompat insets.replaceSystemBarInsetsCompat( - bars.left, bars.top, bars.right, consumed.coerceAtLeast(bars.bottom)) + bars.left, + bars.top, + bars.right, + consumed.coerceAtLeast(bars.bottom), + ) } setup = true diff --git a/app/src/main/java/org/oxycblt/auxio/ui/CoordinatorAppBarLayout.kt b/app/src/main/java/org/oxycblt/auxio/ui/CoordinatorAppBarLayout.kt index 82d5fbbad..d5c1e03b5 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/CoordinatorAppBarLayout.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/CoordinatorAppBarLayout.kt @@ -58,7 +58,14 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr if (child != null) { val coordinator = parent as CoordinatorLayout coordinatorLayoutBehavior?.onNestedPreScroll( - coordinator, this, coordinator, 0, 0, tConsumed, 0) + coordinator, + this, + coordinator, + 0, + 0, + tConsumed, + 0, + ) } true @@ -124,8 +131,10 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr private var currentVerticalOffset: Int? = null override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) { - if (verticalOffset == 0 || - AnimationUtils.currentAnimationTimeMillis() > offsetAnimationMaxEndTime) { + if ( + verticalOffset == 0 || + AnimationUtils.currentAnimationTimeMillis() > offsetAnimationMaxEndTime + ) { // AppBarLayout crashes with IndexOutOfBoundsException when a non-last listener // removes itself, so we have to do the removal asynchronously. appBarLayout.postOnAnimation { appBarLayout.removeOnOffsetChangedListener(this) } diff --git a/app/src/main/java/org/oxycblt/auxio/ui/DialogAwareNavigationListener.kt b/app/src/main/java/org/oxycblt/auxio/ui/DialogAwareNavigationListener.kt index 58fe95c14..76163f559 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/DialogAwareNavigationListener.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/DialogAwareNavigationListener.kt @@ -61,7 +61,7 @@ class DialogAwareNavigationListener(private val callback: () -> Unit) : override fun onDestinationChanged( controller: NavController, destination: NavDestination, - arguments: Bundle? + arguments: Bundle?, ) { // Drop the initial call by NavController that simply provides us with the current // destination. This would cause the selection state to be lost every time the device diff --git a/app/src/main/java/org/oxycblt/auxio/ui/RippleFixMaterialButton.kt b/app/src/main/java/org/oxycblt/auxio/ui/RippleFixMaterialButton.kt index 2586745ae..32a0ad49f 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/RippleFixMaterialButton.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/RippleFixMaterialButton.kt @@ -36,7 +36,7 @@ open class RippleFixMaterialButton constructor( context: Context, attrs: AttributeSet? = null, - @AttrRes defStyleAttr: Int = R.attr.materialButtonStyle + @AttrRes defStyleAttr: Int = R.attr.materialButtonStyle, ) : MaterialButton(context, attrs, defStyleAttr) { init { fixDoubleRipple() diff --git a/app/src/main/java/org/oxycblt/auxio/ui/UISettings.kt b/app/src/main/java/org/oxycblt/auxio/ui/UISettings.kt index 7a490347b..9d5d4c40f 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/UISettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/UISettings.kt @@ -55,7 +55,9 @@ class UISettingsImpl @Inject constructor(@ApplicationContext context: Context) : override val theme: Int get() = sharedPreferences.getInt( - getString(R.string.set_key_theme), AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) + getString(R.string.set_key_theme), + AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM, + ) override val useBlackTheme: Boolean get() = sharedPreferences.getBoolean(getString(R.string.set_key_black_theme), false) @@ -63,7 +65,8 @@ class UISettingsImpl @Inject constructor(@ApplicationContext context: Context) : override var accent: Accent get() = Accent.from( - sharedPreferences.getInt(getString(R.string.set_key_accent), Accent.DEFAULT)) + sharedPreferences.getInt(getString(R.string.set_key_accent), Accent.DEFAULT) + ) set(value) { sharedPreferences.edit { putInt(getString(R.string.set_key_accent), value.index) diff --git a/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingBottomSheetDialogFragment.kt b/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingBottomSheetDialogFragment.kt index 53e3af574..453e866dc 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingBottomSheetDialogFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingBottomSheetDialogFragment.kt @@ -94,7 +94,7 @@ abstract class ViewBindingBottomSheetDialogFragment : final override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ) = onCreateBinding(inflater).also { _binding = it }.root final override fun onViewCreated(view: View, savedInstanceState: Bundle?) { @@ -129,7 +129,8 @@ abstract class ViewBindingBottomSheetDialogFragment : avoidUnusableCollapsedState = metrics.heightPixels - metrics.widthPixels < context.getDimenPixels( - com.google.android.material.R.dimen.design_bottom_sheet_peek_height_min) + com.google.android.material.R.dimen.design_bottom_sheet_peek_height_min + ) behavior.skipCollapsed = avoidUnusableCollapsedState } diff --git a/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingFragment.kt b/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingFragment.kt index 38967d653..3118f69af 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingFragment.kt @@ -80,7 +80,7 @@ abstract class ViewBindingFragment : Fragment() { final override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ) = onCreateBinding(inflater).also { _binding = it }.root final override fun onViewCreated(view: View, savedInstanceState: Bundle?) { diff --git a/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingMaterialDialogFragment.kt b/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingMaterialDialogFragment.kt index 20bb9679a..2802bc858 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingMaterialDialogFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/ViewBindingMaterialDialogFragment.kt @@ -93,7 +93,7 @@ abstract class ViewBindingMaterialDialogFragment : DialogFragm final override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ) = onCreateBinding(inflater).also { _binding = it }.root final override fun onCreateDialog(savedInstanceState: Bundle?) = diff --git a/app/src/main/java/org/oxycblt/auxio/ui/accent/Accent.kt b/app/src/main/java/org/oxycblt/auxio/ui/accent/Accent.kt index 217206d98..2ca399a2a 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/accent/Accent.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/accent/Accent.kt @@ -40,7 +40,8 @@ private val accentNames = R.string.clr_orange, R.string.clr_brown, R.string.clr_grey, - R.string.clr_dynamic) + R.string.clr_dynamic, + ) private val accentThemes = intArrayOf( @@ -60,8 +61,8 @@ private val accentThemes = R.style.Theme_Auxio_Orange, R.style.Theme_Auxio_Brown, R.style.Theme_Auxio_Grey, - R.style.Theme_Auxio_App // Dynamic colors are on the base theme - ) + R.style.Theme_Auxio_App, // Dynamic colors are on the base theme + ) private val accentBlackThemes = intArrayOf( @@ -81,8 +82,8 @@ private val accentBlackThemes = R.style.Theme_Auxio_Orange_Black, R.style.Theme_Auxio_Brown_Black, R.style.Theme_Auxio_Grey_Black, - R.style.Theme_Auxio_Black // Dynamic colors are on the base theme - ) + R.style.Theme_Auxio_Black, // Dynamic colors are on the base theme + ) private val accentPrimaryColors = intArrayOf( @@ -102,7 +103,8 @@ private val accentPrimaryColors = R.color.orange_primary, R.color.brown_primary, R.color.grey_primary, - R.color.dynamic_primary) + R.color.dynamic_primary, + ) /** * The data object for a colored theme to use in the UI. This can be nominally used to gleam some @@ -116,14 +118,17 @@ class Accent private constructor(val index: Int) { /** The name of this [Accent]. */ val name: Int get() = accentNames[index] + /** The theme resource for this accent. */ val theme: Int get() = accentThemes[index] + /** * The black theme resource for this accent. Identical to [theme], but with a black background. */ val blackTheme: Int get() = accentBlackThemes[index] + /** The accent's primary color. */ val primary: Int get() = accentPrimaryColors[index] diff --git a/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentAdapter.kt b/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentAdapter.kt index 41138d718..14cc1fef6 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentAdapter.kt @@ -53,7 +53,7 @@ class AccentAdapter(private val listener: ClickableListListener) : override fun onBindViewHolder( holder: AccentViewHolder, position: Int, - payloads: MutableList + payloads: MutableList, ) { val item = Accent.from(position) if (payloads.isEmpty()) { diff --git a/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentCustomizeDialog.kt b/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentCustomizeDialog.kt index d0093a88f..8a3125a41 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentCustomizeDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentCustomizeDialog.kt @@ -71,7 +71,8 @@ class AccentCustomizeDialog : Accent.from(savedInstanceState.getInt(KEY_PENDING_ACCENT)) } else { uiSettings.accent - }) + } + ) } override fun onSaveInstanceState(outState: Bundle) { diff --git a/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentGridLayoutManager.kt b/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentGridLayoutManager.kt index aae66a179..c8a39643e 100644 --- a/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentGridLayoutManager.kt +++ b/app/src/main/java/org/oxycblt/auxio/ui/accent/AccentGridLayoutManager.kt @@ -35,7 +35,7 @@ class AccentGridLayoutManager( context: Context, attrs: AttributeSet, defStyleAttr: Int, - defStyleRes: Int + defStyleRes: Int, ) : GridLayoutManager(context, attrs, defStyleAttr, defStyleRes) { // We use 56dp here since that's the rough size of the accent item. // This will need to be modified if this is used beyond the accent dialog. diff --git a/app/src/main/java/org/oxycblt/auxio/util/ContextUtil.kt b/app/src/main/java/org/oxycblt/auxio/util/ContextUtil.kt index d2321ab5c..ed03ccb94 100644 --- a/app/src/main/java/org/oxycblt/auxio/util/ContextUtil.kt +++ b/app/src/main/java/org/oxycblt/auxio/util/ContextUtil.kt @@ -183,7 +183,8 @@ fun Context.newMainPendingIntent(): PendingIntent = this, IntegerTable.REQUEST_CODE, Intent(this, MainActivity::class.java).setAction(Intent.ACTION_MAIN), - PendingIntent.FLAG_IMMUTABLE) + PendingIntent.FLAG_IMMUTABLE, + ) /** * Create a [PendingIntent] that will broadcast the specified command when launched. @@ -195,4 +196,5 @@ fun Context.newBroadcastPendingIntent(action: String): PendingIntent = this, IntegerTable.REQUEST_CODE, Intent(action).setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY), - PendingIntent.FLAG_IMMUTABLE) + PendingIntent.FLAG_IMMUTABLE, + ) diff --git a/app/src/main/java/org/oxycblt/auxio/util/CopyleftNoticeTree.kt b/app/src/main/java/org/oxycblt/auxio/util/CopyleftNoticeTree.kt index 09cfd8415..88a50ae89 100644 --- a/app/src/main/java/org/oxycblt/auxio/util/CopyleftNoticeTree.kt +++ b/app/src/main/java/org/oxycblt/auxio/util/CopyleftNoticeTree.kt @@ -37,6 +37,7 @@ class CopyleftNoticeTree : Timber.DebugTree() { tag, "Hey! Auxio is an open-source project licensed under the GPLv3 license!" + "You can fork this project and even add ads, but it still needs to be kept open-source with the same license!", - t) + t, + ) } } diff --git a/app/src/main/java/org/oxycblt/auxio/util/FrameworkUtil.kt b/app/src/main/java/org/oxycblt/auxio/util/FrameworkUtil.kt index 2322a196e..d3bae0826 100644 --- a/app/src/main/java/org/oxycblt/auxio/util/FrameworkUtil.kt +++ b/app/src/main/java/org/oxycblt/auxio/util/FrameworkUtil.kt @@ -76,7 +76,7 @@ private fun isUnderImpl( viewStart: Int, viewEnd: Int, parentEnd: Int, - minTouchTargetSize: Int + minTouchTargetSize: Int, ): Boolean { val viewSize = viewEnd - viewStart if (viewSize >= minTouchTargetSize) { @@ -212,7 +212,8 @@ val WindowInsets.systemGestureInsetsCompat: Insets // API 30+, use window inset map. Insets.max( getCompatInsets(WindowInsets.Type.systemGestures()), - getCompatInsets(WindowInsets.Type.systemBars())) + getCompatInsets(WindowInsets.Type.systemBars()), + ) } Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> { // API 29, use window inset fields. @@ -245,7 +246,8 @@ private fun WindowInsets.getSystemWindowCompatInsets() = systemWindowInsetLeft, systemWindowInsetTop, systemWindowInsetRight, - systemWindowInsetBottom) + systemWindowInsetBottom, + ) /** * Returns "System Bar" [Insets] based on the API 29 [WindowInsets] convention. @@ -270,7 +272,7 @@ fun WindowInsets.replaceSystemBarInsetsCompat( left: Int, top: Int, right: Int, - bottom: Int + bottom: Int, ): WindowInsets { return when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { @@ -278,7 +280,8 @@ fun WindowInsets.replaceSystemBarInsetsCompat( WindowInsets.Builder(this) .setInsets( WindowInsets.Type.systemBars(), - Insets.of(left, top, right, bottom).toPlatformInsets()) + Insets.of(left, top, right, bottom).toPlatformInsets(), + ) .build() } else -> { diff --git a/app/src/main/java/org/oxycblt/auxio/util/StateUtil.kt b/app/src/main/java/org/oxycblt/auxio/util/StateUtil.kt index eb74d8f15..10f1d216d 100644 --- a/app/src/main/java/org/oxycblt/auxio/util/StateUtil.kt +++ b/app/src/main/java/org/oxycblt/auxio/util/StateUtil.kt @@ -36,6 +36,7 @@ import kotlinx.coroutines.launch interface Event { /** The inner [StateFlow] contained by the [Event]. */ val flow: StateFlow + /** * Consume whatever value is currently contained by this instance. * @@ -101,7 +102,7 @@ fun Fragment.collectImmediately(stateFlow: StateFlow, block: (T) -> Unit) fun Fragment.collectImmediately( a: StateFlow, b: StateFlow, - block: (T1, T2) -> Unit + block: (T1, T2) -> Unit, ) { block(a.value, b.value) // We can combine flows, but only if we transform them into one flow output. @@ -124,7 +125,7 @@ fun Fragment.collectImmediately( a: StateFlow, b: StateFlow, c: StateFlow, - block: (T1, T2, T3) -> Unit + block: (T1, T2, T3) -> Unit, ) { block(a.value, b.value, c.value) val combine = combine(a, b, c) { a1, b2, c3 -> Triple(a1, b2, c3) } @@ -142,7 +143,7 @@ fun Fragment.collectImmediately( */ private fun Fragment.launch( state: Lifecycle.State = Lifecycle.State.STARTED, - block: suspend CoroutineScope.() -> Unit + block: suspend CoroutineScope.() -> Unit, ) { viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(state, block) } } diff --git a/app/src/main/java/org/oxycblt/auxio/widgets/WidgetComponent.kt b/app/src/main/java/org/oxycblt/auxio/widgets/WidgetComponent.kt index 5977dff5c..013f3b01a 100644 --- a/app/src/main/java/org/oxycblt/auxio/widgets/WidgetComponent.kt +++ b/app/src/main/java/org/oxycblt/auxio/widgets/WidgetComponent.kt @@ -52,7 +52,7 @@ private constructor( private val imageSettings: ImageSettings, private val bitmapProvider: BitmapProvider, private val playbackManager: PlaybackStateManager, - private val uiSettings: UISettings + private val uiSettings: UISettings, ) : PlaybackStateManager.Listener, UISettings.Listener, ImageSettings.Listener { class Factory @Inject @@ -60,7 +60,7 @@ private constructor( private val imageSettings: ImageSettings, private val bitmapProvider: BitmapProvider, private val playbackManager: PlaybackStateManager, - private val uiSettings: UISettings + private val uiSettings: UISettings, ) { fun create(context: Context) = WidgetComponent(context, imageSettings, bitmapProvider, playbackManager, uiSettings) @@ -128,7 +128,8 @@ private constructor( L.d("Bitmap loaded, uploading state $state") widgetProvider.update(context, uiSettings, state) } - }) + }, + ) } /** Release this instance, preventing any further events from updating the widget instances. */ @@ -157,7 +158,7 @@ private constructor( parent: MusicParent?, queue: List, index: Int, - isShuffled: Boolean + isShuffled: Boolean, ) = update() override fun onProgressionChanged(progression: Progression) = update() @@ -184,6 +185,6 @@ private constructor( val cover: Bitmap?, val isPlaying: Boolean, val repeatMode: RepeatMode, - val isShuffled: Boolean + val isShuffled: Boolean, ) } diff --git a/app/src/main/java/org/oxycblt/auxio/widgets/WidgetProvider.kt b/app/src/main/java/org/oxycblt/auxio/widgets/WidgetProvider.kt index 54976c042..14d398116 100644 --- a/app/src/main/java/org/oxycblt/auxio/widgets/WidgetProvider.kt +++ b/app/src/main/java/org/oxycblt/auxio/widgets/WidgetProvider.kt @@ -49,7 +49,7 @@ class WidgetProvider : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, - appWidgetIds: IntArray + appWidgetIds: IntArray, ) { requestUpdate(context) // Revert to the default layout for now until we get a response from WidgetComponent. @@ -61,7 +61,7 @@ class WidgetProvider : AppWidgetProvider() { context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, - newOptions: Bundle? + newOptions: Bundle?, ) { super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions) // Another adaptive layout backport for API 21+: We are unable to immediately update @@ -102,7 +102,8 @@ class WidgetProvider : AppWidgetProvider() { SizeF(180f, 152f) to defaultLayout, SizeF(304f, 152f) to newWideDockedLayout(context, uiSettings, state), SizeF(180f, 272f) to newThinPaneLayout(context, uiSettings, state), - SizeF(304f, 272f) to newWidePaneLayout(context, uiSettings, state)) + SizeF(304f, 272f) to newWidePaneLayout(context, uiSettings, state), + ) // This is the order in which we will disable cover art layouts if they exceed the // maximum bitmap memory usage. (See the comment in the loop below for more info.) @@ -125,8 +126,11 @@ class WidgetProvider : AppWidgetProvider() { return } catch (e: IllegalArgumentException) { val msg = e.message ?: return - if (!msg.startsWith( - "RemoteViews for widget update exceeds maximum bitmap memory usage")) { + if ( + !msg.startsWith( + "RemoteViews for widget update exceeds maximum bitmap memory usage" + ) + ) { throw e } // Some android devices on Android 12-14 suffer from a bug where the maximum bitmap @@ -191,12 +195,10 @@ class WidgetProvider : AppWidgetProvider() { private fun newThinWaferLayout( context: Context, uiSettings: UISettings, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ) = newRemoteViews(context, R.layout.widget_wafer_thin) - .setupBackground( - uiSettings, - ) + .setupBackground(uiSettings) .setupCover(context, state.takeIf { canDisplayWaferCover(uiSettings) }) .setupFillingCover(uiSettings) .setupTimelineControls(context, state) @@ -204,12 +206,10 @@ class WidgetProvider : AppWidgetProvider() { private fun newWideWaferLayout( context: Context, uiSettings: UISettings, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ) = newRemoteViews(context, R.layout.widget_wafer_wide) - .setupBackground( - uiSettings, - ) + .setupBackground(uiSettings) .setupCover(context, state.takeIf { canDisplayWaferCover(uiSettings) }) .setupFillingCover(uiSettings) .setupFullControls(context, state) @@ -217,48 +217,40 @@ class WidgetProvider : AppWidgetProvider() { private fun newThinDockedLayout( context: Context, uiSettings: UISettings, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ) = newRemoteViews(context, R.layout.widget_docked_thin) - .setupBar( - uiSettings, - ) + .setupBar(uiSettings) .setupCover(context, state) .setupTimelineControls(context, state) private fun newWideDockedLayout( context: Context, uiSettings: UISettings, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ) = newRemoteViews(context, R.layout.widget_docked_wide) - .setupBar( - uiSettings, - ) + .setupBar(uiSettings) .setupCover(context, state) .setupFullControls(context, state) private fun newThinPaneLayout( context: Context, uiSettings: UISettings, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ) = newRemoteViews(context, R.layout.widget_pane_thin) - .setupBackground( - uiSettings, - ) + .setupBackground(uiSettings) .setupPlaybackState(context, state) .setupTimelineControls(context, state) private fun newWidePaneLayout( context: Context, uiSettings: UISettings, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ) = newRemoteViews(context, R.layout.widget_pane_wide) - .setupBackground( - uiSettings, - ) + .setupBackground(uiSettings) .setupPlaybackState(context, state) .setupFullControls(context, state) @@ -266,9 +258,7 @@ class WidgetProvider : AppWidgetProvider() { * Set up the control bar in a [RemoteViews] layout that contains one. This is a kind of * "floating" drawable that sits in front of the cover and contains the controls. */ - private fun RemoteViews.setupBar( - uiSettings: UISettings, - ): RemoteViews { + private fun RemoteViews.setupBar(uiSettings: UISettings): RemoteViews { // Below API 31, enable a rounded bar only if round mode is enabled. // On API 31+, the bar should always be round in order to fit in with other widgets. val background = @@ -285,9 +275,7 @@ class WidgetProvider : AppWidgetProvider() { * Set up the background in a [RemoteViews] layout that contains one. This is largely * self-explanatory, being a solid-color background that sits behind the cover and controls. */ - private fun RemoteViews.setupBackground( - uiSettings: UISettings, - ): RemoteViews { + private fun RemoteViews.setupBackground(uiSettings: UISettings): RemoteViews { // Below API 31, enable a rounded background only if round mode is enabled. // On API 31+, the background should always be round in order to fit in with other // widgets. @@ -309,7 +297,7 @@ class WidgetProvider : AppWidgetProvider() { */ private fun RemoteViews.setupCover( context: Context, - state: WidgetComponent.PlaybackState? + state: WidgetComponent.PlaybackState?, ): RemoteViews { if (state == null) { setImageViewBitmap(R.id.widget_cover, null) @@ -321,8 +309,8 @@ class WidgetProvider : AppWidgetProvider() { setImageViewBitmap(R.id.widget_cover, state.cover) setContentDescription( R.id.widget_cover, - context.getString( - R.string.desc_album_cover, state.song.album.name.resolve(context))) + context.getString(R.string.desc_album_cover, state.song.album.name.resolve(context)), + ) } else { discardCover(context) } @@ -358,7 +346,7 @@ class WidgetProvider : AppWidgetProvider() { */ private fun RemoteViews.setupPlaybackState( context: Context, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ): RemoteViews { setupCover(context, state) setTextViewText(R.id.widget_song, state.song.name.resolve(context)) @@ -374,13 +362,14 @@ class WidgetProvider : AppWidgetProvider() { */ private fun RemoteViews.setupBasicControls( context: Context, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ): RemoteViews { // Hook the play/pause button to the play/pause broadcast that will be recognized // by PlaybackService. setOnClickPendingIntent( R.id.widget_play_pause, - context.newBroadcastPendingIntent(PlaybackActions.ACTION_PLAY_PAUSE)) + context.newBroadcastPendingIntent(PlaybackActions.ACTION_PLAY_PAUSE), + ) // Set up the play/pause button appearance. Like the Android 13 media controls, use // a circular FAB when paused, and a squircle FAB when playing. This does require us @@ -411,7 +400,7 @@ class WidgetProvider : AppWidgetProvider() { */ private fun RemoteViews.setupTimelineControls( context: Context, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ): RemoteViews { // Timeline controls contain the basic controls, set those up setupBasicControls(context, state) @@ -421,10 +410,12 @@ class WidgetProvider : AppWidgetProvider() { // by PlaybackService. setOnClickPendingIntent( R.id.widget_skip_prev, - context.newBroadcastPendingIntent(PlaybackActions.ACTION_SKIP_PREV)) + context.newBroadcastPendingIntent(PlaybackActions.ACTION_SKIP_PREV), + ) setOnClickPendingIntent( R.id.widget_skip_next, - context.newBroadcastPendingIntent(PlaybackActions.ACTION_SKIP_NEXT)) + context.newBroadcastPendingIntent(PlaybackActions.ACTION_SKIP_NEXT), + ) return this } @@ -437,7 +428,7 @@ class WidgetProvider : AppWidgetProvider() { */ private fun RemoteViews.setupFullControls( context: Context, - state: WidgetComponent.PlaybackState + state: WidgetComponent.PlaybackState, ): RemoteViews { // Full controls contain timeline controls, make are set those. setupTimelineControls(context, state) @@ -446,10 +437,12 @@ class WidgetProvider : AppWidgetProvider() { // be recognized by PlaybackService. setOnClickPendingIntent( R.id.widget_repeat, - context.newBroadcastPendingIntent(PlaybackActions.ACTION_INC_REPEAT_MODE)) + context.newBroadcastPendingIntent(PlaybackActions.ACTION_INC_REPEAT_MODE), + ) setOnClickPendingIntent( R.id.widget_shuffle, - context.newBroadcastPendingIntent(PlaybackActions.ACTION_INVERT_SHUFFLE)) + context.newBroadcastPendingIntent(PlaybackActions.ACTION_INVERT_SHUFFLE), + ) // Set up the repeat/shuffle buttons. When working with RemoteViews, we will // need to hard-code different accent tinting configurations, as stateful drawables diff --git a/app/src/main/java/org/oxycblt/auxio/widgets/WidgetUtil.kt b/app/src/main/java/org/oxycblt/auxio/widgets/WidgetUtil.kt index a5e32881b..ace8e4dd5 100644 --- a/app/src/main/java/org/oxycblt/auxio/widgets/WidgetUtil.kt +++ b/app/src/main/java/org/oxycblt/auxio/widgets/WidgetUtil.kt @@ -77,7 +77,7 @@ fun RemoteViews.setLayoutDirection(@IdRes viewId: Int, layoutDirection: Int) { fun AppWidgetManager.updateAppWidgetCompat( context: Context, component: ComponentName, - views: Map + views: Map, ) { check(views.isNotEmpty()) { "Must provide a non-empty map" } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { diff --git a/app/src/main/res/layout/player_swipe_indicator_overlay.xml b/app/src/main/res/layout/player_swipe_indicator_overlay.xml new file mode 100644 index 000000000..32892ac9a --- /dev/null +++ b/app/src/main/res/layout/player_swipe_indicator_overlay.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/player_swipe_indicator_view.xml b/app/src/main/res/layout/player_swipe_indicator_view.xml new file mode 100644 index 000000000..47e01cb53 --- /dev/null +++ b/app/src/main/res/layout/player_swipe_indicator_view.xml @@ -0,0 +1,44 @@ + + + + + + + + + diff --git a/build.gradle b/build.gradle index cb1651cea..8ebeb56bb 100644 --- a/build.gradle +++ b/build.gradle @@ -38,7 +38,7 @@ plugins { spotless { kotlin { target "*/src/**/*.kt" - ktfmt().dropboxStyle() + ktfmt().kotlinlangStyle() licenseHeaderFile("NOTICE") } diff --git a/musikr/src/main/cpp/taglib b/musikr/src/main/cpp/taglib index e831f0929..9c042984d 160000 --- a/musikr/src/main/cpp/taglib +++ b/musikr/src/main/cpp/taglib @@ -1 +1 @@ -Subproject commit e831f0929f25bc581d2106d1f2810f5d8100376e +Subproject commit 9c042984d26af605a6fd1dac7f12bda05219fee7 diff --git a/musikr/src/main/java/org/oxycblt/musikr/Music.kt b/musikr/src/main/java/org/oxycblt/musikr/Music.kt index 507103898..594df1dfd 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Music.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Music.kt @@ -78,7 +78,7 @@ sealed interface Music { private constructor( private val format: Format, private val item: Item, - private val uuid: UUID + private val uuid: UUID, ) : Parcelable { // Cache the hashCode for HashMap efficiency. @IgnoredOnParcel private var hashCode = format.hashCode() @@ -103,7 +103,7 @@ sealed interface Music { ALBUM(0xA10A), ARTIST(0xA109), GENRE(0xA108), - PLAYLIST(0xA107) + PLAYLIST(0xA107), } /** @@ -116,7 +116,7 @@ sealed interface Music { AUXIO("org.oxycblt.auxio"), /** @see musicBrainz */ - MUSICBRAINZ("org.musicbrainz") + MUSICBRAINZ("org.musicbrainz"), } object TypeConverters { @@ -177,7 +177,8 @@ sealed interface Music { .or(digest[12].toLong().and(0xFF).shl(24)) .or(digest[13].toLong().and(0xFF).shl(16)) .or(digest[14].toLong().and(0xFF).shl(8)) - .or(digest[15].toLong().and(0xFF))) + .or(digest[15].toLong().and(0xFF)), + ) return UID(Format.AUXIO, item, uuid) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 80f0be1bd..bd1c7c39b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -70,7 +70,8 @@ interface Musikr { config, ExploreStep.from(context, config), ExtractStep.from(context, config), - EvaluateStep.new(context, config, config.interpretation)) + EvaluateStep.new(context, config, config.interpretation), + ) } } @@ -110,7 +111,7 @@ private class MusikrImpl( private val config: Config, private val exploreStep: ExploreStep, private val extractStep: ExtractStep, - private val evaluateStep: EvaluateStep + private val evaluateStep: EvaluateStep, ) : Musikr { override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope { onProgress(IndexingProgress.Songs(0, 0)) diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/Cache.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/Cache.kt index 74174e32c..0d4811617 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/Cache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/Cache.kt @@ -92,7 +92,7 @@ data class CachedSong( * The time the song was added to the cache. Used for date added values. Should not be used for * cleanup since it is unlikely to be monotonic. */ - val addedMs: Long + val addedMs: Long, ) /** A result of a cache lookup. */ diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt index 7dc285e8b..e71ce4ec9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt @@ -45,7 +45,10 @@ internal abstract class CacheDatabase : RoomDatabase() { companion object { fun from(context: Context) = Room.databaseBuilder( - context.applicationContext, CacheDatabase::class.java, "music_cache.db") + context.applicationContext, + CacheDatabase::class.java, + "music_cache.db", + ) .fallbackToDestructiveMigration() .build() } diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt index c1242f645..65b49e6b5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt @@ -52,7 +52,11 @@ class DBCache private constructor(private val readDao: CacheReadDao) : Cache { CachedSong( file, Properties( - dbSong.mimeType, dbSong.durationMs, dbSong.bitrateKbps, dbSong.sampleRateHz), + dbSong.mimeType, + dbSong.durationMs, + dbSong.bitrateKbps, + dbSong.sampleRateHz, + ), ParsedTags( musicBrainzId = dbSong.musicBrainzId, name = dbSong.name, @@ -74,9 +78,11 @@ class DBCache private constructor(private val readDao: CacheReadDao) : Cache { albumArtistSortNames = dbSong.albumArtistSortNames, genreNames = dbSong.genreNames, replayGainTrackAdjustment = dbSong.replayGainTrackAdjustment, - replayGainAlbumAdjustment = dbSong.replayGainAlbumAdjustment), + replayGainAlbumAdjustment = dbSong.replayGainAlbumAdjustment, + ), coverId = dbSong.coverId, - addedMs = dbSong.addedMs) + addedMs = dbSong.addedMs, + ) return CacheResult.Hit(song) } @@ -136,7 +142,8 @@ private constructor(private val inner: DBCache, private val writeDao: CacheWrite genreNames = cachedSong.tags.genreNames, replayGainTrackAdjustment = cachedSong.tags.replayGainTrackAdjustment, replayGainAlbumAdjustment = cachedSong.tags.replayGainAlbumAdjustment, - coverId = cachedSong.coverId) + coverId = cachedSong.coverId, + ) writeDao.updateSong(dbSong) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/Covers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/Covers.kt index c148fb3a1..3514241a5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/Covers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/Covers.kt @@ -171,6 +171,7 @@ class CoverCollection private constructor(val covers: List) { .entries .sortedByDescending { it.key } .sortedByDescending { it.value.size } - .map { it.value.first() }) + .map { it.value.first() } + ) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt index 9d3594632..a095f5d02 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt @@ -139,22 +139,13 @@ class MutableFSCovers(private val context: Context) : MutableCovers { private companion object { private val preferredCoverNames = listOf("front", "art", "album", "folder", "cover") - private val preferredFormats = - listOf( - "image/webp", - "image/jpg", - "image/jpeg", - "image/png", - ) + private val preferredFormats = listOf("image/webp", "image/jpg", "image/jpeg", "image/png") private val preferredExtensions = listOf("webp", "jpg", "jpeg", "png") } } -private data class FolderCoverImpl( - private val context: Context, - private val uri: Uri, -) : FDCover { +private data class FolderCoverImpl(private val context: Context, private val uri: Uri) : FDCover { override val id = PREFIX + uri.toString() // Implies that client will manage freeing the resources themselves. diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt index f913cd35c..c23bb8cb4 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt @@ -69,7 +69,7 @@ class StoredCovers(private val coverStorage: CoverStorage) : Covers { class MutableStoredCovers( private val src: MutableCovers, private val coverStorage: CoverStorage, - private val transcoding: Transcoding + private val transcoding: Transcoding, ) : MutableCovers { private val base = StoredCovers(coverStorage) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt index 46577fe0e..20c8bfde1 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt @@ -38,7 +38,7 @@ data class Directory( override val uri: Uri?, override val path: Path, val parent: Deferred?, - var children: List + var children: List, ) : FSEntry data class File( @@ -48,7 +48,7 @@ data class File( val modifiedMs: Long, val mimeType: String, val size: Long, - val parent: Deferred? + val parent: Deferred?, ) : FSEntry sealed interface FSUpdate { diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index 0aae7d337..083290436 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -39,7 +39,8 @@ sealed class Location(val uri: Uri, val path: Path) { context.contentResolverSafe.takePersistableUriPermission( uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or - Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + Intent.FLAG_GRANT_WRITE_URI_PERMISSION, + ) } catch (e: Exception) { // Not fully sure what happens if I'm disallowed to take the permission, // check for both circumstances (error or no-op) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Path.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Path.kt index 99630df25..c5cba4ca5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Path.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Path.kt @@ -27,10 +27,7 @@ import java.io.File * @param volume The volume that the path is on. * @param components The components of the path of the file, relative to the root of the volume. */ -data class Path( - val volume: Volume, - val components: Components, -) { +data class Path(val volume: Volume, val components: Components) { /** The name of the file/directory. */ val name: String? get() = components.name diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt index 22d8b8168..79bcc286d 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt @@ -50,7 +50,7 @@ class MediaStore private constructor( private val context: Context, private val volumeManager: VolumeManager, - private val query: Query + private val query: Query, ) : FS { private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager) @@ -93,49 +93,49 @@ private constructor( AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selector, - args.toTypedArray()) { cursor -> - val pathInterpreter = pathInterpreterFactory.wrap(cursor) - val idIndex = - cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns._ID) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.MIME_TYPE) - val sizeIndex = - cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.SIZE) - val dateAddedIndex = - cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_ADDED) - val dateModifiedIndex = - cursor.getColumnIndexOrThrow( - AOSPMediaStore.Audio.AudioColumns.DATE_MODIFIED) + args.toTypedArray(), + ) { cursor -> + val pathInterpreter = pathInterpreterFactory.wrap(cursor) + val idIndex = cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns._ID) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.MIME_TYPE) + val sizeIndex = cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.SIZE) + val dateAddedIndex = + cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_ADDED) + val dateModifiedIndex = + cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_MODIFIED) - while (cursor.moveToNext()) { - val path = pathInterpreter.extract() ?: continue + while (cursor.moveToNext()) { + val path = pathInterpreter.extract() ?: continue - val id = cursor.getLong(idIndex) - val uri = - Uri.withAppendedPath( - AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id.toString()) - val mimeType = cursor.getStringOrNull(mimeTypeIndex) ?: "audio/*" - val size = cursor.getLong(sizeIndex) - val dateAdded = - cursor.getLong(dateAddedIndex) * 1000 // Convert to milliseconds - val dateModified = - cursor.getLong(dateModifiedIndex) * 1000 // Convert to milliseconds + val id = cursor.getLong(idIndex) + val uri = + Uri.withAppendedPath( + AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI, + id.toString(), + ) + val mimeType = cursor.getStringOrNull(mimeTypeIndex) ?: "audio/*" + val size = cursor.getLong(sizeIndex) + val dateAdded = cursor.getLong(dateAddedIndex) * 1000 // Convert to milliseconds + val dateModified = + cursor.getLong(dateModifiedIndex) * 1000 // Convert to milliseconds - // Create file with empty deferred parent - val deviceFile = - File( - uri = uri, - path = path, - modifiedMs = dateModified, - mimeType = mimeType, - size = size, - addedMs = ForwardDateAdded(dateAdded), - parent = null) + // Create file with empty deferred parent + val deviceFile = + File( + uri = uri, + path = path, + modifiedMs = dateModified, + mimeType = mimeType, + size = size, + addedMs = ForwardDateAdded(dateAdded), + parent = null, + ) - allFiles.add(deviceFile) - it.send(deviceFile) - } + allFiles.add(deviceFile) + it.send(deviceFile) } + } } } @@ -150,12 +150,12 @@ private constructor( data class Query( val mode: FilterMode, val filtered: List, - val excludeNonMusic: Boolean + val excludeNonMusic: Boolean, ) enum class FilterMode { INCLUDE, - EXCLUDE + EXCLUDE, } private class ForwardDateAdded(val dateAdded: Long) : AddedMs { @@ -165,7 +165,10 @@ private constructor( companion object { fun from(context: Context, query: Query) = MediaStore( - context = context, volumeManager = VolumeManager.from(context), query = query) + context = context, + volumeManager = VolumeManager.from(context), + query = query, + ) /** * The base selector that works across all versions of android. Excludes files with zero @@ -180,6 +183,7 @@ private constructor( AOSPMediaStore.Audio.AudioColumns.DATE_ADDED, AOSPMediaStore.Audio.AudioColumns.DATE_MODIFIED, AOSPMediaStore.Audio.AudioColumns.SIZE, - AOSPMediaStore.Audio.AudioColumns.MIME_TYPE) + AOSPMediaStore.Audio.AudioColumns.MIME_TYPE, + ) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt index a412da501..aeeb5bb81 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt @@ -79,7 +79,7 @@ internal interface DocumentPathFactory { private class DocumentPathFactoryImpl( private val context: Context, private val volumeManager: VolumeManager, - private val mediaStorePathInterpreterFactory: MediaStorePathInterpreter.Factory + private val mediaStorePathInterpreterFactory: MediaStorePathInterpreter.Factory, ) : DocumentPathFactory { override fun unpackDocumentUri(uri: Uri): Path? { val id = DocumentsContract.getDocumentId(uri) @@ -92,10 +92,12 @@ private class DocumentPathFactoryImpl( val path = context.contentResolverSafe.useQuery( - contentUri, mediaStorePathInterpreterFactory.projection) { - it.moveToFirst() - mediaStorePathInterpreterFactory.wrap(it).extract() - } + contentUri, + mediaStorePathInterpreterFactory.projection, + ) { + it.moveToFirst() + mediaStorePathInterpreterFactory.wrap(it).extract() + } if (path != null) { return path @@ -113,7 +115,9 @@ private class DocumentPathFactoryImpl( // parsed into a Directory instance. val docUri = DocumentsContract.buildDocumentUriUsingTree( - uri, DocumentsContract.getTreeDocumentId(uri)) + uri, + DocumentsContract.getTreeDocumentId(uri), + ) val treeUri = DocumentsContract.getTreeDocumentId(docUri) return fromDocumentId(treeUri) } @@ -151,6 +155,7 @@ private class DocumentPathFactoryImpl( private val POSSIBLE_CONTENT_URI_PREFIXES = arrayOf( Uri.parse("content://downloads/public_downloads"), - Uri.parse("content://downloads/my_downloads")) + Uri.parse("content://downloads/my_downloads"), + ) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/path/MediaStorePathInterpreter.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/path/MediaStorePathInterpreter.kt index d62d1cb45..6ec3cd42d 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/path/MediaStorePathInterpreter.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/path/MediaStorePathInterpreter.kt @@ -125,7 +125,9 @@ private constructor(private val cursor: Cursor, volumeManager: VolumeManager) : override val projection: Array get() = arrayOf( - MediaStore.Audio.AudioColumns.DISPLAY_NAME, MediaStore.Audio.AudioColumns.DATA) + MediaStore.Audio.AudioColumns.DISPLAY_NAME, + MediaStore.Audio.AudioColumns.DATA, + ) override fun createSelector( paths: List @@ -200,7 +202,8 @@ private constructor(private val cursor: Cursor, volumeManager: VolumeManager) : // compared to DATA. MediaStore.Audio.AudioColumns.DISPLAY_NAME, MediaStore.Audio.AudioColumns.VOLUME_NAME, - MediaStore.Audio.AudioColumns.RELATIVE_PATH) + MediaStore.Audio.AudioColumns.RELATIVE_PATH, + ) // The selector should be configured to compare both the volume name and relative path // of the given directories, albeit with some conversion to the analogous MediaStore diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/QueryUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/QueryUtil.kt index 124b93088..0cf3ebbcb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/QueryUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/QueryUtil.kt @@ -46,7 +46,7 @@ internal fun ContentResolver.safeQuery( uri: Uri, projection: Array, selector: String? = null, - args: Array? = null + args: Array? = null, ) = requireNotNull(query(uri, projection, selector, args, null)) { "ContentResolver query failed" } /** @@ -68,5 +68,5 @@ internal inline fun ContentResolver.useQuery( projection: Array, selector: String? = null, args: Array? = null, - block: (Cursor) -> R + block: (Cursor) -> R, ) = safeQuery(uri, projection, selector, args).use(block) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt index 7ec48ff45..61038c01b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt @@ -52,7 +52,7 @@ class SAF private constructor( private val context: Context, private val contentResolver: ContentResolver, - private val query: Query + private val query: Query, ) : FS { override suspend fun explore(files: Channel): Deferred> = coroutineScope { tryAsyncWith(files, Dispatchers.Main) { @@ -64,7 +64,8 @@ private constructor( location.path, null, query.exclude.mapTo(mutableSetOf()) { it.path }, - files) + files, + ) } .tryAwaitAll() } @@ -90,7 +91,7 @@ private constructor( relativePath: Path, parent: Deferred?, exclude: Set, - files: Channel + files: Channel, ): Deferred> = tryAsync(Dispatchers.IO) { // Make a kotlin future @@ -132,7 +133,14 @@ private constructor( if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { recursive.add( exploreDirectoryImpl( - rootUri, childId, newPath, directoryDeferred, exclude, files)) + rootUri, + childId, + newPath, + directoryDeferred, + exclude, + files, + ) + ) } else { val size = cursor.getLong(sizeIndex) val file = @@ -148,7 +156,8 @@ private constructor( JoinAddedMs(context, childUri) } else { NullAddedMs - }) + }, + ) children.add(file) files.send(file) } @@ -161,7 +170,7 @@ private constructor( data class Query( val source: List, val exclude: List, - val withHidden: Boolean + val withHidden: Boolean, ) @RequiresApi(Build.VERSION_CODES.Q) @@ -174,15 +183,17 @@ private constructor( return null } return context.contentResolverSafe.useQuery( - mediaUri, arrayOf(AOSPMediaStore.Files.FileColumns.DATE_ADDED)) { - if (it.moveToFirst()) { - val dateAddedIndex = - it.getColumnIndexOrThrow(AOSPMediaStore.Files.FileColumns.DATE_ADDED) - it.getLong(dateAddedIndex) * 1000 - } else { - null - } + mediaUri, + arrayOf(AOSPMediaStore.Files.FileColumns.DATE_ADDED), + ) { + if (it.moveToFirst()) { + val dateAddedIndex = + it.getColumnIndexOrThrow(AOSPMediaStore.Files.FileColumns.DATE_ADDED) + it.getLong(dateAddedIndex) * 1000 + } else { + null } + } } } @@ -199,6 +210,7 @@ private constructor( DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_SIZE, - DocumentsContract.Document.COLUMN_LAST_MODIFIED) + DocumentsContract.Document.COLUMN_LAST_MODIFIED, + ) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt index c6bb55f66..c4cfefca5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt @@ -27,7 +27,7 @@ import android.os.Looper internal class LocationObserver( private val context: Context, private val uri: Uri, - private val onUpdate: () -> Unit + private val onUpdate: () -> Unit, ) : ContentObserver(Handler(Looper.getMainLooper())), Runnable { private val handler = Handler(Looper.getMainLooper()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/graph/MusicGraph.kt b/musikr/src/main/java/org/oxycblt/musikr/graph/MusicGraph.kt index 71a751d12..ebf1a97c9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/graph/MusicGraph.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/graph/MusicGraph.kt @@ -35,7 +35,7 @@ internal data class MusicGraph( val albumVertex: List, val artistVertex: List, val genreVertex: List, - val playlistVertex: Set + val playlistVertex: Set, ) { interface Builder { fun add(preSong: PreSong) @@ -158,7 +158,8 @@ internal data class MusicGraph( val songIndex = this@MusicGraph.songVertex.indexOf(it) if (songIndex >= 0) { appendLine( - " playlist_$playlistIndex -> song_$songIndex [color=orange];") + " playlist_$playlistIndex -> song_$songIndex [color=orange];" + ) } } } @@ -221,7 +222,8 @@ private class MusicGraphBuilderImpl : MusicGraph.Builder { preSong, albumVertex, songArtistVertices.toMutableList(), - songGenreVertices.toMutableList()) + songGenreVertices.toMutableList(), + ) albumVertex.songVertices.add(songVertex) songArtistVertices.forEach { artistVertex -> @@ -321,7 +323,8 @@ private class MusicGraphBuilderImpl : MusicGraph.Builder { albumVertices.values.toList(), artistVertices.values.toList(), genreVertices.values.toList(), - playlistVertices) + playlistVertices, + ) return graph } @@ -480,7 +483,8 @@ private class MusicGraphBuilderImpl : MusicGraph.Builder { strippedMbidCluster.map { val noAlbumArtistPreAlbum = it.preAlbum.copy( - preArtists = PreArtistsFrom.Individual(it.preAlbum.preArtists.preArtists)) + preArtists = PreArtistsFrom.Individual(it.preAlbum.preArtists.preArtists) + ) val simpleAlbumArtistVertex = albumVertices.getOrPut(noAlbumArtistPreAlbum) { AlbumVertex(noAlbumArtistPreAlbum, it.artistVertices.toMutableList()) @@ -533,7 +537,7 @@ internal class SongVertex( val preSong: PreSong, var albumVertex: AlbumVertex, var artistVertices: MutableList, - var genreVertices: MutableList + var genreVertices: MutableList, ) : Vertex { override var tag: Any? = null @@ -548,9 +552,7 @@ internal class AlbumVertex(val preAlbum: PreAlbum, var artistVertices: MutableLi override fun toString() = "AlbumVertex(preAlbum=$preAlbum)" } -internal class ArtistVertex( - val preArtist: PreArtist, -) : Vertex { +internal class ArtistVertex(val preArtist: PreArtist) : Vertex { val songVertices = mutableSetOf() val albumVertices = mutableSetOf() val genreVertices = mutableSetOf() diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/Metadata.kt b/musikr/src/main/java/org/oxycblt/musikr/metadata/Metadata.kt index ba16830b5..f6c97b5ed 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/metadata/Metadata.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/metadata/Metadata.kt @@ -23,7 +23,7 @@ data class Metadata( val xiph: Map>, val mp4: Map>, val cover: ByteArray?, - val properties: Properties + val properties: Properties, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/musikr/src/main/java/org/oxycblt/musikr/model/ArtistImpl.kt b/musikr/src/main/java/org/oxycblt/musikr/model/ArtistImpl.kt index 095320e19..64b5f1af5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/model/ArtistImpl.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/model/ArtistImpl.kt @@ -52,7 +52,8 @@ internal class ArtistImpl(private val core: ArtistCore) : Artist { override val durationMs = core.songs.sumOf { it.durationMs } override val covers = CoverCollection.from( - core.songs.mapNotNull { it.cover }.ifEmpty { core.albums.flatMap { it.covers.covers } }) + core.songs.mapNotNull { it.cover }.ifEmpty { core.albums.flatMap { it.covers.covers } } + ) private val hashCode = 31 * (31 * uid.hashCode() + core.preArtist.hashCode()) * core.songs.hashCode() diff --git a/musikr/src/main/java/org/oxycblt/musikr/model/LibraryFactory.kt b/musikr/src/main/java/org/oxycblt/musikr/model/LibraryFactory.kt index 92296c80c..ca01987e8 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/model/LibraryFactory.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/model/LibraryFactory.kt @@ -38,7 +38,7 @@ internal interface LibraryFactory { fun create( graph: MusicGraph, storedPlaylists: StoredPlaylists, - playlistInterpreter: PlaylistInterpreter + playlistInterpreter: PlaylistInterpreter, ): MutableLibrary companion object { @@ -50,7 +50,7 @@ private class LibraryFactoryImpl() : LibraryFactory { override fun create( graph: MusicGraph, storedPlaylists: StoredPlaylists, - playlistInterpreter: PlaylistInterpreter + playlistInterpreter: PlaylistInterpreter, ): MutableLibrary { val songs = graph.songVertex.mapTo(mutableSetOf()) { vertex -> @@ -73,7 +73,14 @@ private class LibraryFactoryImpl() : LibraryFactory { PlaylistImpl(PlaylistVertexCore(vertex)) } return LibraryImpl( - songs, albums, artists, genres, playlists, storedPlaylists, playlistInterpreter) + songs, + albums, + artists, + genres, + playlists, + storedPlaylists, + playlistInterpreter, + ) } private class SongVertexCore(private val vertex: SongVertex) : SongCore { diff --git a/musikr/src/main/java/org/oxycblt/musikr/model/LibraryImpl.kt b/musikr/src/main/java/org/oxycblt/musikr/model/LibraryImpl.kt index 9e8777dfe..e7d26512e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/model/LibraryImpl.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/model/LibraryImpl.kt @@ -34,7 +34,7 @@ internal data class LibraryImpl( override val genres: Set, override val playlists: Set, private val storedPlaylists: StoredPlaylists, - private val playlistInterpreter: PlaylistInterpreter + private val playlistInterpreter: PlaylistInterpreter, ) : MutableLibrary { private val songUidMap = songs.associateBy { it.uid } private val v400SongUidMap = songs.associateBy { it.v400Uid } @@ -116,6 +116,6 @@ internal data class LibraryImpl( private class NewPlaylistCore( override val prePlaylist: PrePlaylistInfo, - override val songs: List + override val songs: List, ) : PlaylistCore } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt index 09784d218..fe59e21e5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt @@ -41,7 +41,8 @@ internal interface EvaluateStep { TagInterpreter.new(interpretation), PlaylistInterpreter.new(interpretation), config.storage.storedPlaylists, - LibraryFactory.new()) + LibraryFactory.new(), + ) } } @@ -50,7 +51,7 @@ private class EvaluateStepImpl( private val tagInterpreter: TagInterpreter, private val playlistInterpreter: PlaylistInterpreter, private val storedPlaylists: StoredPlaylists, - private val libraryFactory: LibraryFactory + private val libraryFactory: LibraryFactory, ) : EvaluateStep { override suspend fun evaluate(extractedMusic: Channel): MutableLibrary { val builder = MusicGraph.builder() diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 9d64c42b8..75c95523e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -48,7 +48,7 @@ internal interface ExploreStep { private class ExploreStepImpl(private val fs: FS, private val storage: Storage) : ExploreStep { override suspend fun explore( scope: CoroutineScope, - explored: Channel + explored: Channel, ): Deferred> { val files = Channel(Channel.UNLIMITED) val filesTask = fs.explore(files) @@ -73,8 +73,10 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage) when (item) { is Finalized -> item is NeedsCover -> { - when (val coverResult = - item.cachedSong.coverId?.let { id -> storage.covers.obtain(id) }) { + when ( + val coverResult = + item.cachedSong.coverId?.let { id -> storage.covers.obtain(id) } + ) { is CoverResult.Hit -> Finalized(item.cachedSong.toRawSong(coverResult.cover)) null -> Finalized(item.cachedSong.toRawSong(null)) diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt index f5500b6c0..7708f9618 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt @@ -40,7 +40,7 @@ internal interface ExtractStep { suspend fun extract( scope: CoroutineScope, explored: Channel, - extracted: Channel + extracted: Channel, ): Deferred> companion object { @@ -49,7 +49,8 @@ internal interface ExtractStep { MetadataExtractor.from(context), TagParser.new(), config.storage.cache, - config.storage.covers) + config.storage.covers, + ) } } @@ -57,12 +58,12 @@ private class ExtractStepImpl( private val metadataExtractor: MetadataExtractor, private val tagParser: TagParser, private val cache: MutableCache, - private val covers: MutableCovers + private val covers: MutableCovers, ) : ExtractStep { override suspend fun extract( scope: CoroutineScope, explored: Channel, - extracted: Channel + extracted: Channel, ): Deferred> { val addingMs = System.currentTimeMillis() val extract = Channel(PARALLELISM) @@ -104,7 +105,9 @@ private class ExtractStepImpl( // added query is basically free, it's only saf that has // it's slow hacky workaround that we must accommodate // here.) - item.newSong.file.addedMs.resolve() ?: addingMs)) + item.newSong.file.addedMs.resolve() ?: addingMs, + ) + ) } } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt index 2242c3645..78ec7117a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt @@ -53,5 +53,5 @@ internal data class RawSong( val properties: Properties, val tags: ParsedTags, val cover: Cover?, - val addedMs: Long + val addedMs: Long, ) : Explored.Known, Extracted.Valid diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt index 8f80ff48e..0046266f3 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt @@ -57,7 +57,10 @@ interface ExternalPlaylistManager { companion object { fun from(context: Context): ExternalPlaylistManager = ExternalPlaylistManagerImpl( - context, DocumentPathFactory.from(context), M3U.from(context)) + context, + DocumentPathFactory.from(context), + M3U.from(context), + ) } } @@ -87,7 +90,7 @@ typealias PossiblePaths = List private class ExternalPlaylistManagerImpl( private val context: Context, private val documentPathFactory: DocumentPathFactory, - private val m3u: M3U + private val m3u: M3U, ) : ExternalPlaylistManager { override suspend fun import(uri: Uri): ImportedPlaylist? { val filePath = documentPathFactory.unpackDocumentUri(uri) ?: return null diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/PlaylistFile.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/PlaylistFile.kt index ad52037d6..dc514c40a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/PlaylistFile.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/PlaylistFile.kt @@ -24,7 +24,7 @@ import org.oxycblt.musikr.Song internal data class PlaylistFile( val name: String, val songPointers: List, - val handle: PlaylistHandle + val handle: PlaylistHandle, ) internal sealed interface SongPointer { diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/db/PlaylistDatabase.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/db/PlaylistDatabase.kt index 021b01595..ee33ab0e9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/db/PlaylistDatabase.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/db/PlaylistDatabase.kt @@ -38,7 +38,8 @@ import org.oxycblt.musikr.Music @Database( entities = [PlaylistInfo::class, PlaylistSong::class, PlaylistSongCrossRef::class], version = 30, - exportSchema = false) + exportSchema = false, +) @TypeConverters(Music.UID.TypeConverters::class) internal abstract class PlaylistDatabase : RoomDatabase() { abstract fun playlistDao(): PlaylistDao @@ -46,7 +47,10 @@ internal abstract class PlaylistDatabase : RoomDatabase() { companion object { fun from(context: Context) = Room.databaseBuilder( - context.applicationContext, PlaylistDatabase::class.java, "user_music.db") + context.applicationContext, + PlaylistDatabase::class.java, + "user_music.db", + ) .fallbackToDestructiveMigration() .build() } @@ -83,8 +87,11 @@ internal abstract class PlaylistDao { insertRefs( rawPlaylist.songs.map { PlaylistSongCrossRef( - playlistUid = rawPlaylist.playlistInfo.playlistUid, songUid = it.songUid) - }) + playlistUid = rawPlaylist.playlistInfo.playlistUid, + songUid = it.songUid, + ) + } + ) } /** @@ -119,7 +126,8 @@ internal abstract class PlaylistDao { open suspend fun insertPlaylistSongs(playlistUid: Music.UID, songs: List) { insertSongs(songs) insertRefs( - songs.map { PlaylistSongCrossRef(playlistUid = playlistUid, songUid = it.songUid) }) + songs.map { PlaylistSongCrossRef(playlistUid = playlistUid, songUid = it.songUid) } + ) } /** @@ -134,7 +142,8 @@ internal abstract class PlaylistDao { deleteRefs(playlistUid) insertSongs(songs) insertRefs( - songs.map { PlaylistSongCrossRef(playlistUid = playlistUid, songUid = it.songUid) }) + songs.map { PlaylistSongCrossRef(playlistUid = playlistUid, songUid = it.songUid) } + ) } /** Internal, do not use. */ diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/db/RawPlaylist.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/db/RawPlaylist.kt index 1353458be..2a9061579 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/db/RawPlaylist.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/db/RawPlaylist.kt @@ -36,8 +36,9 @@ internal data class RawPlaylist( @Relation( parentColumn = "playlistUid", entityColumn = "songUid", - associateBy = Junction(PlaylistSongCrossRef::class)) - val songs: List + associateBy = Junction(PlaylistSongCrossRef::class), + ) + val songs: List, ) /** @@ -63,5 +64,5 @@ internal data class RawPlaylist( internal data class PlaylistSongCrossRef( @PrimaryKey(autoGenerate = true) val id: Long = 0, @ColumnInfo(index = true) val playlistUid: Music.UID, - @ColumnInfo(index = true) val songUid: Music.UID + @ColumnInfo(index = true) val songUid: Music.UID, ) diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/db/StoredPlaylistHandle.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/db/StoredPlaylistHandle.kt index 36867202e..cbd772be6 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/db/StoredPlaylistHandle.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/db/StoredPlaylistHandle.kt @@ -23,7 +23,7 @@ import org.oxycblt.musikr.playlist.PlaylistHandle internal class StoredPlaylistHandle( private val playlistInfo: PlaylistInfo, - private val playlistDao: PlaylistDao + private val playlistDao: PlaylistDao, ) : PlaylistHandle { override val uid = playlistInfo.playlistUid diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/db/StoredPlaylists.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/db/StoredPlaylists.kt index 44abce745..bad361abb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/db/StoredPlaylists.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/db/StoredPlaylists.kt @@ -48,6 +48,7 @@ private class StoredPlaylistsImpl(private val playlistDao: PlaylistDao) : Stored PlaylistFile( it.playlistInfo.name, it.songs.map { song -> SongPointer.UID(song.songUid) }, - StoredPlaylistHandle(it.playlistInfo, playlistDao)) + StoredPlaylistHandle(it.playlistInfo, playlistDao), + ) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/interpret/PlaylistInterpreter.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/interpret/PlaylistInterpreter.kt index 2525a4141..84ef71357 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/interpret/PlaylistInterpreter.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/interpret/PlaylistInterpreter.kt @@ -40,7 +40,8 @@ private class PlaylistInterpreterImpl(private val naming: Naming) : PlaylistInte name = naming.name(file.name, null), rawName = file.name, handle = file.handle, - songPointers = file.songPointers) + songPointers = file.songPointers, + ) override fun interpret(name: String, handle: PlaylistHandle): PostPlaylist = PostPlaylist(name = naming.name(name, null), rawName = name, handle = handle) diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/interpret/PrePlaylist.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/interpret/PrePlaylist.kt index 7a16d23c4..b3d43b8e4 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/interpret/PrePlaylist.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/interpret/PrePlaylist.kt @@ -32,7 +32,7 @@ internal data class PrePlaylist( override val name: Name.Known, override val rawName: String?, override val handle: PlaylistHandle, - val songPointers: List + val songPointers: List, ) : PrePlaylistInfo internal data class PostPlaylist( diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt index be4bee901..2931cfb75 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/m3u/M3U.kt @@ -66,7 +66,7 @@ abstract class M3U { playlist: Playlist, outputStream: OutputStream, workingDirectory: Path, - config: ExportConfig + config: ExportConfig, ) companion object { @@ -143,13 +143,14 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() { else -> listOf( InterpretedPath(Components.parseUnix(path), false), - InterpretedPath(Components.parseWindows(path), true)) + InterpretedPath(Components.parseWindows(path), true), + ) } private fun expandInterpretation( path: InterpretedPath, workingDirectory: Path, - volumes: List + volumes: List, ): List { val absoluteInterpretation = Path(workingDirectory.volume, path.components) val relativeInterpretation = @@ -172,7 +173,7 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() { playlist: Playlist, outputStream: OutputStream, workingDirectory: Path, - config: ExportConfig + config: ExportConfig, ) { val writer = outputStream.bufferedWriter() // Try to be as compliant to the spec as possible while also cramming it full of extensions @@ -252,9 +253,11 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() { // and them combine them with the correct relative elements to make sure they // resolve the same. var commonIndex = 0 - while (commonIndex < components.size && - commonIndex < workingDirectory.components.size && - components[commonIndex] == workingDirectory.components[commonIndex]) { + while ( + commonIndex < components.size && + commonIndex < workingDirectory.components.size && + components[commonIndex] == workingDirectory.components[commonIndex] + ) { ++commonIndex } @@ -267,7 +270,7 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() { } commonIndex == components.size -> { // The working directory is deeper in the path, backtrack. - for (i in 0 ..< workingDirectory.components.size - commonIndex) { + for (i in 0.. { // The paths are siblings. Backtrack and append as needed. - for (i in 0 ..< workingDirectory.components.size - commonIndex) { + for (i in 0..) : Comparable /** The earliest [Date] in the range. */ val min: Date, /** the latest [Date] in the range. May be the same as [min]. ] */ - val max: Date + val max: Date, ) : Comparable { init { check(min <= max) { "Min date must be <= max date" } @@ -109,7 +109,8 @@ class Date private constructor(private val tokens: List) : Comparable */ private val ISO8601_REGEX by lazy { Regex( - """^(\d{4})([-.](\d{2})([-.](\d{2})([T ](\d{2})([:.](\d{2})([:.](\d{2})(Z)?)?)?)?)?)?$""") + """^(\d{4})([-.](\d{2})([-.](\d{2})([T ](\d{2})([:.](\d{2})([:.](\d{2})(Z)?)?)?)?)?)?$""" + ) } /** @@ -126,7 +127,8 @@ class Date private constructor(private val tokens: List) : Comparable from( stringYear.substring(0..3).toInt(), stringYear.substring(4..5).toInt(), - stringYear.substring(6..7).toInt()) + stringYear.substring(6..7).toInt(), + ) } else { fromTokens(listOf(year)) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/Name.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/Name.kt index d6f30d834..e961744ec 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/Name.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/Name.kt @@ -90,8 +90,10 @@ class Token internal constructor(internal val collationKey: CollationKey, intern // Numeric strings must be ordered by magnitude, thus immediately short-circuit // the comparison if the lengths do not match. - if (type == Type.NUMERIC && - collationKey.sourceString.length != other.collationKey.sourceString.length) { + if ( + type == Type.NUMERIC && + collationKey.sourceString.length != other.collationKey.sourceString.length + ) { return collationKey.sourceString.length - other.collationKey.sourceString.length } @@ -103,12 +105,12 @@ class Token internal constructor(internal val collationKey: CollationKey, intern /** Compare as a digit string, like "65". */ NUMERIC, /** Compare as a standard alphanumeric string, like "65daysofstatic" */ - LEXICOGRAPHIC + LEXICOGRAPHIC, } } enum class Placeholder { ALBUM, ARTIST, - GENRE + GENRE, } diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/ReleaseType.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/ReleaseType.kt index 709f71588..cf60b980b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/ReleaseType.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/ReleaseType.kt @@ -107,7 +107,7 @@ sealed interface ReleaseType { LIVE, /** A release consisting of another Artists remix of a prior performance. */ - REMIX + REMIX, } companion object { @@ -145,7 +145,7 @@ sealed interface ReleaseType { */ private inline fun List.parseSecondaryTypes( index: Int, - convertRefinement: (Refinement?) -> ReleaseType + convertRefinement: (Refinement?) -> ReleaseType, ): ReleaseType { val secondary = getOrNull(index) return if (secondary.equals("compilation", true)) { @@ -169,7 +169,7 @@ sealed interface ReleaseType { */ private inline fun parseSecondaryTypeImpl( type: String?, - convertRefinement: (Refinement?) -> ReleaseType + convertRefinement: (Refinement?) -> ReleaseType, ) = when { // Parse all the types that have no children diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/format/ID3.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/format/ID3.kt index 4e9390711..ef22ee503 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/format/ID3.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/format/ID3.kt @@ -321,4 +321,5 @@ private val genreTable = "Psybient", // Auxio's extensions, added because Future Garage is also a good genre. - "Future Garage") + "Future Garage", + ) diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/PreMusic.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/PreMusic.kt index 8d7a802fd..8e9eecc27 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/PreMusic.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/PreMusic.kt @@ -54,7 +54,7 @@ internal data class PreSong( val cover: Cover?, val preAlbum: PreAlbum, val preArtists: List, - val preGenres: List + val preGenres: List, ) internal data class PreAlbum( @@ -91,7 +91,4 @@ internal data class PreArtist(val musicBrainzId: UUID?, val name: Name, val rawN ?: Music.UID.auxio(Music.UID.Item.ARTIST) { update(rawName) } } -internal data class PreGenre( - val name: Name, - val rawName: String?, -) +internal data class PreGenre(val name: Name, val rawName: String?) diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt index 9d06722be..7504211e2 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt @@ -48,16 +48,23 @@ private class TagInterpreterImpl(private val interpretation: Interpretation) : T song.tags.artistMusicBrainzIds, song.tags.artistNames, song.tags.artistSortNames, - interpretation) + interpretation, + ) val albumPreArtists = makePreArtists( song.tags.albumArtistMusicBrainzIds, song.tags.albumArtistNames, song.tags.albumArtistSortNames, - interpretation) + interpretation, + ) val preAlbum = makePreAlbum( - song.tags, song.file, individualPreArtists, albumPreArtists, interpretation) + song.tags, + song.file, + individualPreArtists, + albumPreArtists, + interpretation, + ) val rawArtists = individualPreArtists.ifEmpty { albumPreArtists }.ifEmpty { listOf(unknownPreArtist()) } val rawGenres = @@ -146,7 +153,8 @@ private class TagInterpreterImpl(private val interpretation: Interpretation) : T preAlbum = preAlbum, preArtists = rawArtists, preGenres = rawGenres, - cover = song.cover) + cover = song.cover, + ) } private fun makePreAlbum( @@ -154,7 +162,7 @@ private class TagInterpreterImpl(private val interpretation: Interpretation) : T deviceFile: File, individualPreArtists: List, albumPreArtists: List, - interpretation: Interpretation + interpretation: Interpretation, ): PreAlbum { val name = parsedTags.albumName ?: deviceFile.path.directory.name return PreAlbum( @@ -167,14 +175,16 @@ private class TagInterpreterImpl(private val interpretation: Interpretation) : T preArtists = PreArtistsFrom.Album(albumPreArtists).takeIf { it.preArtists.isNotEmpty() } ?: PreArtistsFrom.Individual( - individualPreArtists.ifEmpty { listOf(unknownPreArtist()) })) + individualPreArtists.ifEmpty { listOf(unknownPreArtist()) } + ), + ) } private fun makePreArtists( rawMusicBrainzIds: List, rawNames: List, rawSortNames: List, - interpretation: Interpretation + interpretation: Interpretation, ): List { val musicBrainzIds = interpretation.separators.split(rawMusicBrainzIds) val names = interpretation.separators.split(rawNames) @@ -188,7 +198,7 @@ private class TagInterpreterImpl(private val interpretation: Interpretation) : T musicBrainzId: String?, rawName: String?, sortName: String?, - interpretation: Interpretation + interpretation: Interpretation, ): PreArtist { val name = interpretation.naming.name(rawName, sortName, Placeholder.ARTIST) val musicBrainzId = musicBrainzId?.toUuidOrNull() @@ -199,7 +209,7 @@ private class TagInterpreterImpl(private val interpretation: Interpretation) : T private fun makePreGenres( parsedTags: ParsedTags, - interpretation: Interpretation + interpretation: Interpretation, ): List { val genreNames = parsedTags.genreNames.parseId3GenreNames() diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/parse/ParsedTags.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/parse/ParsedTags.kt index 70ec61959..9e595b388 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/parse/ParsedTags.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/parse/ParsedTags.kt @@ -41,5 +41,5 @@ data class ParsedTags( val albumArtistMusicBrainzIds: List = listOf(), val albumArtistNames: List = listOf(), val albumArtistSortNames: List = listOf(), - val genreNames: List = listOf() + val genreNames: List = listOf(), ) diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagFields.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagFields.kt index 08620d399..77fa86804 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagFields.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagFields.kt @@ -48,15 +48,15 @@ internal fun Metadata.sortName() = (xiph["TITLESORT"] ?: mp4["sonm"] ?: id3v2["T internal fun Metadata.track() = (parseXiphPositionField( xiph["TRACKNUMBER"]?.first(), - (xiph["TOTALTRACKS"] ?: xiph["TRACKTOTAL"] ?: xiph["TRACKC"])?.first()) - ?: (mp4["trkn"] ?: id3v2["TRCK"])?.run { first().parseSlashPositionField() }) + (xiph["TOTALTRACKS"] ?: xiph["TRACKTOTAL"] ?: xiph["TRACKC"])?.first(), + ) ?: (mp4["trkn"] ?: id3v2["TRCK"])?.run { first().parseSlashPositionField() }) // Disc and it's subtitle name. internal fun Metadata.disc() = (parseXiphPositionField( xiph["DISCNUMBER"]?.first(), - (xiph["TOTALDISCS"] ?: xiph["DISCTOTAL"] ?: xiph["DISCC"])?.run { first() }) - ?: (mp4["disk"] ?: id3v2["TPOS"])?.run { first().parseSlashPositionField() }) + (xiph["TOTALDISCS"] ?: xiph["DISCTOTAL"] ?: xiph["DISCC"])?.run { first() }, + ) ?: (mp4["disk"] ?: id3v2["TPOS"])?.run { first().parseSlashPositionField() }) internal fun Metadata.subtitle() = (xiph["DISCSUBTITLE"] ?: id3v2["TSST"])?.first() diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagParser.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagParser.kt index a4dbda470..ecbf4f8c2 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagParser.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/parse/TagParser.kt @@ -60,6 +60,7 @@ private data object TagParserImpl : TagParser { ?: listOf("Various Artists").takeIf { compilation } ?: listOf(), albumArtistSortNames = metadata.albumArtistSortNames() ?: listOf(), - genreNames = metadata.genreNames() ?: listOf()) + genreNames = metadata.genreNames() ?: listOf(), + ) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt index 313835361..2f791ef2e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt @@ -33,7 +33,7 @@ import org.oxycblt.musikr.tag.Date fun CoroutineScope.tryAsync( context: CoroutineContext, - block: suspend () -> Unit + block: suspend () -> Unit, ): Deferred> = async { try { block() diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/DateTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/DateTest.kt index b2cb3380d..1eede7339 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/DateTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/DateTest.kt @@ -27,7 +27,8 @@ class DateTest { fun date_equals_varyingPrecision() { assertTrue( requireNotNull(Date.from("2016-08-16T00:01:02")) != - requireNotNull(Date.from("2016-08-16"))) + requireNotNull(Date.from("2016-08-16")) + ) } @Test @@ -48,10 +49,7 @@ class DateTest { fun date_compareTo_varyingPrecision() { val a = requireNotNull(Date.from("2016-08-16T00:01:02")) val b = requireNotNull(Date.from("2016-08-16")) - assertEquals( - 1, - a.compareTo(b), - ) + assertEquals(1, a.compareTo(b)) } @Test diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/ReleaseTypeTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/ReleaseTypeTest.kt index cd0627547..29af0515c 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/ReleaseTypeTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/ReleaseTypeTest.kt @@ -32,7 +32,9 @@ class ReleaseTypeTest { @Test fun releaseType_parse_secondary() { assertEquals( - ReleaseType.Compilation(null), ReleaseType.parse(listOf("album", "compilation"))) + ReleaseType.Compilation(null), + ReleaseType.parse(listOf("album", "compilation")), + ) assertEquals(ReleaseType.Soundtrack, ReleaseType.parse(listOf("album", "soundtrack"))) assertEquals(ReleaseType.Mix, ReleaseType.parse(listOf("album", "dj-mix"))) assertEquals(ReleaseType.Mixtape, ReleaseType.parse(listOf("album", "mixtape/street"))) @@ -43,30 +45,40 @@ class ReleaseTypeTest { fun releaseType_parse_modifiers() { assertEquals( ReleaseType.Album(ReleaseType.Refinement.LIVE), - ReleaseType.parse(listOf("album", "live"))) + ReleaseType.parse(listOf("album", "live")), + ) assertEquals( ReleaseType.Album(ReleaseType.Refinement.REMIX), - ReleaseType.parse(listOf("album", "remix"))) + ReleaseType.parse(listOf("album", "remix")), + ) assertEquals( - ReleaseType.EP(ReleaseType.Refinement.LIVE), ReleaseType.parse(listOf("ep", "live"))) + ReleaseType.EP(ReleaseType.Refinement.LIVE), + ReleaseType.parse(listOf("ep", "live")), + ) assertEquals( - ReleaseType.EP(ReleaseType.Refinement.REMIX), ReleaseType.parse(listOf("ep", "remix"))) + ReleaseType.EP(ReleaseType.Refinement.REMIX), + ReleaseType.parse(listOf("ep", "remix")), + ) assertEquals( ReleaseType.Single(ReleaseType.Refinement.LIVE), - ReleaseType.parse(listOf("single", "live"))) + ReleaseType.parse(listOf("single", "live")), + ) assertEquals( ReleaseType.Single(ReleaseType.Refinement.REMIX), - ReleaseType.parse(listOf("single", "remix"))) + ReleaseType.parse(listOf("single", "remix")), + ) } @Test fun releaseType_parse_secondaryModifiers() { assertEquals( ReleaseType.Compilation(ReleaseType.Refinement.LIVE), - ReleaseType.parse(listOf("album", "compilation", "live"))) + ReleaseType.parse(listOf("album", "compilation", "live")), + ) assertEquals( ReleaseType.Compilation(ReleaseType.Refinement.REMIX), - ReleaseType.parse(listOf("album", "compilation", "remix"))) + ReleaseType.parse(listOf("album", "compilation", "remix")), + ) } @Test @@ -80,8 +92,12 @@ class ReleaseTypeTest { @Test fun releaseType_parse_orphanedModifier() { assertEquals( - ReleaseType.Album(ReleaseType.Refinement.LIVE), ReleaseType.parse(listOf("live"))) + ReleaseType.Album(ReleaseType.Refinement.LIVE), + ReleaseType.parse(listOf("live")), + ) assertEquals( - ReleaseType.Album(ReleaseType.Refinement.REMIX), ReleaseType.parse(listOf("remix"))) + ReleaseType.Album(ReleaseType.Refinement.REMIX), + ReleaseType.parse(listOf("remix")), + ) } } diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/SeparatorsTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/SeparatorsTest.kt index 3f6ac6dd5..26044e7dc 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/SeparatorsTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/interpret/SeparatorsTest.kt @@ -36,12 +36,15 @@ class SeparatorsTest { fun separators_split_withString_withMultipleChar() { assertEquals( listOf("a", "b", "c", "d", "e", "f"), - Separators.from(",;/+&").split(listOf("a,b;c/d+e&f"))) + Separators.from(",;/+&").split(listOf("a,b;c/d+e&f")), + ) } @Test fun separators_split_withList_withMultipleChar() { assertEquals( - listOf("a,b;c/d", "e&f"), Separators.from(",;/+&").split(listOf("a,b;c/d", "e&f"))) + listOf("a,b;c/d", "e&f"), + Separators.from(",;/+&").split(listOf("a,b;c/d", "e&f")), + ) } } diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt index 47d31032d..1a1c47e9b 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagFieldsTest.kt @@ -52,7 +52,8 @@ class TagFieldsTest { createTestMetadata( id3v2Tags = mapOf("TIT2" to listOf("ID3 Title")), mp4Tags = mapOf("©nam" to listOf("MP4 Title")), - xiphTags = mapOf("TITLE" to listOf("Xiph Title"))) + xiphTags = mapOf("TITLE" to listOf("Xiph Title")), + ) assertEquals("Xiph Title", metadata.name()) } @@ -73,13 +74,15 @@ class TagFieldsTest { // Test Xiph format metadata = createTestMetadata( - xiphTags = mapOf("TRACKNUMBER" to listOf("9"), "TOTALTRACKS" to listOf("15"))) + xiphTags = mapOf("TRACKNUMBER" to listOf("9"), "TOTALTRACKS" to listOf("15")) + ) assertEquals(9, metadata.track()) // Test Xiph alternative total tracks metadata = createTestMetadata( - xiphTags = mapOf("TRACKNUMBER" to listOf("8"), "TRACKTOTAL" to listOf("16"))) + xiphTags = mapOf("TRACKNUMBER" to listOf("8"), "TRACKTOTAL" to listOf("16")) + ) assertEquals(8, metadata.track()) } @@ -96,13 +99,15 @@ class TagFieldsTest { // Test Xiph format metadata = createTestMetadata( - xiphTags = mapOf("DISCNUMBER" to listOf("3"), "TOTALDISCS" to listOf("4"))) + xiphTags = mapOf("DISCNUMBER" to listOf("3"), "TOTALDISCS" to listOf("4")) + ) assertEquals(3, metadata.disc()) // Test Xiph alternative total discs metadata = createTestMetadata( - xiphTags = mapOf("DISCNUMBER" to listOf("2"), "DISCTOTAL" to listOf("5"))) + xiphTags = mapOf("DISCNUMBER" to listOf("2"), "DISCTOTAL" to listOf("5")) + ) assertEquals(2, metadata.disc()) } @@ -118,7 +123,8 @@ class TagFieldsTest { metadata = createTestMetadata( id3v2Tags = mapOf("TSST" to listOf("ID3 Subtitle")), - xiphTags = mapOf("DISCSUBTITLE" to listOf("Xiph Subtitle"))) + xiphTags = mapOf("DISCSUBTITLE" to listOf("Xiph Subtitle")), + ) assertEquals("Xiph Subtitle", metadata.subtitle()) } @@ -144,7 +150,8 @@ class TagFieldsTest { metadata = createTestMetadata( xiphTags = - mapOf("DATE" to listOf("2023-01-01"), "ORIGINALDATE" to listOf("2021-01-01"))) + mapOf("DATE" to listOf("2023-01-01"), "ORIGINALDATE" to listOf("2021-01-01")) + ) assertEquals("2021-01-01", metadata.date().toString()) // Test MP4 date @@ -161,8 +168,9 @@ class TagFieldsTest { mapOf( "TYER" to listOf("2019"), "TDAT" to listOf("0523"), // May 23 - "TIME" to listOf("2145") // 21:45 - )) + "TIME" to listOf("2145"), // 21:45 + ) + ) val date = metadata.date() assertEquals(2019, date?.year) assertEquals(5, date?.month) @@ -179,7 +187,9 @@ class TagFieldsTest { mapOf( "TALB" to listOf("Album Name"), "TSOA" to listOf("Sort Album Name"), - "TXXX:RELEASETYPE" to listOf("compilation"))) + "TXXX:RELEASETYPE" to listOf("compilation"), + ) + ) assertEquals("Album Name", metadata.albumName()) assertEquals("Sort Album Name", metadata.albumSortName()) @@ -195,7 +205,9 @@ class TagFieldsTest { "TPE1" to listOf("Artist 1"), "TPE2" to listOf("Album Artist 1"), "TSOP" to listOf("Artist 1 Sort"), - "TSO2" to listOf("Album Artist 1 Sort"))) + "TSO2" to listOf("Album Artist 1 Sort"), + ) + ) assertEquals(listOf("Artist 1"), metadata.artistNames()) assertEquals(listOf("Album Artist 1"), metadata.albumArtistNames()) @@ -211,7 +223,9 @@ class TagFieldsTest { xiphTags = mapOf( "MUSICBRAINZ_RELEASETRACKID" to listOf("track-mb-id"), - "MUSICBRAINZ_ALBUMID" to listOf("album-mb-id"))) + "MUSICBRAINZ_ALBUMID" to listOf("album-mb-id"), + ) + ) assertEquals("track-mb-id", metadata.musicBrainzId()) assertEquals("album-mb-id", metadata.albumMusicBrainzId()) @@ -223,7 +237,9 @@ class TagFieldsTest { mapOf( "----:COM.APPLE.ITUNES:MUSICBRAINZ RELEASE TRACK ID" to listOf("track-mb-id-2"), - "----:COM.APPLE.ITUNES:MUSICBRAINZ ALBUM ID" to listOf("album-mb-id-2"))) + "----:COM.APPLE.ITUNES:MUSICBRAINZ ALBUM ID" to listOf("album-mb-id-2"), + ) + ) assertEquals("track-mb-id-2", metadata2.musicBrainzId()) assertEquals("album-mb-id-2", metadata2.albumMusicBrainzId()) @@ -272,14 +288,14 @@ class TagFieldsTest { // Test MP4 ReplayGain tags metadata = createTestMetadata( - mp4Tags = - mapOf("----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN" to listOf("-0.32 dB"))) + mp4Tags = mapOf("----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN" to listOf("-0.32 dB")) + ) assertEquals(-0.32f, metadata.replayGainTrackAdjustment()) metadata = createTestMetadata( - mp4Tags = - mapOf("----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN" to listOf("-8.72 dB"))) + mp4Tags = mapOf("----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN" to listOf("-8.72 dB")) + ) assertEquals(-8.72f, metadata.replayGainAlbumAdjustment()) } @@ -303,7 +319,7 @@ class TagFieldsTest { durationMs: Long = 1000, bitrateKbps: Int = 320, sampleRateHz: Int = 44100, - mimeType: String = "audio/mpeg" + mimeType: String = "audio/mpeg", ): Metadata { val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt index f52950015..7a4ef68eb 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParserTest.kt @@ -45,7 +45,9 @@ class TagParserTest { "TYER" to listOf("2020"), "TRCK" to listOf("1/10"), "TPOS" to listOf("1/2"), - "TCON" to listOf("Rock", "Electronic"))) + "TCON" to listOf("Rock", "Electronic"), + ) + ) val tags = tagParser.parse(metadata) @@ -66,7 +68,8 @@ class TagParserTest { createTestMetadata( id3v2Tags = mapOf("TIT2" to listOf("ID3 Song"), "TALB" to listOf("ID3 Album")), xiphTags = mapOf("TITLE" to listOf("Xiph Song"), "ALBUM" to listOf("Xiph Album")), - mp4Tags = mapOf("©nam" to listOf("MP4 Song"), "©alb" to listOf("MP4 Album"))) + mp4Tags = mapOf("©nam" to listOf("MP4 Song"), "©alb" to listOf("MP4 Album")), + ) val tags = tagParser.parse(metadata) @@ -91,8 +94,8 @@ class TagParserTest { // Test compilation album with explicit release type val metadata = createTestMetadata( - id3v2Tags = - mapOf("TCMP" to listOf("1"), "TXXX:RELEASETYPE" to listOf("soundtrack"))) + id3v2Tags = mapOf("TCMP" to listOf("1"), "TXXX:RELEASETYPE" to listOf("soundtrack")) + ) val tags = tagParser.parse(metadata) @@ -120,7 +123,9 @@ class TagParserTest { "TXXX:MUSICBRAINZ RELEASE TRACK ID" to listOf("track-id-123"), "TXXX:MUSICBRAINZ ALBUM ID" to listOf("album-id-456"), "TXXX:MUSICBRAINZ ARTIST ID" to listOf("artist-id-789"), - "TXXX:MUSICBRAINZ ALBUM ARTIST ID" to listOf("album-artist-id-012"))) + "TXXX:MUSICBRAINZ ALBUM ARTIST ID" to listOf("album-artist-id-012"), + ) + ) val tags = tagParser.parse(metadata) @@ -137,7 +142,9 @@ class TagParserTest { xiphTags = mapOf( "REPLAYGAIN_TRACK_GAIN" to listOf("-3.5 dB"), - "REPLAYGAIN_ALBUM_GAIN" to listOf("-2.1 dB"))) + "REPLAYGAIN_ALBUM_GAIN" to listOf("-2.1 dB"), + ) + ) val tags = tagParser.parse(metadata) @@ -153,7 +160,7 @@ class TagParserTest { durationMs: Long = 1000, bitrateKbps: Int = 320, sampleRateHz: Int = 44100, - mimeType: String = "audio/mpeg" + mimeType: String = "audio/mpeg", ): Metadata { val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt index 6eef3a43d..e7a68f96d 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagParsingEdgeCasesTest.kt @@ -66,7 +66,9 @@ class TagParsingEdgeCasesTest { "TRCK" to listOf("not-a-number"), "TPOS" to listOf("also-not-a-number"), "TYER" to listOf("invalid-year"), - "REPLAYGAIN_TRACK_GAIN" to listOf("not-a-float dB"))) + "REPLAYGAIN_TRACK_GAIN" to listOf("not-a-float dB"), + ) + ) val parsedTags = tagParser.parse(metadata) // Verify all numeric fields are null when given invalid values @@ -83,7 +85,8 @@ class TagParsingEdgeCasesTest { createTestMetadata( id3v2Tags = mapOf("TIT2" to listOf("ID3 Title"), "TALB" to listOf("ID3 Album")), mp4Tags = mapOf("©nam" to listOf("MP4 Title"), "©alb" to listOf("MP4 Album")), - xiphTags = mapOf("TITLE" to listOf("Xiph Title"), "ALBUM" to listOf("Xiph Album"))) + xiphTags = mapOf("TITLE" to listOf("Xiph Title"), "ALBUM" to listOf("Xiph Album")), + ) // Individual field extraction assertEquals("Xiph Title", metadata.name()) @@ -105,11 +108,13 @@ class TagParsingEdgeCasesTest { mapOf( "©nam" to listOf("MP4 Title") // No album in MP4 - ), + ), xiphTags = mapOf( // No title in Xiph - "ALBUM" to listOf("Xiph Album"))) + "ALBUM" to listOf("Xiph Album") + ), + ) // Individual field extraction assertEquals("MP4 Title", metadata.name()) // Xiph missing, falls back to MP4 @@ -134,7 +139,8 @@ class TagParsingEdgeCasesTest { // Case 2: Compilation flag with explicit album artist metadata = createTestMetadata( - id3v2Tags = mapOf("TCMP" to listOf("1"), "TPE2" to listOf("Custom Album Artist"))) + id3v2Tags = mapOf("TCMP" to listOf("1"), "TPE2" to listOf("Custom Album Artist")) + ) tags = tagParser.parse(metadata) assertEquals(listOf("Custom Album Artist"), tags.albumArtistNames) assertEquals(listOf("compilation"), tags.releaseTypes) @@ -142,8 +148,8 @@ class TagParsingEdgeCasesTest { // Case 3: Compilation flag with explicit release type metadata = createTestMetadata( - id3v2Tags = - mapOf("TCMP" to listOf("1"), "TXXX:RELEASETYPE" to listOf("soundtrack"))) + id3v2Tags = mapOf("TCMP" to listOf("1"), "TXXX:RELEASETYPE" to listOf("soundtrack")) + ) tags = tagParser.parse(metadata) assertEquals(listOf("Various Artists"), tags.albumArtistNames) assertEquals(listOf("soundtrack"), tags.releaseTypes) @@ -156,7 +162,8 @@ class TagParsingEdgeCasesTest { // Non-numeric characters filtered out var metadata = createTestMetadata( - xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("+2.5 dB some text"))) + xiphTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("+2.5 dB some text")) + ) assertEquals(2.5f, metadata.replayGainTrackAdjustment()) // Zero values filtered @@ -186,8 +193,10 @@ class TagParsingEdgeCasesTest { createTestMetadata( id3v2Tags = mapOf( - "TYER" to listOf("2018"), "TDAT" to listOf("0315") // March 15 - )) + "TYER" to listOf("2018"), + "TDAT" to listOf("0315"), // March 15 + ) + ) assertEquals("2018-03-15", metadata.date().toString()) // Year, date and time @@ -197,8 +206,9 @@ class TagParsingEdgeCasesTest { mapOf( "TYER" to listOf("2018"), "TDAT" to listOf("0315"), // March 15 - "TIME" to listOf("1422") // 14:22 - )) + "TIME" to listOf("1422"), // 14:22 + ) + ) assertEquals("2018-03-15T14:22Z", metadata.date().toString()) // Original year @@ -212,7 +222,9 @@ class TagParsingEdgeCasesTest { mapOf( "TYER" to listOf("2018"), "TDAT" to listOf("invalid"), - "TIME" to listOf("invalid"))) + "TIME" to listOf("invalid"), + ) + ) assertEquals("2018", metadata.date().toString()) // Non-numeric date components @@ -228,7 +240,7 @@ class TagParsingEdgeCasesTest { durationMs: Long = 1000, bitrateKbps: Int = 320, sampleRateHz: Int = 44100, - mimeType: String = "audio/mpeg" + mimeType: String = "audio/mpeg", ): Metadata { val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) diff --git a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagUtilTest.kt b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagUtilTest.kt index bb6f1be08..558a7f53a 100644 --- a/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagUtilTest.kt +++ b/musikr/src/test/java/org/oxycblt/musikr/tag/parse/TagUtilTest.kt @@ -73,7 +73,9 @@ class TagUtilTest { @Test fun correctWhitespace_listOopsAllWhitespace() { assertEquals( - listOf("tcp phagocyte"), listOf(" ", "", " tcp phagocyte").correctWhitespace()) + listOf("tcp phagocyte"), + listOf(" ", "", " tcp phagocyte").correctWhitespace(), + ) } @Test @@ -117,14 +119,16 @@ class TagUtilTest { fun parseId3v2Genre_multi() { assertEquals( listOf("Post-Rock", "Shoegaze", "Glitch"), - listOf("Post-Rock", "Shoegaze", "Glitch").parseId3GenreNames()) + listOf("Post-Rock", "Shoegaze", "Glitch").parseId3GenreNames(), + ) } @Test fun parseId3v2Genre_multiId3v1() { assertEquals( listOf("Post-Rock", "Shoegaze", "Glitch"), - listOf("176", "178", "Glitch").parseId3GenreNames()) + listOf("176", "178", "Glitch").parseId3GenreNames(), + ) } @Test @@ -136,7 +140,8 @@ class TagUtilTest { fun parseId3v2Genre_singleId3v23() { assertEquals( listOf("Post-Rock", "Shoegaze", "Remix", "Cover", "Glitch"), - listOf("(176)(178)(RX)(CR)Glitch").parseId3GenreNames()) + listOf("(176)(178)(RX)(CR)Glitch").parseId3GenreNames(), + ) } @Test