From fd09626577abe70808039b9a4d821d715aeed7bf Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 19 Apr 2026 18:50:08 -0600 Subject: [PATCH] image: deslop stack fetcher --- .../java/org/oxycblt/auxio/image/CoverView.kt | 88 ++--- .../oxycblt/auxio/image/coil/CoilModule.kt | 4 +- .../auxio/image/coil/ComposeCoverUtils.kt | 2 +- .../image/coil/CoverCompositionFetcher.kt | 82 +++++ .../auxio/image/coil/GalleryComposeFetcher.kt | 2 +- .../image/coil/SmatteringComposeFetcher.kt | 2 +- .../auxio/image/coil/StackComposeFetcher.kt | 314 ------------------ .../image/coil/StackCompositionFetcher.kt | 187 +++++++++++ 8 files changed, 319 insertions(+), 362 deletions(-) create mode 100644 app/src/main/java/org/oxycblt/auxio/image/coil/CoverCompositionFetcher.kt delete mode 100644 app/src/main/java/org/oxycblt/auxio/image/coil/StackComposeFetcher.kt create mode 100644 app/src/main/java/org/oxycblt/auxio/image/coil/StackCompositionFetcher.kt 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 f30d2fca8..28d08e557 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/CoverView.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/CoverView.kt @@ -28,6 +28,7 @@ import android.graphics.RectF import android.graphics.drawable.AnimationDrawable import android.graphics.drawable.Drawable import android.util.AttributeSet +import android.util.Size import android.view.Gravity import android.widget.FrameLayout import android.widget.ImageView @@ -60,7 +61,7 @@ import org.oxycblt.auxio.image.coil.GalleryCoverCollection import org.oxycblt.auxio.image.coil.RoundedRectTransformation import org.oxycblt.auxio.image.coil.SmatteringCoverCollection import org.oxycblt.auxio.image.coil.SquareCropTransformation -import org.oxycblt.auxio.image.coil.StackCoverCollection +import org.oxycblt.auxio.image.coil.StackCoverComposition import org.oxycblt.auxio.ui.Effect import org.oxycblt.auxio.ui.Spatial import org.oxycblt.auxio.ui.UISettings @@ -388,10 +389,10 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr // stack of vinyl. val uidSeed = artist.uid.toString().hashCode() bindImpl( - { cornerBounds -> + { size -> SmatteringCoverCollection( artist.covers, - responsiveCornerSize(cornerBounds), + responsiveCornerRatio(size), seededFanAngle(uidSeed), seededTiltAngle(uidSeed), seededZOrder(uidSeed), @@ -413,10 +414,10 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr // Genres are organized like a "gallery" of various covers that overlap eachother, // as if they were framed on a wall. bindImpl( - { cornerBounds -> + { size -> GalleryCoverCollection( genre.covers, - responsiveCornerSize(cornerBounds), + responsiveCornerRatio(size), seededZOrder(genre.uid.toString().hashCode()), backgroundColor(), ) @@ -435,11 +436,11 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr // Playlists are organized in a straight diagonal stack to give the appearance of an // "orderly" pile of covers. bindImpl( - { cornerBounds -> - StackCoverCollection( + { size -> + StackCoverComposition( playlist.covers, - responsiveCornerSize(cornerBounds), - seededZOrder(playlist.uid.toString().hashCode()), + responsiveCornerRatio(size), + playlist.uid.toString().hashCode(), backgroundColor(), ) }, @@ -463,11 +464,11 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr uidSeed: Int = songs.hashCode(), ) = bindImpl( - { cornerBounds -> - StackCoverCollection( + { size -> + StackCoverComposition( CoverCollection.from(songs.mapNotNull { it.cover }), - responsiveCornerSize(cornerBounds), - seededZOrder(uidSeed), + responsiveCornerRatio(size), + uidSeed, backgroundColor(), ) }, @@ -477,7 +478,7 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr ) private fun bindImpl( - img: (RectF) -> Any?, + img: (Size) -> Any?, desc: String, @DrawableRes errorRes: Int, shapeAppearanceModel: ShapeAppearanceModel, @@ -489,38 +490,38 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr } private fun bindWait( - img: (RectF) -> Any?, + img: (Size) -> Any?, desc: String, @DrawableRes errorRes: Int, shapeAppearanceModel: ShapeAppearanceModel, ) { // for some reason randomly corner radii started breaking on menus // fix this by waiting until we are laid out instead - val cornerBounds = resolveCurrentBoundsForCorners() - if (cornerBounds != null) { - bindWithCorners(img, desc, errorRes, cornerBounds, shapeAppearanceModel) + val size = resolveSize() + if (size != null) { + bindSized(img, desc, errorRes, size, shapeAppearanceModel) } else { doOnLayout { bindImpl(img, desc, errorRes, shapeAppearanceModel) } } } - private fun bindWithCorners( - img: (RectF) -> Any?, + private fun bindSized( + img: (Size) -> Any?, desc: String, @DrawableRes errorRes: Int, - cornerBounds: RectF, + size: Size, shapeAppearanceModel: ShapeAppearanceModel, ) { val request = ImageRequest.Builder(context) - .data(img(cornerBounds)) + .data(img(size)) .error( StyledDrawable(context, context.getDrawableCompat(errorRes), iconSize).asImage() ) .target(image) - val cornerRadius = - cornerBounds.let { shapeAppearanceModel.topLeftCornerSize.getCornerSize(it) } + val bounds = RectF(0f, 0f, size.width.toFloat(), size.height.toFloat()) + val cornerRadius = shapeAppearanceModel.topLeftCornerSize.getCornerSize(bounds) val cornersTransformation = RoundedRectTransformation(cornerRadius) val circular = shapeAppearanceModel.topLeftCornerSize is RelativeCornerSize if (circular || imageSettings.forceSquareCovers) { @@ -535,19 +536,23 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr contentDescription = desc } - private fun responsiveCornerSize(cornerBounds: RectF): Float { + private fun responsiveCornerRatio(size: Size): Float { if (!uiSettings.roundMode) { return 0f } - val cornerRadiusPx = squareishShapeAppearance.topLeftCornerSize.getCornerSize(cornerBounds) - if (cornerRadiusPx <= 0f) { + + val bounds = RectF(0f, 0f, size.width.toFloat(), size.height.toFloat()) + val cornerRadius = squareishShapeAppearance.topLeftCornerSize.getCornerSize(bounds) + if (cornerRadius <= 0f) { return 0f } - val minSize = min(cornerBounds.width(), cornerBounds.height()) + val minSize = min(size.width, size.height) if (minSize <= 0f) { + // edge case since i dont want to crash if insane android layout stuff happens + // and somehow makes our sizes zeroable return 0f } - return cornerRadiusPx / minSize + return cornerRadius / minSize } private fun seededZOrder(uidSeed: Int): List { @@ -568,22 +573,19 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr private fun backgroundColor(): Int = context.getColorCompat(R.color.sel_cover_bg).defaultColor - private fun resolveCurrentBoundsForCorners(): RectF? { - val widthPx = firstNonZeroOrNull(width, measuredWidth, layoutParams?.width) - val heightPx = firstNonZeroOrNull(height, measuredHeight, layoutParams?.height) - if (widthPx <= 0 || heightPx <= 0) { + private fun resolveSize(): Size? { + // just try all possible dimens, CoverView can be everywhere, even extremely annoying + // layouts that behave odd + val widthPx = + listOf(width, measuredWidth, layoutParams?.width).firstOrNull { it != null && it > 0 } + val heightPx = + listOf(height, measuredHeight, layoutParams?.height).firstOrNull { + it != null && it > 0 + } + if (widthPx == null || heightPx == null) { return null } - return RectF(0f, 0f, widthPx.toFloat(), heightPx.toFloat()) - } - - private fun firstNonZeroOrNull(vararg candidates: Int?): Int { - for (candidate in candidates) { - if (candidate != null && candidate > 0) { - return candidate - } - } - return 0 + return Size(widthPx, heightPx) } private fun updateShapeAppearance(to: ShapeAppearanceModel) { 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 73250c5be..47b2dfa9f 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 @@ -42,8 +42,8 @@ class CoilModule { galleryFetcherFactory: GalleryComposeFetcher.Factory, smatteringKeyer: SmatteringComposeFetcher.Keyer, smatteringFetcherFactory: SmatteringComposeFetcher.Factory, - stackKeyer: StackComposeFetcher.Keyer, - stackFetcherFactory: StackComposeFetcher.Factory, + stackKeyer: StackCompositionFetcher.Keyer, + stackFetcherFactory: StackCompositionFetcher.Factory, ) = ImageLoader.Builder(context) .components { diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/ComposeCoverUtils.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/ComposeCoverUtils.kt index bf5c5772a..2f2230aa5 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/coil/ComposeCoverUtils.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/ComposeCoverUtils.kt @@ -19,7 +19,7 @@ package org.oxycblt.auxio.image.coil internal object ComposeCoverDefaults { - const val CARD_SIZE_PERCENT = 0.60f + const val OVERLAP_PERCENT = 0.60f const val GAP_RATIO = 0.04f const val MIN_GAP_CORNER_RATIO = 0.35f const val MAX_CORNER_RATIO = 0.15f diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/CoverCompositionFetcher.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/CoverCompositionFetcher.kt new file mode 100644 index 000000000..2f8e76996 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/CoverCompositionFetcher.kt @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2026 Auxio Project + * CoverCompositionFetcher.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.image.coil + +import android.content.Context +import android.graphics.BitmapFactory +import androidx.core.graphics.drawable.toDrawable +import coil3.Bitmap +import coil3.asImage +import coil3.decode.DataSource +import coil3.fetch.FetchResult +import coil3.fetch.Fetcher +import coil3.fetch.ImageFetchResult +import coil3.size.Size +import coil3.size.pxOrElse +import kotlin.math.min +import kotlinx.coroutines.flow.asFlow +import kotlinx.coroutines.flow.mapNotNull +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import org.oxycblt.musikr.covers.CoverCollection + +interface CoverComposition { + val covers: CoverCollection +} + +abstract class CoverCompositionFetcher( + private val context: Context, + private val data: CoverComposition, + private val size: Size, +) : Fetcher { + final override suspend fun fetch(): FetchResult? { + val bitmaps = + data.covers.covers + .asFlow() + .mapNotNull { cover -> cover.open() } + .mapNotNull { stream -> BitmapFactory.decodeStream(stream).also { stream.close() } } + .take(4) + .toList() + if (bitmaps.size < 4) { + val first = bitmaps.firstOrNull() ?: return null + return ImageFetchResult( + image = first.toDrawable(context.resources).asImage(), + isSampled = true, + dataSource = DataSource.DISK, + ) + } + + val squareSize = + min(size.width.pxOrElse { 512 }, size.height.pxOrElse { 512 }).coerceAtLeast(1) + return ImageFetchResult( + image = compose(bitmaps, squareSize).toDrawable(context.resources).asImage(), + isSampled = true, + dataSource = DataSource.DISK, + ) + } + + /** + * Compose the given input cover data into a single FetchResult containing a composed cover + * bitmap. + * + * @param bitmaps The bitmaps to use. + * @param size The size of the square bitmap you should create. + */ + protected abstract fun compose(bitmaps: List, size: Int): Bitmap +} diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/GalleryComposeFetcher.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/GalleryComposeFetcher.kt index da3484654..f3c34bd6f 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/coil/GalleryComposeFetcher.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/GalleryComposeFetcher.kt @@ -158,7 +158,7 @@ private constructor( } val totalSize = config.outputSizePx.toFloat() - val cardSize = totalSize * ComposeCoverDefaults.CARD_SIZE_PERCENT + val cardSize = totalSize * ComposeCoverDefaults.OVERLAP_PERCENT val inset = 0f val cornerRadiusPx = if (config.cornerRadiusPx > 0f) { diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/SmatteringComposeFetcher.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/SmatteringComposeFetcher.kt index 2514da2a7..b9433f263 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/coil/SmatteringComposeFetcher.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/SmatteringComposeFetcher.kt @@ -167,7 +167,7 @@ private constructor( } val totalSize = config.outputSizePx.toFloat() - val cardSize = totalSize * ComposeCoverDefaults.CARD_SIZE_PERCENT + val cardSize = totalSize * ComposeCoverDefaults.OVERLAP_PERCENT val inset = 0f val outset = totalSize * OUTSET_PERCENT val cornerRadiusPx = diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/StackComposeFetcher.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/StackComposeFetcher.kt deleted file mode 100644 index 57c64c7d2..000000000 --- a/app/src/main/java/org/oxycblt/auxio/image/coil/StackComposeFetcher.kt +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2024 Auxio Project - * StackComposeFetcher.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.image.coil - -import android.content.Context -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.graphics.Canvas -import android.graphics.Paint -import android.graphics.Path -import android.graphics.PorterDuff -import android.graphics.PorterDuffXfermode -import android.graphics.Rect -import android.graphics.RectF -import androidx.annotation.ColorInt -import androidx.core.graphics.createBitmap -import androidx.core.graphics.drawable.toDrawable -import coil3.ImageLoader -import coil3.asImage -import coil3.decode.DataSource -import coil3.decode.ImageSource -import coil3.fetch.FetchResult -import coil3.fetch.Fetcher -import coil3.fetch.ImageFetchResult -import coil3.fetch.SourceFetchResult -import coil3.key.Keyer as CoilKeyer -import coil3.request.Options -import coil3.size.Size -import coil3.size.pxOrElse -import java.io.InputStream -import javax.inject.Inject -import kotlin.math.max -import kotlin.math.min -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.asFlow -import kotlinx.coroutines.flow.mapNotNull -import kotlinx.coroutines.flow.take -import kotlinx.coroutines.flow.toList -import kotlinx.coroutines.withContext -import okio.FileSystem -import okio.buffer -import okio.source -import org.oxycblt.musikr.covers.CoverCollection - -data class StackCoverCollection( - val covers: CoverCollection, - val cornerRadiusRatio: Float, - val zOrder: List, - @ColorInt val backgroundColor: Int, -) - -class StackComposeFetcher -private constructor( - private val context: Context, - private val data: StackCoverCollection, - private val size: Size, -) : Fetcher { - override suspend fun fetch(): FetchResult? { - val streams = data.covers.covers.asFlow().mapNotNull { it.open() }.take(4).toList() - if (streams.size == 4) { - return createStack(streams, size).also { - withContext(Dispatchers.IO) { streams.forEach(InputStream::close) } - } - } - - val first = streams.firstOrNull() ?: return null - - withContext(Dispatchers.IO) { - for (i in 1 until streams.size) { - streams[i].close() - } - } - - return SourceFetchResult( - source = ImageSource(first.source().buffer(), FileSystem.SYSTEM, null), - mimeType = null, - dataSource = DataSource.DISK, - ) - } - - private fun createStack(streams: List, size: Size): FetchResult? { - val outputSize = size.stackSize() - val bitmaps = streams.mapNotNull { BitmapFactory.decodeStream(it) } - if (bitmaps.size != streams.size) { - return null - } - val cornerRadiusPx = outputSize * data.cornerRadiusRatio - val stackBitmap = - StackGenerator.generate( - bitmaps, - StackGenerator.Config( - outputSizePx = outputSize, - gapWidthPx = outputSize * ComposeCoverDefaults.GAP_RATIO, - cornerRadiusPx = cornerRadiusPx, - backgroundColor = data.backgroundColor, - zOrder = data.zOrder.validatedZOrder(), - ), - ) - - return ImageFetchResult( - image = stackBitmap.toDrawable(context.resources).asImage(), - isSampled = true, - dataSource = DataSource.DISK, - ) - } - - private fun Size.stackSize(): Int { - val widthPx = width.pxOrElse { 512 } - val heightPx = height.pxOrElse { 512 } - return min(widthPx, heightPx).coerceAtLeast(1) - } - - private object StackGenerator { - data class Config( - val outputSizePx: Int, - val gapWidthPx: Float, - val cornerRadiusPx: Float, - @ColorInt val backgroundColor: Int, - val zOrder: List = listOf(0, 1, 2, 3), - ) - - fun generate(sourceImages: List, config: Config): Bitmap { - if (sourceImages.size != 4) { - throw IllegalArgumentException("Stack requires exactly 4 images.") - } - - val result = createBitmap(config.outputSizePx, config.outputSizePx) - val canvas = Canvas(result) - - canvas.drawColor(config.backgroundColor) - - val gapPaint = - Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = config.backgroundColor - style = Paint.Style.FILL - } - val imagePaint = - Paint(Paint.ANTI_ALIAS_FLAG).apply { - // Use the background color for the mask so anti-aliased edges blend - // toward it, avoiding dark/light fringing artifacts - color = config.backgroundColor - } - - val totalSize = config.outputSizePx.toFloat() - val inset = 0f - val contentSize = totalSize - val layoutCardSize = - (totalSize * ComposeCoverDefaults.CARD_SIZE_PERCENT).coerceAtMost(contentSize) - val drawCardSize = max(layoutCardSize, contentSize) - val expansion = drawCardSize - layoutCardSize - val availableSpan = (contentSize - layoutCardSize).coerceAtLeast(0f) - val lastIndex = sourceImages.lastIndex - val maxStep = - when { - lastIndex <= 0 -> 0f - lastIndex == 1 -> availableSpan - else -> availableSpan / (lastIndex - 1) - } - val step = maxStep - - val baseX = inset - val baseY = totalSize - inset - layoutCardSize - - val normalizedOrder = config.zOrder.validatedZOrder() - val cornerRadiusPx = - if (config.cornerRadiusPx > 0f) { - min(config.cornerRadiusPx, totalSize * ComposeCoverDefaults.MAX_CORNER_RATIO) - } else { - 0f - } - val gapWidthPx = - if (cornerRadiusPx > 0f) { - max( - config.gapWidthPx, - cornerRadiusPx * ComposeCoverDefaults.MIN_GAP_CORNER_RATIO, - ) - } else { - config.gapWidthPx - } - val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f) - - for (stackIndex in sourceImages.indices) { - val imageIndex = normalizedOrder.getOrElse(stackIndex) { stackIndex } - val bitmap = sourceImages[imageIndex] - - val offsetX = baseX + (stackIndex * step) - val offsetY = baseY - (stackIndex * step) - - val baseRect = - RectF( - offsetX, - offsetY - expansion, - offsetX + drawCardSize, - offsetY - expansion + drawCardSize, - ) - - val hasGap = stackIndex > 0 && gapWidthPx > 0f - val innerRect = RectF(baseRect) - if (hasGap) { - innerRect.left += gapWidthPx - innerRect.bottom -= gapWidthPx - } - - if (hasGap) { - val gapPath = - Path().apply { - addRoundRect( - baseRect, - floatArrayOf( - cornerRadiusPx, - cornerRadiusPx, - cornerRadiusPx, - cornerRadiusPx, - cornerRadiusPx, - cornerRadiusPx, - cornerRadiusPx, - cornerRadiusPx, - ), - Path.Direction.CW, - ) - } - canvas.drawPath(gapPath, gapPaint) - } - - if (innerRect.width() > 0 && innerRect.height() > 0) { - val savedLayer = canvas.saveLayer(innerRect, null) - val topLeftRadius = if (hasGap) innerRadius else cornerRadiusPx - val topRightRadius = cornerRadiusPx - val bottomRightRadius = if (hasGap) innerRadius else cornerRadiusPx - val bottomLeftRadius = if (hasGap) innerRadius else cornerRadiusPx - val maskPath = - Path().apply { - addRoundRect( - innerRect, - floatArrayOf( - topLeftRadius, - topLeftRadius, - topRightRadius, - topRightRadius, - bottomRightRadius, - bottomRightRadius, - bottomLeftRadius, - bottomLeftRadius, - ), - Path.Direction.CW, - ) - } - canvas.drawPath(maskPath, imagePaint) - - imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) - drawBitmapCover(canvas, bitmap, innerRect, imagePaint) - imagePaint.xfermode = null - - canvas.restoreToCount(savedLayer) - } - } - - return result - } - - private fun drawBitmapCover(canvas: Canvas, bitmap: Bitmap, dest: RectF, paint: Paint) { - val bitmapRatio = bitmap.width.toFloat() / bitmap.height.toFloat() - val destRatio = dest.width() / dest.height() - - val srcRect = Rect(0, 0, bitmap.width, bitmap.height) - - if (bitmapRatio > destRatio) { - val newWidth = (bitmap.height * destRatio).toInt() - val xOffset = (bitmap.width - newWidth) / 2 - srcRect.left = xOffset - srcRect.right = xOffset + newWidth - } else { - val newHeight = (bitmap.width / destRatio).toInt() - val yOffset = (bitmap.height - newHeight) / 2 - srcRect.top = yOffset - srcRect.bottom = yOffset + newHeight - } - - canvas.drawBitmap(bitmap, srcRect, dest, paint) - } - } - - class Factory @Inject constructor() : Fetcher.Factory { - override fun create( - data: StackCoverCollection, - options: Options, - imageLoader: ImageLoader, - ) = StackComposeFetcher(options.context, data, options.size) - } - - class Keyer @Inject constructor() : CoilKeyer { - override fun key(data: StackCoverCollection, options: Options): String { - val config = - "${data.cornerRadiusRatio}.${data.zOrder.joinToString(".")}.${data.backgroundColor}" - return "s:${data.covers.hashCode()}.${options.size.width}.${options.size.height}.$config" - } - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/image/coil/StackCompositionFetcher.kt b/app/src/main/java/org/oxycblt/auxio/image/coil/StackCompositionFetcher.kt new file mode 100644 index 000000000..3d74e8f1b --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/image/coil/StackCompositionFetcher.kt @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2024 Auxio Project + * StackCompositionFetcher.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.image.coil + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Path +import android.graphics.PorterDuff +import android.graphics.PorterDuffXfermode +import android.graphics.Rect +import android.graphics.RectF +import androidx.annotation.ColorInt +import androidx.core.graphics.createBitmap +import coil3.ImageLoader +import coil3.fetch.Fetcher +import coil3.key.Keyer as CoilKeyer +import coil3.request.Options +import coil3.size.Size +import javax.inject.Inject +import kotlin.math.max +import kotlin.math.min +import kotlin.random.Random +import org.oxycblt.musikr.covers.CoverCollection + +data class StackCoverComposition( + override val covers: CoverCollection, + val cornerRadiusRatio: Float, + val seed: Int, + @ColorInt val backgroundColor: Int, +) : CoverComposition + +/** + * A fetcher that stacks covers towards the upper left corner, creating an orderly feeling. Used for + * playlists. + * + * @author OxygenCobalt (Alexander Capehart) + */ +class StackCompositionFetcher +private constructor(context: Context, val data: StackCoverComposition, size: Size) : + CoverCompositionFetcher(context, data, size) { + private val gapPaint = + Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = data.backgroundColor + style = Paint.Style.FILL + } + + private val coverPaint = + Paint(Paint.ANTI_ALIAS_FLAG).apply { + // Use the background color for the mask so anti-aliased edges blend + // toward it, avoiding dark/light fringing artifacts + color = data.backgroundColor + } + + override fun compose(bitmaps: List, size: Int): Bitmap { + val sizef = size.toFloat() + val cornerRadius = + min(sizef * data.cornerRadiusRatio, sizef * ComposeCoverDefaults.MAX_CORNER_RATIO) + val gapWidthPx = + max( + sizef * ComposeCoverDefaults.GAP_RATIO, + cornerRadius * ComposeCoverDefaults.MIN_GAP_CORNER_RATIO, + ) + val zOrder = bitmaps.indices.toList().shuffled(Random(data.seed)) + val result = createBitmap(size, size) + val canvas = Canvas(result) + canvas.drawColor(data.backgroundColor) + // this is how much we will overlap covers onto eachother + val overlapSize = (sizef * ComposeCoverDefaults.OVERLAP_PERCENT).coerceAtMost(sizef) + // in turn this is the visible fraction we will get of a cover post-overlap + val visibleSize = sizef - overlapSize + // by dividing it by 2 you uhhhhhhhh...hm.... + // this is a hard-coded constant derived when i was deslopping gpt output knowing + // that we will always have 4 covers. specifically its the simplification of + // (lastIndex - 1) = (3 - 1) = 2. + // without this the covers just zoom around. very wired. + // this is why i dont want raw unreviewed ai slop in the codebase btw. lesson learned + val maxStep = visibleSize / 2 + // re-adjust our corner radius by the actual width of the gap + // (this makes corners proportional, i do this elsewhere and it looks nice) + val innerRadius = (cornerRadius - gapWidthPx).coerceAtLeast(0f) + for (stackIndex in bitmaps.indices) { + val imageIndex = zOrder[stackIndex] + val bitmap = bitmaps[imageIndex] + + // move diagonally, the more we move in x the more we should offset in y + val offsetX = stackIndex * maxStep + val offsetY = visibleSize - offsetX // x = y here + + // base frame for gap + val baseRect = + RectF( + offsetX, + offsetY - visibleSize, + offsetX + sizef, + offsetY - visibleSize + sizef, + ) + // possible adjusted frame + val coverRect = RectF(baseRect) + + val hasGap = stackIndex > 0 && gapWidthPx > 0f + if (hasGap) { + // draw gap + val gapPath = teardrop(baseRect, cornerRadius) + canvas.drawPath(gapPath, gapPaint) + // adjust cover accordingly to compensate + coverRect.left += gapWidthPx + coverRect.bottom -= gapWidthPx + } + + // draw cover on map + val savedLayer = canvas.saveLayer(coverRect, null) + val maskPath = teardrop(coverRect, if (hasGap) innerRadius else 0f) + canvas.drawPath(maskPath, coverPaint) + // special flags to avoid weird outlines + coverPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) + drawBitmapCover(canvas, bitmap, coverRect, coverPaint) + coverPaint.xfermode = null + canvas.restoreToCount(savedLayer) + } + + return result + } + + private fun teardrop(rect: RectF, radius: Float) = + Path().apply { + addRoundRect( + rect, + floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, radius, radius), + Path.Direction.CW, + ) + } + + private fun drawBitmapCover(canvas: Canvas, bitmap: Bitmap, dest: RectF, paint: Paint) { + val bitmapRatio = bitmap.width.toFloat() / bitmap.height.toFloat() + val destRatio = dest.width() / dest.height() + + val srcRect = Rect(0, 0, bitmap.width, bitmap.height) + + // crop the bitmap if it's not properly 1:1 + if (bitmapRatio > destRatio) { + val newWidth = (bitmap.height * destRatio).toInt() + val xOffset = (bitmap.width - newWidth) / 2 + srcRect.left = xOffset + srcRect.right = xOffset + newWidth + } else { + val newHeight = (bitmap.width / destRatio).toInt() + val yOffset = (bitmap.height - newHeight) / 2 + srcRect.top = yOffset + srcRect.bottom = yOffset + newHeight + } + + canvas.drawBitmap(bitmap, srcRect, dest, paint) + } + + class Factory @Inject constructor() : Fetcher.Factory { + override fun create( + data: StackCoverComposition, + options: Options, + imageLoader: ImageLoader, + ) = StackCompositionFetcher(options.context, data, options.size) + } + + class Keyer @Inject constructor() : CoilKeyer { + override fun key(data: StackCoverComposition, options: Options): String { + val config = "${data.cornerRadiusRatio}.${data.seed}.${data.backgroundColor}" + return "s:${data.covers.hashCode()}.${options.size.width}.${options.size.height}.$config" + } + } +}