slop
This commit is contained in:
@@ -19,14 +19,13 @@
|
||||
package org.oxycblt.auxio.home.list
|
||||
|
||||
import android.os.Bundle
|
||||
import android.text.format.DateUtils
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.view.isInvisible
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.fragment.app.activityViewModels
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import java.util.Formatter
|
||||
import java.util.Calendar
|
||||
import org.oxycblt.auxio.R
|
||||
import org.oxycblt.auxio.databinding.FragmentHomeListBinding
|
||||
import org.oxycblt.auxio.detail.DetailViewModel
|
||||
@@ -40,9 +39,8 @@ import org.oxycblt.auxio.list.recycler.FastScrollRecyclerView
|
||||
import org.oxycblt.auxio.list.sort.Sort
|
||||
import org.oxycblt.auxio.music.IndexingState
|
||||
import org.oxycblt.auxio.music.MusicViewModel
|
||||
import org.oxycblt.auxio.music.resolve
|
||||
import org.oxycblt.auxio.playback.PlaybackViewModel
|
||||
import org.oxycblt.auxio.playback.formatDurationMs
|
||||
import org.oxycblt.auxio.playback.formatDurationMsPopup
|
||||
import org.oxycblt.auxio.util.collectImmediately
|
||||
import org.oxycblt.musikr.Album
|
||||
import org.oxycblt.musikr.Music
|
||||
@@ -65,9 +63,6 @@ class AlbumListFragment :
|
||||
override val musicModel: MusicViewModel by activityViewModels()
|
||||
override val playbackModel: PlaybackViewModel by activityViewModels()
|
||||
private val albumAdapter = AlbumAdapter(this)
|
||||
// Save memory by re-using the same formatter and string builder when creating popup text
|
||||
private val formatterSb = StringBuilder(64)
|
||||
private val formatter = Formatter(formatterSb)
|
||||
|
||||
override fun onCreateBinding(inflater: LayoutInflater) =
|
||||
FragmentHomeListBinding.inflate(inflater)
|
||||
@@ -110,37 +105,41 @@ class AlbumListFragment :
|
||||
}
|
||||
}
|
||||
|
||||
override fun getPopup(pos: Int): String? {
|
||||
override fun getPopupData(pos: Int): FastScrollRecyclerView.PopupProvider.PopupData? {
|
||||
val album = homeModel.albumList.value.getOrNull(pos) ?: return null
|
||||
// Change how we display the popup depending on the current sort mode.
|
||||
return when (homeModel.albumSort.mode) {
|
||||
// By Name -> Use Name
|
||||
is Sort.Mode.ByName -> album.name.thumb()
|
||||
is Sort.Mode.ByName ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(album.name.thumb() ?: "?")
|
||||
|
||||
// By Artist -> Use name of first artist
|
||||
is Sort.Mode.ByArtist -> album.artists[0].name.thumb()
|
||||
is Sort.Mode.ByArtist ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(album.artists[0].name.thumb() ?: "?")
|
||||
|
||||
// Date -> Use minimum date (Maximum dates are not sorted by, so showing them is odd)
|
||||
is Sort.Mode.ByDate -> album.dates?.run { min.resolve(requireContext()) }
|
||||
// Date -> Use year of the range minimum
|
||||
is Sort.Mode.ByDate -> {
|
||||
val year = album.dates?.min?.year ?: return null
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(getString(R.string.fmt_number, year))
|
||||
}
|
||||
|
||||
// Duration -> Use formatted duration
|
||||
is Sort.Mode.ByDuration -> album.durationMs.formatDurationMs(false)
|
||||
// Duration -> Use compact bucket duration
|
||||
is Sort.Mode.ByDuration ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(
|
||||
album.durationMs.formatDurationMsPopup()
|
||||
)
|
||||
|
||||
// Count -> Use song count
|
||||
is Sort.Mode.ByCount -> album.songs.size.toString()
|
||||
is Sort.Mode.ByCount ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(album.songs.size.toString())
|
||||
|
||||
// Last added -> Format as date
|
||||
// Last added -> Use year
|
||||
is Sort.Mode.ByDateAdded -> {
|
||||
val dateAddedMillis = album.addedMs
|
||||
formatterSb.setLength(0)
|
||||
DateUtils.formatDateRange(
|
||||
context,
|
||||
formatter,
|
||||
dateAddedMillis,
|
||||
dateAddedMillis,
|
||||
DateUtils.FORMAT_ABBREV_ALL,
|
||||
)
|
||||
.toString()
|
||||
val calendar = Calendar.getInstance()
|
||||
calendar.timeInMillis = album.addedMs
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(
|
||||
getString(R.string.fmt_number, calendar.get(Calendar.YEAR))
|
||||
)
|
||||
}
|
||||
|
||||
// Unsupported sort, error gracefully
|
||||
|
||||
@@ -39,7 +39,7 @@ import org.oxycblt.auxio.list.sort.Sort
|
||||
import org.oxycblt.auxio.music.IndexingState
|
||||
import org.oxycblt.auxio.music.MusicViewModel
|
||||
import org.oxycblt.auxio.playback.PlaybackViewModel
|
||||
import org.oxycblt.auxio.playback.formatDurationMs
|
||||
import org.oxycblt.auxio.playback.formatDurationMsPopup
|
||||
import org.oxycblt.auxio.util.collectImmediately
|
||||
import org.oxycblt.auxio.util.positiveOrNull
|
||||
import org.oxycblt.musikr.Artist
|
||||
@@ -105,18 +105,25 @@ class ArtistListFragment :
|
||||
}
|
||||
}
|
||||
|
||||
override fun getPopup(pos: Int): String? {
|
||||
override fun getPopupData(pos: Int): FastScrollRecyclerView.PopupProvider.PopupData? {
|
||||
val artist = homeModel.artistList.value.getOrNull(pos) ?: return null
|
||||
// Change how we display the popup depending on the current sort mode.
|
||||
return when (homeModel.artistSort.mode) {
|
||||
// By Name -> Use Name
|
||||
is Sort.Mode.ByName -> artist.name.thumb()
|
||||
is Sort.Mode.ByName ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(artist.name.thumb() ?: "?")
|
||||
|
||||
// Duration -> Use formatted duration
|
||||
is Sort.Mode.ByDuration -> artist.durationMs?.formatDurationMs(false)
|
||||
// Duration -> Use compact bucket duration
|
||||
is Sort.Mode.ByDuration ->
|
||||
artist.durationMs?.formatDurationMsPopup()?.let {
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(it)
|
||||
}
|
||||
|
||||
// Count -> Use song count
|
||||
is Sort.Mode.ByCount -> artist.songs.size.positiveOrNull()?.toString()
|
||||
is Sort.Mode.ByCount ->
|
||||
artist.songs.size.positiveOrNull()?.toString()?.let {
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(it)
|
||||
}
|
||||
|
||||
// Unsupported sort, error gracefully
|
||||
else -> null
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.oxycblt.auxio.home.list
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import androidx.appcompat.widget.AppCompatImageView
|
||||
import org.oxycblt.auxio.home.list.CookieShapeDrawable
|
||||
|
||||
/** A placeholder [androidx.appcompat.widget.AppCompatImageView] with a 6-sided cookie expressive background shape. */
|
||||
class CookieImageView
|
||||
@JvmOverloads
|
||||
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
|
||||
AppCompatImageView(context, attrs, defStyleAttr) {
|
||||
init {
|
||||
background = CookieShapeDrawable(context)
|
||||
scaleType = ScaleType.CENTER_INSIDE
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ import org.oxycblt.auxio.list.sort.Sort
|
||||
import org.oxycblt.auxio.music.IndexingState
|
||||
import org.oxycblt.auxio.music.MusicViewModel
|
||||
import org.oxycblt.auxio.playback.PlaybackViewModel
|
||||
import org.oxycblt.auxio.playback.formatDurationMs
|
||||
import org.oxycblt.auxio.playback.formatDurationMsPopup
|
||||
import org.oxycblt.auxio.util.collectImmediately
|
||||
import org.oxycblt.musikr.Genre
|
||||
import org.oxycblt.musikr.Music
|
||||
@@ -104,18 +104,23 @@ class GenreListFragment :
|
||||
}
|
||||
}
|
||||
|
||||
override fun getPopup(pos: Int): String? {
|
||||
override fun getPopupData(pos: Int): FastScrollRecyclerView.PopupProvider.PopupData? {
|
||||
val genre = homeModel.genreList.value.getOrNull(pos) ?: return null
|
||||
// Change how we display the popup depending on the current sort mode.
|
||||
return when (homeModel.genreSort.mode) {
|
||||
// By Name -> Use Name
|
||||
is Sort.Mode.ByName -> genre.name.thumb()
|
||||
is Sort.Mode.ByName ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(genre.name.thumb() ?: "?")
|
||||
|
||||
// Duration -> Use formatted duration
|
||||
is Sort.Mode.ByDuration -> genre.durationMs.formatDurationMs(false)
|
||||
// Duration -> Use compact bucket duration
|
||||
is Sort.Mode.ByDuration ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(
|
||||
genre.durationMs.formatDurationMsPopup()
|
||||
)
|
||||
|
||||
// Count -> Use song count
|
||||
is Sort.Mode.ByCount -> genre.songs.size.toString()
|
||||
is Sort.Mode.ByCount ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(genre.songs.size.toString())
|
||||
|
||||
// Unsupported sort, error gracefully
|
||||
else -> null
|
||||
|
||||
@@ -18,8 +18,26 @@
|
||||
|
||||
package org.oxycblt.auxio.home.list
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.ColorFilter
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.PathMeasure
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.graphics.drawable.Drawable
|
||||
import androidx.core.text.isDigitsOnly
|
||||
import com.google.android.material.R
|
||||
import org.oxycblt.auxio.ui.ExpressiveShapes
|
||||
import org.oxycblt.auxio.util.getAttrColorCompat
|
||||
import org.oxycblt.musikr.tag.Name
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
fun Name.thumb() =
|
||||
when (this) {
|
||||
@@ -29,3 +47,100 @@ fun Name.thumb() =
|
||||
}
|
||||
is Name.Unknown -> "?"
|
||||
}
|
||||
|
||||
/**
|
||||
* A drawable that fills its bounds with the expressive 6-sided cookie shape.
|
||||
*
|
||||
* The shape is always rendered as a centered square and uniformly scaled from its geometric center
|
||||
* to avoid distortion in non-square bounds.
|
||||
*/
|
||||
class CookieShapeDrawable(context: Context) : Drawable() {
|
||||
private val pathPosition = FloatArray(2)
|
||||
private val pathMatrix = Matrix()
|
||||
private val pathBounds = RectF()
|
||||
private val paint =
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = context.getAttrColorCompat(R.attr.colorSurfaceVariant).defaultColor
|
||||
style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
private var fittedPath = Path()
|
||||
|
||||
override fun onBoundsChange(bounds: Rect) {
|
||||
super.onBoundsChange(bounds)
|
||||
rebuildPath()
|
||||
}
|
||||
|
||||
private fun rebuildPath() {
|
||||
val drawableBounds = bounds
|
||||
if (drawableBounds.isEmpty) {
|
||||
fittedPath = Path()
|
||||
return
|
||||
}
|
||||
|
||||
val size = min(drawableBounds.width(), drawableBounds.height()).toFloat()
|
||||
val left = drawableBounds.exactCenterX() - size / 2f
|
||||
val top = drawableBounds.exactCenterY() - size / 2f
|
||||
pathBounds.set(left, top, left + size, top + size)
|
||||
|
||||
fittedPath = ExpressiveShapes.getCookie6Sided(pathBounds)
|
||||
val maxRadius = computeMaxRadius(fittedPath, pathBounds.centerX(), pathBounds.centerY())
|
||||
if (maxRadius > 0f) {
|
||||
val targetRadius = size / 2f
|
||||
val uniformScale = targetRadius / maxRadius
|
||||
pathMatrix.reset()
|
||||
pathMatrix.setScale(
|
||||
uniformScale,
|
||||
uniformScale,
|
||||
pathBounds.centerX(),
|
||||
pathBounds.centerY(),
|
||||
)
|
||||
fittedPath.transform(pathMatrix)
|
||||
}
|
||||
}
|
||||
|
||||
override fun draw(canvas: Canvas) {
|
||||
if (fittedPath.isEmpty) {
|
||||
return
|
||||
}
|
||||
canvas.drawPath(fittedPath, paint)
|
||||
}
|
||||
|
||||
override fun setAlpha(alpha: Int) {
|
||||
paint.alpha = alpha.coerceIn(0, 255)
|
||||
invalidateSelf()
|
||||
}
|
||||
|
||||
override fun setColorFilter(colorFilter: ColorFilter?) {
|
||||
paint.colorFilter = colorFilter
|
||||
invalidateSelf()
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun getOpacity(): Int {
|
||||
return PixelFormat.TRANSLUCENT
|
||||
}
|
||||
|
||||
private fun computeMaxRadius(source: Path, centerX: Float, centerY: Float): Float {
|
||||
val measure = PathMeasure(source, false)
|
||||
var maxRadius = 0f
|
||||
|
||||
do {
|
||||
val length = measure.length
|
||||
if (length <= 0f) {
|
||||
continue
|
||||
}
|
||||
|
||||
val sampleCount = max((length / 1f).roundToInt(), 1)
|
||||
for (sample in 0..sampleCount) {
|
||||
val distance = length * sample / sampleCount
|
||||
if (measure.getPosTan(distance, pathPosition, null)) {
|
||||
maxRadius =
|
||||
max(maxRadius, hypot(pathPosition[0] - centerX, pathPosition[1] - centerY))
|
||||
}
|
||||
}
|
||||
} while (measure.nextContour())
|
||||
|
||||
return maxRadius
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ import org.oxycblt.auxio.list.sort.Sort
|
||||
import org.oxycblt.auxio.music.IndexingState
|
||||
import org.oxycblt.auxio.music.MusicViewModel
|
||||
import org.oxycblt.auxio.playback.PlaybackViewModel
|
||||
import org.oxycblt.auxio.playback.formatDurationMs
|
||||
import org.oxycblt.auxio.playback.formatDurationMsPopup
|
||||
import org.oxycblt.auxio.util.collectImmediately
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.MusicParent
|
||||
@@ -105,18 +105,23 @@ class PlaylistListFragment :
|
||||
}
|
||||
}
|
||||
|
||||
override fun getPopup(pos: Int): String? {
|
||||
override fun getPopupData(pos: Int): FastScrollRecyclerView.PopupProvider.PopupData? {
|
||||
val playlist = homeModel.playlistList.value.getOrNull(pos) ?: return null
|
||||
// Change how we display the popup depending on the current sort mode.
|
||||
return when (homeModel.playlistSort.mode) {
|
||||
// By Name -> Use Name
|
||||
is Sort.Mode.ByName -> playlist.name.thumb()
|
||||
is Sort.Mode.ByName ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(playlist.name.thumb() ?: "?")
|
||||
|
||||
// Duration -> Use formatted duration
|
||||
is Sort.Mode.ByDuration -> playlist.durationMs.formatDurationMs(false)
|
||||
// Duration -> Use compact bucket duration
|
||||
is Sort.Mode.ByDuration ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(
|
||||
playlist.durationMs.formatDurationMsPopup()
|
||||
)
|
||||
|
||||
// Count -> Use song count
|
||||
is Sort.Mode.ByCount -> playlist.songs.size.toString()
|
||||
is Sort.Mode.ByCount ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(playlist.songs.size.toString())
|
||||
|
||||
// Unsupported sort, error gracefully
|
||||
else -> null
|
||||
|
||||
@@ -19,14 +19,13 @@
|
||||
package org.oxycblt.auxio.home.list
|
||||
|
||||
import android.os.Bundle
|
||||
import android.text.format.DateUtils
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.view.isInvisible
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.fragment.app.activityViewModels
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import java.util.Formatter
|
||||
import java.util.Calendar
|
||||
import org.oxycblt.auxio.R
|
||||
import org.oxycblt.auxio.databinding.FragmentHomeListBinding
|
||||
import org.oxycblt.auxio.home.HomeViewModel
|
||||
@@ -39,9 +38,8 @@ import org.oxycblt.auxio.list.recycler.SongViewHolder
|
||||
import org.oxycblt.auxio.list.sort.Sort
|
||||
import org.oxycblt.auxio.music.IndexingState
|
||||
import org.oxycblt.auxio.music.MusicViewModel
|
||||
import org.oxycblt.auxio.music.resolve
|
||||
import org.oxycblt.auxio.playback.PlaybackViewModel
|
||||
import org.oxycblt.auxio.playback.formatDurationMs
|
||||
import org.oxycblt.auxio.playback.formatDurationMsPopup
|
||||
import org.oxycblt.auxio.util.collectImmediately
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.MusicParent
|
||||
@@ -63,10 +61,6 @@ class SongListFragment :
|
||||
override val playbackModel: PlaybackViewModel by activityViewModels()
|
||||
private val songAdapter = SongAdapter(this)
|
||||
|
||||
// Save memory by re-using the same formatter and string builder when creating popup text
|
||||
private val formatterSb = StringBuilder(64)
|
||||
private val formatter = Formatter(formatterSb)
|
||||
|
||||
override fun onCreateBinding(inflater: LayoutInflater) =
|
||||
FragmentHomeListBinding.inflate(inflater)
|
||||
|
||||
@@ -108,39 +102,45 @@ class SongListFragment :
|
||||
}
|
||||
}
|
||||
|
||||
override fun getPopup(pos: Int): String? {
|
||||
override fun getPopupData(pos: Int): FastScrollRecyclerView.PopupProvider.PopupData? {
|
||||
val song = homeModel.songList.value.getOrNull(pos) ?: return null
|
||||
// Change how we display the popup depending on the current sort mode.
|
||||
// Note: We don't use the more correct individual artist name here, as sorts are largely
|
||||
// based off the names of the parent objects and not the child objects.
|
||||
return when (homeModel.songSort.mode) {
|
||||
// Name -> Use name
|
||||
is Sort.Mode.ByName -> song.name.thumb()
|
||||
is Sort.Mode.ByName ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(song.name.thumb() ?: "?")
|
||||
|
||||
// Artist -> Use name of first artist
|
||||
is Sort.Mode.ByArtist -> song.album.artists[0].name.thumb()
|
||||
is Sort.Mode.ByArtist ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(
|
||||
song.album.artists[0].name.thumb() ?: "?"
|
||||
)
|
||||
|
||||
// Album -> Use Album Name
|
||||
is Sort.Mode.ByAlbum -> song.album.name.thumb()
|
||||
is Sort.Mode.ByAlbum ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(song.album.name.thumb() ?: "?")
|
||||
|
||||
// Year -> Use Full Year
|
||||
is Sort.Mode.ByDate -> song.album.dates?.resolve(requireContext())
|
||||
// Date -> Use year of the range minimum
|
||||
is Sort.Mode.ByDate -> {
|
||||
val year = song.album.dates?.min?.year ?: return null
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(getString(R.string.fmt_number, year))
|
||||
}
|
||||
|
||||
// Duration -> Use formatted duration
|
||||
is Sort.Mode.ByDuration -> song.durationMs.formatDurationMs(false)
|
||||
// Duration -> Use compact bucket duration
|
||||
is Sort.Mode.ByDuration ->
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(
|
||||
song.durationMs.formatDurationMsPopup()
|
||||
)
|
||||
|
||||
// Last added -> Format as date
|
||||
// Last added -> Use year
|
||||
is Sort.Mode.ByDateAdded -> {
|
||||
val dateAddedMillis = song.addedMs
|
||||
formatterSb.setLength(0)
|
||||
DateUtils.formatDateRange(
|
||||
context,
|
||||
formatter,
|
||||
dateAddedMillis,
|
||||
dateAddedMillis,
|
||||
DateUtils.FORMAT_ABBREV_ALL,
|
||||
)
|
||||
.toString()
|
||||
val calendar = Calendar.getInstance()
|
||||
calendar.timeInMillis = song.addedMs
|
||||
FastScrollRecyclerView.PopupProvider.PopupData(
|
||||
getString(R.string.fmt_number, calendar.get(Calendar.YEAR))
|
||||
)
|
||||
}
|
||||
|
||||
// Unsupported sort, error gracefully
|
||||
|
||||
@@ -458,7 +458,18 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
* @param errorRes The resource of the error drawable to use if the cover cannot be loaded.
|
||||
*/
|
||||
fun bind(songs: List<Song>, desc: String, @DrawableRes errorRes: Int) =
|
||||
bindImpl({ CoverCollection.from(songs.mapNotNull { it.cover }) }, desc, errorRes)
|
||||
bindImpl(
|
||||
{
|
||||
StackCoverCollection(
|
||||
CoverCollection.from(songs.mapNotNull { it.cover }),
|
||||
coverCollectionCornerRatio(),
|
||||
coverCollectionZOrder(songs.hashCode()),
|
||||
coverCollectionBackgroundColor(),
|
||||
)
|
||||
},
|
||||
desc,
|
||||
errorRes,
|
||||
)
|
||||
|
||||
private fun bindImpl(
|
||||
cover: () -> Any?,
|
||||
|
||||
@@ -22,10 +22,19 @@ import android.animation.Animator
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.ColorFilter
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.PathMeasure
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.os.Build
|
||||
import android.text.TextUtils
|
||||
import android.text.Layout
|
||||
import android.util.AttributeSet
|
||||
import android.util.TypedValue
|
||||
import android.view.Gravity
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
@@ -39,18 +48,24 @@ import androidx.core.view.isEmpty
|
||||
import androidx.core.view.isInvisible
|
||||
import androidx.core.view.updatePaddingRelative
|
||||
import androidx.core.widget.TextViewCompat
|
||||
import androidx.dynamicanimation.animation.FloatValueHolder
|
||||
import androidx.dynamicanimation.animation.SpringAnimation
|
||||
import androidx.dynamicanimation.animation.SpringForce
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.google.android.material.R as MR
|
||||
import com.google.android.material.motion.MotionUtils
|
||||
import com.google.android.material.textview.MaterialTextView
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
import org.oxycblt.auxio.R
|
||||
import org.oxycblt.auxio.ui.MaterialFadingSlider
|
||||
import org.oxycblt.auxio.ui.ExpressiveShapes
|
||||
import org.oxycblt.auxio.ui.MaterialSlider
|
||||
import org.oxycblt.auxio.util.getAttrColorCompat
|
||||
import org.oxycblt.auxio.util.getAttrResourceId
|
||||
import org.oxycblt.auxio.util.getDimenPixels
|
||||
import org.oxycblt.auxio.util.getDrawableCompat
|
||||
import org.oxycblt.auxio.util.inflater
|
||||
import org.oxycblt.auxio.util.isRtl
|
||||
import org.oxycblt.auxio.util.isUnder
|
||||
@@ -80,6 +95,8 @@ import org.oxycblt.auxio.util.systemBarInsetsCompat
|
||||
* - Added documentation
|
||||
* - Completely new design
|
||||
* - New scroll position backend
|
||||
* - M3 (Expressive) Redesign
|
||||
* - Dynamic popups
|
||||
*
|
||||
* @author Hai Zhang, Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@@ -107,48 +124,92 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
hideThumb()
|
||||
}
|
||||
}
|
||||
private val popupContainerSize = context.getDimenPixels(R.dimen.size_fast_scroll_popup)
|
||||
private val popupTextAutoScaleMinSize =
|
||||
context.getDimenPixels(R.dimen.text_size_fast_scroll_popup_min)
|
||||
private val popupTextAutoScaleMaxSize =
|
||||
context.getDimenPixels(R.dimen.text_size_fast_scroll_popup_max)
|
||||
private val popupTextAutoScaleStepGranularity =
|
||||
context.getDimenPixels(R.dimen.text_size_fast_scroll_popup_step)
|
||||
private val popupTextAutoScaleMinSizePx = popupTextAutoScaleMinSize.coerceAtLeast(1)
|
||||
private val popupTextAutoScaleMaxSizePx =
|
||||
popupTextAutoScaleMaxSize.coerceAtLeast(popupTextAutoScaleMinSizePx)
|
||||
private val popupTextAutoScaleStepGranularityPx =
|
||||
popupTextAutoScaleStepGranularity.coerceAtLeast(1)
|
||||
private var popupTextAutoScaleCeilingPx = popupTextAutoScaleMaxSizePx
|
||||
private var popupTextAutoScaleKey: PopupTextAutoScaleKey? = null
|
||||
|
||||
private val popupView =
|
||||
MaterialTextView(context).apply {
|
||||
minimumWidth = context.getDimenPixels(R.dimen.size_touchable_large)
|
||||
minimumHeight = context.getDimenPixels(R.dimen.size_touchable_small)
|
||||
|
||||
TextViewCompat.setTextAppearance(
|
||||
private val popupTextView =
|
||||
createPopupTextView(context).apply {
|
||||
setTextColor(context.getAttrColorCompat(MR.attr.colorOnSecondary))
|
||||
maxLines = POPUP_TEXT_SINGLE_LINE_COUNT
|
||||
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(
|
||||
this,
|
||||
context.getAttrResourceId(
|
||||
com.google.android.material.R.attr.textAppearanceHeadlineMediumEmphasized
|
||||
popupTextAutoScaleMinSizePx,
|
||||
popupTextAutoScaleCeilingPx,
|
||||
popupTextAutoScaleStepGranularityPx,
|
||||
TypedValue.COMPLEX_UNIT_PX,
|
||||
)
|
||||
}
|
||||
private val popupTextMeasurementView = createPopupTextView(context)
|
||||
private val popupTextWidestDigit: Char = run {
|
||||
val paint = popupTextMeasurementView.paint
|
||||
('0'..'9').maxByOrNull { paint.measureText(it.toString()) } ?: '0'
|
||||
}
|
||||
private val popupBackgroundDrawable = SoftBurstPopupDrawable(context)
|
||||
private val popupView =
|
||||
FrameLayout(context).apply {
|
||||
elevation = context.getDimenPixels(MR.dimen.m3_sys_elevation_level1).toFloat()
|
||||
background = popupBackgroundDrawable
|
||||
minimumWidth = popupContainerSize
|
||||
minimumHeight = popupContainerSize
|
||||
|
||||
val paddingHorizontal =
|
||||
context.getDimenPixels(R.dimen.padding_fast_scroll_popup_horizontal)
|
||||
val paddingVertical = context.getDimenPixels(R.dimen.padding_fast_scroll_popup_vertical)
|
||||
updatePaddingRelative(
|
||||
start = paddingHorizontal,
|
||||
top = paddingVertical,
|
||||
end = paddingHorizontal,
|
||||
bottom = paddingVertical,
|
||||
)
|
||||
addView(
|
||||
popupTextView,
|
||||
FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
Gravity.CENTER,
|
||||
),
|
||||
)
|
||||
setTextColor(
|
||||
context.getAttrColorCompat(com.google.android.material.R.attr.colorOnSecondary)
|
||||
)
|
||||
ellipsize = TextUtils.TruncateAt.MIDDLE
|
||||
gravity = Gravity.CENTER
|
||||
includeFontPadding = false
|
||||
|
||||
elevation =
|
||||
context
|
||||
.getDimenPixels(com.google.android.material.R.dimen.m3_sys_elevation_level1)
|
||||
.toFloat()
|
||||
background = context.getDrawableCompat(R.drawable.ui_popup)
|
||||
val paddingStart = context.getDimenPixels(R.dimen.spacing_medium)
|
||||
val paddingEnd = paddingStart + context.getDimenPixels(R.dimen.spacing_tiny) / 2
|
||||
updatePaddingRelative(start = paddingStart, end = paddingEnd)
|
||||
layoutParams =
|
||||
FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
)
|
||||
.apply {
|
||||
marginEnd = context.getDimenPixels(R.dimen.size_touchable_small)
|
||||
gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP
|
||||
}
|
||||
FrameLayout.LayoutParams(popupContainerSize, popupContainerSize).apply {
|
||||
marginEnd = context.getDimenPixels(R.dimen.size_touchable_small)
|
||||
gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP
|
||||
}
|
||||
}
|
||||
private val popupSlider =
|
||||
MaterialFadingSlider(MaterialSlider.large(context, popupView.minimumWidth / 2)).apply {
|
||||
jumpOut(popupView)
|
||||
private val popupTextStaggerDelayMillis =
|
||||
MotionUtils.resolveThemeDuration(context, MR.attr.motionDurationShort2, 100).toLong()
|
||||
private val popupSpatialSpring =
|
||||
MotionUtils.resolveThemeSpringForce(
|
||||
context,
|
||||
MR.attr.motionSpringFastSpatial,
|
||||
MR.style.Motion_Material3_Spring_Standard_Fast_Spatial,
|
||||
)
|
||||
private val popupEffectsSpring =
|
||||
MotionUtils.resolveThemeSpringForce(
|
||||
context,
|
||||
MR.attr.motionSpringDefaultEffects,
|
||||
MR.style.Motion_Material3_Spring_Standard_Default_Effects,
|
||||
)
|
||||
private var popupShapeScaleAnimation: SpringAnimation? = null
|
||||
private var popupShapeAlphaAnimation: SpringAnimation? = null
|
||||
private var popupTextScaleAnimation: SpringAnimation? = null
|
||||
private var popupTextAlphaAnimation: SpringAnimation? = null
|
||||
private val popupTextRevealRunnable = Runnable {
|
||||
if (showingPopup) {
|
||||
animatePopupTextIn()
|
||||
}
|
||||
private var popupAnimator: Animator? = null
|
||||
}
|
||||
private var showingPopup = false
|
||||
|
||||
// Touch
|
||||
@@ -211,6 +272,7 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
init {
|
||||
overlay.add(thumbView)
|
||||
overlay.add(popupView)
|
||||
jumpOutPopup()
|
||||
|
||||
addItemDecoration(
|
||||
object : ItemDecoration() {
|
||||
@@ -243,6 +305,15 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
private fun onPreDraw() {
|
||||
updateThumbState()
|
||||
|
||||
val thumbRange = thumbOffsetRange
|
||||
val scrollFraction =
|
||||
if (thumbRange > 0) {
|
||||
(thumbOffset / thumbRange.toFloat()).coerceIn(0f, 1f)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
popupBackgroundDrawable.scrollRotationDegrees = scrollFraction * 360f
|
||||
|
||||
thumbView.layoutDirection = layoutDirection
|
||||
thumbView.measure(
|
||||
MeasureSpec.makeMeasureSpec(thumbWidth, MeasureSpec.EXACTLY),
|
||||
@@ -266,51 +337,61 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
NO_POSITION
|
||||
}
|
||||
|
||||
val popupText: String
|
||||
val provider = popupProvider
|
||||
if (firstAdapterPos != NO_POSITION && provider != null) {
|
||||
val hasPopupProvider = firstAdapterPos != NO_POSITION && provider != null
|
||||
val popupData =
|
||||
if (hasPopupProvider) {
|
||||
provider.getPopupData(firstAdapterPos)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val popupText: String
|
||||
if (hasPopupProvider) {
|
||||
popupView.isInvisible = false
|
||||
// Get the popup text. If there is none, we default to "?".
|
||||
popupText = provider.getPopup(firstAdapterPos) ?: "?"
|
||||
popupText = popupData?.text ?: "?"
|
||||
} else {
|
||||
// No valid position or provider, do not show the popup.
|
||||
popupView.isInvisible = false
|
||||
popupView.isInvisible = true
|
||||
popupText = ""
|
||||
}
|
||||
val popupLayoutParams = popupView.layoutParams as FrameLayout.LayoutParams
|
||||
|
||||
if (popupView.text != popupText) {
|
||||
popupView.text = popupText
|
||||
val popupMaxWidth =
|
||||
width -
|
||||
thumbPadding.left -
|
||||
thumbPadding.right -
|
||||
thumbWidth -
|
||||
popupLayoutParams.leftMargin -
|
||||
popupLayoutParams.rightMargin
|
||||
val popupMaxHeight =
|
||||
height -
|
||||
thumbPadding.top -
|
||||
thumbPadding.bottom -
|
||||
popupLayoutParams.topMargin -
|
||||
popupLayoutParams.bottomMargin
|
||||
|
||||
val widthMeasureSpec =
|
||||
ViewGroup.getChildMeasureSpec(
|
||||
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
|
||||
thumbPadding.left +
|
||||
thumbPadding.right +
|
||||
thumbWidth +
|
||||
popupLayoutParams.leftMargin +
|
||||
popupLayoutParams.rightMargin,
|
||||
popupLayoutParams.width,
|
||||
)
|
||||
|
||||
val heightMeasureSpec =
|
||||
ViewGroup.getChildMeasureSpec(
|
||||
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
|
||||
thumbPadding.top +
|
||||
thumbPadding.bottom +
|
||||
popupLayoutParams.topMargin +
|
||||
popupLayoutParams.bottomMargin,
|
||||
popupLayoutParams.height,
|
||||
)
|
||||
|
||||
popupView.measure(widthMeasureSpec, heightMeasureSpec)
|
||||
val maxPopupSize = min(popupMaxWidth, popupMaxHeight).coerceAtLeast(0)
|
||||
val popupSize =
|
||||
if (maxPopupSize > 0) {
|
||||
popupContainerSize.coerceAtMost(maxPopupSize)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
updatePopupTextAutoScaleConfigFor(popupText, popupSize)
|
||||
if (popupTextView.text != popupText) {
|
||||
popupTextView.text = popupText
|
||||
if (showingPopup) {
|
||||
doPopupVibration()
|
||||
}
|
||||
}
|
||||
popupView.measure(
|
||||
MeasureSpec.makeMeasureSpec(popupSize, MeasureSpec.EXACTLY),
|
||||
MeasureSpec.makeMeasureSpec(popupSize, MeasureSpec.EXACTLY),
|
||||
)
|
||||
|
||||
val popupWidth = popupView.measuredWidth
|
||||
val popupHeight = popupView.measuredHeight
|
||||
val popupWidth = popupSize
|
||||
val popupHeight = popupSize
|
||||
val popupLeft =
|
||||
if (layoutDirection == View.LAYOUT_DIRECTION_RTL) {
|
||||
thumbPadding.left + thumbWidth + popupLayoutParams.leftMargin
|
||||
@@ -484,8 +565,10 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
}
|
||||
|
||||
showingPopup = true
|
||||
popupAnimator?.cancel()
|
||||
popupAnimator = popupSlider.slideIn(popupView).also { it.start() }
|
||||
resetPopupTextAutoScaleConfig()
|
||||
cancelPopupAnimations()
|
||||
animatePopupShapeIn()
|
||||
popupView.postDelayed(popupTextRevealRunnable, popupTextStaggerDelayMillis)
|
||||
}
|
||||
|
||||
private fun hidePopup() {
|
||||
@@ -494,8 +577,235 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
}
|
||||
|
||||
showingPopup = false
|
||||
popupAnimator?.cancel()
|
||||
popupAnimator = popupSlider.slideOut(popupView).also { it.start() }
|
||||
cancelPopupAnimations()
|
||||
animatePopupTextOut()
|
||||
animatePopupShapeOut()
|
||||
}
|
||||
|
||||
private fun jumpOutPopup() {
|
||||
popupBackgroundDrawable.revealScale = POPUP_SHAPE_HIDDEN_SCALE
|
||||
popupBackgroundDrawable.revealAlpha = 0f
|
||||
popupTextView.alpha = 0f
|
||||
popupTextView.scaleX = POPUP_TEXT_HIDDEN_SCALE
|
||||
popupTextView.scaleY = POPUP_TEXT_HIDDEN_SCALE
|
||||
}
|
||||
|
||||
private fun cancelPopupAnimations() {
|
||||
popupView.removeCallbacks(popupTextRevealRunnable)
|
||||
popupShapeScaleAnimation?.cancel()
|
||||
popupShapeScaleAnimation = null
|
||||
popupShapeAlphaAnimation?.cancel()
|
||||
popupShapeAlphaAnimation = null
|
||||
popupTextScaleAnimation?.cancel()
|
||||
popupTextScaleAnimation = null
|
||||
popupTextAlphaAnimation?.cancel()
|
||||
popupTextAlphaAnimation = null
|
||||
}
|
||||
|
||||
private fun animatePopupShapeIn() {
|
||||
popupShapeScaleAnimation =
|
||||
springTo(
|
||||
startValue = popupBackgroundDrawable.revealScale,
|
||||
finalValue = 1f,
|
||||
springTemplate = popupSpatialSpring,
|
||||
minimumVisibleChange = 0.001f,
|
||||
) {
|
||||
popupBackgroundDrawable.revealScale = it
|
||||
}
|
||||
popupShapeAlphaAnimation =
|
||||
springTo(
|
||||
startValue = popupBackgroundDrawable.revealAlpha,
|
||||
finalValue = 1f,
|
||||
springTemplate = popupEffectsSpring,
|
||||
minimumVisibleChange = 1f / 255f,
|
||||
) {
|
||||
popupBackgroundDrawable.revealAlpha = it
|
||||
}
|
||||
}
|
||||
|
||||
private fun animatePopupShapeOut() {
|
||||
popupShapeScaleAnimation =
|
||||
springTo(
|
||||
startValue = popupBackgroundDrawable.revealScale,
|
||||
finalValue = POPUP_SHAPE_HIDDEN_SCALE,
|
||||
springTemplate = popupSpatialSpring,
|
||||
minimumVisibleChange = 0.001f,
|
||||
) {
|
||||
popupBackgroundDrawable.revealScale = it
|
||||
}
|
||||
popupShapeAlphaAnimation =
|
||||
springTo(
|
||||
startValue = popupBackgroundDrawable.revealAlpha,
|
||||
finalValue = 0f,
|
||||
springTemplate = popupEffectsSpring,
|
||||
minimumVisibleChange = 1f / 255f,
|
||||
) {
|
||||
popupBackgroundDrawable.revealAlpha = it
|
||||
}
|
||||
}
|
||||
|
||||
private fun animatePopupTextIn() {
|
||||
popupTextScaleAnimation =
|
||||
springTo(
|
||||
startValue = popupTextView.scaleX,
|
||||
finalValue = 1f,
|
||||
springTemplate = popupSpatialSpring,
|
||||
minimumVisibleChange = 0.001f,
|
||||
) {
|
||||
popupTextView.scaleX = it
|
||||
popupTextView.scaleY = it
|
||||
}
|
||||
popupTextAlphaAnimation =
|
||||
springTo(
|
||||
startValue = popupTextView.alpha,
|
||||
finalValue = 1f,
|
||||
springTemplate = popupEffectsSpring,
|
||||
minimumVisibleChange = 1f / 255f,
|
||||
) {
|
||||
popupTextView.alpha = it
|
||||
}
|
||||
}
|
||||
|
||||
private fun animatePopupTextOut() {
|
||||
popupTextScaleAnimation =
|
||||
springTo(
|
||||
startValue = popupTextView.scaleX,
|
||||
finalValue = POPUP_TEXT_HIDDEN_SCALE,
|
||||
springTemplate = popupSpatialSpring,
|
||||
minimumVisibleChange = 0.001f,
|
||||
) {
|
||||
popupTextView.scaleX = it
|
||||
popupTextView.scaleY = it
|
||||
}
|
||||
popupTextAlphaAnimation =
|
||||
springTo(
|
||||
startValue = popupTextView.alpha,
|
||||
finalValue = 0f,
|
||||
springTemplate = popupEffectsSpring,
|
||||
minimumVisibleChange = 1f / 255f,
|
||||
) {
|
||||
popupTextView.alpha = it
|
||||
}
|
||||
}
|
||||
|
||||
private fun createPopupTextView(context: Context): MaterialTextView =
|
||||
MaterialTextView(context).apply {
|
||||
TextViewCompat.setTextAppearance(
|
||||
this,
|
||||
context.getAttrResourceId(MR.attr.textAppearanceHeadlineMediumEmphasized),
|
||||
)
|
||||
ellipsize = null
|
||||
gravity = Gravity.CENTER
|
||||
textAlignment = View.TEXT_ALIGNMENT_CENTER
|
||||
includeFontPadding = false
|
||||
setHorizontallyScrolling(false)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
breakStrategy = Layout.BREAK_STRATEGY_SIMPLE
|
||||
hyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE
|
||||
}
|
||||
}
|
||||
|
||||
private fun resetPopupTextAutoScaleConfig() {
|
||||
popupTextAutoScaleKey = null
|
||||
applyPopupTextAutoScaleConfig(popupTextAutoScaleMaxSizePx)
|
||||
}
|
||||
|
||||
private fun updatePopupTextAutoScaleConfigFor(text: String, popupSize: Int) {
|
||||
if (popupSize <= 0) {
|
||||
resetPopupTextAutoScaleConfig()
|
||||
return
|
||||
}
|
||||
|
||||
val exemplar = normalizeToExemplar(text)
|
||||
val key = PopupTextAutoScaleKey(exemplar = exemplar, popupSize = popupSize)
|
||||
if (popupTextAutoScaleKey == key) {
|
||||
return
|
||||
}
|
||||
popupTextAutoScaleKey = key
|
||||
|
||||
if (exemplar == null) {
|
||||
applyPopupTextAutoScaleConfig(popupTextAutoScaleMaxSizePx)
|
||||
return
|
||||
}
|
||||
|
||||
val textWidth =
|
||||
(popupSize - popupView.paddingLeft - popupView.paddingRight).coerceAtLeast(1)
|
||||
val textHeight =
|
||||
(popupSize - popupView.paddingTop - popupView.paddingBottom).coerceAtLeast(1)
|
||||
val ceilingPx = measurePopupTextCeiling(exemplar, textWidth, textHeight)
|
||||
applyPopupTextAutoScaleConfig(ceilingPx)
|
||||
}
|
||||
|
||||
private fun normalizeToExemplar(text: String): String? {
|
||||
if (text.length <= 1) return null
|
||||
return buildString(text.length) {
|
||||
for (c in text) {
|
||||
append(if (c.isDigit()) popupTextWidestDigit else c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun measurePopupTextCeiling(
|
||||
exemplar: String,
|
||||
availableWidth: Int,
|
||||
availableHeight: Int,
|
||||
): Int {
|
||||
val paint = popupTextMeasurementView.paint
|
||||
val savedSize = paint.textSize
|
||||
var bestSize = popupTextAutoScaleMinSizePx
|
||||
for (sizePx in
|
||||
popupTextAutoScaleMaxSizePx downTo
|
||||
popupTextAutoScaleMinSizePx step
|
||||
popupTextAutoScaleStepGranularityPx) {
|
||||
paint.textSize = sizePx.toFloat()
|
||||
val w = paint.measureText(exemplar)
|
||||
val metrics = paint.fontMetrics
|
||||
val h = metrics.descent - metrics.ascent
|
||||
if (w <= availableWidth && h <= availableHeight) {
|
||||
bestSize = sizePx
|
||||
break
|
||||
}
|
||||
}
|
||||
paint.textSize = savedSize
|
||||
return bestSize
|
||||
}
|
||||
|
||||
private fun applyPopupTextAutoScaleConfig(maxSizePx: Int) {
|
||||
popupTextAutoScaleCeilingPx =
|
||||
maxSizePx.coerceIn(popupTextAutoScaleMinSizePx, popupTextAutoScaleMaxSizePx)
|
||||
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(
|
||||
popupTextView,
|
||||
popupTextAutoScaleMinSizePx,
|
||||
popupTextAutoScaleCeilingPx,
|
||||
popupTextAutoScaleStepGranularityPx,
|
||||
TypedValue.COMPLEX_UNIT_PX,
|
||||
)
|
||||
}
|
||||
|
||||
private fun springTo(
|
||||
startValue: Float,
|
||||
finalValue: Float,
|
||||
springTemplate: SpringForce,
|
||||
minimumVisibleChange: Float,
|
||||
update: (Float) -> Unit,
|
||||
): SpringAnimation {
|
||||
val animation =
|
||||
SpringAnimation(FloatValueHolder(startValue)).apply {
|
||||
spring =
|
||||
SpringForce().apply {
|
||||
dampingRatio = springTemplate.dampingRatio
|
||||
stiffness = springTemplate.stiffness
|
||||
finalPosition = finalValue
|
||||
}
|
||||
setStartValue(startValue)
|
||||
setMinimumVisibleChange(minimumVisibleChange)
|
||||
addUpdateListener { _, value, _ -> update(value) }
|
||||
addEndListener { _, canceled, value, _ ->
|
||||
update(if (canceled) value else finalValue)
|
||||
}
|
||||
}
|
||||
animation.animateToFinalPosition(finalValue)
|
||||
return animation
|
||||
}
|
||||
|
||||
private fun doPopupVibration() {
|
||||
@@ -518,13 +828,15 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
/** An interface to provide text to use in the popup when fast-scrolling. */
|
||||
interface PopupProvider {
|
||||
/**
|
||||
* Get text to use in the popup at the specified position.
|
||||
* Get popup metadata at the specified position.
|
||||
*
|
||||
* @param pos The position in the list.
|
||||
* @return A [String] to use in the popup. Null if there is no applicable text for the popup
|
||||
* at [pos].
|
||||
* @return A [PopupData] to use in the popup. Null if there is no applicable text for the
|
||||
* popup at [pos].
|
||||
*/
|
||||
fun getPopup(pos: Int): String?
|
||||
fun getPopupData(pos: Int): PopupData?
|
||||
|
||||
data class PopupData(val text: String)
|
||||
}
|
||||
|
||||
/** A listener for fast scroller interactions. */
|
||||
@@ -539,5 +851,151 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
|
||||
private companion object {
|
||||
const val AUTO_HIDE_SCROLLBAR_DELAY_MILLIS = 500
|
||||
const val POPUP_SHAPE_HIDDEN_SCALE = 0.62f
|
||||
const val POPUP_TEXT_HIDDEN_SCALE = 0.78f
|
||||
const val POPUP_TEXT_SINGLE_LINE_COUNT = 1
|
||||
}
|
||||
|
||||
private data class PopupTextAutoScaleKey(val exemplar: String?, val popupSize: Int)
|
||||
}
|
||||
|
||||
private class SoftBurstPopupDrawable(context: Context) : Drawable() {
|
||||
private val baseRotationDegrees = 14f
|
||||
private val pathPosition = FloatArray(2)
|
||||
private val pathMatrix = Matrix()
|
||||
private val pathBounds = RectF()
|
||||
private val paint =
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color =
|
||||
context
|
||||
.getAttrColorCompat(com.google.android.material.R.attr.colorSecondary)
|
||||
.defaultColor
|
||||
style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
private var fittedPath = Path()
|
||||
private var shapeAlpha = 255
|
||||
var revealScale = 1f
|
||||
set(value) {
|
||||
val clampedValue = value.coerceIn(0f, 1f)
|
||||
if (field == clampedValue) {
|
||||
return
|
||||
}
|
||||
|
||||
field = clampedValue
|
||||
invalidateSelf()
|
||||
}
|
||||
|
||||
var revealAlpha = 1f
|
||||
set(value) {
|
||||
val clampedValue = value.coerceIn(0f, 1f)
|
||||
if (field == clampedValue) {
|
||||
return
|
||||
}
|
||||
|
||||
field = clampedValue
|
||||
updatePaintAlpha()
|
||||
}
|
||||
|
||||
var scrollRotationDegrees = 0f
|
||||
set(value) {
|
||||
if (field == value) {
|
||||
return
|
||||
}
|
||||
|
||||
field = value
|
||||
invalidateSelf()
|
||||
}
|
||||
|
||||
override fun onBoundsChange(bounds: Rect) {
|
||||
super.onBoundsChange(bounds)
|
||||
rebuildPath()
|
||||
}
|
||||
|
||||
private fun rebuildPath() {
|
||||
val drawableBounds = bounds
|
||||
if (drawableBounds.isEmpty) {
|
||||
fittedPath = Path()
|
||||
return
|
||||
}
|
||||
|
||||
val size = min(drawableBounds.width(), drawableBounds.height()).toFloat()
|
||||
val left = drawableBounds.exactCenterX() - size / 2f
|
||||
val top = drawableBounds.exactCenterY() - size / 2f
|
||||
pathBounds.set(left, top, left + size, top + size)
|
||||
|
||||
fittedPath = ExpressiveShapes.getSoftBurst(pathBounds)
|
||||
val maxRadius = computeMaxRadius(fittedPath, pathBounds.centerX(), pathBounds.centerY())
|
||||
if (maxRadius > 0f) {
|
||||
val targetRadius = size / 2f
|
||||
val uniformScale = targetRadius / maxRadius
|
||||
pathMatrix.reset()
|
||||
pathMatrix.setScale(
|
||||
uniformScale,
|
||||
uniformScale,
|
||||
pathBounds.centerX(),
|
||||
pathBounds.centerY(),
|
||||
)
|
||||
fittedPath.transform(pathMatrix)
|
||||
}
|
||||
}
|
||||
|
||||
override fun draw(canvas: Canvas) {
|
||||
if (fittedPath.isEmpty) {
|
||||
return
|
||||
}
|
||||
|
||||
val checkpoint = canvas.save()
|
||||
canvas.scale(revealScale, revealScale, pathBounds.centerX(), pathBounds.centerY())
|
||||
canvas.rotate(
|
||||
baseRotationDegrees + scrollRotationDegrees,
|
||||
pathBounds.centerX(),
|
||||
pathBounds.centerY(),
|
||||
)
|
||||
canvas.drawPath(fittedPath, paint)
|
||||
canvas.restoreToCount(checkpoint)
|
||||
}
|
||||
|
||||
override fun setAlpha(alpha: Int) {
|
||||
shapeAlpha = alpha.coerceIn(0, 255)
|
||||
updatePaintAlpha()
|
||||
}
|
||||
|
||||
override fun setColorFilter(colorFilter: ColorFilter?) {
|
||||
paint.colorFilter = colorFilter
|
||||
invalidateSelf()
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun getOpacity(): Int {
|
||||
return PixelFormat.TRANSLUCENT
|
||||
}
|
||||
|
||||
private fun computeMaxRadius(source: Path, centerX: Float, centerY: Float): Float {
|
||||
val measure = PathMeasure(source, false)
|
||||
var maxRadius = 0f
|
||||
|
||||
do {
|
||||
val length = measure.length
|
||||
if (length <= 0f) {
|
||||
continue
|
||||
}
|
||||
|
||||
val sampleCount = max((length / 1f).roundToInt(), 1)
|
||||
for (sample in 0..sampleCount) {
|
||||
val distance = length * sample / sampleCount
|
||||
if (measure.getPosTan(distance, pathPosition, null)) {
|
||||
maxRadius =
|
||||
max(maxRadius, hypot(pathPosition[0] - centerX, pathPosition[1] - centerY))
|
||||
}
|
||||
}
|
||||
} while (measure.nextContour())
|
||||
|
||||
return maxRadius
|
||||
}
|
||||
|
||||
private fun updatePaintAlpha() {
|
||||
paint.alpha = (shapeAlpha * revealAlpha).roundToInt().coerceIn(0, 255)
|
||||
invalidateSelf()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* SoftBurstImageView.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.list.recycler
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import androidx.appcompat.widget.AppCompatImageView
|
||||
|
||||
/** A placeholder [AppCompatImageView] with a soft-burst expressive background shape. */
|
||||
class SoftBurstImageView
|
||||
@JvmOverloads
|
||||
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
|
||||
AppCompatImageView(context, attrs, defStyleAttr) {
|
||||
init {
|
||||
background = SoftBurstShapeDrawable(context)
|
||||
scaleType = ScaleType.CENTER_INSIDE
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* SoftBurstShapeDrawable.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.list.recycler
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.ColorFilter
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.PathMeasure
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.graphics.drawable.Drawable
|
||||
import org.oxycblt.auxio.ui.ExpressiveShapes
|
||||
import com.google.android.material.R as MR
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
import org.oxycblt.auxio.util.getAttrColorCompat
|
||||
|
||||
/**
|
||||
* A drawable that fills its bounds with the expressive soft-burst shape.
|
||||
*
|
||||
* The shape is always rendered as a centered square and uniformly scaled from its geometric center
|
||||
* to avoid distortion in non-square bounds.
|
||||
*/
|
||||
class SoftBurstShapeDrawable(context: Context) : Drawable() {
|
||||
private val pathPosition = FloatArray(2)
|
||||
private val pathMatrix = Matrix()
|
||||
private val pathBounds = RectF()
|
||||
private val paint =
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = context.getAttrColorCompat(MR.attr.colorSecondaryContainer).defaultColor
|
||||
style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
private var fittedPath = Path()
|
||||
|
||||
override fun onBoundsChange(bounds: Rect) {
|
||||
super.onBoundsChange(bounds)
|
||||
rebuildPath()
|
||||
}
|
||||
|
||||
private fun rebuildPath() {
|
||||
val drawableBounds = bounds
|
||||
if (drawableBounds.isEmpty) {
|
||||
fittedPath = Path()
|
||||
return
|
||||
}
|
||||
|
||||
val size = min(drawableBounds.width(), drawableBounds.height()).toFloat()
|
||||
val left = drawableBounds.exactCenterX() - size / 2f
|
||||
val top = drawableBounds.exactCenterY() - size / 2f
|
||||
pathBounds.set(left, top, left + size, top + size)
|
||||
|
||||
fittedPath = ExpressiveShapes.getSoftBurst(pathBounds)
|
||||
val maxRadius = computeMaxRadius(fittedPath, pathBounds.centerX(), pathBounds.centerY())
|
||||
if (maxRadius > 0f) {
|
||||
val targetRadius = size / 2f
|
||||
val uniformScale = targetRadius / maxRadius
|
||||
pathMatrix.reset()
|
||||
pathMatrix.setScale(
|
||||
uniformScale,
|
||||
uniformScale,
|
||||
pathBounds.centerX(),
|
||||
pathBounds.centerY(),
|
||||
)
|
||||
fittedPath.transform(pathMatrix)
|
||||
}
|
||||
}
|
||||
|
||||
override fun draw(canvas: Canvas) {
|
||||
if (fittedPath.isEmpty) {
|
||||
return
|
||||
}
|
||||
canvas.drawPath(fittedPath, paint)
|
||||
}
|
||||
|
||||
override fun setAlpha(alpha: Int) {
|
||||
paint.alpha = alpha.coerceIn(0, 255)
|
||||
invalidateSelf()
|
||||
}
|
||||
|
||||
override fun setColorFilter(colorFilter: ColorFilter?) {
|
||||
paint.colorFilter = colorFilter
|
||||
invalidateSelf()
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun getOpacity(): Int {
|
||||
return PixelFormat.TRANSLUCENT
|
||||
}
|
||||
|
||||
private fun computeMaxRadius(source: Path, centerX: Float, centerY: Float): Float {
|
||||
val measure = PathMeasure(source, false)
|
||||
var maxRadius = 0f
|
||||
|
||||
do {
|
||||
val length = measure.length
|
||||
if (length <= 0f) {
|
||||
continue
|
||||
}
|
||||
|
||||
val sampleCount = max((length / 1f).roundToInt(), 1)
|
||||
for (sample in 0..sampleCount) {
|
||||
val distance = length * sample / sampleCount
|
||||
if (measure.getPosTan(distance, pathPosition, null)) {
|
||||
maxRadius =
|
||||
max(maxRadius, hypot(pathPosition[0] - centerX, pathPosition[1] - centerY))
|
||||
}
|
||||
}
|
||||
} while (measure.nextContour())
|
||||
|
||||
return maxRadius
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,7 @@ class PlaybackBarFragment : ViewBindingFragment<FragmentPlaybackBarBinding>() {
|
||||
|
||||
override fun onDestroyBinding(binding: FragmentPlaybackBarBinding) {
|
||||
super.onDestroyBinding(binding)
|
||||
binding.playbackSecondaryAction.clearPendingIcon()
|
||||
// Marquee elements leak if they are not disabled when the views are destroyed.
|
||||
binding.playbackSong.isSelected = false
|
||||
binding.playbackInfo.isSelected = false
|
||||
|
||||
@@ -190,6 +190,7 @@ class PlaybackPanelFragment :
|
||||
|
||||
override fun onDestroyBinding(binding: FragmentPlaybackPanelBinding) {
|
||||
equalizerLauncher = null
|
||||
binding.playbackRepeat.clearPendingIcon()
|
||||
binding.playbackSong.isSelected = false
|
||||
binding.playbackArtist.isSelected = false
|
||||
binding.playbackAlbum?.isSelected = false
|
||||
@@ -252,10 +253,9 @@ class PlaybackPanelFragment :
|
||||
}
|
||||
|
||||
private fun updateRepeat(repeatMode: RepeatMode) {
|
||||
requireBinding().playbackRepeat.apply {
|
||||
setIconResource(repeatMode.icon)
|
||||
isChecked = repeatMode != RepeatMode.NONE
|
||||
}
|
||||
val repeatButton = requireBinding().playbackRepeat
|
||||
repeatButton.isChecked = repeatMode != RepeatMode.NONE
|
||||
repeatButton.setIconResource(repeatMode.icon)
|
||||
}
|
||||
|
||||
private fun updatePlaying(isPlaying: Boolean) {
|
||||
|
||||
@@ -18,7 +18,11 @@
|
||||
|
||||
package org.oxycblt.auxio.playback
|
||||
|
||||
import android.icu.text.MeasureFormat
|
||||
import android.icu.util.Measure
|
||||
import android.icu.util.MeasureUnit
|
||||
import android.text.format.DateUtils
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Convert milliseconds into deci-seconds (1/10th of a second).
|
||||
@@ -56,6 +60,24 @@ fun Long.dsToSecs() = floorDiv(10)
|
||||
*/
|
||||
fun Long.formatDurationMs(isElapsed: Boolean) = msToSecs().formatDurationSecs(isElapsed)
|
||||
|
||||
/**
|
||||
* Format a millisecond duration into a compact, locale-aware bucket string suitable for fast-scroll
|
||||
* popups. Durations are bucketed into the most significant time unit:
|
||||
* - Less than 1 minute: "<1m" (using locale-narrow minute abbreviation)
|
||||
* - 1–59 minutes: "Nm" (e.g., "5m", "42m")
|
||||
* - 1+ hours: "Nh" (e.g., "2h", "142h")
|
||||
*/
|
||||
fun Long.formatDurationMsPopup(): String {
|
||||
val totalMinutes = floorDiv(60_000)
|
||||
val totalHours = totalMinutes / 60
|
||||
val fmt = MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.NARROW)
|
||||
return when {
|
||||
totalMinutes < 1 -> "<" + fmt.format(Measure(1, MeasureUnit.MINUTE))
|
||||
totalHours < 1 -> fmt.format(Measure(totalMinutes, MeasureUnit.MINUTE))
|
||||
else -> fmt.format(Measure(totalHours, MeasureUnit.HOUR))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* // * Format a deci-second value (1/10th of a second) into a string duration.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* ExpressiveShapes.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.ui
|
||||
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Path
|
||||
import android.graphics.PointF
|
||||
import android.graphics.RectF
|
||||
import kotlin.math.acos
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.tan
|
||||
|
||||
object ExpressiveShapes {
|
||||
|
||||
/** Generates the "6-Sided Cookie" path scaled to the given bounds. */
|
||||
fun getCookie6Sided(bounds: RectF): Path {
|
||||
// Raw normalized data from Material3 source
|
||||
val points =
|
||||
listOf(PointNRound(0.723f, 0.884f, 0.394f), PointNRound(0.500f, 1.099f, 0.398f))
|
||||
return generatePolygonPath(bounds, points, reps = 6)
|
||||
}
|
||||
|
||||
/** Generates the "Soft Burst" path scaled to the given bounds. */
|
||||
fun getSoftBurst(bounds: RectF): Path {
|
||||
// Raw normalized data from Material3 source
|
||||
val points =
|
||||
listOf(PointNRound(0.193f, 0.277f, 0.053f), PointNRound(0.176f, 0.055f, 0.053f))
|
||||
return generatePolygonPath(bounds, points, reps = 10)
|
||||
}
|
||||
|
||||
// --- Internal Logic ---
|
||||
|
||||
private data class PointNRound(val x: Float, val y: Float, val r: Float)
|
||||
|
||||
private data class Vertex(val x: Float, val y: Float, val r: Float)
|
||||
|
||||
private fun generatePolygonPath(bounds: RectF, rawPoints: List<PointNRound>, reps: Int): Path {
|
||||
val centerX = 0.5f
|
||||
val centerY = 0.5f
|
||||
val vertices = ArrayList<Vertex>()
|
||||
val numPoints = rawPoints.size
|
||||
|
||||
// 1. Generate all vertices by rotating the raw points around (0.5, 0.5)
|
||||
// Replicates 'doRepeat' logic from Compose source
|
||||
for (i in 0 until numPoints * reps) {
|
||||
val pointIndex = i % numPoints
|
||||
val p = rawPoints[pointIndex]
|
||||
|
||||
// Calculate rotation for this repetition
|
||||
// In source: (it / np) * 360f / reps
|
||||
val repIndex = i / numPoints
|
||||
val rotationDeg = (repIndex * 360f) / reps
|
||||
|
||||
// Rotate the point
|
||||
val (rx, ry) = rotatePoint(p.x, p.y, centerX, centerY, rotationDeg)
|
||||
vertices.add(Vertex(rx, ry, p.r))
|
||||
}
|
||||
|
||||
// 2. Normalize vertices to fit exactly in 0..1 bounds
|
||||
// (The raw points might exceed 0..1 or be off-center)
|
||||
val normalizedPath = createRoundedPath(vertices)
|
||||
|
||||
// 3. Transform (Scale/Translate) to target bounds
|
||||
// We compute the bounds of the normalized path to scale it correctly
|
||||
val pathBounds = RectF()
|
||||
normalizedPath.computeBounds(pathBounds, true)
|
||||
|
||||
val matrix = Matrix()
|
||||
matrix.setRectToRect(pathBounds, bounds, Matrix.ScaleToFit.CENTER)
|
||||
normalizedPath.transform(matrix)
|
||||
|
||||
return normalizedPath
|
||||
}
|
||||
|
||||
private fun rotatePoint(
|
||||
x: Float,
|
||||
y: Float,
|
||||
cx: Float,
|
||||
cy: Float,
|
||||
degrees: Float,
|
||||
): Pair<Float, Float> {
|
||||
val rad = Math.toRadians(degrees.toDouble())
|
||||
val cos = cos(rad)
|
||||
val sin = sin(rad)
|
||||
val dx = x - cx
|
||||
val dy = y - cy
|
||||
val nx = dx * cos - dy * sin + cx
|
||||
val ny = dx * sin + dy * cos + cy
|
||||
return Pair(nx.toFloat(), ny.toFloat())
|
||||
}
|
||||
|
||||
private fun createRoundedPath(vertices: List<Vertex>): Path {
|
||||
val path = Path()
|
||||
val n = vertices.size
|
||||
if (n < 3) {
|
||||
return path
|
||||
}
|
||||
|
||||
// Precompute all corner cuts so each edge connects from this corner's end
|
||||
// to the next corner's start in one consistent winding direction.
|
||||
val corners =
|
||||
List(n) { i ->
|
||||
calculateCorner(vertices[(i - 1 + n) % n], vertices[i], vertices[(i + 1) % n])
|
||||
}
|
||||
|
||||
path.moveTo(corners[0].start.x, corners[0].start.y)
|
||||
|
||||
for (i in 0 until n) {
|
||||
val curr = vertices[i]
|
||||
val corner = corners[i]
|
||||
val nextCorner = corners[(i + 1) % n]
|
||||
|
||||
path.quadTo(curr.x, curr.y, corner.end.x, corner.end.y)
|
||||
path.lineTo(nextCorner.start.x, nextCorner.start.y)
|
||||
}
|
||||
path.close()
|
||||
return path
|
||||
}
|
||||
|
||||
private data class Corner(val start: PointF, val end: PointF)
|
||||
|
||||
private fun calculateCorner(prev: Vertex, curr: Vertex, next: Vertex): Corner {
|
||||
// Vector 1: curr -> prev
|
||||
val v1x = prev.x - curr.x
|
||||
val v1y = prev.y - curr.y
|
||||
val len1 = hypot(v1x, v1y)
|
||||
|
||||
// Vector 2: curr -> next
|
||||
val v2x = next.x - curr.x
|
||||
val v2y = next.y - curr.y
|
||||
val len2 = hypot(v2x, v2y)
|
||||
|
||||
// Angle between vectors
|
||||
// dot product = |a||b|cos(theta)
|
||||
val dot = (v1x * v2x + v1y * v2y)
|
||||
val angleRad = acos((dot / (len1 * len2)).coerceIn(-1.0f, 1.0f))
|
||||
|
||||
// Distance from vertex to tangent point: d = radius / tan(theta/2)
|
||||
// The angle 'theta' here is the angle *between* the vectors.
|
||||
// The internal angle of the corner is actually related to this.
|
||||
// Standard formula for corner cut: dist = r / tan(internalAngle / 2)
|
||||
// Here 'angleRad' is the angle between the two edges.
|
||||
val tanHalf = tan(angleRad / 2.0)
|
||||
|
||||
// Calculate cut distance based on radius
|
||||
var dist = if (tanHalf != 0.0) (curr.r / tanHalf).toFloat() else 0f
|
||||
|
||||
// Clamp distance to avoid overlapping corners (max half the edge length)
|
||||
// Note: For "Cookie" shape, the radius is huge, so this clamping essentially
|
||||
// turns the edges into single points, creating a full curve.
|
||||
val limit = min(len1, len2) / 2.0f
|
||||
if (dist > limit) dist = limit
|
||||
|
||||
// Calculate Start point (on curr->prev line)
|
||||
val startX = curr.x + (v1x / len1) * dist
|
||||
val startY = curr.y + (v1y / len1) * dist
|
||||
|
||||
// Calculate End point (on curr->next line)
|
||||
val endX = curr.x + (v2x / len2) * dist
|
||||
val endY = curr.y + (v2y / len2) * dist
|
||||
|
||||
return Corner(PointF(startX, startY), PointF(endX, endY))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright (c) 2026 Auxio Project
|
||||
* WidthFixMaterialButton.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.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import androidx.annotation.AttrRes
|
||||
import androidx.annotation.DrawableRes
|
||||
import com.google.android.material.R
|
||||
|
||||
/**
|
||||
* A [RippleFixMaterialButton] that works around a bug where changing the icon while the button's
|
||||
* ripple/press animation is active causes a width change that "sticks". The workaround defers
|
||||
* re-applying the icon until the button is no longer pressed.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
class WidthFixMaterialButton
|
||||
@JvmOverloads
|
||||
constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
@AttrRes defStyleAttr: Int = R.attr.materialButtonStyle,
|
||||
) : RippleFixMaterialButton(context, attrs, defStyleAttr) {
|
||||
private var pendingIconRes: Int? = null
|
||||
private var appliedIconRes: Int? = null
|
||||
|
||||
private val applyPendingIconRunnable =
|
||||
object : Runnable {
|
||||
override fun run() {
|
||||
val iconRes = pendingIconRes ?: return
|
||||
if (isPressed) {
|
||||
postOnAnimation(this)
|
||||
return
|
||||
}
|
||||
if (appliedIconRes != iconRes) {
|
||||
super@WidthFixMaterialButton.setIconResource(iconRes)
|
||||
appliedIconRes = iconRes
|
||||
}
|
||||
pendingIconRes = null
|
||||
}
|
||||
}
|
||||
|
||||
override fun setIconResource(@DrawableRes iconRes: Int) {
|
||||
super.setIconResource(iconRes)
|
||||
pendingIconRes = iconRes
|
||||
removeCallbacks(applyPendingIconRunnable)
|
||||
postOnAnimation(applyPendingIconRunnable)
|
||||
}
|
||||
|
||||
fun clearPendingIcon() {
|
||||
removeCallbacks(applyPendingIconRunnable)
|
||||
pendingIconRes = null
|
||||
appliedIconRes = null
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user