image: add recognizable cover arrangements
This commit is contained in:
@@ -48,16 +48,17 @@ import coil3.request.transformations
|
|||||||
import coil3.util.CoilUtils
|
import coil3.util.CoilUtils
|
||||||
import com.google.android.material.R as MR
|
import com.google.android.material.R as MR
|
||||||
import com.google.android.material.shape.MaterialShapeDrawable
|
import com.google.android.material.shape.MaterialShapeDrawable
|
||||||
|
import com.google.android.material.shape.RelativeCornerSize
|
||||||
import com.google.android.material.shape.ShapeAppearanceModel
|
import com.google.android.material.shape.ShapeAppearanceModel
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import kotlin.math.min
|
|
||||||
import kotlin.random.Random
|
import kotlin.random.Random
|
||||||
import org.oxycblt.auxio.R
|
import org.oxycblt.auxio.R
|
||||||
import org.oxycblt.auxio.image.coil.Collage2Config
|
import org.oxycblt.auxio.image.coil.GalleryCoverCollection
|
||||||
import org.oxycblt.auxio.image.coil.RoundedRectTransformation
|
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.SquareCropTransformation
|
||||||
import org.oxycblt.auxio.image.coil.enableCoverCollectionCollage
|
import org.oxycblt.auxio.image.coil.StackCoverCollection
|
||||||
import org.oxycblt.auxio.ui.MaterialFader
|
import org.oxycblt.auxio.ui.MaterialFader
|
||||||
import org.oxycblt.auxio.ui.UISettings
|
import org.oxycblt.auxio.ui.UISettings
|
||||||
import org.oxycblt.auxio.util.getAttrColorCompat
|
import org.oxycblt.auxio.util.getAttrColorCompat
|
||||||
@@ -108,6 +109,9 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
private val indicatorMatrixDst = RectF()
|
private val indicatorMatrixDst = RectF()
|
||||||
|
|
||||||
private val shapeAppearance: ShapeAppearanceModel
|
private val shapeAppearance: ShapeAppearanceModel
|
||||||
|
private val circleShapeAppearance: ShapeAppearanceModel
|
||||||
|
private var currentShapeAppearance: ShapeAppearanceModel
|
||||||
|
private var circleCropEnabled = false
|
||||||
|
|
||||||
init {
|
init {
|
||||||
// Obtain some StyledImageView attributes to use later when theming the custom view.
|
// Obtain some StyledImageView attributes to use later when theming the custom view.
|
||||||
@@ -131,6 +135,9 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
} else {
|
} else {
|
||||||
ShapeAppearanceModel.builder().build()
|
ShapeAppearanceModel.builder().build()
|
||||||
}
|
}
|
||||||
|
circleShapeAppearance =
|
||||||
|
ShapeAppearanceModel.builder().setAllCornerSizes(RelativeCornerSize(0.5f)).build()
|
||||||
|
currentShapeAppearance = shapeAppearance
|
||||||
iconSize =
|
iconSize =
|
||||||
styledAttrs.getDimensionPixelSize(R.styleable.CoverView_iconSize, -1).takeIf {
|
styledAttrs.getDimensionPixelSize(R.styleable.CoverView_iconSize, -1).takeIf {
|
||||||
it != -1
|
it != -1
|
||||||
@@ -286,6 +293,9 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
|
|
||||||
// Add backgrounds to each child for visual consistency
|
// Add backgrounds to each child for visual consistency
|
||||||
for (child in children) {
|
for (child in children) {
|
||||||
|
if (child == selectionBadge) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
child.apply {
|
child.apply {
|
||||||
// If there are rounded corners, we want to make sure view content will be cropped
|
// If there are rounded corners, we want to make sure view content will be cropped
|
||||||
// with it.
|
// with it.
|
||||||
@@ -293,12 +303,21 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
background =
|
background =
|
||||||
MaterialShapeDrawable().apply {
|
MaterialShapeDrawable().apply {
|
||||||
fillColor = context.getColorCompat(R.color.sel_cover_bg)
|
fillColor = context.getColorCompat(R.color.sel_cover_bg)
|
||||||
shapeAppearanceModel = shapeAppearance
|
shapeAppearanceModel = currentShapeAppearance
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun updateShapeAppearance(useCircleCrop: Boolean) {
|
||||||
|
if (circleCropEnabled == useCircleCrop) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
circleCropEnabled = useCircleCrop
|
||||||
|
currentShapeAppearance = if (useCircleCrop) circleShapeAppearance else shapeAppearance
|
||||||
|
applyBackgroundsToChildren()
|
||||||
|
}
|
||||||
|
|
||||||
private fun invalidateRootAlpha() {
|
private fun invalidateRootAlpha() {
|
||||||
alpha = if (isEnabled || isSelected) 1f else 0.5f
|
alpha = if (isEnabled || isSelected) 1f else 0.5f
|
||||||
}
|
}
|
||||||
@@ -366,14 +385,24 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
*
|
*
|
||||||
* @param artist The [Artist] to bind to the view.
|
* @param artist The [Artist] to bind to the view.
|
||||||
*/
|
*/
|
||||||
fun bind(artist: Artist) =
|
fun bind(artist: Artist) {
|
||||||
|
// For artists we both engage in circle cropping but also arrange them
|
||||||
|
// in a "smattering" of random rotation/tilt to give the feeling of a messy
|
||||||
|
// stack of vinyl.
|
||||||
|
val uidSeed = artist.uid.hashCode()
|
||||||
bindImpl(
|
bindImpl(
|
||||||
artist.covers,
|
SmatteringCoverCollection(
|
||||||
|
artist.covers,
|
||||||
|
uiSettings.roundMode,
|
||||||
|
coverCollectionFanAngle(uidSeed),
|
||||||
|
coverCollectionTiltAngle(uidSeed),
|
||||||
|
coverCollectionZOrder(uidSeed),
|
||||||
|
),
|
||||||
context.getString(R.string.desc_artist_image, artist.name),
|
context.getString(R.string.desc_artist_image, artist.name),
|
||||||
R.drawable.ic_artist_24,
|
R.drawable.ic_artist_24,
|
||||||
) {
|
useCircleCrop = true,
|
||||||
it.enableCoverCollectionCollage(coverCollectionCollageConfig(artist.uid.hashCode()))
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bind a [Genre]'s image to this view.
|
* Bind a [Genre]'s image to this view.
|
||||||
@@ -381,13 +410,17 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
* @param genre The [Genre] to bind to the view.
|
* @param genre The [Genre] to bind to the view.
|
||||||
*/
|
*/
|
||||||
fun bind(genre: Genre) =
|
fun bind(genre: Genre) =
|
||||||
|
// Genres are organized like a "gallery" of various covers that overlap eachother,
|
||||||
|
// as if they were framed on a wall.
|
||||||
bindImpl(
|
bindImpl(
|
||||||
genre.covers,
|
GalleryCoverCollection(
|
||||||
|
genre.covers,
|
||||||
|
uiSettings.roundMode,
|
||||||
|
coverCollectionZOrder(genre.uid.hashCode()),
|
||||||
|
),
|
||||||
context.getString(R.string.desc_genre_image, genre.name),
|
context.getString(R.string.desc_genre_image, genre.name),
|
||||||
R.drawable.ic_genre_24,
|
R.drawable.ic_genre_24,
|
||||||
) {
|
)
|
||||||
it.enableCoverCollectionCollage(coverCollectionCollageConfig(genre.uid.hashCode()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bind a [Playlist]'s image to this view.
|
* Bind a [Playlist]'s image to this view.
|
||||||
@@ -395,8 +428,14 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
* @param playlist the [Playlist] to bind.
|
* @param playlist the [Playlist] to bind.
|
||||||
*/
|
*/
|
||||||
fun bind(playlist: Playlist) =
|
fun bind(playlist: Playlist) =
|
||||||
|
// Playlists are organized in a straight diagonal stack to give the appearance of an
|
||||||
|
// "orderly" pile of covers.
|
||||||
bindImpl(
|
bindImpl(
|
||||||
playlist.covers,
|
StackCoverCollection(
|
||||||
|
playlist.covers,
|
||||||
|
uiSettings.roundMode,
|
||||||
|
coverCollectionZOrder(playlist.uid.hashCode()),
|
||||||
|
),
|
||||||
context.getString(R.string.desc_playlist_image, playlist.name),
|
context.getString(R.string.desc_playlist_image, playlist.name),
|
||||||
R.drawable.ic_playlist_24,
|
R.drawable.ic_playlist_24,
|
||||||
)
|
)
|
||||||
@@ -415,8 +454,10 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
cover: Any?,
|
cover: Any?,
|
||||||
desc: String,
|
desc: String,
|
||||||
@DrawableRes errorRes: Int,
|
@DrawableRes errorRes: Int,
|
||||||
|
useCircleCrop: Boolean = false,
|
||||||
configure: (ImageRequest.Builder) -> ImageRequest.Builder = { it },
|
configure: (ImageRequest.Builder) -> ImageRequest.Builder = { it },
|
||||||
) {
|
) {
|
||||||
|
updateShapeAppearance(useCircleCrop)
|
||||||
val request =
|
val request =
|
||||||
configure(
|
configure(
|
||||||
ImageRequest.Builder(context)
|
ImageRequest.Builder(context)
|
||||||
@@ -430,10 +471,9 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
|
|
||||||
val cornerBounds = resolveCornerBounds()
|
val cornerBounds = resolveCornerBounds()
|
||||||
val cornerRadius =
|
val cornerRadius =
|
||||||
cornerBounds?.let { shapeAppearance.topLeftCornerSize.getCornerSize(it) } ?: 0f
|
cornerBounds?.let { currentShapeAppearance.topLeftCornerSize.getCornerSize(it) } ?: 0f
|
||||||
val cornersTransformation =
|
val cornersTransformation = RoundedRectTransformation(cornerRadius)
|
||||||
RoundedRectTransformation(cornerRadius)
|
if (useCircleCrop || imageSettings.forceSquareCovers) {
|
||||||
if (imageSettings.forceSquareCovers) {
|
|
||||||
request.transformations(SquareCropTransformation.INSTANCE, cornersTransformation)
|
request.transformations(SquareCropTransformation.INSTANCE, cornersTransformation)
|
||||||
} else {
|
} else {
|
||||||
request.transformations(cornersTransformation)
|
request.transformations(cornersTransformation)
|
||||||
@@ -445,33 +485,22 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
|||||||
contentDescription = desc
|
contentDescription = desc
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun coverCollectionCollageConfig(uidSeed: Int): Collage2Config {
|
|
||||||
val zOrder = coverCollectionZOrder(uidSeed)
|
|
||||||
val baseConfig = Collage2Config(insetPercent = 0f, zOrder = zOrder)
|
|
||||||
if (!uiSettings.roundMode) {
|
|
||||||
return baseConfig.copy(cornerRadiusRatio = 0f)
|
|
||||||
}
|
|
||||||
|
|
||||||
val bounds = resolveCornerBounds() ?: return baseConfig
|
|
||||||
val cornerRadiusPx = shapeAppearance.topLeftCornerSize.getCornerSize(bounds)
|
|
||||||
if (cornerRadiusPx <= 0f) {
|
|
||||||
return baseConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
val minSize = min(bounds.width(), bounds.height())
|
|
||||||
if (minSize <= 0f) {
|
|
||||||
return baseConfig
|
|
||||||
}
|
|
||||||
val cornerRatio = cornerRadiusPx / minSize
|
|
||||||
return baseConfig.copy(cornerRadiusRatio = cornerRatio)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun coverCollectionZOrder(uidSeed: Int): List<Int> {
|
private fun coverCollectionZOrder(uidSeed: Int): List<Int> {
|
||||||
val order = mutableListOf(0, 1, 2, 3)
|
val order = mutableListOf(0, 1, 2, 3)
|
||||||
order.shuffle(Random(uidSeed.toLong()))
|
order.shuffle(Random(uidSeed.toLong()))
|
||||||
return order
|
return order
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun coverCollectionFanAngle(uidSeed: Int): Float {
|
||||||
|
val random = Random(uidSeed.toLong())
|
||||||
|
return random.nextFloat() * 10f + 5f // 5-15 degrees
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun coverCollectionTiltAngle(uidSeed: Int): Float {
|
||||||
|
val random = Random(uidSeed.toLong())
|
||||||
|
return random.nextFloat() * 20f - 10f // -10 to +10 degrees
|
||||||
|
}
|
||||||
|
|
||||||
private fun resolveCornerBounds(): RectF? {
|
private fun resolveCornerBounds(): RectF? {
|
||||||
val widthPx = resolveSizePx(width, measuredWidth, layoutParams?.width)
|
val widthPx = resolveSizePx(width, measuredWidth, layoutParams?.width)
|
||||||
val heightPx = resolveSizePx(height, measuredHeight, layoutParams?.height)
|
val heightPx = resolveSizePx(height, measuredHeight, layoutParams?.height)
|
||||||
|
|||||||
@@ -36,19 +36,25 @@ class CoilModule {
|
|||||||
@Provides
|
@Provides
|
||||||
fun imageLoader(
|
fun imageLoader(
|
||||||
@ApplicationContext context: Context,
|
@ApplicationContext context: Context,
|
||||||
coverKeyer: CoverKeyer,
|
coverKeyer: CoverFetcher.Keyer,
|
||||||
coverFactory: CoverFetcher.Factory,
|
coverFactory: CoverFetcher.Factory,
|
||||||
coverCollectionKeyer: CoverCollectionKeyer,
|
galleryKeyer: GalleryComposeFetcher.Keyer,
|
||||||
collageCoverCollectionFactory: Collage2Fetcher.Factory,
|
galleryFetcherFactory: GalleryComposeFetcher.Factory,
|
||||||
coverCollectionFactory: CoverCollectionFetcher.Factory,
|
smatteringKeyer: SmatteringComposeFetcher.Keyer,
|
||||||
|
smatteringFetcherFactory: SmatteringComposeFetcher.Factory,
|
||||||
|
stackKeyer: StackComposeFetcher.Keyer,
|
||||||
|
stackFetcherFactory: StackComposeFetcher.Factory,
|
||||||
) =
|
) =
|
||||||
ImageLoader.Builder(context)
|
ImageLoader.Builder(context)
|
||||||
.components {
|
.components {
|
||||||
add(coverKeyer)
|
add(coverKeyer)
|
||||||
add(coverFactory)
|
add(coverFactory)
|
||||||
add(coverCollectionKeyer)
|
add(galleryKeyer)
|
||||||
add(collageCoverCollectionFactory)
|
add(galleryFetcherFactory)
|
||||||
add(coverCollectionFactory)
|
add(smatteringKeyer)
|
||||||
|
add(smatteringFetcherFactory)
|
||||||
|
add(stackKeyer)
|
||||||
|
add(stackFetcherFactory)
|
||||||
}
|
}
|
||||||
// Use our own crossfade with error drawable support
|
// Use our own crossfade with error drawable support
|
||||||
.transitionFactory(ErrorCrossfadeTransitionFactory())
|
.transitionFactory(ErrorCrossfadeTransitionFactory())
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2024 Auxio Project
|
||||||
|
* ComposeCoverUtils.kt is part of Auxio.
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.oxycblt.auxio.image.coil
|
||||||
|
|
||||||
|
internal object ComposeCoverDefaults {
|
||||||
|
const val CARD_SIZE_PERCENT = 0.60f
|
||||||
|
const val GAP_RATIO = 0.04f
|
||||||
|
const val CORNER_RATIO = 0.08f
|
||||||
|
const val MIN_GAP_CORNER_RATIO = 0.35f
|
||||||
|
const val MAX_CORNER_RATIO = 0.15f
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun List<Int>.validatedZOrder(): List<Int> {
|
||||||
|
val expected = listOf(0, 1, 2, 3)
|
||||||
|
require(size == expected.size && distinct().size == expected.size && containsAll(expected)) {
|
||||||
|
"zOrder must be a permutation of [0, 1, 2, 3], got $this"
|
||||||
|
}
|
||||||
|
return this
|
||||||
|
}
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2024 Auxio Project
|
|
||||||
* CoverCollectionFetcher.kt is part of Auxio.
|
|
||||||
*
|
|
||||||
* This program is free software: you can redistribute it and/or modify
|
|
||||||
* it under the terms of the GNU General Public License as published by
|
|
||||||
* the Free Software Foundation, either version 3 of the License, or
|
|
||||||
* (at your option) any later version.
|
|
||||||
*
|
|
||||||
* This program is distributed in the hope that it will be useful,
|
|
||||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
* GNU General Public License for more details.
|
|
||||||
*
|
|
||||||
* You should have received a copy of the GNU General Public License
|
|
||||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package org.oxycblt.auxio.image.coil
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.graphics.BitmapFactory
|
|
||||||
import android.graphics.Canvas
|
|
||||||
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.request.Options
|
|
||||||
import coil3.size.Dimension
|
|
||||||
import coil3.size.Size
|
|
||||||
import coil3.size.pxOrElse
|
|
||||||
import java.io.InputStream
|
|
||||||
import javax.inject.Inject
|
|
||||||
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
|
|
||||||
|
|
||||||
class CoverCollectionFetcher
|
|
||||||
private constructor(
|
|
||||||
private val context: Context,
|
|
||||||
private val covers: CoverCollection,
|
|
||||||
private val size: Size,
|
|
||||||
) : Fetcher {
|
|
||||||
override suspend fun fetch(): FetchResult? {
|
|
||||||
val streams = covers.covers.asFlow().mapNotNull { it.open() }.take(4).toList()
|
|
||||||
// We don't immediately check for mosaic feasibility from album count alone, as that
|
|
||||||
// does not factor in InputStreams failing to load. Instead, only check once we
|
|
||||||
// definitely have image data to use.
|
|
||||||
if (streams.size == 4) {
|
|
||||||
// Make sure we free the InputStreams once we've transformed them into a
|
|
||||||
// mosaic.
|
|
||||||
return createMosaic(streams, size).also {
|
|
||||||
withContext(Dispatchers.IO) { streams.forEach(InputStream::close) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not enough covers for a mosaic, take the first one (if that even exists)
|
|
||||||
val first = streams.firstOrNull() ?: return null
|
|
||||||
|
|
||||||
// All but the first stream will be unused, free their resources
|
|
||||||
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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Derived from phonograph: https://github.com/kabouzeid/Phonograph */
|
|
||||||
private suspend fun createMosaic(streams: List<InputStream>, size: Size): FetchResult {
|
|
||||||
// Use whatever size coil gives us to create the mosaic.
|
|
||||||
val mosaicSize = android.util.Size(size.width.mosaicSize(), size.height.mosaicSize())
|
|
||||||
val mosaicFrameSize =
|
|
||||||
Size(Dimension(mosaicSize.width / 2), Dimension(mosaicSize.height / 2))
|
|
||||||
|
|
||||||
val mosaicBitmap = createBitmap(mosaicSize.width, mosaicSize.height)
|
|
||||||
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 == mosaicSize.height) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
// Crop the bitmap down to a square so it leaves no empty space
|
|
||||||
// TODO: Work around this
|
|
||||||
val bitmap =
|
|
||||||
SquareCropTransformation.INSTANCE.transform(
|
|
||||||
BitmapFactory.decodeStream(stream),
|
|
||||||
mosaicFrameSize,
|
|
||||||
)
|
|
||||||
canvas.drawBitmap(bitmap, x.toFloat(), y.toFloat(), null)
|
|
||||||
|
|
||||||
x += bitmap.width
|
|
||||||
if (x == mosaicSize.width) {
|
|
||||||
x = 0
|
|
||||||
y += bitmap.height
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// It's way easier to map this into a drawable then try to serialize it into an
|
|
||||||
// BufferedSource. Just make sure we mark it as "sampled" so Coil doesn't try to
|
|
||||||
// load low-res mosaics into high-res ImageViews.
|
|
||||||
return ImageFetchResult(
|
|
||||||
image = mosaicBitmap.toDrawable(context.resources).asImage(),
|
|
||||||
isSampled = true,
|
|
||||||
dataSource = DataSource.DISK,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun Dimension.mosaicSize(): Int {
|
|
||||||
// Since we want the mosaic to be perfectly divisible into two, we need to round any
|
|
||||||
// odd image sizes upwards to prevent the mosaic creation from failing.
|
|
||||||
val size = pxOrElse { 512 }
|
|
||||||
return if (size.mod(2) > 0) size + 1 else size
|
|
||||||
}
|
|
||||||
|
|
||||||
class Factory @Inject constructor() : Fetcher.Factory<CoverCollection> {
|
|
||||||
override fun create(data: CoverCollection, options: Options, imageLoader: ImageLoader) =
|
|
||||||
CoverCollectionFetcher(options.context, data, options.size)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -24,6 +24,7 @@ import coil3.decode.ImageSource
|
|||||||
import coil3.fetch.FetchResult
|
import coil3.fetch.FetchResult
|
||||||
import coil3.fetch.Fetcher
|
import coil3.fetch.Fetcher
|
||||||
import coil3.fetch.SourceFetchResult
|
import coil3.fetch.SourceFetchResult
|
||||||
|
import coil3.key.Keyer as CoilKeyer
|
||||||
import coil3.request.Options
|
import coil3.request.Options
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import okio.FileSystem
|
import okio.FileSystem
|
||||||
@@ -45,4 +46,8 @@ class CoverFetcher private constructor(private val cover: Cover) : Fetcher {
|
|||||||
override fun create(data: Cover, options: Options, imageLoader: ImageLoader) =
|
override fun create(data: Cover, options: Options, imageLoader: ImageLoader) =
|
||||||
CoverFetcher(data)
|
CoverFetcher(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class Keyer @Inject constructor() : CoilKeyer<Cover> {
|
||||||
|
override fun key(data: Cover, options: Options) = "${data.id}&${options.size}"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+116
-147
@@ -1,6 +1,6 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2024 Auxio Project
|
* Copyright (c) 2024 Auxio Project
|
||||||
* CollageCoverCollectionFetcher.kt is part of Auxio.
|
* GalleryComposeFetcher.kt is part of Auxio.
|
||||||
*
|
*
|
||||||
* This program is free software: you can redistribute it and/or modify
|
* 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
|
* it under the terms of the GNU General Public License as published by
|
||||||
@@ -31,7 +31,6 @@ import android.graphics.Rect
|
|||||||
import android.graphics.RectF
|
import android.graphics.RectF
|
||||||
import androidx.core.graphics.createBitmap
|
import androidx.core.graphics.createBitmap
|
||||||
import androidx.core.graphics.drawable.toDrawable
|
import androidx.core.graphics.drawable.toDrawable
|
||||||
import coil3.Extras
|
|
||||||
import coil3.ImageLoader
|
import coil3.ImageLoader
|
||||||
import coil3.asImage
|
import coil3.asImage
|
||||||
import coil3.decode.DataSource
|
import coil3.decode.DataSource
|
||||||
@@ -40,13 +39,13 @@ import coil3.fetch.FetchResult
|
|||||||
import coil3.fetch.Fetcher
|
import coil3.fetch.Fetcher
|
||||||
import coil3.fetch.ImageFetchResult
|
import coil3.fetch.ImageFetchResult
|
||||||
import coil3.fetch.SourceFetchResult
|
import coil3.fetch.SourceFetchResult
|
||||||
import coil3.getExtra
|
import coil3.key.Keyer as CoilKeyer
|
||||||
import coil3.request.ImageRequest
|
|
||||||
import coil3.request.Options
|
import coil3.request.Options
|
||||||
import coil3.size.Size
|
import coil3.size.Size
|
||||||
import coil3.size.pxOrElse
|
import coil3.size.pxOrElse
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import kotlin.math.max
|
||||||
import kotlin.math.min
|
import kotlin.math.min
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.asFlow
|
import kotlinx.coroutines.flow.asFlow
|
||||||
@@ -61,76 +60,20 @@ import org.oxycblt.auxio.R
|
|||||||
import org.oxycblt.auxio.util.getColorCompat
|
import org.oxycblt.auxio.util.getColorCompat
|
||||||
import org.oxycblt.musikr.covers.CoverCollection
|
import org.oxycblt.musikr.covers.CoverCollection
|
||||||
|
|
||||||
private const val DEFAULT_CARD_SIZE_PERCENT = 0.60f
|
data class GalleryCoverCollection(
|
||||||
private const val DEFAULT_INSET_PERCENT = 0.10f
|
val covers: CoverCollection,
|
||||||
private const val DEFAULT_GAP_RATIO = 0.04f
|
val useRoundedCorners: Boolean,
|
||||||
private const val DEFAULT_CORNER_RATIO = 0.08f
|
val zOrder: List<Int>,
|
||||||
|
)
|
||||||
|
|
||||||
private fun List<Int>.normalizedZOrder(): List<Int> {
|
class GalleryComposeFetcher
|
||||||
val expected = listOf(0, 1, 2, 3)
|
|
||||||
return if (size == expected.size && distinct().size == expected.size && containsAll(expected)) {
|
|
||||||
this
|
|
||||||
} else {
|
|
||||||
expected
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
data class Collage2Config(
|
|
||||||
val cardSizePercent: Float = DEFAULT_CARD_SIZE_PERCENT,
|
|
||||||
val insetPercent: Float = DEFAULT_INSET_PERCENT,
|
|
||||||
val gapWidthRatio: Float = DEFAULT_GAP_RATIO,
|
|
||||||
val cornerRadiusRatio: Float = DEFAULT_CORNER_RATIO,
|
|
||||||
val zOrder: List<Int> = listOf(0, 1, 2, 3),
|
|
||||||
) {
|
|
||||||
fun normalized(): Collage2Config {
|
|
||||||
val normalizedZOrder = zOrder.normalizedZOrder()
|
|
||||||
return copy(
|
|
||||||
cardSizePercent = cardSizePercent.coerceIn(0.5f, 1f),
|
|
||||||
insetPercent = insetPercent.coerceIn(0f, 0.25f),
|
|
||||||
gapWidthRatio = gapWidthRatio.coerceIn(0f, 0.1f),
|
|
||||||
cornerRadiusRatio = cornerRadiusRatio.coerceIn(0f, 0.25f),
|
|
||||||
zOrder = normalizedZOrder,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun cacheKey(): String {
|
|
||||||
val config = normalized()
|
|
||||||
return buildString {
|
|
||||||
append("card=")
|
|
||||||
append(config.cardSizePercent)
|
|
||||||
append("&inset=")
|
|
||||||
append(config.insetPercent)
|
|
||||||
append("&gap=")
|
|
||||||
append(config.gapWidthRatio)
|
|
||||||
append("&corner=")
|
|
||||||
append(config.cornerRadiusRatio)
|
|
||||||
append("&order=")
|
|
||||||
append(config.zOrder.joinToString("-"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal object CoverCollectionExtras {
|
|
||||||
val COLLAGE = Extras.Key(false)
|
|
||||||
val COLLAGE_CONFIG = Extras.Key<Collage2Config?>(null)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun ImageRequest.Builder.enableCoverCollectionCollage(
|
|
||||||
config: Collage2Config = Collage2Config(),
|
|
||||||
): ImageRequest.Builder = apply {
|
|
||||||
extras[CoverCollectionExtras.COLLAGE] = true
|
|
||||||
extras[CoverCollectionExtras.COLLAGE_CONFIG] = config
|
|
||||||
}
|
|
||||||
|
|
||||||
class Collage2Fetcher
|
|
||||||
private constructor(
|
private constructor(
|
||||||
private val context: Context,
|
private val context: Context,
|
||||||
private val covers: CoverCollection,
|
private val data: GalleryCoverCollection,
|
||||||
private val size: Size,
|
private val size: Size,
|
||||||
private val config: Collage2Config,
|
|
||||||
) : Fetcher {
|
) : Fetcher {
|
||||||
override suspend fun fetch(): FetchResult? {
|
override suspend fun fetch(): FetchResult? {
|
||||||
val streams = covers.covers.asFlow().mapNotNull { it.open() }.take(4).toList()
|
val streams = data.covers.covers.asFlow().mapNotNull { it.open() }.take(4).toList()
|
||||||
if (streams.size == 4) {
|
if (streams.size == 4) {
|
||||||
return createCollage(streams, size).also {
|
return createCollage(streams, size).also {
|
||||||
withContext(Dispatchers.IO) { streams.forEach(InputStream::close) }
|
withContext(Dispatchers.IO) { streams.forEach(InputStream::close) }
|
||||||
@@ -158,18 +101,17 @@ private constructor(
|
|||||||
if (bitmaps.size != streams.size) {
|
if (bitmaps.size != streams.size) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
val normalizedConfig = config.normalized()
|
val cornerRadiusPx =
|
||||||
|
if (data.useRoundedCorners) outputSize * ComposeCoverDefaults.CORNER_RATIO else 0f
|
||||||
val collageBitmap =
|
val collageBitmap =
|
||||||
CollageGenerator.generate(
|
CollageGenerator.generate(
|
||||||
bitmaps,
|
bitmaps,
|
||||||
CollageGenerator.Config(
|
CollageGenerator.Config(
|
||||||
outputSizePx = outputSize,
|
outputSizePx = outputSize,
|
||||||
cardSizePercent = normalizedConfig.cardSizePercent,
|
gapWidthPx = outputSize * ComposeCoverDefaults.GAP_RATIO,
|
||||||
insetPercent = normalizedConfig.insetPercent,
|
cornerRadiusPx = cornerRadiusPx,
|
||||||
gapWidthPx = outputSize * normalizedConfig.gapWidthRatio,
|
|
||||||
cornerRadiusPx = outputSize * normalizedConfig.cornerRadiusRatio,
|
|
||||||
backgroundColor = context.getColorCompat(R.color.sel_cover_bg).defaultColor,
|
backgroundColor = context.getColorCompat(R.color.sel_cover_bg).defaultColor,
|
||||||
zOrder = normalizedConfig.zOrder,
|
zOrder = data.zOrder.validatedZOrder(),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -189,8 +131,6 @@ private constructor(
|
|||||||
private object CollageGenerator {
|
private object CollageGenerator {
|
||||||
data class Config(
|
data class Config(
|
||||||
val outputSizePx: Int,
|
val outputSizePx: Int,
|
||||||
val cardSizePercent: Float,
|
|
||||||
val insetPercent: Float,
|
|
||||||
val gapWidthPx: Float,
|
val gapWidthPx: Float,
|
||||||
val cornerRadiusPx: Float,
|
val cornerRadiusPx: Float,
|
||||||
val backgroundColor: Int = Color.parseColor("#0f111a"),
|
val backgroundColor: Int = Color.parseColor("#0f111a"),
|
||||||
@@ -215,24 +155,27 @@ private constructor(
|
|||||||
val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
|
||||||
val totalSize = config.outputSizePx.toFloat()
|
val totalSize = config.outputSizePx.toFloat()
|
||||||
val cardSize = totalSize * config.cardSizePercent
|
val cardSize = totalSize * ComposeCoverDefaults.CARD_SIZE_PERCENT
|
||||||
val inset = totalSize * config.insetPercent
|
val inset = 0f
|
||||||
|
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 p0 = RectF(inset, inset, inset + cardSize, inset + cardSize)
|
val p0 = RectF(inset, inset, inset + cardSize, inset + cardSize)
|
||||||
val p1 =
|
val p1 = RectF(totalSize - cardSize - inset, inset, totalSize - inset, inset + cardSize)
|
||||||
RectF(
|
val p2 = RectF(inset, totalSize - cardSize - inset, inset + cardSize, totalSize - inset)
|
||||||
totalSize - cardSize - inset,
|
|
||||||
inset,
|
|
||||||
totalSize - inset,
|
|
||||||
inset + cardSize,
|
|
||||||
)
|
|
||||||
val p2 =
|
|
||||||
RectF(
|
|
||||||
inset,
|
|
||||||
totalSize - cardSize - inset,
|
|
||||||
inset + cardSize,
|
|
||||||
totalSize - inset,
|
|
||||||
)
|
|
||||||
val p3 =
|
val p3 =
|
||||||
RectF(
|
RectF(
|
||||||
totalSize - cardSize - inset,
|
totalSize - cardSize - inset,
|
||||||
@@ -242,53 +185,46 @@ private constructor(
|
|||||||
)
|
)
|
||||||
|
|
||||||
val positions = listOf(p0, p1, p2, p3)
|
val positions = listOf(p0, p1, p2, p3)
|
||||||
|
val tiles =
|
||||||
|
positions.mapIndexed { index, baseRect ->
|
||||||
|
val isTop = index < 2
|
||||||
|
val isLeft = index % 2 == 0
|
||||||
|
val isBottom = !isTop
|
||||||
|
val isRight = !isLeft
|
||||||
|
|
||||||
for (imageIndex in config.zOrder) {
|
val innerRect = RectF(baseRect)
|
||||||
val bitmap = sourceImages[imageIndex]
|
innerRect.left += if (isLeft) 0f else gapWidthPx
|
||||||
val isTop = imageIndex < 2
|
innerRect.top += if (isTop) 0f else gapWidthPx
|
||||||
val isLeft = imageIndex % 2 == 0
|
innerRect.right -= if (isRight) 0f else gapWidthPx
|
||||||
val isBottom = !isTop
|
innerRect.bottom -= if (isBottom) 0f else gapWidthPx
|
||||||
val isRight = !isLeft
|
|
||||||
|
|
||||||
val baseRect = RectF(positions[imageIndex])
|
val gapRect = RectF(innerRect)
|
||||||
|
gapRect.inset(-gapWidthPx, -gapWidthPx)
|
||||||
|
|
||||||
val innerRect = RectF(baseRect)
|
val gapRadius = cornerRadiusPx
|
||||||
innerRect.left += if (isLeft) 0f else config.gapWidthPx
|
val gapTopLeft = if (!isTop && !isLeft) gapRadius else 0f
|
||||||
innerRect.top += if (isTop) 0f else config.gapWidthPx
|
val gapTopRight = if (!isTop && !isRight) gapRadius else 0f
|
||||||
innerRect.right -= if (isRight) 0f else config.gapWidthPx
|
val gapBottomRight = if (!isBottom && !isRight) gapRadius else 0f
|
||||||
innerRect.bottom -= if (isBottom) 0f else config.gapWidthPx
|
val gapBottomLeft = if (!isBottom && !isLeft) gapRadius else 0f
|
||||||
|
val gapPath =
|
||||||
|
Path().apply {
|
||||||
|
addRoundRect(
|
||||||
|
gapRect,
|
||||||
|
floatArrayOf(
|
||||||
|
gapTopLeft,
|
||||||
|
gapTopLeft,
|
||||||
|
gapTopRight,
|
||||||
|
gapTopRight,
|
||||||
|
gapBottomRight,
|
||||||
|
gapBottomRight,
|
||||||
|
gapBottomLeft,
|
||||||
|
gapBottomLeft,
|
||||||
|
),
|
||||||
|
Path.Direction.CW,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
val gapRect = RectF(innerRect)
|
val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f)
|
||||||
gapRect.inset(-config.gapWidthPx, -config.gapWidthPx)
|
|
||||||
|
|
||||||
val gapRadius = config.cornerRadiusPx
|
|
||||||
val gapTopLeft = if (!isTop && !isLeft) gapRadius else 0f
|
|
||||||
val gapTopRight = if (!isTop && !isRight) gapRadius else 0f
|
|
||||||
val gapBottomRight = if (!isBottom && !isRight) gapRadius else 0f
|
|
||||||
val gapBottomLeft = if (!isBottom && !isLeft) gapRadius else 0f
|
|
||||||
val gapPath =
|
|
||||||
Path().apply {
|
|
||||||
addRoundRect(
|
|
||||||
gapRect,
|
|
||||||
floatArrayOf(
|
|
||||||
gapTopLeft,
|
|
||||||
gapTopLeft,
|
|
||||||
gapTopRight,
|
|
||||||
gapTopRight,
|
|
||||||
gapBottomRight,
|
|
||||||
gapBottomRight,
|
|
||||||
gapBottomLeft,
|
|
||||||
gapBottomLeft,
|
|
||||||
),
|
|
||||||
Path.Direction.CW,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
canvas.drawPath(gapPath, gapPaint)
|
|
||||||
|
|
||||||
if (innerRect.width() > 0 && innerRect.height() > 0) {
|
|
||||||
val savedLayer = canvas.saveLayer(innerRect, null)
|
|
||||||
|
|
||||||
val innerRadius = (config.cornerRadiusPx - config.gapWidthPx).coerceAtLeast(0f)
|
|
||||||
val topLeftRadius = if (!isTop && !isLeft) innerRadius else 0f
|
val topLeftRadius = if (!isTop && !isLeft) innerRadius else 0f
|
||||||
val topRightRadius = if (!isTop && !isRight) innerRadius else 0f
|
val topRightRadius = if (!isTop && !isRight) innerRadius else 0f
|
||||||
val bottomRightRadius = if (!isBottom && !isRight) innerRadius else 0f
|
val bottomRightRadius = if (!isBottom && !isRight) innerRadius else 0f
|
||||||
@@ -310,19 +246,48 @@ private constructor(
|
|||||||
Path.Direction.CW,
|
Path.Direction.CW,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
canvas.drawPath(maskPath, imagePaint)
|
|
||||||
|
TileGeometry(innerRect, gapPath, maskPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
val zOrder = config.zOrder
|
||||||
|
for ((orderIndex, imageIndex) in zOrder.withIndex()) {
|
||||||
|
val bitmap = sourceImages[imageIndex]
|
||||||
|
val tile = tiles[imageIndex]
|
||||||
|
val visiblePath = Path(tile.gapPath)
|
||||||
|
for (index in orderIndex + 1 until zOrder.size) {
|
||||||
|
visiblePath.op(tiles[zOrder[index]].gapPath, Path.Op.DIFFERENCE)
|
||||||
|
if (visiblePath.isEmpty) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (visiblePath.isEmpty) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.drawPath(visiblePath, gapPaint)
|
||||||
|
|
||||||
|
if (tile.innerRect.width() > 0 && tile.innerRect.height() > 0) {
|
||||||
|
val clipSave = canvas.save()
|
||||||
|
canvas.clipPath(visiblePath)
|
||||||
|
val savedLayer = canvas.saveLayer(tile.innerRect, null)
|
||||||
|
canvas.drawPath(tile.maskPath, imagePaint)
|
||||||
|
|
||||||
imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
|
imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
|
||||||
drawBitmapCover(canvas, bitmap, innerRect, imagePaint)
|
drawBitmapCover(canvas, bitmap, tile.innerRect, imagePaint)
|
||||||
imagePaint.xfermode = null
|
imagePaint.xfermode = null
|
||||||
|
|
||||||
canvas.restoreToCount(savedLayer)
|
canvas.restoreToCount(savedLayer)
|
||||||
|
canvas.restoreToCount(clipSave)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private data class TileGeometry(val innerRect: RectF, val gapPath: Path, val maskPath: Path)
|
||||||
|
|
||||||
private fun drawBitmapCover(canvas: Canvas, bitmap: Bitmap, dest: RectF, paint: Paint) {
|
private fun drawBitmapCover(canvas: Canvas, bitmap: Bitmap, dest: RectF, paint: Paint) {
|
||||||
val bitmapRatio = bitmap.width.toFloat() / bitmap.height.toFloat()
|
val bitmapRatio = bitmap.width.toFloat() / bitmap.height.toFloat()
|
||||||
val destRatio = dest.width() / dest.height()
|
val destRatio = dest.width() / dest.height()
|
||||||
@@ -345,15 +310,19 @@ private constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Factory @Inject constructor() : Fetcher.Factory<CoverCollection> {
|
class Factory @Inject constructor() : Fetcher.Factory<GalleryCoverCollection> {
|
||||||
override fun create(data: CoverCollection, options: Options, imageLoader: ImageLoader) =
|
override fun create(
|
||||||
if (options.getExtra(CoverCollectionExtras.COLLAGE)) {
|
data: GalleryCoverCollection,
|
||||||
val config =
|
options: Options,
|
||||||
options.getExtra(CoverCollectionExtras.COLLAGE_CONFIG)
|
imageLoader: ImageLoader,
|
||||||
?: Collage2Config()
|
) = GalleryComposeFetcher(options.context, data, options.size)
|
||||||
Collage2Fetcher(options.context, data, options.size, config)
|
}
|
||||||
} else {
|
|
||||||
null
|
class Keyer @Inject constructor() : CoilKeyer<GalleryCoverCollection> {
|
||||||
}
|
override fun key(data: GalleryCoverCollection, options: Options): String {
|
||||||
|
val config =
|
||||||
|
"${if (data.useRoundedCorners) "r" else "s"}.${data.zOrder.joinToString(".")}"
|
||||||
|
return "g:${data.covers.hashCode()}.${options.size.width}.${options.size.height}.$config"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2021 Auxio Project
|
|
||||||
* Keyers.kt is part of Auxio.
|
|
||||||
*
|
|
||||||
* This program is free software: you can redistribute it and/or modify
|
|
||||||
* it under the terms of the GNU General Public License as published by
|
|
||||||
* the Free Software Foundation, either version 3 of the License, or
|
|
||||||
* (at your option) any later version.
|
|
||||||
*
|
|
||||||
* This program is distributed in the hope that it will be useful,
|
|
||||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
* GNU General Public License for more details.
|
|
||||||
*
|
|
||||||
* You should have received a copy of the GNU General Public License
|
|
||||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package org.oxycblt.auxio.image.coil
|
|
||||||
|
|
||||||
import coil3.getExtra
|
|
||||||
import coil3.key.Keyer
|
|
||||||
import coil3.request.Options
|
|
||||||
import javax.inject.Inject
|
|
||||||
import org.oxycblt.musikr.covers.Cover
|
|
||||||
import org.oxycblt.musikr.covers.CoverCollection
|
|
||||||
|
|
||||||
class CoverKeyer @Inject constructor() : Keyer<Cover> {
|
|
||||||
override fun key(data: Cover, options: Options) = "${data.id}&${options.size}"
|
|
||||||
}
|
|
||||||
|
|
||||||
class CoverCollectionKeyer @Inject constructor() : Keyer<CoverCollection> {
|
|
||||||
override fun key(data: CoverCollection, options: Options) =
|
|
||||||
if (options.getExtra(CoverCollectionExtras.COLLAGE)) {
|
|
||||||
val config =
|
|
||||||
options.getExtra(CoverCollectionExtras.COLLAGE_CONFIG)
|
|
||||||
?: Collage2Config()
|
|
||||||
"multi:${data.hashCode()}&${options.size}&collage=${config.cacheKey()}"
|
|
||||||
} else {
|
|
||||||
"multi:${data.hashCode()}&${options.size}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,332 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2024 Auxio Project
|
||||||
|
* SmatteringComposeFetcher.kt is part of Auxio.
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.oxycblt.auxio.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.core.graphics.createBitmap
|
||||||
|
import androidx.core.graphics.drawable.toDrawable
|
||||||
|
import androidx.core.graphics.toColorInt
|
||||||
|
import androidx.core.graphics.withRotation
|
||||||
|
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.auxio.R
|
||||||
|
import org.oxycblt.auxio.util.getColorCompat
|
||||||
|
import org.oxycblt.musikr.covers.CoverCollection
|
||||||
|
|
||||||
|
private const val OUTSET_PERCENT = 0.08f
|
||||||
|
|
||||||
|
data class SmatteringCoverCollection(
|
||||||
|
val covers: CoverCollection,
|
||||||
|
val useRoundedCorners: Boolean,
|
||||||
|
val fanAngleDeg: Float,
|
||||||
|
val tiltAngleDeg: Float,
|
||||||
|
val zOrder: List<Int>,
|
||||||
|
)
|
||||||
|
|
||||||
|
class SmatteringComposeFetcher
|
||||||
|
private constructor(
|
||||||
|
private val context: Context,
|
||||||
|
private val data: SmatteringCoverCollection,
|
||||||
|
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 createStackCollage(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 createStackCollage(streams: List<InputStream>, size: Size): FetchResult? {
|
||||||
|
val outputSize = size.collageSize()
|
||||||
|
val bitmaps = streams.mapNotNull { BitmapFactory.decodeStream(it) }
|
||||||
|
if (bitmaps.size != streams.size) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val cornerRadiusPx =
|
||||||
|
if (data.useRoundedCorners) outputSize * ComposeCoverDefaults.CORNER_RATIO else 0f
|
||||||
|
val collageBitmap =
|
||||||
|
StackCollageGenerator.generate(
|
||||||
|
bitmaps,
|
||||||
|
StackCollageGenerator.Config(
|
||||||
|
outputSizePx = outputSize,
|
||||||
|
gapWidthPx = outputSize * ComposeCoverDefaults.GAP_RATIO,
|
||||||
|
cornerRadiusPx = cornerRadiusPx,
|
||||||
|
fanAngleDeg = data.fanAngleDeg,
|
||||||
|
tiltAngleDeg = data.tiltAngleDeg,
|
||||||
|
backgroundColor = context.getColorCompat(R.color.sel_cover_bg).defaultColor,
|
||||||
|
zOrder = data.zOrder.validatedZOrder(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
return ImageFetchResult(
|
||||||
|
image = collageBitmap.toDrawable(context.resources).asImage(),
|
||||||
|
isSampled = true,
|
||||||
|
dataSource = DataSource.DISK,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Size.collageSize(): Int {
|
||||||
|
val widthPx = width.pxOrElse { 512 }
|
||||||
|
val heightPx = height.pxOrElse { 512 }
|
||||||
|
return min(widthPx, heightPx).coerceAtLeast(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
private object StackCollageGenerator {
|
||||||
|
data class Config(
|
||||||
|
val outputSizePx: Int,
|
||||||
|
val gapWidthPx: Float,
|
||||||
|
val cornerRadiusPx: Float,
|
||||||
|
val fanAngleDeg: Float,
|
||||||
|
val tiltAngleDeg: Float,
|
||||||
|
val backgroundColor: Int = "#0f111a".toColorInt(),
|
||||||
|
val zOrder: List<Int> = listOf(0, 1, 2, 3),
|
||||||
|
)
|
||||||
|
|
||||||
|
fun generate(sourceImages: List<Bitmap>, config: Config): Bitmap {
|
||||||
|
if (sourceImages.size != 4) {
|
||||||
|
throw IllegalArgumentException("Collage 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)
|
||||||
|
|
||||||
|
val totalSize = config.outputSizePx.toFloat()
|
||||||
|
val cardSize = totalSize * ComposeCoverDefaults.CARD_SIZE_PERCENT
|
||||||
|
val inset = 0f
|
||||||
|
val outset = totalSize * OUTSET_PERCENT
|
||||||
|
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 p0 = RectF(inset, inset, inset + cardSize, inset + cardSize)
|
||||||
|
val p1 = RectF(totalSize - cardSize - inset, inset, totalSize - inset, inset + cardSize)
|
||||||
|
val p2 = RectF(inset, totalSize - cardSize - inset, inset + cardSize, totalSize - inset)
|
||||||
|
val p3 =
|
||||||
|
RectF(
|
||||||
|
totalSize - cardSize - inset,
|
||||||
|
totalSize - cardSize - inset,
|
||||||
|
totalSize - inset,
|
||||||
|
totalSize - inset,
|
||||||
|
)
|
||||||
|
|
||||||
|
val positions = listOf(p0, p1, p2, p3)
|
||||||
|
|
||||||
|
for (imageIndex in config.zOrder) {
|
||||||
|
val bitmap = sourceImages[imageIndex]
|
||||||
|
val isTop = imageIndex < 2
|
||||||
|
val isLeft = imageIndex % 2 == 0
|
||||||
|
val isBottom = !isTop
|
||||||
|
val isRight = !isLeft
|
||||||
|
|
||||||
|
val baseRect =
|
||||||
|
RectF(positions[imageIndex]).apply {
|
||||||
|
if (outset > 0f) {
|
||||||
|
inset(-outset, -outset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val centerX = baseRect.centerX()
|
||||||
|
val centerY = baseRect.centerY()
|
||||||
|
val rotation =
|
||||||
|
if (imageIndex == 0 || imageIndex == 3) {
|
||||||
|
config.tiltAngleDeg - config.fanAngleDeg
|
||||||
|
} else {
|
||||||
|
config.tiltAngleDeg + config.fanAngleDeg
|
||||||
|
}
|
||||||
|
|
||||||
|
val innerRect = RectF(baseRect)
|
||||||
|
innerRect.left += if (isLeft) 0f else gapWidthPx
|
||||||
|
innerRect.top += if (isTop) 0f else gapWidthPx
|
||||||
|
innerRect.right -= if (isRight) 0f else gapWidthPx
|
||||||
|
innerRect.bottom -= if (isBottom) 0f else gapWidthPx
|
||||||
|
|
||||||
|
val gapRect = RectF(innerRect)
|
||||||
|
gapRect.inset(-gapWidthPx, -gapWidthPx)
|
||||||
|
|
||||||
|
val gapRadius = cornerRadiusPx
|
||||||
|
val gapTopLeft = if (!isTop && !isLeft) gapRadius else 0f
|
||||||
|
val gapTopRight = if (!isTop && !isRight) gapRadius else 0f
|
||||||
|
val gapBottomRight = if (!isBottom && !isRight) gapRadius else 0f
|
||||||
|
val gapBottomLeft = if (!isBottom && !isLeft) gapRadius else 0f
|
||||||
|
val gapPath =
|
||||||
|
Path().apply {
|
||||||
|
addRoundRect(
|
||||||
|
gapRect,
|
||||||
|
floatArrayOf(
|
||||||
|
gapTopLeft,
|
||||||
|
gapTopLeft,
|
||||||
|
gapTopRight,
|
||||||
|
gapTopRight,
|
||||||
|
gapBottomRight,
|
||||||
|
gapBottomRight,
|
||||||
|
gapBottomLeft,
|
||||||
|
gapBottomLeft,
|
||||||
|
),
|
||||||
|
Path.Direction.CW,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.withRotation(rotation, centerX, centerY) {
|
||||||
|
drawPath(gapPath, gapPaint)
|
||||||
|
|
||||||
|
if (innerRect.width() > 0 && innerRect.height() > 0) {
|
||||||
|
val savedLayer = saveLayer(innerRect, null)
|
||||||
|
|
||||||
|
val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f)
|
||||||
|
val topLeftRadius = if (!isTop && !isLeft) innerRadius else 0f
|
||||||
|
val topRightRadius = if (!isTop && !isRight) innerRadius else 0f
|
||||||
|
val bottomRightRadius = if (!isBottom && !isRight) innerRadius else 0f
|
||||||
|
val bottomLeftRadius = if (!isBottom && !isLeft) innerRadius else 0f
|
||||||
|
val maskPath =
|
||||||
|
Path().apply {
|
||||||
|
addRoundRect(
|
||||||
|
innerRect,
|
||||||
|
floatArrayOf(
|
||||||
|
topLeftRadius,
|
||||||
|
topLeftRadius,
|
||||||
|
topRightRadius,
|
||||||
|
topRightRadius,
|
||||||
|
bottomRightRadius,
|
||||||
|
bottomRightRadius,
|
||||||
|
bottomLeftRadius,
|
||||||
|
bottomLeftRadius,
|
||||||
|
),
|
||||||
|
Path.Direction.CW,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
drawPath(maskPath, imagePaint)
|
||||||
|
|
||||||
|
imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
|
||||||
|
drawBitmapCover(this, bitmap, innerRect, imagePaint)
|
||||||
|
imagePaint.xfermode = null
|
||||||
|
|
||||||
|
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<SmatteringCoverCollection> {
|
||||||
|
override fun create(
|
||||||
|
data: SmatteringCoverCollection,
|
||||||
|
options: Options,
|
||||||
|
imageLoader: ImageLoader,
|
||||||
|
) = SmatteringComposeFetcher(options.context, data, options.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
class Keyer @Inject constructor() : CoilKeyer<SmatteringCoverCollection> {
|
||||||
|
override fun key(data: SmatteringCoverCollection, options: Options): String {
|
||||||
|
val config =
|
||||||
|
"${if (data.useRoundedCorners) "r" else "s"}.${data.fanAngleDeg}.${data.tiltAngleDeg}.${data.zOrder.joinToString(".")}"
|
||||||
|
return "m:${data.covers.hashCode()}.${options.size.width}.${options.size.height}.$config"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
/*
|
||||||
|
* 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 <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
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.core.graphics.createBitmap
|
||||||
|
import androidx.core.graphics.drawable.toDrawable
|
||||||
|
import androidx.core.graphics.toColorInt
|
||||||
|
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.auxio.R
|
||||||
|
import org.oxycblt.auxio.util.getColorCompat
|
||||||
|
import org.oxycblt.musikr.covers.CoverCollection
|
||||||
|
|
||||||
|
data class StackCoverCollection(
|
||||||
|
val covers: CoverCollection,
|
||||||
|
val useRoundedCorners: Boolean,
|
||||||
|
val zOrder: List<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<InputStream>, size: Size): FetchResult? {
|
||||||
|
val outputSize = size.stackSize()
|
||||||
|
val bitmaps = streams.mapNotNull { BitmapFactory.decodeStream(it) }
|
||||||
|
if (bitmaps.size != streams.size) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val cornerRadiusPx =
|
||||||
|
if (data.useRoundedCorners) outputSize * ComposeCoverDefaults.CORNER_RATIO else 0f
|
||||||
|
val stackBitmap =
|
||||||
|
StackGenerator.generate(
|
||||||
|
bitmaps,
|
||||||
|
StackGenerator.Config(
|
||||||
|
outputSizePx = outputSize,
|
||||||
|
gapWidthPx = outputSize * ComposeCoverDefaults.GAP_RATIO,
|
||||||
|
cornerRadiusPx = cornerRadiusPx,
|
||||||
|
backgroundColor = context.getColorCompat(R.color.sel_cover_bg).defaultColor,
|
||||||
|
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,
|
||||||
|
val backgroundColor: Int = "#0f111a".toColorInt(),
|
||||||
|
val zOrder: List<Int> = listOf(0, 1, 2, 3),
|
||||||
|
)
|
||||||
|
|
||||||
|
fun generate(sourceImages: List<Bitmap>, 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)
|
||||||
|
|
||||||
|
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<StackCoverCollection> {
|
||||||
|
override fun create(
|
||||||
|
data: StackCoverCollection,
|
||||||
|
options: Options,
|
||||||
|
imageLoader: ImageLoader,
|
||||||
|
) = StackComposeFetcher(options.context, data, options.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
class Keyer @Inject constructor() : CoilKeyer<StackCoverCollection> {
|
||||||
|
override fun key(data: StackCoverCollection, options: Options): String {
|
||||||
|
val config =
|
||||||
|
"${if (data.useRoundedCorners) "r" else "s"}.${data.zOrder.joinToString(".")}"
|
||||||
|
return "s:${data.covers.hashCode()}.${options.size.width}.${options.size.height}.$config"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user