all: cleanup code

Clean up code and fits a bunch of miscellaneous issues.
This commit is contained in:
OxygenCobalt
2021-11-24 20:22:30 -07:00
parent 6b54d4b783
commit 4ccaa7c4bb
51 changed files with 192 additions and 289 deletions
@@ -24,7 +24,7 @@ import coil.ImageLoaderFactory
import coil.request.CachePolicy
import org.oxycblt.auxio.coil.AlbumArtFetcher
import org.oxycblt.auxio.coil.ArtistImageFetcher
import org.oxycblt.auxio.coil.CrossfadeTransition
import org.oxycblt.auxio.coil.ErrorCrossfadeFactory
import org.oxycblt.auxio.coil.GenreImageFetcher
import org.oxycblt.auxio.coil.MusicKeyer
import org.oxycblt.auxio.settings.SettingsManager
@@ -48,7 +48,7 @@ class AuxioApp : Application(), ImageLoaderFactory {
add(GenreImageFetcher.Factory())
add(MusicKeyer())
}
.transitionFactory(CrossfadeTransition.Factory())
.transitionFactory(ErrorCrossfadeFactory())
.diskCachePolicy(CachePolicy.DISABLED) // Not downloading anything, so no disk-caching
.build()
}
@@ -40,6 +40,8 @@ import org.oxycblt.auxio.util.logD
/**
* A wrapper around the home fragment that shows the playback fragment and controls
* the more high-level navigation features.
* @author OxygenCobalt
* TODO: Handle backnav with playback view
*/
class MainFragment : Fragment(), PlaybackLayout.ActionCallback {
private val playbackModel: PlaybackViewModel by activityViewModels()
@@ -29,9 +29,18 @@ import org.oxycblt.auxio.util.logD
import java.io.ByteArrayInputStream
import java.io.InputStream
/**
* The base implementation for all image fetchers in Auxio.
* @author OxygenCobalt
*/
abstract class AuxioFetcher : Fetcher {
private val settingsManager = SettingsManager.getInstance()
/**
* Fetch the artwork of an [album].
* This call respects user configuration and has proper redundancy in the case that
* an API fails to load.
*/
protected suspend fun fetchArt(context: Context, album: Album): InputStream? {
if (!settingsManager.showCovers) {
return null
@@ -44,62 +53,14 @@ abstract class AuxioFetcher : Fetcher {
}
}
/**
* Create a mosaic image from multiple streams of image data, Code adapted from Phonograph
* https://github.com/kabouzeid/Phonograph
*/
protected fun createMosaic(context: Context, streams: List<InputStream>): FetchResult? {
if (streams.size < 4) {
return streams.getOrNull(0)?.let { stream ->
return SourceResult(
source = ImageSource(stream.source().buffer(), context),
mimeType = null,
dataSource = DataSource.DISK
)
}
@Suppress("BlockingMethodInNonBlockingContext")
private suspend fun fetchMediaStoreCovers(context: Context, data: Album): InputStream? {
val uri = data.id.toAlbumArtURI()
// Eliminate any chance that this blocking call might mess up the cancellation process
return withContext(Dispatchers.IO) {
context.contentResolver.openInputStream(uri)
}
// Use a fixed 512x512 canvas for the mosaics. Preferably we would adapt this mosaic to
// target ImageView size, but Coil seems to start image loading before we can even get
// a width/height for the view, making that impractical.
val mosaicBitmap = Bitmap.createBitmap(
MOSAIC_BITMAP_SIZE, MOSAIC_BITMAP_SIZE, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(mosaicBitmap)
var x = 0
var y = 0
// For each stream, create a bitmap scaled to 1/4th of the mosaics combined size
// and place it on a corner of the canvas.
for (stream in streams) {
if (y == MOSAIC_BITMAP_SIZE) {
break
}
val bitmap = Bitmap.createScaledBitmap(
BitmapFactory.decodeStream(stream),
MOSAIC_BITMAP_INCREMENT,
MOSAIC_BITMAP_INCREMENT,
true
)
canvas.drawBitmap(bitmap, x.toFloat(), y.toFloat(), null)
x += MOSAIC_BITMAP_INCREMENT
if (x == MOSAIC_BITMAP_SIZE) {
x = 0
y += MOSAIC_BITMAP_INCREMENT
}
}
return DrawableResult(
drawable = mosaicBitmap.toDrawable(context.resources),
isSampled = false,
dataSource = DataSource.DISK
)
}
private suspend fun fetchQualityCovers(context: Context, album: Album): InputStream? {
@@ -139,22 +100,12 @@ abstract class AuxioFetcher : Fetcher {
return null
}
@Suppress("BlockingMethodInNonBlockingContext")
private suspend fun fetchMediaStoreCovers(context: Context, data: Album): InputStream? {
val uri = data.id.toAlbumArtURI()
// Eliminate any chance that this blocking call might mess up the cancellation process
return withContext(Dispatchers.IO) {
context.contentResolver.openInputStream(uri)
}
}
private suspend fun fetchAospMetadataCovers(context: Context, album: Album): InputStream? {
private fun fetchAospMetadataCovers(context: Context, album: Album): InputStream? {
val extractor = MediaMetadataRetriever()
extractor.use { ext ->
// To be safe, just make sure that this blocking call is wrapped so it doesn't
// cause problems
// This call is time-consuming but it also doesn't seem to hold up the main thread,
// so it's probably fine not to wrap it.
ext.setDataSource(context, album.songs[0].id.toURI())
// Get the embedded picture from MediaMetadataRetriever, which will return a full
@@ -244,6 +195,64 @@ abstract class AuxioFetcher : Fetcher {
return stream
}
/**
* Create a mosaic image from multiple streams of image data, Code adapted from Phonograph
* https://github.com/kabouzeid/Phonograph
*/
protected fun createMosaic(context: Context, streams: List<InputStream>): FetchResult? {
if (streams.size < 4) {
return streams.getOrNull(0)?.let { stream ->
return SourceResult(
source = ImageSource(stream.source().buffer(), context),
mimeType = null,
dataSource = DataSource.DISK
)
}
}
// Use a fixed 512x512 canvas for the mosaics. Preferably we would adapt this mosaic to
// target ImageView size, but Coil seems to start image loading before we can even get
// a width/height for the view, making that impractical.
val mosaicBitmap = Bitmap.createBitmap(
MOSAIC_BITMAP_SIZE, MOSAIC_BITMAP_SIZE, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(mosaicBitmap)
var x = 0
var y = 0
// For each stream, create a bitmap scaled to 1/4th of the mosaics combined size
// and place it on a corner of the canvas.
for (stream in streams) {
if (y == MOSAIC_BITMAP_SIZE) {
break
}
val bitmap = Bitmap.createScaledBitmap(
BitmapFactory.decodeStream(stream),
MOSAIC_BITMAP_INCREMENT,
MOSAIC_BITMAP_INCREMENT,
true
)
canvas.drawBitmap(bitmap, x.toFloat(), y.toFloat(), null)
x += MOSAIC_BITMAP_INCREMENT
if (x == MOSAIC_BITMAP_SIZE) {
x = 0
y += MOSAIC_BITMAP_INCREMENT
}
}
return DrawableResult(
drawable = mosaicBitmap.toDrawable(context.resources),
isSampled = false,
dataSource = DataSource.DISK
)
}
companion object {
private const val MOSAIC_BITMAP_SIZE = 512
private const val MOSAIC_BITMAP_INCREMENT = 256
@@ -1,88 +0,0 @@
package org.oxycblt.auxio.coil
import android.widget.ImageView
import coil.decode.DataSource
import coil.drawable.CrossfadeDrawable
import coil.request.ErrorResult
import coil.request.ImageResult
import coil.request.SuccessResult
import coil.size.Scale
import coil.transition.Transition
import coil.transition.TransitionTarget
/**
* A modified variant of coil's CrossfadeTransition that actually animates error results.
* You know. Like it used to.
*
* @author Coil Team
*/
class CrossfadeTransition @JvmOverloads constructor(
private val target: TransitionTarget,
private val result: ImageResult,
private val durationMillis: Int = CrossfadeDrawable.DEFAULT_DURATION,
private val preferExactIntrinsicSize: Boolean = false
) : Transition {
init {
require(durationMillis > 0) { "durationMillis must be > 0." }
}
override fun transition() {
val drawable = CrossfadeDrawable(
start = target.drawable,
end = result.drawable,
scale = (target.view as? ImageView)?.scale ?: Scale.FIT,
durationMillis = durationMillis,
fadeStart = !(result is SuccessResult && result.isPlaceholderCached),
preferExactIntrinsicSize = preferExactIntrinsicSize
)
when (result) {
is SuccessResult -> target.onSuccess(drawable)
is ErrorResult -> target.onError(drawable)
}
}
val ImageView.scale: Scale
get() = when (scaleType) {
ImageView.ScaleType.FIT_START, ImageView.ScaleType.FIT_CENTER,
ImageView.ScaleType.FIT_END, ImageView.ScaleType.CENTER_INSIDE -> Scale.FIT
else -> Scale.FILL
}
class Factory @JvmOverloads constructor(
val durationMillis: Int = CrossfadeDrawable.DEFAULT_DURATION,
val preferExactIntrinsicSize: Boolean = false
) : Transition.Factory {
init {
require(durationMillis > 0) { "durationMillis must be > 0." }
}
override fun create(target: TransitionTarget, result: ImageResult): Transition {
// !!!!!!!!!!!!!! MODIFICATION !!!!!!!!!!!!!!
// Remove the error check for this transition. Usually when something errors in
// Auxio it will stay erroring, so not crossfading on an error looks weird.
// Don't animate if the request was fulfilled by the memory cache.
if (result is SuccessResult && result.dataSource == DataSource.MEMORY_CACHE) {
return Transition.Factory.NONE.create(target, result)
}
return CrossfadeTransition(target, result, durationMillis, preferExactIntrinsicSize)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is Factory &&
durationMillis == other.durationMillis &&
preferExactIntrinsicSize == other.preferExactIntrinsicSize
}
override fun hashCode(): Int {
var result = durationMillis
result = 31 * result + preferExactIntrinsicSize.hashCode()
return result
}
}
}
@@ -0,0 +1,25 @@
package org.oxycblt.auxio.coil
import coil.decode.DataSource
import coil.drawable.CrossfadeDrawable
import coil.request.ImageResult
import coil.request.SuccessResult
import coil.transition.CrossfadeTransition
import coil.transition.Transition
import coil.transition.TransitionTarget
/**
* A copy of [CrossfadeTransition.Factory] that applies a transition to error results.
* You know. Like they used to.
* @author Coil Team
*/
class ErrorCrossfadeFactory : Transition.Factory {
override fun create(target: TransitionTarget, result: ImageResult): Transition {
// Don't animate if the request was fulfilled by the memory cache.
if (result is SuccessResult && result.dataSource == DataSource.MEMORY_CACHE) {
return Transition.Factory.NONE.create(target, result)
}
return CrossfadeTransition(target, result, CrossfadeDrawable.DEFAULT_DURATION, false)
}
}
@@ -35,8 +35,7 @@ import org.oxycblt.auxio.music.Song
import kotlin.math.min
/**
* Fetcher that returns the album art for a given [Album]. Handles settings on whether to use
* quality covers or not.
* Fetcher that returns the album art for a given [Album] or [Song], depending on the factory used.
* @author OxygenCobalt
*/
class AlbumArtFetcher private constructor(
@@ -54,18 +53,22 @@ class AlbumArtFetcher private constructor(
}
class SongFactory : Fetcher.Factory<Song> {
override fun create(data: Song, options: Options, imageLoader: ImageLoader): Fetcher? {
override fun create(data: Song, options: Options, imageLoader: ImageLoader): Fetcher {
return AlbumArtFetcher(options.context, data.album)
}
}
class AlbumFactory : Fetcher.Factory<Album> {
override fun create(data: Album, options: Options, imageLoader: ImageLoader): Fetcher? {
override fun create(data: Album, options: Options, imageLoader: ImageLoader): Fetcher {
return AlbumArtFetcher(options.context, data)
}
}
}
/**
* Fetcher that fetches the image for an [Artist]
* @author OxygenCobalt
*/
class ArtistImageFetcher private constructor(
private val context: Context,
private val artist: Artist
@@ -79,12 +82,16 @@ class ArtistImageFetcher private constructor(
}
class Factory : Fetcher.Factory<Artist> {
override fun create(data: Artist, options: Options, imageLoader: ImageLoader): Fetcher? {
override fun create(data: Artist, options: Options, imageLoader: ImageLoader): Fetcher {
return ArtistImageFetcher(options.context, data)
}
}
}
/**
* Fetcher that fetches the image for a [Genre]
* @author OxygenCobalt
*/
class GenreImageFetcher private constructor(
private val context: Context,
private val genre: Genre
@@ -99,7 +106,7 @@ class GenreImageFetcher private constructor(
}
class Factory : Fetcher.Factory<Genre> {
override fun create(data: Genre, options: Options, imageLoader: ImageLoader): Fetcher? {
override fun create(data: Genre, options: Options, imageLoader: ImageLoader): Fetcher {
return GenreImageFetcher(options.context, data)
}
}
@@ -3,12 +3,17 @@ package org.oxycblt.auxio.coil
import coil.key.Keyer
import coil.request.Options
import org.oxycblt.auxio.music.Music
import org.oxycblt.auxio.music.Song
/**
* A basic keyer for music data.
*/
class MusicKeyer : Keyer<Music> {
override fun key(data: Music, options: Options): String? {
return "${data::class.simpleName}: ${data.id}"
override fun key(data: Music, options: Options): String {
return if (data is Song) {
key(data.album, options)
} else {
"${data::class.simpleName}: ${data.id}"
}
}
}
@@ -20,6 +20,7 @@ import org.oxycblt.auxio.ui.EdgeAppBarLayout
* recyclerview is scrolled beyond it's first item (a.k.a the header). This is used instead of
* CollapsingToolbarLayout since that thing is a mess with crippling bugs and state issues.
* This just works.
* @author OxygenCobalt
*/
class DetailAppBarLayout @JvmOverloads constructor(
context: Context,
@@ -72,7 +72,7 @@ class ExcludedDialog : LifecycleDialog() {
binding.excludedRecycler.adapter = adapter
// Now that the dialog exists, we get the view manually when the dialog is shown
// and override its click-listener so that the dialog does not auto-dismiss when we
// and override its click listener so that the dialog does not auto-dismiss when we
// click the "Add"/"Save" buttons. This prevents the dialog from disappearing in the former
// and the app from crashing in the latter.
val dialog = requireDialog() as AlertDialog
@@ -46,7 +46,7 @@ class ExcludedEntryAdapter(
@SuppressLint("NotifyDataSetChanged")
fun submitList(newPaths: MutableList<String>) {
paths = newPaths
notifyDataSetChanged() // TODO: Consider using remove/addition
notifyDataSetChanged()
}
inner class ViewHolder(
@@ -26,7 +26,7 @@ import androidx.core.view.postDelayed
import androidx.core.view.updatePadding
import com.google.android.material.color.MaterialColors
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.ViewCompactPlaybackBinding
import org.oxycblt.auxio.databinding.ViewPlaybackBarBinding
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.util.inflater
import org.oxycblt.auxio.util.resolveAttr
@@ -34,14 +34,14 @@ import org.oxycblt.auxio.util.systemBarsCompat
/**
* A view displaying the playback state in a compact manner. This is only meant to be used
* by [PlaybackBarLayout].
* by [PlaybackLayout].
*/
class PlaybackBarView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = -1
) : ConstraintLayout(context, attrs, defStyleAttr) {
private val binding = ViewCompactPlaybackBinding.inflate(context.inflater, this, true)
private val binding = ViewPlaybackBarBinding.inflate(context.inflater, this, true)
private var mCallback: PlaybackLayout.ActionCallback? = null
init {
@@ -389,6 +389,11 @@ class PlaybackLayout @JvmOverloads constructor(
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
playbackBarView.clearCallback()
}
override fun onSaveInstanceState(): Parcelable = Bundle().apply {
putParcelable("superState", super.onSaveInstanceState())
putSerializable(
@@ -525,15 +530,21 @@ class PlaybackLayout @JvmOverloads constructor(
* Update the view transitions done when the panel slides up.
*/
private fun updatePanelTransition() {
contentView.alpha = min(1 - panelOffset, 1f)
val outAlpha = min(1 - panelOffset, 1f)
val inAlpha = max(panelOffset, 0f)
contentView.apply {
alpha = outAlpha
isInvisible = alpha == 0f
}
// Slowly reduce the elevation as we slide up, eventually resulting in a neutral color
// instead of an elevated one when fully expanded.
(playbackContainerView.background as MaterialShapeDrawable).alpha = (min(1 - panelOffset, 1f) * 255).toInt()
(playbackContainerView.background as MaterialShapeDrawable).alpha = (outAlpha * 255).toInt()
// Fade out our bar view as we slide up
playbackBarView.apply {
alpha = min(1 - panelOffset, 1f)
alpha = outAlpha
isInvisible = alpha == 0f
// When edge-to-edge is enabled, the playback bar will not fade out into the
@@ -546,7 +557,6 @@ class PlaybackLayout @JvmOverloads constructor(
// of the playback view. This seems to be the least obtrusive way to do this.
lastInsets?.systemBarsCompat?.let { bars ->
val params = layoutParams as FrameLayout.LayoutParams
val oldTopMargin = params.topMargin
params.setMargins(
@@ -565,7 +575,7 @@ class PlaybackLayout @JvmOverloads constructor(
// Fade in our panel as we slide up
playbackPanelView.apply {
alpha = max(panelOffset, 0f)
alpha = inAlpha
isInvisible = alpha == 0f
}
}
@@ -34,7 +34,6 @@ import coil.imageLoader
import coil.request.ImageRequest
import coil.transform.RoundedCornersTransformation
import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.Song
import org.oxycblt.auxio.playback.state.PlaybackStateManager
import org.oxycblt.auxio.util.isLandscape