all: reformat

This commit is contained in:
Alexander Capehart
2026-08-29 15:29:20 -06:00
parent d19cd9dc34
commit bf6c70192b
18 changed files with 220 additions and 216 deletions
@@ -239,31 +239,30 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
val playbackIndicator = (playbackIndicator ?: return).view val playbackIndicator = (playbackIndicator ?: return).view
val iconSize = iconSize ?: (measuredWidth / 2) val iconSize = iconSize ?: (measuredWidth / 2)
playbackIndicator.apply { playbackIndicator.apply {
imageMatrix = imageMatrix = indicatorMatrix.apply {
indicatorMatrix.apply { reset()
reset() drawable?.let { drawable ->
drawable?.let { drawable -> // First scale the icon up to the desired size.
// First scale the icon up to the desired size. indicatorMatrixSrc.set(
indicatorMatrixSrc.set( 0f,
0f, 0f,
0f, drawable.intrinsicWidth.toFloat(),
drawable.intrinsicWidth.toFloat(), drawable.intrinsicHeight.toFloat(),
drawable.intrinsicHeight.toFloat(), )
) indicatorMatrixDst.set(0f, 0f, iconSize.toFloat(), iconSize.toFloat())
indicatorMatrixDst.set(0f, 0f, iconSize.toFloat(), iconSize.toFloat()) indicatorMatrix.setRectToRect(
indicatorMatrix.setRectToRect( indicatorMatrixSrc,
indicatorMatrixSrc, indicatorMatrixDst,
indicatorMatrixDst, Matrix.ScaleToFit.CENTER,
Matrix.ScaleToFit.CENTER, )
)
// Then actually center it into the icon. // Then actually center it into the icon.
indicatorMatrix.postTranslate( indicatorMatrix.postTranslate(
(measuredWidth - iconSize) / 2f, (measuredWidth - iconSize) / 2f,
(measuredHeight - iconSize) / 2f, (measuredHeight - iconSize) / 2f,
) )
}
} }
}
} }
} }
@@ -88,50 +88,49 @@ private constructor(context: Context, private val data: GalleryCoverCollection,
val positions = listOf(p0, p1, p2, p3) val positions = listOf(p0, p1, p2, p3)
// first we actually have to aggregate the geometry here so that // first we actually have to aggregate the geometry here so that
// our overlaps will actually work // our overlaps will actually work
val tiles = val tiles = positions.mapIndexed { index, baseRect ->
positions.mapIndexed { index, baseRect -> // generate path-tiles for each cover
// generate path-tiles for each cover val isTop = index < 2
val isTop = index < 2 val isLeft = index % 2 == 0
val isLeft = index % 2 == 0 val isBottom = !isTop
val isBottom = !isTop val isRight = !isLeft
val isRight = !isLeft
// inset base cover rect to prevent rounded corners from stacking in a way // inset base cover rect to prevent rounded corners from stacking in a way
// that leads weird "holes" and is instead more dynamic // that leads weird "holes" and is instead more dynamic
// todo: refine this so we can do dynamic overlap? // todo: refine this so we can do dynamic overlap?
val innerRect = RectF(baseRect) val innerRect = RectF(baseRect)
innerRect.left += if (isLeft) 0f else gapWidthPx innerRect.left += if (isLeft) 0f else gapWidthPx
innerRect.top += if (isTop) 0f else gapWidthPx innerRect.top += if (isTop) 0f else gapWidthPx
innerRect.right -= if (isRight) 0f else gapWidthPx innerRect.right -= if (isRight) 0f else gapWidthPx
innerRect.bottom -= if (isBottom) 0f else gapWidthPx innerRect.bottom -= if (isBottom) 0f else gapWidthPx
// set up the actual gap path // set up the actual gap path
val gapRect = RectF(innerRect) val gapRect = RectF(innerRect)
gapRect.inset(-gapWidthPx, -gapWidthPx) gapRect.inset(-gapWidthPx, -gapWidthPx)
val gapPath = val gapPath =
rounded( rounded(
gapRect, gapRect,
topLeft = if (!isTop && !isLeft) cornerRadiusPx else 0f, topLeft = if (!isTop && !isLeft) cornerRadiusPx else 0f,
topRight = if (!isTop && !isRight) cornerRadiusPx else 0f, topRight = if (!isTop && !isRight) cornerRadiusPx else 0f,
bottomRight = if (!isBottom && !isRight) cornerRadiusPx else 0f, bottomRight = if (!isBottom && !isRight) cornerRadiusPx else 0f,
bottomLeft = if (!isBottom && !isLeft) cornerRadiusPx else 0f, bottomLeft = if (!isBottom && !isLeft) cornerRadiusPx else 0f,
) )
// then the inner mask // then the inner mask
// adjust corner radii to make up for gap // adjust corner radii to make up for gap
val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f) val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f)
val maskPath = val maskPath =
rounded( rounded(
innerRect, innerRect,
topLeft = if (!isTop && !isLeft) innerRadius else 0f, topLeft = if (!isTop && !isLeft) innerRadius else 0f,
topRight = if (!isTop && !isRight) innerRadius else 0f, topRight = if (!isTop && !isRight) innerRadius else 0f,
bottomRight = if (!isBottom && !isRight) innerRadius else 0f, bottomRight = if (!isBottom && !isRight) innerRadius else 0f,
bottomLeft = if (!isBottom && !isLeft) innerRadius else 0f, bottomLeft = if (!isBottom && !isLeft) innerRadius else 0f,
) )
TileGeometry(innerRect, gapPath, maskPath) TileGeometry(innerRect, gapPath, maskPath)
} }
for ((orderIndex, imageIndex) in zOrder.withIndex()) { for ((orderIndex, imageIndex) in zOrder.withIndex()) {
val bitmap = bitmaps[imageIndex] val bitmap = bitmaps[imageIndex]
@@ -135,8 +135,9 @@ private constructor(
// Cancel the previous music loading job. // Cancel the previous music loading job.
currentIndexJob?.cancel() currentIndexJob?.cancel()
// Start a new music loading job on a co-routine. // Start a new music loading job on a co-routine.
currentIndexJob = currentIndexJob = indexScope.launch {
indexScope.launch { musicRepository.index(this@IndexingHolder, withCache) } musicRepository.index(this@IndexingHolder, withCache)
}
} }
override fun onIndexingStateChanged() { override fun onIndexingStateChanged() {
@@ -102,14 +102,18 @@ constructor(
fun getRoot() = BrowserRoot(MediaSessionUID.Tab(TabNode.Root).toString(), Bundle()) fun getRoot() = BrowserRoot(MediaSessionUID.Tab(TabNode.Root).toString(), Bundle())
fun getItem(mediaId: String, result: Result<MediaItem>) = fun getItem(mediaId: String, result: Result<MediaItem>) = result.dispatch {
result.dispatch { musicBrowser.getItem(mediaId) } musicBrowser.getItem(mediaId)
}
fun getChildren(mediaId: String, maxTabs: Int, result: Result<MutableList<MediaItem>>) = fun getChildren(mediaId: String, maxTabs: Int, result: Result<MutableList<MediaItem>>) =
result.dispatch { musicBrowser.getChildren(mediaId, maxTabs)?.toMutableList() } result.dispatch {
musicBrowser.getChildren(mediaId, maxTabs)?.toMutableList()
}
fun search(query: String, result: Result<MutableList<MediaItem>>) = fun search(query: String, result: Result<MutableList<MediaItem>>) = result.dispatchAsync {
result.dispatchAsync { musicBrowser.search(query) } musicBrowser.search(query)
}
private fun <T> Result<T>.dispatch(body: () -> T?) { private fun <T> Result<T>.dispatch(body: () -> T?) {
try { try {
@@ -194,14 +194,13 @@ constructor(
// Replace the previous position co-routine with a new one that uses the new // Replace the previous position co-routine with a new one that uses the new
// state information. // state information.
lastPositionJob?.cancel() lastPositionJob?.cancel()
lastPositionJob = lastPositionJob = viewModelScope.launch {
viewModelScope.launch { while (true) {
while (true) { _positionDs.value = progression.calculateElapsedPositionMs().msToDs()
_positionDs.value = progression.calculateElapsedPositionMs().msToDs() // Wait a deci-second for the next position tick.
// Wait a deci-second for the next position tick. delay(100)
delay(100)
}
} }
}
} }
override fun onRepeatModeChanged(repeatMode: RepeatMode) { override fun onRepeatModeChanged(repeatMode: RepeatMode) {
@@ -310,17 +310,16 @@ private constructor(
* @param queue The current queue to upload. * @param queue The current queue to upload.
*/ */
private fun updateQueue(queue: List<Song>) { private fun updateQueue(queue: List<Song>) {
val queueItems = val queueItems = queue.mapIndexed { i, song ->
queue.mapIndexed { i, song -> val description =
val description = song.toMediaDescription(
song.toMediaDescription( context,
context, { putInt(MediaSessionInterface.KEY_QUEUE_POS, i) },
{ putInt(MediaSessionInterface.KEY_QUEUE_POS, i) }, )
) // Store the item index so we can then use the analogous index in the
// Store the item index so we can then use the analogous index in the // playback state.
// playback state. MediaSessionCompat.QueueItem(description, i.toLong())
MediaSessionCompat.QueueItem(description, i.toLong()) }
}
L.d("Uploading ${queueItems.size} songs to MediaSession queue") L.d("Uploading ${queueItems.size} songs to MediaSession queue")
mediaSession.setQueue(queueItems) mediaSession.setQueue(queueItems)
} }
@@ -89,14 +89,11 @@ private constructor(
private fun scheduleAutoStop() { private fun scheduleAutoStop() {
autoStopJob?.cancel() autoStopJob?.cancel()
autoStopJob = autoStopJob = scope.launch {
scope.launch { delay(AUTO_STOP_DELAY_MS)
delay(AUTO_STOP_DELAY_MS) L.d("Auto-stop timer expired after ${AUTO_STOP_DELAY_MS / 60000} minutes of inactivity")
L.d( playbackManager.endSession()
"Auto-stop timer expired after ${AUTO_STOP_DELAY_MS / 60000} minutes of inactivity" }
)
playbackManager.endSession()
}
} }
private fun cancelAutoStop() { private fun cancelAutoStop() {
@@ -123,12 +123,11 @@ class SecondsView(context: Context, attrs: AttributeSet?) : LinearLayout(context
val one = alphaSpring.alpha(binding.icon1, cyclicAlpha[row]) val one = alphaSpring.alpha(binding.icon1, cyclicAlpha[row])
val two = alphaSpring.alpha(binding.icon2, cyclicAlpha[row + 1]) val two = alphaSpring.alpha(binding.icon2, cyclicAlpha[row + 1])
val three = alphaSpring.alpha(binding.icon3, cyclicAlpha[row + 2]) val three = alphaSpring.alpha(binding.icon3, cyclicAlpha[row + 2])
val endListener = val endListener = DynamicAnimation.OnAnimationEndListener { _, cancelled, _, _ ->
DynamicAnimation.OnAnimationEndListener { _, cancelled, _, _ -> if (!cancelled) {
if (!cancelled) { cycle((at + 1) % 5)
cycle((at + 1) % 5)
}
} }
}
when { when {
cyclicAlpha[row] != binding.icon1.alpha -> { cyclicAlpha[row] != binding.icon1.alpha -> {
one.addEndListener(endListener) one.addEndListener(endListener)
@@ -102,10 +102,9 @@ constructor(
// Searching is time-consuming, so do it in the background. // Searching is time-consuming, so do it in the background.
L.d("Searching music library for $query") L.d("Searching music library for $query")
currentSearchJob = currentSearchJob = viewModelScope.launch {
viewModelScope.launch { _searchResults.value = searchImpl(library, query).also { yield() }
_searchResults.value = searchImpl(library, query).also { yield() } }
}
} }
private suspend fun searchImpl(library: Library, query: String): List<Item> { private suspend fun searchImpl(library: Library, query: String): List<Item> {
@@ -51,30 +51,27 @@ class MusicPreferenceFragment : BasePreferenceFragment(R.xml.preferences_music)
override fun onSetupPreference(preference: Preference) { override fun onSetupPreference(preference: Preference) {
if (preference.key == getString(R.string.set_key_cover_mode)) { if (preference.key == getString(R.string.set_key_cover_mode)) {
L.d("Configuring cover mode setting") L.d("Configuring cover mode setting")
preference.onPreferenceChangeListener = preference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, _ ->
Preference.OnPreferenceChangeListener { _, _ -> L.d("Cover mode changed, reloading music")
L.d("Cover mode changed, reloading music") musicModel.refresh()
musicModel.refresh() true
true }
}
} }
if (preference.key == getString(R.string.set_key_square_covers)) { if (preference.key == getString(R.string.set_key_square_covers)) {
L.d("Configuring square cover setting") L.d("Configuring square cover setting")
preference.onPreferenceChangeListener = preference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, _ ->
Preference.OnPreferenceChangeListener { _, _ -> L.d("Cover mode changed, resetting image memory cache")
L.d("Cover mode changed, resetting image memory cache") imageLoader.memoryCache?.clear()
imageLoader.memoryCache?.clear() true
true }
}
} }
if (preference.key == getString(R.string.set_key_with_hidden)) { if (preference.key == getString(R.string.set_key_with_hidden)) {
L.d("Configuring ignore hidden files setting") L.d("Configuring ignore hidden files setting")
preference.onPreferenceChangeListener = preference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, _ ->
Preference.OnPreferenceChangeListener { _, _ -> L.d("Ignore hidden files setting changed, reloading music")
L.d("Ignore hidden files setting changed, reloading music") musicModel.refresh()
musicModel.refresh() true
true }
}
} }
} }
} }
@@ -51,26 +51,25 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
private var scrollingChild: View? = null private var scrollingChild: View? = null
private val tConsumed = IntArray(2) private val tConsumed = IntArray(2)
private val onPreDraw = private val onPreDraw = ViewTreeObserver.OnPreDrawListener {
ViewTreeObserver.OnPreDrawListener { val child = findScrollingChild()
val child = findScrollingChild()
if (child != null) { if (child != null) {
val coordinator = parent as CoordinatorLayout val coordinator = parent as CoordinatorLayout
coordinatorLayoutBehavior?.onNestedPreScroll( coordinatorLayoutBehavior?.onNestedPreScroll(
coordinator, coordinator,
this, this,
coordinator, coordinator,
0, 0,
0, 0,
tConsumed, tConsumed,
0, 0,
) )
}
true
} }
true
}
init { init {
fitsSystemWindows = true fitsSystemWindows = true
viewTreeObserver.addOnPreDrawListener(onPreDraw) viewTreeObserver.addOnPreDrawListener(onPreDraw)
@@ -309,7 +309,10 @@ class WidgetProvider : AppWidgetProvider() {
setImageViewBitmap(R.id.widget_cover, state.cover) setImageViewBitmap(R.id.widget_cover, state.cover)
setContentDescription( setContentDescription(
R.id.widget_cover, R.id.widget_cover,
context.getString(R.string.desc_album_cover, state.song.album.name.resolve(context)), context.getString(
R.string.desc_album_cover,
state.song.album.name.resolve(context),
),
) )
} else { } else {
discardCover(context) discardCover(context)
@@ -41,10 +41,9 @@ class DBCache private constructor(private val readDao: CacheReadDao) : Cache {
private val mappingLock = Mutex() private val mappingLock = Mutex()
override suspend fun read(file: File): CacheResult { override suspend fun read(file: File): CacheResult {
val currentMapping = val currentMapping = mappingLock.withLock {
mappingLock.withLock { mapping ?: readDao.selectAllSongs().associateBy { it.uri }.also { mapping = it }
mapping ?: readDao.selectAllSongs().associateBy { it.uri }.also { mapping = it } }
}
val dbSong = currentMapping[file.uri] ?: return CacheResult.Miss(file) val dbSong = currentMapping[file.uri] ?: return CacheResult.Miss(file)
if (dbSong.modifiedMs != file.modifiedMs) { if (dbSong.modifiedMs != file.modifiedMs) {
return CacheResult.Stale(file, dbSong.addedMs) return CacheResult.Stale(file, dbSong.addedMs)
@@ -148,8 +147,7 @@ private constructor(private val inner: DBCache, private val writeDao: CacheWrite
return MutableDBCache(DBCache.from(db), db.writeDao()) return MutableDBCache(DBCache.from(db), db.writeDao())
} }
internal fun from(inner: DBCache, writeDao: CacheWriteDao) = internal fun from(inner: DBCache, writeDao: CacheWriteDao) = MutableDBCache(inner, writeDao)
MutableDBCache(inner, writeDao)
private const val BATCH_SIZE = 500 private const val BATCH_SIZE = 500
} }
@@ -381,14 +381,13 @@ private class MusicGraphBuilderImpl : MusicGraph.Builder {
return return
} }
// No full MBID coverage, discard the MBIDs from the graph. // No full MBID coverage, discard the MBIDs from the graph.
val strippedCluster = val strippedCluster = cluster.map {
cluster.map { val noMbidPreArtist = it.preArtist.copy(musicBrainzId = null)
val noMbidPreArtist = it.preArtist.copy(musicBrainzId = null) val simpleMbidVertex =
val simpleMbidVertex = artistVertices.getOrPut(noMbidPreArtist) { ArtistVertex(noMbidPreArtist) }
artistVertices.getOrPut(noMbidPreArtist) { ArtistVertex(noMbidPreArtist) } meldArtistVertices(it, simpleMbidVertex)
meldArtistVertices(it, simpleMbidVertex) simpleMbidVertex
simpleMbidVertex }
}
simplifyArtistClusterImpl(strippedCluster) simplifyArtistClusterImpl(strippedCluster)
} }
@@ -457,41 +456,41 @@ private class MusicGraphBuilderImpl : MusicGraph.Builder {
return return
} }
// No full MBID coverage, discard the MBIDs from the graph. // No full MBID coverage, discard the MBIDs from the graph.
val strippedMbidCluster = val strippedMbidCluster = cluster.map {
cluster.map { val noMbidPreAlbum = it.preAlbum.copy(musicBrainzId = null)
val noMbidPreAlbum = it.preAlbum.copy(musicBrainzId = null) val simpleMbidVertex =
val simpleMbidVertex = albumVertices.getOrPut(noMbidPreAlbum) {
albumVertices.getOrPut(noMbidPreAlbum) { AlbumVertex(noMbidPreAlbum, it.artistVertices.toMutableList())
AlbumVertex(noMbidPreAlbum, it.artistVertices.toMutableList()) }
} meldAlbumVertices(it, simpleMbidVertex)
meldAlbumVertices(it, simpleMbidVertex) simpleMbidVertex
simpleMbidVertex }
} val fullAlbumArtistCoverage = strippedMbidCluster.all {
val fullAlbumArtistCoverage = it.preAlbum.preArtists is PreArtistsFrom.Album
strippedMbidCluster.all { it.preAlbum.preArtists is PreArtistsFrom.Album } }
if (fullAlbumArtistCoverage) { if (fullAlbumArtistCoverage) {
// All albums have album artists, we can reasonably cluster around artists // All albums have album artists, we can reasonably cluster around artists
// rather than just name. // rather than just name.
val albumArtistClusters = val albumArtistClusters = strippedMbidCluster.groupBy {
strippedMbidCluster.groupBy { it.preAlbum.preArtists.preArtists } it.preAlbum.preArtists.preArtists
}
for (albumArtistCluster in albumArtistClusters.values) { for (albumArtistCluster in albumArtistClusters.values) {
simplifyAlbumClusterImpl(albumArtistCluster) simplifyAlbumClusterImpl(albumArtistCluster)
} }
return return
} }
val strippedAlbumArtistCluster = val strippedAlbumArtistCluster = strippedMbidCluster.map {
strippedMbidCluster.map { val noAlbumArtistPreAlbum =
val noAlbumArtistPreAlbum = it.preAlbum.copy(
it.preAlbum.copy( preArtists = PreArtistsFrom.Individual(it.preAlbum.preArtists.preArtists)
preArtists = PreArtistsFrom.Individual(it.preAlbum.preArtists.preArtists) )
) val simpleAlbumArtistVertex =
val simpleAlbumArtistVertex = albumVertices.getOrPut(noAlbumArtistPreAlbum) {
albumVertices.getOrPut(noAlbumArtistPreAlbum) { AlbumVertex(noAlbumArtistPreAlbum, it.artistVertices.toMutableList())
AlbumVertex(noAlbumArtistPreAlbum, it.artistVertices.toMutableList()) }
} meldAlbumVertices(it, simpleAlbumArtistVertex)
meldAlbumVertices(it, simpleAlbumArtistVertex) simpleAlbumArtistVertex
simpleAlbumArtistVertex }
}
simplifyAlbumClusterImpl(strippedAlbumArtistCluster) simplifyAlbumClusterImpl(strippedAlbumArtistCluster)
} }
@@ -32,7 +32,6 @@ import androidx.room.RoomDatabase
import androidx.room.Transaction import androidx.room.Transaction
import androidx.room.TypeConverters import androidx.room.TypeConverters
import androidx.room.migration.Migration import androidx.room.migration.Migration
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteQueryBuilder import androidx.sqlite.db.SupportSQLiteQueryBuilder
import org.oxycblt.musikr.Music import org.oxycblt.musikr.Music
@@ -60,23 +59,36 @@ internal abstract class PlaylistDatabase : RoomDatabase() {
) )
.addMigrations( .addMigrations(
object : Migration(30, 75) { object : Migration(30, 75) {
private fun washUids(db: SupportSQLiteDatabase, table: String, column: String) { private fun washUids(
val playlistUidMigration = db.query( db: SupportSQLiteDatabase,
SupportSQLiteQueryBuilder.builder(table) table: String,
.columns(arrayOf(column)) column: String,
.create() ) {
).use { val playlistUidMigration =
val migrations = mutableListOf<Pair<String, String>>() db.query(
val playlistUidIndex = it.getColumnIndexOrThrow(column) SupportSQLiteQueryBuilder.builder(table)
while (it.moveToNext()) { .columns(arrayOf(column))
val oldUid = .create()
requireNotNull(it.getStringOrNull(playlistUidIndex)) { "catastrophic migration failure: $table has no UID" } )
val newUid = .use {
requireNotNull(Music.UID.fromString(oldUid)) { "catastrophic migration failure: $table has bad UID" }.toString() val migrations = mutableListOf<Pair<String, String>>()
migrations.add(oldUid to newUid) val playlistUidIndex = it.getColumnIndexOrThrow(column)
} while (it.moveToNext()) {
migrations val oldUid =
} requireNotNull(
it.getStringOrNull(playlistUidIndex)
) {
"catastrophic migration failure: $table has no UID"
}
val newUid =
requireNotNull(Music.UID.fromString(oldUid)) {
"catastrophic migration failure: $table has bad UID"
}
.toString()
migrations.add(oldUid to newUid)
}
migrations
}
for ((old, new) in playlistUidMigration) { for ((old, new) in playlistUidMigration) {
db.update( db.update(
table, table,
@@ -85,7 +97,7 @@ internal abstract class PlaylistDatabase : RoomDatabase() {
put(column, old) put(column, old)
}, },
"$column = ?", "$column = ?",
arrayOf(new) arrayOf(new),
) )
} }
for ((old, new) in playlistUidMigration) { for ((old, new) in playlistUidMigration) {
@@ -96,10 +108,11 @@ internal abstract class PlaylistDatabase : RoomDatabase() {
put(column, new) put(column, new)
}, },
"$column = ?", "$column = ?",
arrayOf(old) arrayOf(old),
) )
} }
} }
override fun migrate(db: SupportSQLiteDatabase) { override fun migrate(db: SupportSQLiteDatabase) {
washUids(db, "PlaylistInfo", "playlistUid") washUids(db, "PlaylistInfo", "playlistUid")
washUids(db, "PlaylistSongCrossRef", "playlistUid") washUids(db, "PlaylistSongCrossRef", "playlistUid")
@@ -116,8 +116,9 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
// based on the programs that generated it. I more or less have to consider any possible // based on the programs that generated it. I more or less have to consider any possible
// interpretation as valid. // interpretation as valid.
val interpretations = interpretPath(unlikelyToBeNull(path)) val interpretations = interpretPath(unlikelyToBeNull(path))
val possibilities = val possibilities = interpretations.flatMap {
interpretations.flatMap { expandInterpretation(it, workingDirectory, volumes) } expandInterpretation(it, workingDirectory, volumes)
}
paths.add(possibilities) paths.add(possibilities)
} }
@@ -156,12 +157,11 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
val relativeInterpretation = val relativeInterpretation =
Path(workingDirectory.volume, path.components.absoluteTo(workingDirectory.components)) Path(workingDirectory.volume, path.components.absoluteTo(workingDirectory.components))
val volumeExactMatch = volumes.find { it.components?.contains(path.components) == true } val volumeExactMatch = volumes.find { it.components?.contains(path.components) == true }
val volumeInterpretation = val volumeInterpretation = volumeExactMatch?.let {
volumeExactMatch?.let { val components =
val components = unlikelyToBeNull(volumeExactMatch.components).containing(path.components)
unlikelyToBeNull(volumeExactMatch.components).containing(path.components) Path(volumeExactMatch, components)
Path(volumeExactMatch, components) }
}
return if (path.likelyAbsolute) { return if (path.likelyAbsolute) {
listOfNotNull(volumeInterpretation, absoluteInterpretation, relativeInterpretation) listOfNotNull(volumeInterpretation, absoluteInterpretation, relativeInterpretation)
} else { } else {
@@ -47,11 +47,10 @@ internal fun String.parseSlashPositionField() =
* *
* @see transformPositionField * @see transformPositionField
*/ */
internal fun parseXiphPositionField(pos: String?, total: String?) = internal fun parseXiphPositionField(pos: String?, total: String?) = pos?.let { posStr ->
pos?.let { posStr -> posStr.toIntOrNull()?.let { transformPositionField(it, total?.toIntOrNull()) }
posStr.toIntOrNull()?.let { transformPositionField(it, total?.toIntOrNull()) } ?: posStr.parseSlashPositionField()
?: posStr.parseSlashPositionField() }
}
/** /**
* Transform a raw position + total field into a position a way that tolerates placeholder values. * Transform a raw position + total field into a position a way that tolerates placeholder values.
@@ -15,15 +15,15 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package org.oxycblt.musikr.cache.db package org.oxycblt.musikr.cache.db
import io.mockk.Runs
import io.mockk.coEvery import io.mockk.coEvery
import io.mockk.coVerify import io.mockk.coVerify
import io.mockk.every import io.mockk.every
import io.mockk.just import io.mockk.just
import io.mockk.mockk import io.mockk.mockk
import io.mockk.Runs
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test