{"results":{"result":{"added-files":{"code-health":8.192704527893302,"old-code-health":0.0,"files":[{"file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","loc":365,"code-health":8.255785876377233},{"file":"app/src/main/java/org/akanework/gramophone/ui/fragments/compose/MultiQueue.kt","loc":782,"code-health":8.163261187488397}]},"external-review-url":"https://github.com/FoedusProgramme/Gramophone/pull/865","old-code-health":7.164958544679486,"modified-files":{"code-health":7.041912935266054,"old-code-health":7.164958544679486,"files":[{"file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneExtensions.kt","loc":665,"old-loc":543,"code-health":7.788037646779413,"old-code-health":8.283981080161325},{"file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","loc":1491,"old-loc":1420,"code-health":4.410979387219089,"old-code-health":4.529901886903539},{"file":"app/src/main/java/org/akanework/gramophone/ui/adapters/BaseDecorAdapter.kt","loc":280,"old-loc":251,"code-health":8.48655062256644,"old-code-health":8.611108519496959},{"file":"app/src/main/java/org/akanework/gramophone/ui/adapters/SongAdapter.kt","loc":345,"old-loc":346,"code-health":8.74647379144627,"old-code-health":8.74647379144627},{"file":"app/src/main/java/org/akanework/gramophone/ui/components/PlaylistQueueSheet.kt","loc":384,"old-loc":239,"code-health":8.375984271357197,"old-code-health":9.536386775820924},{"file":"app/src/main/java/org/akanework/gramophone/ui/fragments/settings/ExperimentalSettingsFragment.kt","loc":88,"old-loc":86,"code-health":10.0,"old-code-health":10.0},{"file":"app/src/main/java/org/akanework/gramophone/logic/utils/exoplayer/EndedWorkaroundPlayer.kt","loc":98,"old-loc":54,"code-health":10.0,"old-code-health":10.0},{"file":"app/src/main/java/org/akanework/gramophone/ui/adapters/PlaylistAdapter.kt","loc":320,"old-loc":320,"code-health":9.27267860277969,"old-code-health":9.27267860277969},{"file":"app/src/main/java/org/akanework/gramophone/ui/fragments/ViewPagerFragment.kt","loc":254,"old-loc":250,"code-health":8.478108679529118,"old-code-health":8.487606535303968},{"file":"app/src/main/java/org/akanework/gramophone/ui/Compose.kt","loc":99,"old-loc":90,"code-health":10.0,"old-code-health":10.0}]},"removed-files":{"code-health":0.0,"old-code-health":0.0,"files":[]},"external-review-id":"865","analysis-time":"2026-05-23T19:58:02Z","negative-impact-count":16,"suppressions":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"affected-hotspots":3,"commits":["30b8070aa0fb43bb9c9c83296a5fe01729d4fe74","3da9516da6a77deae4cff77cc1158c5cb3a3eca3","2ff38a78b1d14c9277f5e4600c7fb4657291de9d","d203f1046d0dfe252fb90499be8b81da9ba00c0a","48bea12e7d3527e008174c0e35f5ce8c45638c84","6bc2fa14283531dae88a9c101f996e268f43d6fd","13649b3f480e7926458310694949367ad690a11c","a1398efbf7d136f8b0308229ec0ad261399d0977","7b7344f91f6ad2ad107f5f99ad907078edc1d9d2","b958d4faff6051ba58fd003867bf3ab9828c2d71","98f0bc758c84c3ffa895ca6c3ec4ec5e5cb61f2e","5df595236f227db7ebe83cd4213c6d25af295e6b","bbc79bf73bef45de7620daf4960b08694a00a5ad","41541ff3bdeb5ef866b2b113d13a46b7a9f210b0"],"is-negative-review":true,"negative-findings":{"number-of-types":7,"number-of-files-touched":5,"findings":[{"name":"Global Conditionals","file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneExtensions.kt","change-type":"degraded","change-level":"warning","is-hotspot?":true,"what-changed":"The global code outside of functions increases in cyclomatic complexity from 31 to 37, threshold = 10","refactoring-examples":null},{"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 50 % of all functions have primitive types as arguments.","name":"Primitive Obsession","file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneExtensions.kt","refactoring-examples":[{"diff":"diff --git a/primitive-obsession.ts b/primitive-obsession.ts\nindex 38bae186cc..24116eddcc 100644\n--- a/primitive-obsession.ts\n+++ b/primitive-obsession.ts\n@@ -1,8 +1,8 @@\n-// Problem: It's hard to know what this function does, and what values are valid as parameters.\n-function getPopularRepositories(String baseURL, String query, Integer pages, Integer pageSize, String sortorder): Json {\n-\tlet pages == null ? 10 : pages\n-\tlet pageSize == null ? 10 : pageSize\n-  return httpClient.get(`${baseURL}?q=${query}&pages=${pages}&pageSize=${pageSize}&sortorder=${sortorder}`)\n+// Refactoring: extract the pagination & API logic into a class, and it will\n+// attract validation and other logic related to the specific query. It's now\n+// easier to use and to maintain the getPopularRepositories function!\n+function getPopularRepositories(query: PaginatedRepoQuery): Json {\n+  return httpClient.get(query.getURL())\n     .map(json => json.repositories)\n     .filter(repository => repositry.stargazersCount > 1000)\n }\n","language":"kotlin","improvement-type":"Primitive Obsession"}],"change-level":"warning","is-hotspot?":true,"what-changed":"In this module, 50.0% of all function arguments are primitive types, threshold = 30.0%","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","change-type":"introduced"},{"method":"GramophonePlaybackService.onCreate","why-it-occurs":"A Complex Method has a high cyclomatic complexity. The recommended threshold for the Kotlin language is a cyclomatic complexity lower than 9.","name":"Complex Method","file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","refactoring-examples":[{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"55","loc-deleted":"18","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.413528317237752"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2026-01-01T13:23:52Z","current-rev":"7b370dff","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt","previous-rev":"a28de050","commit-title":"Apply all changes to ReplayGain settings UI instantly","language":"Kotlin","id":"0b5f2af002c123e31559e28ae55352e7ced73cb3","model-score":0.29,"author-id":null,"project-id":64193,"delta-file-score":0.25683072,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt b/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\nindex 9322d8fc..edd9763a 100644\n--- a/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\n+++ b/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\n@@ -12,154 +12,192 @@ import java.nio.ByteBuffer\n class ReplayGainAudioProcessor : BaseAudioProcessor() {\n-\tcompanion object {\n-\t\tprivate const val TAG = \"ReplayGainAP\"\n-\t}\n-\tprivate var compressor: AdaptiveDynamicRangeCompression? = null\n-\tprivate var waitingForFlush = false\n-\tvar mode = ReplayGainUtil.Mode.None\n-\t\tprivate set\n-\tvar rgGain = 0 // dB\n-\t\tprivate set\n-\tvar nonRgGain = 0 // dB\n-\t\tprivate set\n-\tvar boostGain = 0 // dB\n-\t\tprivate set\n-\tvar offloadEnabled = false\n-\t\tprivate set\n-\tvar reduceGain = false\n-\t\tprivate set\n-\tvar boostGainChangedListener: (() -> Unit)? = null\n-\tvar offloadEnabledChangedListener: (() -> Unit)? = null\n-\tprivate var gain = 1f\n-\tprivate var kneeThresholdDb: Float? = null\n-\tprivate var tags: ReplayGainUtil.ReplayGainInfo? = null\n-\toverride fun queueInput(inputBuffer: ByteBuffer) {\n-\t\tval frameCount = inputBuffer.remaining() / inputAudioFormat.bytesPerFrame\n-\t\tval outputBuffer = replaceOutputBuffer(frameCount * outputAudioFormat.bytesPerFrame)\n-\t\tif (inputBuffer.hasRemaining()) {\n-\t\t\tif (compressor != null) {\n-\t\t\t\tcompressor!!.compress(\n-\t\t\t\t\tinputAudioFormat.channelCount,\n-\t\t\t\t\tgain,\n-\t\t\t\t\tkneeThresholdDb!!, 1f, inputBuffer,\n-\t\t\t\t\toutputBuffer, frameCount\n-\t\t\t\t)\n-\t\t\t\tinputBuffer.position(inputBuffer.limit())\n-\t\t\t\toutputBuffer.position(frameCount * outputAudioFormat.bytesPerFrame)\n-\t\t\t} else {\n-\t\t\t\tif (gain == 1f) {\n-\t\t\t\t\toutputBuffer.put(inputBuffer)\n-\t\t\t\t} else {\n-\t\t\t\t\twhile (inputBuffer.hasRemaining()) {\n-\t\t\t\t\t\toutputBuffer.putFloat(inputBuffer.getFloat() * gain)\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t}\n-\t\t}\n-\t\toutputBuffer.flip()\n-\t}\n+    companion object {\n+        private const val TAG = \"ReplayGainAP\"\n+    }\n \n-\toverride fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {\n-\t\tif (inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {\n-\t\t\tthrow UnhandledAudioFormatException(\n-\t\t\t\t\"Invalid PCM encoding. Expected float PCM.\", inputAudioFormat\n-\t\t\t)\n-\t\t}\n-\t\t// TODO(ASAP): if setMode and setNonRgGain required reconfiguration, we could be a lot lazier.\n-\t\tif (((tags?.trackGain == null && tags?.albumGain == null)\n-\t\t\t|| (tags?.trackGain != null && tags?.trackGain != 1f)\n-\t\t\t|| (tags?.albumGain != null && tags?.albumGain != 1f)) && !Flags.TEST_RG_OFFLOAD) {\n-\t\t\treturn inputAudioFormat\n-\t\t}\n-\t\t// if there's RG metadata but it says we don't need to do anything, we can skip all work.\n-\t\treturn AudioProcessor.AudioFormat.NOT_SET\n-\t}\n+    private var compressor: AdaptiveDynamicRangeCompression? = null\n+    private var waitingForFlush = false\n+    var mode = ReplayGainUtil.Mode.None\n+        private set\n+    var rgGain = 0 // dB\n+        private set\n+    var nonRgGain = 0 // dB\n+        private set\n+    var boostGain = 0 // dB\n+        private set\n+    var offloadEnabled = false\n+        private set\n+    var reduceGain = false\n+        private set\n+    var settingsChangedListener: (() -> Unit)? = null\n+    var boostGainChangedListener: (() -> Unit)? = null\n+    var offloadEnabledChangedListener: (() -> Unit)? = null\n+    private var gain = 1f\n+    private var kneeThresholdDb: Float? = null\n+    private var tags: ReplayGainUtil.ReplayGainInfo? = null\n+    override fun queueInput(inputBuffer: ByteBuffer) {\n+        val frameCount = inputBuffer.remaining() / inputAudioFormat.bytesPerFrame\n+        val outputBuffer = replaceOutputBuffer(frameCount * outputAudioFormat.bytesPerFrame)\n+        if (inputBuffer.hasRemaining()) {\n+            if (compressor != null) {\n+                compressor!!.compress(\n+                    inputAudioFormat.channelCount,\n+                    gain,\n+                    kneeThresholdDb!!, 1f, inputBuffer,\n+                    outputBuffer, frameCount\n+                )\n+                inputBuffer.position(inputBuffer.limit())\n+                outputBuffer.position(frameCount * outputAudioFormat.bytesPerFrame)\n+            } else {\n+                if (gain == 1f) {\n+                    outputBuffer.put(inputBuffer)\n+                } else {\n+                    while (inputBuffer.hasRemaining()) {\n+                        outputBuffer.putFloat(inputBuffer.getFloat() * gain)\n+                    }\n+                }\n+            }\n+        }\n+        outputBuffer.flip()\n+    }\n \n-\t@Synchronized\n-\tfun setMode(mode: ReplayGainUtil.Mode) {\n-\t\tthis.mode = mode\n-\t}\n+    override fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {\n+        if (inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {\n+            throw UnhandledAudioFormatException(\n+                \"Invalid PCM encoding. Expected float PCM.\", inputAudioFormat\n+            )\n+        }\n+        if (Flags.TEST_RG_OFFLOAD) {\n+            return AudioProcessor.AudioFormat.NOT_SET\n+        }\n+        return inputAudioFormat\n+    }\n \n-\t@Synchronized\n-\tfun setRgGain(rgGain: Int) {\n-\t\tthis.rgGain = rgGain\n-\t}\n+    @Synchronized\n+    fun setMode(mode: ReplayGainUtil.Mode, doNotNotifyListener: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.mode == mode) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.mode = mode\n+        }\n+        if (!doNotNotifyListener) {\n+            listener?.invoke()\n+            computeGain()\n+        }\n+    }\n \n-\t@Synchronized\n-\tfun setNonRgGain(nonRgGain: Int) {\n-\t\tthis.nonRgGain = nonRgGain\n-\t}\n+    @Synchronized\n+    fun setRgGain(rgGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.rgGain == rgGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.rgGain = rgGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setBoostGain(boostGain: Int) {\n-\t\tval changed: Boolean\n-\t\tval listener: (() -> Unit)?\n-\t\tsynchronized(this) {\n-\t\t\tchanged = this.boostGain != boostGain\n-\t\t\tlistener = boostGainChangedListener\n-\t\t\tthis.boostGain = boostGain\n-\t\t}\n-\t\tif (changed) {\n-\t\t\tlistener?.invoke()\n-\t\t}\n-\t}\n+    @Synchronized\n+    fun setNonRgGain(nonRgGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.nonRgGain == nonRgGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.nonRgGain = nonRgGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\t@Synchronized\n-\tfun setReduceGain(reduceGain: Boolean) {\n-\t\tthis.reduceGain = reduceGain\n-\t}\n+    fun setBoostGain(boostGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.boostGain == boostGain) {\n+                return\n+            }\n+            listener = boostGainChangedListener\n+            this.boostGain = boostGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setOffloadEnabled(offloadEnabled: Boolean) {\n-\t\tval changed: Boolean\n-\t\tval listener: (() -> Unit)?\n-\t\tsynchronized(this) {\n-\t\t\tchanged = this.offloadEnabled != offloadEnabled\n-\t\t\tlistener = offloadEnabledChangedListener\n-\t\t\tthis.offloadEnabled = offloadEnabled\n-\t\t}\n-\t\tif (changed) {\n-\t\t\tlistener?.invoke()\n-\t\t}\n-\t}\n+    @Synchronized\n+    fun setReduceGain(reduceGain: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.reduceGain == reduceGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.reduceGain = reduceGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setRootFormat(inputFormat: Format) {\n-\t\ttags = ReplayGainUtil.parse(inputFormat)\n-\t}\n+    fun setOffloadEnabled(offloadEnabled: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.offloadEnabled == offloadEnabled) {\n+                return\n+            }\n+            listener = offloadEnabledChangedListener\n+            this.offloadEnabled = offloadEnabled\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tprivate fun computeGain() {\n-\t\tval mode: ReplayGainUtil.Mode\n-\t\tval rgGain: Int\n-\t\tval nonRgGain: Int\n-\t\tval reduceGain: Boolean\n-\t\tsynchronized(this) {\n-\t\t\tmode = this.mode\n-\t\t\trgGain = this.rgGain\n-\t\t\tnonRgGain = this.nonRgGain\n-\t\t\treduceGain = this.reduceGain\n-\t\t}\n-\t\tval gain = ReplayGainUtil.calculateGain(tags, mode, rgGain,\n-\t\t\treduceGain, ReplayGainUtil.RATIO)\n-\t\tthis.gain = gain?.first ?: ReplayGainUtil.dbToAmpl(nonRgGain.toFloat())\n-\t\tthis.kneeThresholdDb = gain?.second\n-\t\tif (kneeThresholdDb != null) {\n-\t\t\tif (compressor == null)\n-\t\t\t\tcompressor = AdaptiveDynamicRangeCompression()\n-\t\t\tLog.w(TAG, \"using dynamic range compression\")\n-\t\t\tcompressor!!.init(\n-\t\t\t\tinputAudioFormat.sampleRate,\n-\t\t\t\tReplayGainUtil.TAU_ATTACK, ReplayGainUtil.TAU_RELEASE,\n-\t\t\t\tReplayGainUtil.RATIO\n-\t\t\t)\n-\t\t} else {\n-\t\t\tonReset() // delete compressor\n-\t\t}\n-\t}\n+    fun setRootFormat(inputFormat: Format) {\n+        tags = ReplayGainUtil.parse(inputFormat)\n+    }\n \n-\toverride fun onFlush(streamMetadata: AudioProcessor.StreamMetadata) {\n-\t\twaitingForFlush = false\n-\t\tcomputeGain()\n-\t}\n+    private fun computeGain() {\n+        val mode: ReplayGainUtil.Mode\n+        val rgGain: Int\n+        val nonRgGain: Int\n+        val reduceGain: Boolean\n+        synchronized(this) {\n+            mode = this.mode\n+            rgGain = this.rgGain\n+            nonRgGain = this.nonRgGain\n+            reduceGain = this.reduceGain\n+        }\n+        val gain = ReplayGainUtil.calculateGain(\n+            tags, mode, rgGain,\n+            reduceGain, ReplayGainUtil.RATIO\n+        )\n+        this.gain = gain?.first ?: ReplayGainUtil.dbToAmpl(nonRgGain.toFloat())\n+        this.kneeThresholdDb = gain?.second\n+        if (kneeThresholdDb != null) {\n+            if (compressor == null)\n+                compressor = AdaptiveDynamicRangeCompression()\n+            Log.w(TAG, \"using dynamic range compression\")\n+            compressor!!.init(\n+                inputAudioFormat.sampleRate,\n+                ReplayGainUtil.TAU_ATTACK, ReplayGainUtil.TAU_RELEASE,\n+                ReplayGainUtil.RATIO\n+            )\n+        } else {\n+            onReset() // delete compressor\n+        }\n+    }\n \n-\toverride fun onReset() {\n-\t\tcompressor?.release()\n-\t\tcompressor = null\n-\t}\n+    override fun onFlush(streamMetadata: AudioProcessor.StreamMetadata) {\n+        waitingForFlush = false\n+        computeGain()\n+    }\n+\n+    override fun onReset() {\n+        compressor?.release()\n+        compressor = null\n+    }\n }\n\\ No newline at end of file\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"98","loc-deleted":"95","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.17","delta-n-functions":"0","current-file-score":"9.6882083290695"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2025-12-28T14:59:12Z","current-rev":"94ecf81c","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt","previous-rev":"e902c1a0","commit-title":"Fixed crash due to multi-threading in DetailedFolderAdapter by using flow","language":"Kotlin","id":"e405b227f4992e1b04b98c38c75adc72f4bb6c38","model-score":0.15,"author-id":null,"project-id":64193,"delta-file-score":0.35111132,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt b/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\nindex 122c10d2..52781726 100644\n--- a/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\n+++ b/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\n@@ -19,3 +19,2 @@ package org.akanework.gramophone.ui.adapters\n \n-import android.annotation.SuppressLint\n import android.view.View\n@@ -27,3 +26,2 @@ import androidx.core.view.doOnLayout\n import androidx.fragment.app.Fragment\n-import androidx.media3.common.MediaItem\n import androidx.preference.PreferenceManager\n@@ -33,2 +31,5 @@ import androidx.recyclerview.widget.DiffUtil\n import androidx.recyclerview.widget.RecyclerView\n+import kotlinx.collections.immutable.ImmutableList\n+import kotlinx.collections.immutable.persistentListOf\n+import kotlinx.collections.immutable.toImmutableList\n import kotlinx.coroutines.CoroutineScope\n@@ -36,6 +37,9 @@ import kotlinx.coroutines.Dispatchers\n import kotlinx.coroutines.cancel\n+import kotlinx.coroutines.channels.BufferOverflow\n import kotlinx.coroutines.flow.MutableSharedFlow\n import kotlinx.coroutines.flow.MutableStateFlow\n+import kotlinx.coroutines.flow.combine\n+import kotlinx.coroutines.flow.combineTransform\n+import kotlinx.coroutines.flow.map\n import kotlinx.coroutines.launch\n-import kotlinx.coroutines.runBlocking\n import kotlinx.coroutines.withContext\n@@ -44,2 +48,3 @@ import org.akanework.gramophone.R\n import org.akanework.gramophone.logic.comparators.SupportComparator\n+import org.akanework.gramophone.logic.emitOrDie\n import org.akanework.gramophone.logic.getStringStrict\n@@ -86,4 +91,34 @@ class DetailedFolderAdapter(\n         Sorter.Type.ByFilePathAscending)\n+    private var fileNodePath = MutableSharedFlow<List<String>>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)\n     private val liveData = if (isDetailed) mainActivity.reader.folderStructureFlow\n         else mainActivity.reader.shallowFolderFlow\n+    private val dataFlow = liveData.combineTransform(fileNodePath) { root, path ->\n+        var item: FileNode? = root\n+        for (path in path) {\n+            item = item?.folderList?.get(path)\n+        }\n+        if (item == null || path.isEmpty()) {\n+            var newPath = mutableListOf<String>()\n+            if (isDetailed) {\n+                while (item?.folderList?.size == 1) {\n+                    newPath.add(item.folderList.keys.first())\n+                    item = item.folderList.values.first()\n+                }\n+            }\n+            // This may race with user click if a folder was deleted while a user clicks.\n+            fileNodePath.emitOrDie(newPath)\n+            return@combineTransform // we will run again with new path soon\n+        }\n+        emit(item)\n+    }\n+    private val folderFlow = dataFlow.combine(sortType) { item, sortType ->\n+        if (sortType == Sorter.Type.BySizeDescending)\n+            item.folderList.values.sortedByDescending { it.folderList.size + it.songList.size }\n+        else\n+            item.folderList.values.sortedWith(\n+                SupportComparator.createAlphanumericComparator(cnv = {\n+                    it.folderName\n+                }))\n+    }\n+    private var folderList: List<FileNode>? = null\n     private var scope: CoroutineScope? = null\n@@ -91,7 +126,6 @@ class DetailedFolderAdapter(\n     private val folderAdapter: FolderListAdapter =\n-        FolderListAdapter(listOf(), mainActivity, this)\n-    private val songList = MutableSharedFlow<List<MediaItem>>(1)\n+        FolderListAdapter(persistentListOf(), mainActivity, this)\n     private val decorAdapter = BaseDecorAdapter<DetailedFolderAdapter>(this, R.plurals.folders_plural)\n     private val songAdapter: SongAdapter =\n-        SongAdapter(fragment, songList, folder = true).apply {\n+        SongAdapter(fragment, dataFlow.map { it.songList }, folder = true).apply {\n             onFullyDrawnListener = { reportFullyDrawn() }\n@@ -108,4 +142,2 @@ class DetailedFolderAdapter(\n     }\n-    private var root: FileNode? = null\n-    private var fileNodePath = ArrayList<String>()\n     private var recyclerView: MyRecyclerView? = null\n@@ -120,7 +152,28 @@ class DetailedFolderAdapter(\n         this.scope!!.launch {\n-            liveData.collect {\n-                if (root !== it)\n-                    withContext(Dispatchers.Main) {\n-                        onChanged(it)\n+            folderFlow.collect { newList ->\n+                val oldList = folderList\n+                val canDiff = oldList != null && this@DetailedFolderAdapter.recyclerView != null\n+                val diffResult = if (canDiff) DiffUtil.calculateDiff(\n+                    DiffCallback(oldList, newList)) else null\n+                withContext(Dispatchers.Main) {\n+                    folderList = newList.toImmutableList()\n+                    if (diffResult != null)\n+                        diffResult.dispatchUpdatesTo(folderAdapter)\n+                    else\n+                        @Suppress(\"NotifyDataSetChanged\")\n+                        folderAdapter.notifyDataSetChanged()\n+                    decorAdapter.updateSongCounter()\n+                    this@DetailedFolderAdapter.recyclerView?.doOnLayout {\n+                        this@DetailedFolderAdapter.recyclerView?.postOnAnimation {\n+                            folderAdapter.reportFullyDrawn()\n+                        }\n                     }\n+                }\n+            }\n+        }\n+        this.scope!!.launch {\n+            fileNodePath.collect {\n+                withContext(Dispatchers.Main) {\n+                    folderPopAdapter.enabled = !it.isEmpty()\n+                }\n             }\n@@ -135,21 +188,13 @@ class DetailedFolderAdapter(\n \n-    fun onChanged(value: FileNode) {\n-        root = value\n-        var value = value\n-        if (fileNodePath.isEmpty() && isDetailed) {\n-            while (value.folderList.size == 1) {\n-                fileNodePath.add(value.folderList.keys.first())\n-                value = value.folderList.values.first()\n-            }\n-        }\n-        update(null)\n-    }\n-\n     fun enter(path: String?) {\n+        val currentPath = fileNodePath.replayCache.firstOrNull() ?: return\n         if (path != null) {\n-            fileNodePath.add(path)\n-            update(false)\n-        } else if (fileNodePath.isNotEmpty()) {\n-            fileNodePath.removeAt(fileNodePath.lastIndex)\n-            update(true)\n+            update(false) {\n+                fileNodePath.emitOrDie(currentPath + path)\n+            }\n+        } else if (currentPath.isNotEmpty()) {\n+            update(true) {\n+                // Remove last\n+                fileNodePath.emitOrDie(currentPath.subList(0, currentPath.size - 1))\n+            }\n         }\n@@ -159,22 +204,28 @@ class DetailedFolderAdapter(\n         sortType.value = type\n-        update(null)\n     }\n \n-    private fun update(invertedDirection: Boolean?) {\n-        var item = root\n-        for (path in fileNodePath) {\n-            item = item?.folderList?.get(path)\n-        }\n-        if (item == null) {\n-            fileNodePath.clear()\n-            item = root\n-        }\n-        val doUpdate = { canDiff: Boolean ->\n-            folderPopAdapter.enabled = fileNodePath.isNotEmpty()\n-            folderAdapter.updateList(item?.folderList?.values ?: listOf(), canDiff, sortType.value)\n-            runBlocking { songList.emit(item?.songList ?: listOf()) }\n-        }\n+    private class DiffCallback(\n+        private val oldList: List<FileNode>,\n+        private val newList: List<FileNode>,\n+    ) : DiffUtil.Callback() {\n+        override fun getOldListSize() = oldList.size\n+\n+        override fun getNewListSize() = newList.size\n+\n+        override fun areItemsTheSame(\n+            oldItemPosition: Int,\n+            newItemPosition: Int,\n+        ) = oldList[oldItemPosition].folderName == newList[newItemPosition].folderName\n+\n+        override fun areContentsTheSame(\n+            oldItemPosition: Int,\n+            newItemPosition: Int,\n+        ) = oldList[oldItemPosition] == newList[newItemPosition]\n+\n+    }\n+\n+    private fun update(invertedDirection: Boolean, doUpdate: () -> Unit) {\n         recyclerView.let {\n-            if (it == null || invertedDirection == null) {\n-                doUpdate(it != null)\n+            if (it == null) {\n+                doUpdate()\n                 return@let\n@@ -209,3 +260,3 @@ class DetailedFolderAdapter(\n                     }\n-                    doUpdate(false)\n+                    doUpdate()\n                 }\n@@ -248,3 +299,3 @@ class DetailedFolderAdapter(\n     private class FolderListAdapter(\n-        private var folderList: List<FileNode>,\n+        private var folderList: ImmutableList<FileNode>,\n         private val activity: MainActivity,\n@@ -253,3 +304,2 @@ class DetailedFolderAdapter(\n \n-        @SuppressLint(\"SetTextI18n\")\n         override fun onBindViewHolder(holder: ViewHolder, position: Int) {\n@@ -276,51 +326,4 @@ class DetailedFolderAdapter(\n \n-        @SuppressLint(\"NotifyDataSetChanged\")\n-        fun updateList(newCollection: Collection<FileNode>, canDiff: Boolean, sortType: Sorter.Type) {\n-            val newList = newCollection.toMutableList()\n-            CoroutineScope(Dispatchers.Default).launch {\n-                val diffResult = if (canDiff) DiffUtil.calculateDiff(\n-                    DiffCallback(folderList, newList)) else null\n-                val newList2 = if (sortType == Sorter.Type.BySizeDescending)\n-                    newList.sortedByDescending { it.folderList.size + it.songList.size }\n-                else\n-                    newList.sortedWith(\n-                    SupportComparator.createAlphanumericComparator(cnv = {\n-                        it.folderName\n-                    }))\n-                withContext(Dispatchers.Main) {\n-                    folderList = newList2\n-                    if (diffResult != null)\n-                        diffResult.dispatchUpdatesTo(this@FolderListAdapter)\n-                    else\n-                        notifyDataSetChanged()\n-                    folderFragment.decorAdapter.updateSongCounter()\n-                    folderFragment.recyclerView?.doOnLayout {\n-                        folderFragment.recyclerView?.postOnAnimation { reportFullyDrawn() }\n-                    }\n-                }\n-            }\n-        }\n-\n-        private inner class DiffCallback(\n-            private val oldList: List<FileNode>,\n-            private val newList: List<FileNode>,\n-        ) : DiffUtil.Callback() {\n-            override fun getOldListSize() = oldList.size\n-\n-            override fun getNewListSize() = newList.size\n-\n-            override fun areItemsTheSame(\n-                oldItemPosition: Int,\n-                newItemPosition: Int,\n-            ) = oldList[oldItemPosition].folderName == newList[newItemPosition].folderName\n-\n-            override fun areContentsTheSame(\n-                oldItemPosition: Int,\n-                newItemPosition: Int,\n-            ) = oldList[oldItemPosition] == newList[newItemPosition]\n-\n-        }\n-\n         var onFullyDrawnListener: (() -> Unit)? = null\n-        private fun reportFullyDrawn() {\n+        fun reportFullyDrawn() {\n             onFullyDrawnListener?.invoke()\n","improvement-type":"Complex Method"}],"change-level":"warning","is-hotspot?":true,"line":280,"what-changed":"GramophonePlaybackService.onCreate already has high cyclomatic complexity, and now it increases in Lines of Code from 315 to 319","how-to-fix":"There are many reasons for Complex Method. Sometimes, another design approach is beneficial such as a) modeling state using an explicit state machine rather than conditionals, or b) using table lookup rather than long chains of logic. In other scenarios, the function can be split using [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html). Just make sure you extract natural and cohesive functions. Complex Methods can also be addressed by identifying complex conditional expressions and then using the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring.","change-type":"degraded"},{"method":"GramophonePlaybackService.onCustomCommand","why-it-occurs":"A Complex Method has a high cyclomatic complexity. The recommended threshold for the Kotlin language is a cyclomatic complexity lower than 9.","name":"Complex Method","file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","refactoring-examples":[{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"55","loc-deleted":"18","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.413528317237752"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2026-01-01T13:23:52Z","current-rev":"7b370dff","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt","previous-rev":"a28de050","commit-title":"Apply all changes to ReplayGain settings UI instantly","language":"Kotlin","id":"0b5f2af002c123e31559e28ae55352e7ced73cb3","model-score":0.29,"author-id":null,"project-id":64193,"delta-file-score":0.25683072,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt b/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\nindex 9322d8fc..edd9763a 100644\n--- a/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\n+++ b/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\n@@ -12,154 +12,192 @@ import java.nio.ByteBuffer\n class ReplayGainAudioProcessor : BaseAudioProcessor() {\n-\tcompanion object {\n-\t\tprivate const val TAG = \"ReplayGainAP\"\n-\t}\n-\tprivate var compressor: AdaptiveDynamicRangeCompression? = null\n-\tprivate var waitingForFlush = false\n-\tvar mode = ReplayGainUtil.Mode.None\n-\t\tprivate set\n-\tvar rgGain = 0 // dB\n-\t\tprivate set\n-\tvar nonRgGain = 0 // dB\n-\t\tprivate set\n-\tvar boostGain = 0 // dB\n-\t\tprivate set\n-\tvar offloadEnabled = false\n-\t\tprivate set\n-\tvar reduceGain = false\n-\t\tprivate set\n-\tvar boostGainChangedListener: (() -> Unit)? = null\n-\tvar offloadEnabledChangedListener: (() -> Unit)? = null\n-\tprivate var gain = 1f\n-\tprivate var kneeThresholdDb: Float? = null\n-\tprivate var tags: ReplayGainUtil.ReplayGainInfo? = null\n-\toverride fun queueInput(inputBuffer: ByteBuffer) {\n-\t\tval frameCount = inputBuffer.remaining() / inputAudioFormat.bytesPerFrame\n-\t\tval outputBuffer = replaceOutputBuffer(frameCount * outputAudioFormat.bytesPerFrame)\n-\t\tif (inputBuffer.hasRemaining()) {\n-\t\t\tif (compressor != null) {\n-\t\t\t\tcompressor!!.compress(\n-\t\t\t\t\tinputAudioFormat.channelCount,\n-\t\t\t\t\tgain,\n-\t\t\t\t\tkneeThresholdDb!!, 1f, inputBuffer,\n-\t\t\t\t\toutputBuffer, frameCount\n-\t\t\t\t)\n-\t\t\t\tinputBuffer.position(inputBuffer.limit())\n-\t\t\t\toutputBuffer.position(frameCount * outputAudioFormat.bytesPerFrame)\n-\t\t\t} else {\n-\t\t\t\tif (gain == 1f) {\n-\t\t\t\t\toutputBuffer.put(inputBuffer)\n-\t\t\t\t} else {\n-\t\t\t\t\twhile (inputBuffer.hasRemaining()) {\n-\t\t\t\t\t\toutputBuffer.putFloat(inputBuffer.getFloat() * gain)\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t}\n-\t\t}\n-\t\toutputBuffer.flip()\n-\t}\n+    companion object {\n+        private const val TAG = \"ReplayGainAP\"\n+    }\n \n-\toverride fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {\n-\t\tif (inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {\n-\t\t\tthrow UnhandledAudioFormatException(\n-\t\t\t\t\"Invalid PCM encoding. Expected float PCM.\", inputAudioFormat\n-\t\t\t)\n-\t\t}\n-\t\t// TODO(ASAP): if setMode and setNonRgGain required reconfiguration, we could be a lot lazier.\n-\t\tif (((tags?.trackGain == null && tags?.albumGain == null)\n-\t\t\t|| (tags?.trackGain != null && tags?.trackGain != 1f)\n-\t\t\t|| (tags?.albumGain != null && tags?.albumGain != 1f)) && !Flags.TEST_RG_OFFLOAD) {\n-\t\t\treturn inputAudioFormat\n-\t\t}\n-\t\t// if there's RG metadata but it says we don't need to do anything, we can skip all work.\n-\t\treturn AudioProcessor.AudioFormat.NOT_SET\n-\t}\n+    private var compressor: AdaptiveDynamicRangeCompression? = null\n+    private var waitingForFlush = false\n+    var mode = ReplayGainUtil.Mode.None\n+        private set\n+    var rgGain = 0 // dB\n+        private set\n+    var nonRgGain = 0 // dB\n+        private set\n+    var boostGain = 0 // dB\n+        private set\n+    var offloadEnabled = false\n+        private set\n+    var reduceGain = false\n+        private set\n+    var settingsChangedListener: (() -> Unit)? = null\n+    var boostGainChangedListener: (() -> Unit)? = null\n+    var offloadEnabledChangedListener: (() -> Unit)? = null\n+    private var gain = 1f\n+    private var kneeThresholdDb: Float? = null\n+    private var tags: ReplayGainUtil.ReplayGainInfo? = null\n+    override fun queueInput(inputBuffer: ByteBuffer) {\n+        val frameCount = inputBuffer.remaining() / inputAudioFormat.bytesPerFrame\n+        val outputBuffer = replaceOutputBuffer(frameCount * outputAudioFormat.bytesPerFrame)\n+        if (inputBuffer.hasRemaining()) {\n+            if (compressor != null) {\n+                compressor!!.compress(\n+                    inputAudioFormat.channelCount,\n+                    gain,\n+                    kneeThresholdDb!!, 1f, inputBuffer,\n+                    outputBuffer, frameCount\n+                )\n+                inputBuffer.position(inputBuffer.limit())\n+                outputBuffer.position(frameCount * outputAudioFormat.bytesPerFrame)\n+            } else {\n+                if (gain == 1f) {\n+                    outputBuffer.put(inputBuffer)\n+                } else {\n+                    while (inputBuffer.hasRemaining()) {\n+                        outputBuffer.putFloat(inputBuffer.getFloat() * gain)\n+                    }\n+                }\n+            }\n+        }\n+        outputBuffer.flip()\n+    }\n \n-\t@Synchronized\n-\tfun setMode(mode: ReplayGainUtil.Mode) {\n-\t\tthis.mode = mode\n-\t}\n+    override fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {\n+        if (inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {\n+            throw UnhandledAudioFormatException(\n+                \"Invalid PCM encoding. Expected float PCM.\", inputAudioFormat\n+            )\n+        }\n+        if (Flags.TEST_RG_OFFLOAD) {\n+            return AudioProcessor.AudioFormat.NOT_SET\n+        }\n+        return inputAudioFormat\n+    }\n \n-\t@Synchronized\n-\tfun setRgGain(rgGain: Int) {\n-\t\tthis.rgGain = rgGain\n-\t}\n+    @Synchronized\n+    fun setMode(mode: ReplayGainUtil.Mode, doNotNotifyListener: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.mode == mode) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.mode = mode\n+        }\n+        if (!doNotNotifyListener) {\n+            listener?.invoke()\n+            computeGain()\n+        }\n+    }\n \n-\t@Synchronized\n-\tfun setNonRgGain(nonRgGain: Int) {\n-\t\tthis.nonRgGain = nonRgGain\n-\t}\n+    @Synchronized\n+    fun setRgGain(rgGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.rgGain == rgGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.rgGain = rgGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setBoostGain(boostGain: Int) {\n-\t\tval changed: Boolean\n-\t\tval listener: (() -> Unit)?\n-\t\tsynchronized(this) {\n-\t\t\tchanged = this.boostGain != boostGain\n-\t\t\tlistener = boostGainChangedListener\n-\t\t\tthis.boostGain = boostGain\n-\t\t}\n-\t\tif (changed) {\n-\t\t\tlistener?.invoke()\n-\t\t}\n-\t}\n+    @Synchronized\n+    fun setNonRgGain(nonRgGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.nonRgGain == nonRgGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.nonRgGain = nonRgGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\t@Synchronized\n-\tfun setReduceGain(reduceGain: Boolean) {\n-\t\tthis.reduceGain = reduceGain\n-\t}\n+    fun setBoostGain(boostGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.boostGain == boostGain) {\n+                return\n+            }\n+            listener = boostGainChangedListener\n+            this.boostGain = boostGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setOffloadEnabled(offloadEnabled: Boolean) {\n-\t\tval changed: Boolean\n-\t\tval listener: (() -> Unit)?\n-\t\tsynchronized(this) {\n-\t\t\tchanged = this.offloadEnabled != offloadEnabled\n-\t\t\tlistener = offloadEnabledChangedListener\n-\t\t\tthis.offloadEnabled = offloadEnabled\n-\t\t}\n-\t\tif (changed) {\n-\t\t\tlistener?.invoke()\n-\t\t}\n-\t}\n+    @Synchronized\n+    fun setReduceGain(reduceGain: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.reduceGain == reduceGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.reduceGain = reduceGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setRootFormat(inputFormat: Format) {\n-\t\ttags = ReplayGainUtil.parse(inputFormat)\n-\t}\n+    fun setOffloadEnabled(offloadEnabled: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.offloadEnabled == offloadEnabled) {\n+                return\n+            }\n+            listener = offloadEnabledChangedListener\n+            this.offloadEnabled = offloadEnabled\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tprivate fun computeGain() {\n-\t\tval mode: ReplayGainUtil.Mode\n-\t\tval rgGain: Int\n-\t\tval nonRgGain: Int\n-\t\tval reduceGain: Boolean\n-\t\tsynchronized(this) {\n-\t\t\tmode = this.mode\n-\t\t\trgGain = this.rgGain\n-\t\t\tnonRgGain = this.nonRgGain\n-\t\t\treduceGain = this.reduceGain\n-\t\t}\n-\t\tval gain = ReplayGainUtil.calculateGain(tags, mode, rgGain,\n-\t\t\treduceGain, ReplayGainUtil.RATIO)\n-\t\tthis.gain = gain?.first ?: ReplayGainUtil.dbToAmpl(nonRgGain.toFloat())\n-\t\tthis.kneeThresholdDb = gain?.second\n-\t\tif (kneeThresholdDb != null) {\n-\t\t\tif (compressor == null)\n-\t\t\t\tcompressor = AdaptiveDynamicRangeCompression()\n-\t\t\tLog.w(TAG, \"using dynamic range compression\")\n-\t\t\tcompressor!!.init(\n-\t\t\t\tinputAudioFormat.sampleRate,\n-\t\t\t\tReplayGainUtil.TAU_ATTACK, ReplayGainUtil.TAU_RELEASE,\n-\t\t\t\tReplayGainUtil.RATIO\n-\t\t\t)\n-\t\t} else {\n-\t\t\tonReset() // delete compressor\n-\t\t}\n-\t}\n+    fun setRootFormat(inputFormat: Format) {\n+        tags = ReplayGainUtil.parse(inputFormat)\n+    }\n \n-\toverride fun onFlush(streamMetadata: AudioProcessor.StreamMetadata) {\n-\t\twaitingForFlush = false\n-\t\tcomputeGain()\n-\t}\n+    private fun computeGain() {\n+        val mode: ReplayGainUtil.Mode\n+        val rgGain: Int\n+        val nonRgGain: Int\n+        val reduceGain: Boolean\n+        synchronized(this) {\n+            mode = this.mode\n+            rgGain = this.rgGain\n+            nonRgGain = this.nonRgGain\n+            reduceGain = this.reduceGain\n+        }\n+        val gain = ReplayGainUtil.calculateGain(\n+            tags, mode, rgGain,\n+            reduceGain, ReplayGainUtil.RATIO\n+        )\n+        this.gain = gain?.first ?: ReplayGainUtil.dbToAmpl(nonRgGain.toFloat())\n+        this.kneeThresholdDb = gain?.second\n+        if (kneeThresholdDb != null) {\n+            if (compressor == null)\n+                compressor = AdaptiveDynamicRangeCompression()\n+            Log.w(TAG, \"using dynamic range compression\")\n+            compressor!!.init(\n+                inputAudioFormat.sampleRate,\n+                ReplayGainUtil.TAU_ATTACK, ReplayGainUtil.TAU_RELEASE,\n+                ReplayGainUtil.RATIO\n+            )\n+        } else {\n+            onReset() // delete compressor\n+        }\n+    }\n \n-\toverride fun onReset() {\n-\t\tcompressor?.release()\n-\t\tcompressor = null\n-\t}\n+    override fun onFlush(streamMetadata: AudioProcessor.StreamMetadata) {\n+        waitingForFlush = false\n+        computeGain()\n+    }\n+\n+    override fun onReset() {\n+        compressor?.release()\n+        compressor = null\n+    }\n }\n\\ No newline at end of file\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"98","loc-deleted":"95","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.17","delta-n-functions":"0","current-file-score":"9.6882083290695"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2025-12-28T14:59:12Z","current-rev":"94ecf81c","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt","previous-rev":"e902c1a0","commit-title":"Fixed crash due to multi-threading in DetailedFolderAdapter by using flow","language":"Kotlin","id":"e405b227f4992e1b04b98c38c75adc72f4bb6c38","model-score":0.15,"author-id":null,"project-id":64193,"delta-file-score":0.35111132,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt b/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\nindex 122c10d2..52781726 100644\n--- a/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\n+++ b/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\n@@ -19,3 +19,2 @@ package org.akanework.gramophone.ui.adapters\n \n-import android.annotation.SuppressLint\n import android.view.View\n@@ -27,3 +26,2 @@ import androidx.core.view.doOnLayout\n import androidx.fragment.app.Fragment\n-import androidx.media3.common.MediaItem\n import androidx.preference.PreferenceManager\n@@ -33,2 +31,5 @@ import androidx.recyclerview.widget.DiffUtil\n import androidx.recyclerview.widget.RecyclerView\n+import kotlinx.collections.immutable.ImmutableList\n+import kotlinx.collections.immutable.persistentListOf\n+import kotlinx.collections.immutable.toImmutableList\n import kotlinx.coroutines.CoroutineScope\n@@ -36,6 +37,9 @@ import kotlinx.coroutines.Dispatchers\n import kotlinx.coroutines.cancel\n+import kotlinx.coroutines.channels.BufferOverflow\n import kotlinx.coroutines.flow.MutableSharedFlow\n import kotlinx.coroutines.flow.MutableStateFlow\n+import kotlinx.coroutines.flow.combine\n+import kotlinx.coroutines.flow.combineTransform\n+import kotlinx.coroutines.flow.map\n import kotlinx.coroutines.launch\n-import kotlinx.coroutines.runBlocking\n import kotlinx.coroutines.withContext\n@@ -44,2 +48,3 @@ import org.akanework.gramophone.R\n import org.akanework.gramophone.logic.comparators.SupportComparator\n+import org.akanework.gramophone.logic.emitOrDie\n import org.akanework.gramophone.logic.getStringStrict\n@@ -86,4 +91,34 @@ class DetailedFolderAdapter(\n         Sorter.Type.ByFilePathAscending)\n+    private var fileNodePath = MutableSharedFlow<List<String>>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)\n     private val liveData = if (isDetailed) mainActivity.reader.folderStructureFlow\n         else mainActivity.reader.shallowFolderFlow\n+    private val dataFlow = liveData.combineTransform(fileNodePath) { root, path ->\n+        var item: FileNode? = root\n+        for (path in path) {\n+            item = item?.folderList?.get(path)\n+        }\n+        if (item == null || path.isEmpty()) {\n+            var newPath = mutableListOf<String>()\n+            if (isDetailed) {\n+                while (item?.folderList?.size == 1) {\n+                    newPath.add(item.folderList.keys.first())\n+                    item = item.folderList.values.first()\n+                }\n+            }\n+            // This may race with user click if a folder was deleted while a user clicks.\n+            fileNodePath.emitOrDie(newPath)\n+            return@combineTransform // we will run again with new path soon\n+        }\n+        emit(item)\n+    }\n+    private val folderFlow = dataFlow.combine(sortType) { item, sortType ->\n+        if (sortType == Sorter.Type.BySizeDescending)\n+            item.folderList.values.sortedByDescending { it.folderList.size + it.songList.size }\n+        else\n+            item.folderList.values.sortedWith(\n+                SupportComparator.createAlphanumericComparator(cnv = {\n+                    it.folderName\n+                }))\n+    }\n+    private var folderList: List<FileNode>? = null\n     private var scope: CoroutineScope? = null\n@@ -91,7 +126,6 @@ class DetailedFolderAdapter(\n     private val folderAdapter: FolderListAdapter =\n-        FolderListAdapter(listOf(), mainActivity, this)\n-    private val songList = MutableSharedFlow<List<MediaItem>>(1)\n+        FolderListAdapter(persistentListOf(), mainActivity, this)\n     private val decorAdapter = BaseDecorAdapter<DetailedFolderAdapter>(this, R.plurals.folders_plural)\n     private val songAdapter: SongAdapter =\n-        SongAdapter(fragment, songList, folder = true).apply {\n+        SongAdapter(fragment, dataFlow.map { it.songList }, folder = true).apply {\n             onFullyDrawnListener = { reportFullyDrawn() }\n@@ -108,4 +142,2 @@ class DetailedFolderAdapter(\n     }\n-    private var root: FileNode? = null\n-    private var fileNodePath = ArrayList<String>()\n     private var recyclerView: MyRecyclerView? = null\n@@ -120,7 +152,28 @@ class DetailedFolderAdapter(\n         this.scope!!.launch {\n-            liveData.collect {\n-                if (root !== it)\n-                    withContext(Dispatchers.Main) {\n-                        onChanged(it)\n+            folderFlow.collect { newList ->\n+                val oldList = folderList\n+                val canDiff = oldList != null && this@DetailedFolderAdapter.recyclerView != null\n+                val diffResult = if (canDiff) DiffUtil.calculateDiff(\n+                    DiffCallback(oldList, newList)) else null\n+                withContext(Dispatchers.Main) {\n+                    folderList = newList.toImmutableList()\n+                    if (diffResult != null)\n+                        diffResult.dispatchUpdatesTo(folderAdapter)\n+                    else\n+                        @Suppress(\"NotifyDataSetChanged\")\n+                        folderAdapter.notifyDataSetChanged()\n+                    decorAdapter.updateSongCounter()\n+                    this@DetailedFolderAdapter.recyclerView?.doOnLayout {\n+                        this@DetailedFolderAdapter.recyclerView?.postOnAnimation {\n+                            folderAdapter.reportFullyDrawn()\n+                        }\n                     }\n+                }\n+            }\n+        }\n+        this.scope!!.launch {\n+            fileNodePath.collect {\n+                withContext(Dispatchers.Main) {\n+                    folderPopAdapter.enabled = !it.isEmpty()\n+                }\n             }\n@@ -135,21 +188,13 @@ class DetailedFolderAdapter(\n \n-    fun onChanged(value: FileNode) {\n-        root = value\n-        var value = value\n-        if (fileNodePath.isEmpty() && isDetailed) {\n-            while (value.folderList.size == 1) {\n-                fileNodePath.add(value.folderList.keys.first())\n-                value = value.folderList.values.first()\n-            }\n-        }\n-        update(null)\n-    }\n-\n     fun enter(path: String?) {\n+        val currentPath = fileNodePath.replayCache.firstOrNull() ?: return\n         if (path != null) {\n-            fileNodePath.add(path)\n-            update(false)\n-        } else if (fileNodePath.isNotEmpty()) {\n-            fileNodePath.removeAt(fileNodePath.lastIndex)\n-            update(true)\n+            update(false) {\n+                fileNodePath.emitOrDie(currentPath + path)\n+            }\n+        } else if (currentPath.isNotEmpty()) {\n+            update(true) {\n+                // Remove last\n+                fileNodePath.emitOrDie(currentPath.subList(0, currentPath.size - 1))\n+            }\n         }\n@@ -159,22 +204,28 @@ class DetailedFolderAdapter(\n         sortType.value = type\n-        update(null)\n     }\n \n-    private fun update(invertedDirection: Boolean?) {\n-        var item = root\n-        for (path in fileNodePath) {\n-            item = item?.folderList?.get(path)\n-        }\n-        if (item == null) {\n-            fileNodePath.clear()\n-            item = root\n-        }\n-        val doUpdate = { canDiff: Boolean ->\n-            folderPopAdapter.enabled = fileNodePath.isNotEmpty()\n-            folderAdapter.updateList(item?.folderList?.values ?: listOf(), canDiff, sortType.value)\n-            runBlocking { songList.emit(item?.songList ?: listOf()) }\n-        }\n+    private class DiffCallback(\n+        private val oldList: List<FileNode>,\n+        private val newList: List<FileNode>,\n+    ) : DiffUtil.Callback() {\n+        override fun getOldListSize() = oldList.size\n+\n+        override fun getNewListSize() = newList.size\n+\n+        override fun areItemsTheSame(\n+            oldItemPosition: Int,\n+            newItemPosition: Int,\n+        ) = oldList[oldItemPosition].folderName == newList[newItemPosition].folderName\n+\n+        override fun areContentsTheSame(\n+            oldItemPosition: Int,\n+            newItemPosition: Int,\n+        ) = oldList[oldItemPosition] == newList[newItemPosition]\n+\n+    }\n+\n+    private fun update(invertedDirection: Boolean, doUpdate: () -> Unit) {\n         recyclerView.let {\n-            if (it == null || invertedDirection == null) {\n-                doUpdate(it != null)\n+            if (it == null) {\n+                doUpdate()\n                 return@let\n@@ -209,3 +260,3 @@ class DetailedFolderAdapter(\n                     }\n-                    doUpdate(false)\n+                    doUpdate()\n                 }\n@@ -248,3 +299,3 @@ class DetailedFolderAdapter(\n     private class FolderListAdapter(\n-        private var folderList: List<FileNode>,\n+        private var folderList: ImmutableList<FileNode>,\n         private val activity: MainActivity,\n@@ -253,3 +304,2 @@ class DetailedFolderAdapter(\n \n-        @SuppressLint(\"SetTextI18n\")\n         override fun onBindViewHolder(holder: ViewHolder, position: Int) {\n@@ -276,51 +326,4 @@ class DetailedFolderAdapter(\n \n-        @SuppressLint(\"NotifyDataSetChanged\")\n-        fun updateList(newCollection: Collection<FileNode>, canDiff: Boolean, sortType: Sorter.Type) {\n-            val newList = newCollection.toMutableList()\n-            CoroutineScope(Dispatchers.Default).launch {\n-                val diffResult = if (canDiff) DiffUtil.calculateDiff(\n-                    DiffCallback(folderList, newList)) else null\n-                val newList2 = if (sortType == Sorter.Type.BySizeDescending)\n-                    newList.sortedByDescending { it.folderList.size + it.songList.size }\n-                else\n-                    newList.sortedWith(\n-                    SupportComparator.createAlphanumericComparator(cnv = {\n-                        it.folderName\n-                    }))\n-                withContext(Dispatchers.Main) {\n-                    folderList = newList2\n-                    if (diffResult != null)\n-                        diffResult.dispatchUpdatesTo(this@FolderListAdapter)\n-                    else\n-                        notifyDataSetChanged()\n-                    folderFragment.decorAdapter.updateSongCounter()\n-                    folderFragment.recyclerView?.doOnLayout {\n-                        folderFragment.recyclerView?.postOnAnimation { reportFullyDrawn() }\n-                    }\n-                }\n-            }\n-        }\n-\n-        private inner class DiffCallback(\n-            private val oldList: List<FileNode>,\n-            private val newList: List<FileNode>,\n-        ) : DiffUtil.Callback() {\n-            override fun getOldListSize() = oldList.size\n-\n-            override fun getNewListSize() = newList.size\n-\n-            override fun areItemsTheSame(\n-                oldItemPosition: Int,\n-                newItemPosition: Int,\n-            ) = oldList[oldItemPosition].folderName == newList[newItemPosition].folderName\n-\n-            override fun areContentsTheSame(\n-                oldItemPosition: Int,\n-                newItemPosition: Int,\n-            ) = oldList[oldItemPosition] == newList[newItemPosition]\n-\n-        }\n-\n         var onFullyDrawnListener: (() -> Unit)? = null\n-        private fun reportFullyDrawn() {\n+        fun reportFullyDrawn() {\n             onFullyDrawnListener?.invoke()\n","improvement-type":"Complex Method"}],"change-level":"warning","is-hotspot?":true,"line":911,"what-changed":"GramophonePlaybackService.onCustomCommand increases in cyclomatic complexity from 9 to 10, threshold = 9","how-to-fix":"There are many reasons for Complex Method. Sometimes, another design approach is beneficial such as a) modeling state using an explicit state machine rather than conditionals, or b) using table lookup rather than long chains of logic. In other scenarios, the function can be split using [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html). Just make sure you extract natural and cohesive functions. Complex Methods can also be addressed by identifying complex conditional expressions and then using the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring.","change-type":"degraded"},{"method":"QueueBoard.setCurrQueue","why-it-occurs":"A Complex Method has a high cyclomatic complexity. The recommended threshold for the Kotlin language is a cyclomatic complexity lower than 9.","name":"Complex Method","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":[{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"55","loc-deleted":"18","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.413528317237752"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2026-01-01T13:23:52Z","current-rev":"7b370dff","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt","previous-rev":"a28de050","commit-title":"Apply all changes to ReplayGain settings UI instantly","language":"Kotlin","id":"0b5f2af002c123e31559e28ae55352e7ced73cb3","model-score":0.29,"author-id":null,"project-id":64193,"delta-file-score":0.25683072,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt b/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\nindex 9322d8fc..edd9763a 100644\n--- a/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\n+++ b/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\n@@ -12,154 +12,192 @@ import java.nio.ByteBuffer\n class ReplayGainAudioProcessor : BaseAudioProcessor() {\n-\tcompanion object {\n-\t\tprivate const val TAG = \"ReplayGainAP\"\n-\t}\n-\tprivate var compressor: AdaptiveDynamicRangeCompression? = null\n-\tprivate var waitingForFlush = false\n-\tvar mode = ReplayGainUtil.Mode.None\n-\t\tprivate set\n-\tvar rgGain = 0 // dB\n-\t\tprivate set\n-\tvar nonRgGain = 0 // dB\n-\t\tprivate set\n-\tvar boostGain = 0 // dB\n-\t\tprivate set\n-\tvar offloadEnabled = false\n-\t\tprivate set\n-\tvar reduceGain = false\n-\t\tprivate set\n-\tvar boostGainChangedListener: (() -> Unit)? = null\n-\tvar offloadEnabledChangedListener: (() -> Unit)? = null\n-\tprivate var gain = 1f\n-\tprivate var kneeThresholdDb: Float? = null\n-\tprivate var tags: ReplayGainUtil.ReplayGainInfo? = null\n-\toverride fun queueInput(inputBuffer: ByteBuffer) {\n-\t\tval frameCount = inputBuffer.remaining() / inputAudioFormat.bytesPerFrame\n-\t\tval outputBuffer = replaceOutputBuffer(frameCount * outputAudioFormat.bytesPerFrame)\n-\t\tif (inputBuffer.hasRemaining()) {\n-\t\t\tif (compressor != null) {\n-\t\t\t\tcompressor!!.compress(\n-\t\t\t\t\tinputAudioFormat.channelCount,\n-\t\t\t\t\tgain,\n-\t\t\t\t\tkneeThresholdDb!!, 1f, inputBuffer,\n-\t\t\t\t\toutputBuffer, frameCount\n-\t\t\t\t)\n-\t\t\t\tinputBuffer.position(inputBuffer.limit())\n-\t\t\t\toutputBuffer.position(frameCount * outputAudioFormat.bytesPerFrame)\n-\t\t\t} else {\n-\t\t\t\tif (gain == 1f) {\n-\t\t\t\t\toutputBuffer.put(inputBuffer)\n-\t\t\t\t} else {\n-\t\t\t\t\twhile (inputBuffer.hasRemaining()) {\n-\t\t\t\t\t\toutputBuffer.putFloat(inputBuffer.getFloat() * gain)\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t}\n-\t\t}\n-\t\toutputBuffer.flip()\n-\t}\n+    companion object {\n+        private const val TAG = \"ReplayGainAP\"\n+    }\n \n-\toverride fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {\n-\t\tif (inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {\n-\t\t\tthrow UnhandledAudioFormatException(\n-\t\t\t\t\"Invalid PCM encoding. Expected float PCM.\", inputAudioFormat\n-\t\t\t)\n-\t\t}\n-\t\t// TODO(ASAP): if setMode and setNonRgGain required reconfiguration, we could be a lot lazier.\n-\t\tif (((tags?.trackGain == null && tags?.albumGain == null)\n-\t\t\t|| (tags?.trackGain != null && tags?.trackGain != 1f)\n-\t\t\t|| (tags?.albumGain != null && tags?.albumGain != 1f)) && !Flags.TEST_RG_OFFLOAD) {\n-\t\t\treturn inputAudioFormat\n-\t\t}\n-\t\t// if there's RG metadata but it says we don't need to do anything, we can skip all work.\n-\t\treturn AudioProcessor.AudioFormat.NOT_SET\n-\t}\n+    private var compressor: AdaptiveDynamicRangeCompression? = null\n+    private var waitingForFlush = false\n+    var mode = ReplayGainUtil.Mode.None\n+        private set\n+    var rgGain = 0 // dB\n+        private set\n+    var nonRgGain = 0 // dB\n+        private set\n+    var boostGain = 0 // dB\n+        private set\n+    var offloadEnabled = false\n+        private set\n+    var reduceGain = false\n+        private set\n+    var settingsChangedListener: (() -> Unit)? = null\n+    var boostGainChangedListener: (() -> Unit)? = null\n+    var offloadEnabledChangedListener: (() -> Unit)? = null\n+    private var gain = 1f\n+    private var kneeThresholdDb: Float? = null\n+    private var tags: ReplayGainUtil.ReplayGainInfo? = null\n+    override fun queueInput(inputBuffer: ByteBuffer) {\n+        val frameCount = inputBuffer.remaining() / inputAudioFormat.bytesPerFrame\n+        val outputBuffer = replaceOutputBuffer(frameCount * outputAudioFormat.bytesPerFrame)\n+        if (inputBuffer.hasRemaining()) {\n+            if (compressor != null) {\n+                compressor!!.compress(\n+                    inputAudioFormat.channelCount,\n+                    gain,\n+                    kneeThresholdDb!!, 1f, inputBuffer,\n+                    outputBuffer, frameCount\n+                )\n+                inputBuffer.position(inputBuffer.limit())\n+                outputBuffer.position(frameCount * outputAudioFormat.bytesPerFrame)\n+            } else {\n+                if (gain == 1f) {\n+                    outputBuffer.put(inputBuffer)\n+                } else {\n+                    while (inputBuffer.hasRemaining()) {\n+                        outputBuffer.putFloat(inputBuffer.getFloat() * gain)\n+                    }\n+                }\n+            }\n+        }\n+        outputBuffer.flip()\n+    }\n \n-\t@Synchronized\n-\tfun setMode(mode: ReplayGainUtil.Mode) {\n-\t\tthis.mode = mode\n-\t}\n+    override fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {\n+        if (inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {\n+            throw UnhandledAudioFormatException(\n+                \"Invalid PCM encoding. Expected float PCM.\", inputAudioFormat\n+            )\n+        }\n+        if (Flags.TEST_RG_OFFLOAD) {\n+            return AudioProcessor.AudioFormat.NOT_SET\n+        }\n+        return inputAudioFormat\n+    }\n \n-\t@Synchronized\n-\tfun setRgGain(rgGain: Int) {\n-\t\tthis.rgGain = rgGain\n-\t}\n+    @Synchronized\n+    fun setMode(mode: ReplayGainUtil.Mode, doNotNotifyListener: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.mode == mode) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.mode = mode\n+        }\n+        if (!doNotNotifyListener) {\n+            listener?.invoke()\n+            computeGain()\n+        }\n+    }\n \n-\t@Synchronized\n-\tfun setNonRgGain(nonRgGain: Int) {\n-\t\tthis.nonRgGain = nonRgGain\n-\t}\n+    @Synchronized\n+    fun setRgGain(rgGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.rgGain == rgGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.rgGain = rgGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setBoostGain(boostGain: Int) {\n-\t\tval changed: Boolean\n-\t\tval listener: (() -> Unit)?\n-\t\tsynchronized(this) {\n-\t\t\tchanged = this.boostGain != boostGain\n-\t\t\tlistener = boostGainChangedListener\n-\t\t\tthis.boostGain = boostGain\n-\t\t}\n-\t\tif (changed) {\n-\t\t\tlistener?.invoke()\n-\t\t}\n-\t}\n+    @Synchronized\n+    fun setNonRgGain(nonRgGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.nonRgGain == nonRgGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.nonRgGain = nonRgGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\t@Synchronized\n-\tfun setReduceGain(reduceGain: Boolean) {\n-\t\tthis.reduceGain = reduceGain\n-\t}\n+    fun setBoostGain(boostGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.boostGain == boostGain) {\n+                return\n+            }\n+            listener = boostGainChangedListener\n+            this.boostGain = boostGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setOffloadEnabled(offloadEnabled: Boolean) {\n-\t\tval changed: Boolean\n-\t\tval listener: (() -> Unit)?\n-\t\tsynchronized(this) {\n-\t\t\tchanged = this.offloadEnabled != offloadEnabled\n-\t\t\tlistener = offloadEnabledChangedListener\n-\t\t\tthis.offloadEnabled = offloadEnabled\n-\t\t}\n-\t\tif (changed) {\n-\t\t\tlistener?.invoke()\n-\t\t}\n-\t}\n+    @Synchronized\n+    fun setReduceGain(reduceGain: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.reduceGain == reduceGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.reduceGain = reduceGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setRootFormat(inputFormat: Format) {\n-\t\ttags = ReplayGainUtil.parse(inputFormat)\n-\t}\n+    fun setOffloadEnabled(offloadEnabled: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.offloadEnabled == offloadEnabled) {\n+                return\n+            }\n+            listener = offloadEnabledChangedListener\n+            this.offloadEnabled = offloadEnabled\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tprivate fun computeGain() {\n-\t\tval mode: ReplayGainUtil.Mode\n-\t\tval rgGain: Int\n-\t\tval nonRgGain: Int\n-\t\tval reduceGain: Boolean\n-\t\tsynchronized(this) {\n-\t\t\tmode = this.mode\n-\t\t\trgGain = this.rgGain\n-\t\t\tnonRgGain = this.nonRgGain\n-\t\t\treduceGain = this.reduceGain\n-\t\t}\n-\t\tval gain = ReplayGainUtil.calculateGain(tags, mode, rgGain,\n-\t\t\treduceGain, ReplayGainUtil.RATIO)\n-\t\tthis.gain = gain?.first ?: ReplayGainUtil.dbToAmpl(nonRgGain.toFloat())\n-\t\tthis.kneeThresholdDb = gain?.second\n-\t\tif (kneeThresholdDb != null) {\n-\t\t\tif (compressor == null)\n-\t\t\t\tcompressor = AdaptiveDynamicRangeCompression()\n-\t\t\tLog.w(TAG, \"using dynamic range compression\")\n-\t\t\tcompressor!!.init(\n-\t\t\t\tinputAudioFormat.sampleRate,\n-\t\t\t\tReplayGainUtil.TAU_ATTACK, ReplayGainUtil.TAU_RELEASE,\n-\t\t\t\tReplayGainUtil.RATIO\n-\t\t\t)\n-\t\t} else {\n-\t\t\tonReset() // delete compressor\n-\t\t}\n-\t}\n+    fun setRootFormat(inputFormat: Format) {\n+        tags = ReplayGainUtil.parse(inputFormat)\n+    }\n \n-\toverride fun onFlush(streamMetadata: AudioProcessor.StreamMetadata) {\n-\t\twaitingForFlush = false\n-\t\tcomputeGain()\n-\t}\n+    private fun computeGain() {\n+        val mode: ReplayGainUtil.Mode\n+        val rgGain: Int\n+        val nonRgGain: Int\n+        val reduceGain: Boolean\n+        synchronized(this) {\n+            mode = this.mode\n+            rgGain = this.rgGain\n+            nonRgGain = this.nonRgGain\n+            reduceGain = this.reduceGain\n+        }\n+        val gain = ReplayGainUtil.calculateGain(\n+            tags, mode, rgGain,\n+            reduceGain, ReplayGainUtil.RATIO\n+        )\n+        this.gain = gain?.first ?: ReplayGainUtil.dbToAmpl(nonRgGain.toFloat())\n+        this.kneeThresholdDb = gain?.second\n+        if (kneeThresholdDb != null) {\n+            if (compressor == null)\n+                compressor = AdaptiveDynamicRangeCompression()\n+            Log.w(TAG, \"using dynamic range compression\")\n+            compressor!!.init(\n+                inputAudioFormat.sampleRate,\n+                ReplayGainUtil.TAU_ATTACK, ReplayGainUtil.TAU_RELEASE,\n+                ReplayGainUtil.RATIO\n+            )\n+        } else {\n+            onReset() // delete compressor\n+        }\n+    }\n \n-\toverride fun onReset() {\n-\t\tcompressor?.release()\n-\t\tcompressor = null\n-\t}\n+    override fun onFlush(streamMetadata: AudioProcessor.StreamMetadata) {\n+        waitingForFlush = false\n+        computeGain()\n+    }\n+\n+    override fun onReset() {\n+        compressor?.release()\n+        compressor = null\n+    }\n }\n\\ No newline at end of file\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"98","loc-deleted":"95","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.17","delta-n-functions":"0","current-file-score":"9.6882083290695"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2025-12-28T14:59:12Z","current-rev":"94ecf81c","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt","previous-rev":"e902c1a0","commit-title":"Fixed crash due to multi-threading in DetailedFolderAdapter by using flow","language":"Kotlin","id":"e405b227f4992e1b04b98c38c75adc72f4bb6c38","model-score":0.15,"author-id":null,"project-id":64193,"delta-file-score":0.35111132,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt b/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\nindex 122c10d2..52781726 100644\n--- a/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\n+++ b/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\n@@ -19,3 +19,2 @@ package org.akanework.gramophone.ui.adapters\n \n-import android.annotation.SuppressLint\n import android.view.View\n@@ -27,3 +26,2 @@ import androidx.core.view.doOnLayout\n import androidx.fragment.app.Fragment\n-import androidx.media3.common.MediaItem\n import androidx.preference.PreferenceManager\n@@ -33,2 +31,5 @@ import androidx.recyclerview.widget.DiffUtil\n import androidx.recyclerview.widget.RecyclerView\n+import kotlinx.collections.immutable.ImmutableList\n+import kotlinx.collections.immutable.persistentListOf\n+import kotlinx.collections.immutable.toImmutableList\n import kotlinx.coroutines.CoroutineScope\n@@ -36,6 +37,9 @@ import kotlinx.coroutines.Dispatchers\n import kotlinx.coroutines.cancel\n+import kotlinx.coroutines.channels.BufferOverflow\n import kotlinx.coroutines.flow.MutableSharedFlow\n import kotlinx.coroutines.flow.MutableStateFlow\n+import kotlinx.coroutines.flow.combine\n+import kotlinx.coroutines.flow.combineTransform\n+import kotlinx.coroutines.flow.map\n import kotlinx.coroutines.launch\n-import kotlinx.coroutines.runBlocking\n import kotlinx.coroutines.withContext\n@@ -44,2 +48,3 @@ import org.akanework.gramophone.R\n import org.akanework.gramophone.logic.comparators.SupportComparator\n+import org.akanework.gramophone.logic.emitOrDie\n import org.akanework.gramophone.logic.getStringStrict\n@@ -86,4 +91,34 @@ class DetailedFolderAdapter(\n         Sorter.Type.ByFilePathAscending)\n+    private var fileNodePath = MutableSharedFlow<List<String>>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)\n     private val liveData = if (isDetailed) mainActivity.reader.folderStructureFlow\n         else mainActivity.reader.shallowFolderFlow\n+    private val dataFlow = liveData.combineTransform(fileNodePath) { root, path ->\n+        var item: FileNode? = root\n+        for (path in path) {\n+            item = item?.folderList?.get(path)\n+        }\n+        if (item == null || path.isEmpty()) {\n+            var newPath = mutableListOf<String>()\n+            if (isDetailed) {\n+                while (item?.folderList?.size == 1) {\n+                    newPath.add(item.folderList.keys.first())\n+                    item = item.folderList.values.first()\n+                }\n+            }\n+            // This may race with user click if a folder was deleted while a user clicks.\n+            fileNodePath.emitOrDie(newPath)\n+            return@combineTransform // we will run again with new path soon\n+        }\n+        emit(item)\n+    }\n+    private val folderFlow = dataFlow.combine(sortType) { item, sortType ->\n+        if (sortType == Sorter.Type.BySizeDescending)\n+            item.folderList.values.sortedByDescending { it.folderList.size + it.songList.size }\n+        else\n+            item.folderList.values.sortedWith(\n+                SupportComparator.createAlphanumericComparator(cnv = {\n+                    it.folderName\n+                }))\n+    }\n+    private var folderList: List<FileNode>? = null\n     private var scope: CoroutineScope? = null\n@@ -91,7 +126,6 @@ class DetailedFolderAdapter(\n     private val folderAdapter: FolderListAdapter =\n-        FolderListAdapter(listOf(), mainActivity, this)\n-    private val songList = MutableSharedFlow<List<MediaItem>>(1)\n+        FolderListAdapter(persistentListOf(), mainActivity, this)\n     private val decorAdapter = BaseDecorAdapter<DetailedFolderAdapter>(this, R.plurals.folders_plural)\n     private val songAdapter: SongAdapter =\n-        SongAdapter(fragment, songList, folder = true).apply {\n+        SongAdapter(fragment, dataFlow.map { it.songList }, folder = true).apply {\n             onFullyDrawnListener = { reportFullyDrawn() }\n@@ -108,4 +142,2 @@ class DetailedFolderAdapter(\n     }\n-    private var root: FileNode? = null\n-    private var fileNodePath = ArrayList<String>()\n     private var recyclerView: MyRecyclerView? = null\n@@ -120,7 +152,28 @@ class DetailedFolderAdapter(\n         this.scope!!.launch {\n-            liveData.collect {\n-                if (root !== it)\n-                    withContext(Dispatchers.Main) {\n-                        onChanged(it)\n+            folderFlow.collect { newList ->\n+                val oldList = folderList\n+                val canDiff = oldList != null && this@DetailedFolderAdapter.recyclerView != null\n+                val diffResult = if (canDiff) DiffUtil.calculateDiff(\n+                    DiffCallback(oldList, newList)) else null\n+                withContext(Dispatchers.Main) {\n+                    folderList = newList.toImmutableList()\n+                    if (diffResult != null)\n+                        diffResult.dispatchUpdatesTo(folderAdapter)\n+                    else\n+                        @Suppress(\"NotifyDataSetChanged\")\n+                        folderAdapter.notifyDataSetChanged()\n+                    decorAdapter.updateSongCounter()\n+                    this@DetailedFolderAdapter.recyclerView?.doOnLayout {\n+                        this@DetailedFolderAdapter.recyclerView?.postOnAnimation {\n+                            folderAdapter.reportFullyDrawn()\n+                        }\n                     }\n+                }\n+            }\n+        }\n+        this.scope!!.launch {\n+            fileNodePath.collect {\n+                withContext(Dispatchers.Main) {\n+                    folderPopAdapter.enabled = !it.isEmpty()\n+                }\n             }\n@@ -135,21 +188,13 @@ class DetailedFolderAdapter(\n \n-    fun onChanged(value: FileNode) {\n-        root = value\n-        var value = value\n-        if (fileNodePath.isEmpty() && isDetailed) {\n-            while (value.folderList.size == 1) {\n-                fileNodePath.add(value.folderList.keys.first())\n-                value = value.folderList.values.first()\n-            }\n-        }\n-        update(null)\n-    }\n-\n     fun enter(path: String?) {\n+        val currentPath = fileNodePath.replayCache.firstOrNull() ?: return\n         if (path != null) {\n-            fileNodePath.add(path)\n-            update(false)\n-        } else if (fileNodePath.isNotEmpty()) {\n-            fileNodePath.removeAt(fileNodePath.lastIndex)\n-            update(true)\n+            update(false) {\n+                fileNodePath.emitOrDie(currentPath + path)\n+            }\n+        } else if (currentPath.isNotEmpty()) {\n+            update(true) {\n+                // Remove last\n+                fileNodePath.emitOrDie(currentPath.subList(0, currentPath.size - 1))\n+            }\n         }\n@@ -159,22 +204,28 @@ class DetailedFolderAdapter(\n         sortType.value = type\n-        update(null)\n     }\n \n-    private fun update(invertedDirection: Boolean?) {\n-        var item = root\n-        for (path in fileNodePath) {\n-            item = item?.folderList?.get(path)\n-        }\n-        if (item == null) {\n-            fileNodePath.clear()\n-            item = root\n-        }\n-        val doUpdate = { canDiff: Boolean ->\n-            folderPopAdapter.enabled = fileNodePath.isNotEmpty()\n-            folderAdapter.updateList(item?.folderList?.values ?: listOf(), canDiff, sortType.value)\n-            runBlocking { songList.emit(item?.songList ?: listOf()) }\n-        }\n+    private class DiffCallback(\n+        private val oldList: List<FileNode>,\n+        private val newList: List<FileNode>,\n+    ) : DiffUtil.Callback() {\n+        override fun getOldListSize() = oldList.size\n+\n+        override fun getNewListSize() = newList.size\n+\n+        override fun areItemsTheSame(\n+            oldItemPosition: Int,\n+            newItemPosition: Int,\n+        ) = oldList[oldItemPosition].folderName == newList[newItemPosition].folderName\n+\n+        override fun areContentsTheSame(\n+            oldItemPosition: Int,\n+            newItemPosition: Int,\n+        ) = oldList[oldItemPosition] == newList[newItemPosition]\n+\n+    }\n+\n+    private fun update(invertedDirection: Boolean, doUpdate: () -> Unit) {\n         recyclerView.let {\n-            if (it == null || invertedDirection == null) {\n-                doUpdate(it != null)\n+            if (it == null) {\n+                doUpdate()\n                 return@let\n@@ -209,3 +260,3 @@ class DetailedFolderAdapter(\n                     }\n-                    doUpdate(false)\n+                    doUpdate()\n                 }\n@@ -248,3 +299,3 @@ class DetailedFolderAdapter(\n     private class FolderListAdapter(\n-        private var folderList: List<FileNode>,\n+        private var folderList: ImmutableList<FileNode>,\n         private val activity: MainActivity,\n@@ -253,3 +304,2 @@ class DetailedFolderAdapter(\n \n-        @SuppressLint(\"SetTextI18n\")\n         override fun onBindViewHolder(holder: ViewHolder, position: Int) {\n@@ -276,51 +326,4 @@ class DetailedFolderAdapter(\n \n-        @SuppressLint(\"NotifyDataSetChanged\")\n-        fun updateList(newCollection: Collection<FileNode>, canDiff: Boolean, sortType: Sorter.Type) {\n-            val newList = newCollection.toMutableList()\n-            CoroutineScope(Dispatchers.Default).launch {\n-                val diffResult = if (canDiff) DiffUtil.calculateDiff(\n-                    DiffCallback(folderList, newList)) else null\n-                val newList2 = if (sortType == Sorter.Type.BySizeDescending)\n-                    newList.sortedByDescending { it.folderList.size + it.songList.size }\n-                else\n-                    newList.sortedWith(\n-                    SupportComparator.createAlphanumericComparator(cnv = {\n-                        it.folderName\n-                    }))\n-                withContext(Dispatchers.Main) {\n-                    folderList = newList2\n-                    if (diffResult != null)\n-                        diffResult.dispatchUpdatesTo(this@FolderListAdapter)\n-                    else\n-                        notifyDataSetChanged()\n-                    folderFragment.decorAdapter.updateSongCounter()\n-                    folderFragment.recyclerView?.doOnLayout {\n-                        folderFragment.recyclerView?.postOnAnimation { reportFullyDrawn() }\n-                    }\n-                }\n-            }\n-        }\n-\n-        private inner class DiffCallback(\n-            private val oldList: List<FileNode>,\n-            private val newList: List<FileNode>,\n-        ) : DiffUtil.Callback() {\n-            override fun getOldListSize() = oldList.size\n-\n-            override fun getNewListSize() = newList.size\n-\n-            override fun areItemsTheSame(\n-                oldItemPosition: Int,\n-                newItemPosition: Int,\n-            ) = oldList[oldItemPosition].folderName == newList[newItemPosition].folderName\n-\n-            override fun areContentsTheSame(\n-                oldItemPosition: Int,\n-                newItemPosition: Int,\n-            ) = oldList[oldItemPosition] == newList[newItemPosition]\n-\n-        }\n-\n         var onFullyDrawnListener: (() -> Unit)? = null\n-        private fun reportFullyDrawn() {\n+        fun reportFullyDrawn() {\n             onFullyDrawnListener?.invoke()\n","improvement-type":"Complex Method"}],"change-level":"warning","is-hotspot?":false,"line":341,"what-changed":"QueueBoard.setCurrQueue has a cyclomatic complexity of 15, threshold = 9","how-to-fix":"There are many reasons for Complex Method. Sometimes, another design approach is beneficial such as a) modeling state using an explicit state machine rather than conditionals, or b) using table lookup rather than long chains of logic. In other scenarios, the function can be split using [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html). Just make sure you extract natural and cohesive functions. Complex Methods can also be addressed by identifying complex conditional expressions and then using the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring.","change-type":"introduced"},{"method":"QueueBoard.addQueue","why-it-occurs":"A Complex Method has a high cyclomatic complexity. The recommended threshold for the Kotlin language is a cyclomatic complexity lower than 9.","name":"Complex Method","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":[{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"55","loc-deleted":"18","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.413528317237752"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2026-01-01T13:23:52Z","current-rev":"7b370dff","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt","previous-rev":"a28de050","commit-title":"Apply all changes to ReplayGain settings UI instantly","language":"Kotlin","id":"0b5f2af002c123e31559e28ae55352e7ced73cb3","model-score":0.29,"author-id":null,"project-id":64193,"delta-file-score":0.25683072,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt b/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\nindex 9322d8fc..edd9763a 100644\n--- a/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\n+++ b/app/src/main/java/org/akanework/gramophone/logic/utils/ReplayGainAudioProcessor.kt\n@@ -12,154 +12,192 @@ import java.nio.ByteBuffer\n class ReplayGainAudioProcessor : BaseAudioProcessor() {\n-\tcompanion object {\n-\t\tprivate const val TAG = \"ReplayGainAP\"\n-\t}\n-\tprivate var compressor: AdaptiveDynamicRangeCompression? = null\n-\tprivate var waitingForFlush = false\n-\tvar mode = ReplayGainUtil.Mode.None\n-\t\tprivate set\n-\tvar rgGain = 0 // dB\n-\t\tprivate set\n-\tvar nonRgGain = 0 // dB\n-\t\tprivate set\n-\tvar boostGain = 0 // dB\n-\t\tprivate set\n-\tvar offloadEnabled = false\n-\t\tprivate set\n-\tvar reduceGain = false\n-\t\tprivate set\n-\tvar boostGainChangedListener: (() -> Unit)? = null\n-\tvar offloadEnabledChangedListener: (() -> Unit)? = null\n-\tprivate var gain = 1f\n-\tprivate var kneeThresholdDb: Float? = null\n-\tprivate var tags: ReplayGainUtil.ReplayGainInfo? = null\n-\toverride fun queueInput(inputBuffer: ByteBuffer) {\n-\t\tval frameCount = inputBuffer.remaining() / inputAudioFormat.bytesPerFrame\n-\t\tval outputBuffer = replaceOutputBuffer(frameCount * outputAudioFormat.bytesPerFrame)\n-\t\tif (inputBuffer.hasRemaining()) {\n-\t\t\tif (compressor != null) {\n-\t\t\t\tcompressor!!.compress(\n-\t\t\t\t\tinputAudioFormat.channelCount,\n-\t\t\t\t\tgain,\n-\t\t\t\t\tkneeThresholdDb!!, 1f, inputBuffer,\n-\t\t\t\t\toutputBuffer, frameCount\n-\t\t\t\t)\n-\t\t\t\tinputBuffer.position(inputBuffer.limit())\n-\t\t\t\toutputBuffer.position(frameCount * outputAudioFormat.bytesPerFrame)\n-\t\t\t} else {\n-\t\t\t\tif (gain == 1f) {\n-\t\t\t\t\toutputBuffer.put(inputBuffer)\n-\t\t\t\t} else {\n-\t\t\t\t\twhile (inputBuffer.hasRemaining()) {\n-\t\t\t\t\t\toutputBuffer.putFloat(inputBuffer.getFloat() * gain)\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t}\n-\t\t}\n-\t\toutputBuffer.flip()\n-\t}\n+    companion object {\n+        private const val TAG = \"ReplayGainAP\"\n+    }\n \n-\toverride fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {\n-\t\tif (inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {\n-\t\t\tthrow UnhandledAudioFormatException(\n-\t\t\t\t\"Invalid PCM encoding. Expected float PCM.\", inputAudioFormat\n-\t\t\t)\n-\t\t}\n-\t\t// TODO(ASAP): if setMode and setNonRgGain required reconfiguration, we could be a lot lazier.\n-\t\tif (((tags?.trackGain == null && tags?.albumGain == null)\n-\t\t\t|| (tags?.trackGain != null && tags?.trackGain != 1f)\n-\t\t\t|| (tags?.albumGain != null && tags?.albumGain != 1f)) && !Flags.TEST_RG_OFFLOAD) {\n-\t\t\treturn inputAudioFormat\n-\t\t}\n-\t\t// if there's RG metadata but it says we don't need to do anything, we can skip all work.\n-\t\treturn AudioProcessor.AudioFormat.NOT_SET\n-\t}\n+    private var compressor: AdaptiveDynamicRangeCompression? = null\n+    private var waitingForFlush = false\n+    var mode = ReplayGainUtil.Mode.None\n+        private set\n+    var rgGain = 0 // dB\n+        private set\n+    var nonRgGain = 0 // dB\n+        private set\n+    var boostGain = 0 // dB\n+        private set\n+    var offloadEnabled = false\n+        private set\n+    var reduceGain = false\n+        private set\n+    var settingsChangedListener: (() -> Unit)? = null\n+    var boostGainChangedListener: (() -> Unit)? = null\n+    var offloadEnabledChangedListener: (() -> Unit)? = null\n+    private var gain = 1f\n+    private var kneeThresholdDb: Float? = null\n+    private var tags: ReplayGainUtil.ReplayGainInfo? = null\n+    override fun queueInput(inputBuffer: ByteBuffer) {\n+        val frameCount = inputBuffer.remaining() / inputAudioFormat.bytesPerFrame\n+        val outputBuffer = replaceOutputBuffer(frameCount * outputAudioFormat.bytesPerFrame)\n+        if (inputBuffer.hasRemaining()) {\n+            if (compressor != null) {\n+                compressor!!.compress(\n+                    inputAudioFormat.channelCount,\n+                    gain,\n+                    kneeThresholdDb!!, 1f, inputBuffer,\n+                    outputBuffer, frameCount\n+                )\n+                inputBuffer.position(inputBuffer.limit())\n+                outputBuffer.position(frameCount * outputAudioFormat.bytesPerFrame)\n+            } else {\n+                if (gain == 1f) {\n+                    outputBuffer.put(inputBuffer)\n+                } else {\n+                    while (inputBuffer.hasRemaining()) {\n+                        outputBuffer.putFloat(inputBuffer.getFloat() * gain)\n+                    }\n+                }\n+            }\n+        }\n+        outputBuffer.flip()\n+    }\n \n-\t@Synchronized\n-\tfun setMode(mode: ReplayGainUtil.Mode) {\n-\t\tthis.mode = mode\n-\t}\n+    override fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {\n+        if (inputAudioFormat.encoding != C.ENCODING_PCM_FLOAT) {\n+            throw UnhandledAudioFormatException(\n+                \"Invalid PCM encoding. Expected float PCM.\", inputAudioFormat\n+            )\n+        }\n+        if (Flags.TEST_RG_OFFLOAD) {\n+            return AudioProcessor.AudioFormat.NOT_SET\n+        }\n+        return inputAudioFormat\n+    }\n \n-\t@Synchronized\n-\tfun setRgGain(rgGain: Int) {\n-\t\tthis.rgGain = rgGain\n-\t}\n+    @Synchronized\n+    fun setMode(mode: ReplayGainUtil.Mode, doNotNotifyListener: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.mode == mode) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.mode = mode\n+        }\n+        if (!doNotNotifyListener) {\n+            listener?.invoke()\n+            computeGain()\n+        }\n+    }\n \n-\t@Synchronized\n-\tfun setNonRgGain(nonRgGain: Int) {\n-\t\tthis.nonRgGain = nonRgGain\n-\t}\n+    @Synchronized\n+    fun setRgGain(rgGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.rgGain == rgGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.rgGain = rgGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setBoostGain(boostGain: Int) {\n-\t\tval changed: Boolean\n-\t\tval listener: (() -> Unit)?\n-\t\tsynchronized(this) {\n-\t\t\tchanged = this.boostGain != boostGain\n-\t\t\tlistener = boostGainChangedListener\n-\t\t\tthis.boostGain = boostGain\n-\t\t}\n-\t\tif (changed) {\n-\t\t\tlistener?.invoke()\n-\t\t}\n-\t}\n+    @Synchronized\n+    fun setNonRgGain(nonRgGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.nonRgGain == nonRgGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.nonRgGain = nonRgGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\t@Synchronized\n-\tfun setReduceGain(reduceGain: Boolean) {\n-\t\tthis.reduceGain = reduceGain\n-\t}\n+    fun setBoostGain(boostGain: Int) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.boostGain == boostGain) {\n+                return\n+            }\n+            listener = boostGainChangedListener\n+            this.boostGain = boostGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setOffloadEnabled(offloadEnabled: Boolean) {\n-\t\tval changed: Boolean\n-\t\tval listener: (() -> Unit)?\n-\t\tsynchronized(this) {\n-\t\t\tchanged = this.offloadEnabled != offloadEnabled\n-\t\t\tlistener = offloadEnabledChangedListener\n-\t\t\tthis.offloadEnabled = offloadEnabled\n-\t\t}\n-\t\tif (changed) {\n-\t\t\tlistener?.invoke()\n-\t\t}\n-\t}\n+    @Synchronized\n+    fun setReduceGain(reduceGain: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.reduceGain == reduceGain) {\n+                return\n+            }\n+            listener = settingsChangedListener\n+            this.reduceGain = reduceGain\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tfun setRootFormat(inputFormat: Format) {\n-\t\ttags = ReplayGainUtil.parse(inputFormat)\n-\t}\n+    fun setOffloadEnabled(offloadEnabled: Boolean) {\n+        val listener: (() -> Unit)?\n+        synchronized(this) {\n+            if (this.offloadEnabled == offloadEnabled) {\n+                return\n+            }\n+            listener = offloadEnabledChangedListener\n+            this.offloadEnabled = offloadEnabled\n+        }\n+        listener?.invoke()\n+        computeGain()\n+    }\n \n-\tprivate fun computeGain() {\n-\t\tval mode: ReplayGainUtil.Mode\n-\t\tval rgGain: Int\n-\t\tval nonRgGain: Int\n-\t\tval reduceGain: Boolean\n-\t\tsynchronized(this) {\n-\t\t\tmode = this.mode\n-\t\t\trgGain = this.rgGain\n-\t\t\tnonRgGain = this.nonRgGain\n-\t\t\treduceGain = this.reduceGain\n-\t\t}\n-\t\tval gain = ReplayGainUtil.calculateGain(tags, mode, rgGain,\n-\t\t\treduceGain, ReplayGainUtil.RATIO)\n-\t\tthis.gain = gain?.first ?: ReplayGainUtil.dbToAmpl(nonRgGain.toFloat())\n-\t\tthis.kneeThresholdDb = gain?.second\n-\t\tif (kneeThresholdDb != null) {\n-\t\t\tif (compressor == null)\n-\t\t\t\tcompressor = AdaptiveDynamicRangeCompression()\n-\t\t\tLog.w(TAG, \"using dynamic range compression\")\n-\t\t\tcompressor!!.init(\n-\t\t\t\tinputAudioFormat.sampleRate,\n-\t\t\t\tReplayGainUtil.TAU_ATTACK, ReplayGainUtil.TAU_RELEASE,\n-\t\t\t\tReplayGainUtil.RATIO\n-\t\t\t)\n-\t\t} else {\n-\t\t\tonReset() // delete compressor\n-\t\t}\n-\t}\n+    fun setRootFormat(inputFormat: Format) {\n+        tags = ReplayGainUtil.parse(inputFormat)\n+    }\n \n-\toverride fun onFlush(streamMetadata: AudioProcessor.StreamMetadata) {\n-\t\twaitingForFlush = false\n-\t\tcomputeGain()\n-\t}\n+    private fun computeGain() {\n+        val mode: ReplayGainUtil.Mode\n+        val rgGain: Int\n+        val nonRgGain: Int\n+        val reduceGain: Boolean\n+        synchronized(this) {\n+            mode = this.mode\n+            rgGain = this.rgGain\n+            nonRgGain = this.nonRgGain\n+            reduceGain = this.reduceGain\n+        }\n+        val gain = ReplayGainUtil.calculateGain(\n+            tags, mode, rgGain,\n+            reduceGain, ReplayGainUtil.RATIO\n+        )\n+        this.gain = gain?.first ?: ReplayGainUtil.dbToAmpl(nonRgGain.toFloat())\n+        this.kneeThresholdDb = gain?.second\n+        if (kneeThresholdDb != null) {\n+            if (compressor == null)\n+                compressor = AdaptiveDynamicRangeCompression()\n+            Log.w(TAG, \"using dynamic range compression\")\n+            compressor!!.init(\n+                inputAudioFormat.sampleRate,\n+                ReplayGainUtil.TAU_ATTACK, ReplayGainUtil.TAU_RELEASE,\n+                ReplayGainUtil.RATIO\n+            )\n+        } else {\n+            onReset() // delete compressor\n+        }\n+    }\n \n-\toverride fun onReset() {\n-\t\tcompressor?.release()\n-\t\tcompressor = null\n-\t}\n+    override fun onFlush(streamMetadata: AudioProcessor.StreamMetadata) {\n+        waitingForFlush = false\n+        computeGain()\n+    }\n+\n+    override fun onReset() {\n+        compressor?.release()\n+        compressor = null\n+    }\n }\n\\ No newline at end of file\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"98","loc-deleted":"95","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.17","delta-n-functions":"0","current-file-score":"9.6882083290695"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2025-12-28T14:59:12Z","current-rev":"94ecf81c","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt","previous-rev":"e902c1a0","commit-title":"Fixed crash due to multi-threading in DetailedFolderAdapter by using flow","language":"Kotlin","id":"e405b227f4992e1b04b98c38c75adc72f4bb6c38","model-score":0.15,"author-id":null,"project-id":64193,"delta-file-score":0.35111132,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt b/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\nindex 122c10d2..52781726 100644\n--- a/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\n+++ b/app/src/main/java/org/akanework/gramophone/ui/adapters/DetailedFolderAdapter.kt\n@@ -19,3 +19,2 @@ package org.akanework.gramophone.ui.adapters\n \n-import android.annotation.SuppressLint\n import android.view.View\n@@ -27,3 +26,2 @@ import androidx.core.view.doOnLayout\n import androidx.fragment.app.Fragment\n-import androidx.media3.common.MediaItem\n import androidx.preference.PreferenceManager\n@@ -33,2 +31,5 @@ import androidx.recyclerview.widget.DiffUtil\n import androidx.recyclerview.widget.RecyclerView\n+import kotlinx.collections.immutable.ImmutableList\n+import kotlinx.collections.immutable.persistentListOf\n+import kotlinx.collections.immutable.toImmutableList\n import kotlinx.coroutines.CoroutineScope\n@@ -36,6 +37,9 @@ import kotlinx.coroutines.Dispatchers\n import kotlinx.coroutines.cancel\n+import kotlinx.coroutines.channels.BufferOverflow\n import kotlinx.coroutines.flow.MutableSharedFlow\n import kotlinx.coroutines.flow.MutableStateFlow\n+import kotlinx.coroutines.flow.combine\n+import kotlinx.coroutines.flow.combineTransform\n+import kotlinx.coroutines.flow.map\n import kotlinx.coroutines.launch\n-import kotlinx.coroutines.runBlocking\n import kotlinx.coroutines.withContext\n@@ -44,2 +48,3 @@ import org.akanework.gramophone.R\n import org.akanework.gramophone.logic.comparators.SupportComparator\n+import org.akanework.gramophone.logic.emitOrDie\n import org.akanework.gramophone.logic.getStringStrict\n@@ -86,4 +91,34 @@ class DetailedFolderAdapter(\n         Sorter.Type.ByFilePathAscending)\n+    private var fileNodePath = MutableSharedFlow<List<String>>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)\n     private val liveData = if (isDetailed) mainActivity.reader.folderStructureFlow\n         else mainActivity.reader.shallowFolderFlow\n+    private val dataFlow = liveData.combineTransform(fileNodePath) { root, path ->\n+        var item: FileNode? = root\n+        for (path in path) {\n+            item = item?.folderList?.get(path)\n+        }\n+        if (item == null || path.isEmpty()) {\n+            var newPath = mutableListOf<String>()\n+            if (isDetailed) {\n+                while (item?.folderList?.size == 1) {\n+                    newPath.add(item.folderList.keys.first())\n+                    item = item.folderList.values.first()\n+                }\n+            }\n+            // This may race with user click if a folder was deleted while a user clicks.\n+            fileNodePath.emitOrDie(newPath)\n+            return@combineTransform // we will run again with new path soon\n+        }\n+        emit(item)\n+    }\n+    private val folderFlow = dataFlow.combine(sortType) { item, sortType ->\n+        if (sortType == Sorter.Type.BySizeDescending)\n+            item.folderList.values.sortedByDescending { it.folderList.size + it.songList.size }\n+        else\n+            item.folderList.values.sortedWith(\n+                SupportComparator.createAlphanumericComparator(cnv = {\n+                    it.folderName\n+                }))\n+    }\n+    private var folderList: List<FileNode>? = null\n     private var scope: CoroutineScope? = null\n@@ -91,7 +126,6 @@ class DetailedFolderAdapter(\n     private val folderAdapter: FolderListAdapter =\n-        FolderListAdapter(listOf(), mainActivity, this)\n-    private val songList = MutableSharedFlow<List<MediaItem>>(1)\n+        FolderListAdapter(persistentListOf(), mainActivity, this)\n     private val decorAdapter = BaseDecorAdapter<DetailedFolderAdapter>(this, R.plurals.folders_plural)\n     private val songAdapter: SongAdapter =\n-        SongAdapter(fragment, songList, folder = true).apply {\n+        SongAdapter(fragment, dataFlow.map { it.songList }, folder = true).apply {\n             onFullyDrawnListener = { reportFullyDrawn() }\n@@ -108,4 +142,2 @@ class DetailedFolderAdapter(\n     }\n-    private var root: FileNode? = null\n-    private var fileNodePath = ArrayList<String>()\n     private var recyclerView: MyRecyclerView? = null\n@@ -120,7 +152,28 @@ class DetailedFolderAdapter(\n         this.scope!!.launch {\n-            liveData.collect {\n-                if (root !== it)\n-                    withContext(Dispatchers.Main) {\n-                        onChanged(it)\n+            folderFlow.collect { newList ->\n+                val oldList = folderList\n+                val canDiff = oldList != null && this@DetailedFolderAdapter.recyclerView != null\n+                val diffResult = if (canDiff) DiffUtil.calculateDiff(\n+                    DiffCallback(oldList, newList)) else null\n+                withContext(Dispatchers.Main) {\n+                    folderList = newList.toImmutableList()\n+                    if (diffResult != null)\n+                        diffResult.dispatchUpdatesTo(folderAdapter)\n+                    else\n+                        @Suppress(\"NotifyDataSetChanged\")\n+                        folderAdapter.notifyDataSetChanged()\n+                    decorAdapter.updateSongCounter()\n+                    this@DetailedFolderAdapter.recyclerView?.doOnLayout {\n+                        this@DetailedFolderAdapter.recyclerView?.postOnAnimation {\n+                            folderAdapter.reportFullyDrawn()\n+                        }\n                     }\n+                }\n+            }\n+        }\n+        this.scope!!.launch {\n+            fileNodePath.collect {\n+                withContext(Dispatchers.Main) {\n+                    folderPopAdapter.enabled = !it.isEmpty()\n+                }\n             }\n@@ -135,21 +188,13 @@ class DetailedFolderAdapter(\n \n-    fun onChanged(value: FileNode) {\n-        root = value\n-        var value = value\n-        if (fileNodePath.isEmpty() && isDetailed) {\n-            while (value.folderList.size == 1) {\n-                fileNodePath.add(value.folderList.keys.first())\n-                value = value.folderList.values.first()\n-            }\n-        }\n-        update(null)\n-    }\n-\n     fun enter(path: String?) {\n+        val currentPath = fileNodePath.replayCache.firstOrNull() ?: return\n         if (path != null) {\n-            fileNodePath.add(path)\n-            update(false)\n-        } else if (fileNodePath.isNotEmpty()) {\n-            fileNodePath.removeAt(fileNodePath.lastIndex)\n-            update(true)\n+            update(false) {\n+                fileNodePath.emitOrDie(currentPath + path)\n+            }\n+        } else if (currentPath.isNotEmpty()) {\n+            update(true) {\n+                // Remove last\n+                fileNodePath.emitOrDie(currentPath.subList(0, currentPath.size - 1))\n+            }\n         }\n@@ -159,22 +204,28 @@ class DetailedFolderAdapter(\n         sortType.value = type\n-        update(null)\n     }\n \n-    private fun update(invertedDirection: Boolean?) {\n-        var item = root\n-        for (path in fileNodePath) {\n-            item = item?.folderList?.get(path)\n-        }\n-        if (item == null) {\n-            fileNodePath.clear()\n-            item = root\n-        }\n-        val doUpdate = { canDiff: Boolean ->\n-            folderPopAdapter.enabled = fileNodePath.isNotEmpty()\n-            folderAdapter.updateList(item?.folderList?.values ?: listOf(), canDiff, sortType.value)\n-            runBlocking { songList.emit(item?.songList ?: listOf()) }\n-        }\n+    private class DiffCallback(\n+        private val oldList: List<FileNode>,\n+        private val newList: List<FileNode>,\n+    ) : DiffUtil.Callback() {\n+        override fun getOldListSize() = oldList.size\n+\n+        override fun getNewListSize() = newList.size\n+\n+        override fun areItemsTheSame(\n+            oldItemPosition: Int,\n+            newItemPosition: Int,\n+        ) = oldList[oldItemPosition].folderName == newList[newItemPosition].folderName\n+\n+        override fun areContentsTheSame(\n+            oldItemPosition: Int,\n+            newItemPosition: Int,\n+        ) = oldList[oldItemPosition] == newList[newItemPosition]\n+\n+    }\n+\n+    private fun update(invertedDirection: Boolean, doUpdate: () -> Unit) {\n         recyclerView.let {\n-            if (it == null || invertedDirection == null) {\n-                doUpdate(it != null)\n+            if (it == null) {\n+                doUpdate()\n                 return@let\n@@ -209,3 +260,3 @@ class DetailedFolderAdapter(\n                     }\n-                    doUpdate(false)\n+                    doUpdate()\n                 }\n@@ -248,3 +299,3 @@ class DetailedFolderAdapter(\n     private class FolderListAdapter(\n-        private var folderList: List<FileNode>,\n+        private var folderList: ImmutableList<FileNode>,\n         private val activity: MainActivity,\n@@ -253,3 +304,2 @@ class DetailedFolderAdapter(\n \n-        @SuppressLint(\"SetTextI18n\")\n         override fun onBindViewHolder(holder: ViewHolder, position: Int) {\n@@ -276,51 +326,4 @@ class DetailedFolderAdapter(\n \n-        @SuppressLint(\"NotifyDataSetChanged\")\n-        fun updateList(newCollection: Collection<FileNode>, canDiff: Boolean, sortType: Sorter.Type) {\n-            val newList = newCollection.toMutableList()\n-            CoroutineScope(Dispatchers.Default).launch {\n-                val diffResult = if (canDiff) DiffUtil.calculateDiff(\n-                    DiffCallback(folderList, newList)) else null\n-                val newList2 = if (sortType == Sorter.Type.BySizeDescending)\n-                    newList.sortedByDescending { it.folderList.size + it.songList.size }\n-                else\n-                    newList.sortedWith(\n-                    SupportComparator.createAlphanumericComparator(cnv = {\n-                        it.folderName\n-                    }))\n-                withContext(Dispatchers.Main) {\n-                    folderList = newList2\n-                    if (diffResult != null)\n-                        diffResult.dispatchUpdatesTo(this@FolderListAdapter)\n-                    else\n-                        notifyDataSetChanged()\n-                    folderFragment.decorAdapter.updateSongCounter()\n-                    folderFragment.recyclerView?.doOnLayout {\n-                        folderFragment.recyclerView?.postOnAnimation { reportFullyDrawn() }\n-                    }\n-                }\n-            }\n-        }\n-\n-        private inner class DiffCallback(\n-            private val oldList: List<FileNode>,\n-            private val newList: List<FileNode>,\n-        ) : DiffUtil.Callback() {\n-            override fun getOldListSize() = oldList.size\n-\n-            override fun getNewListSize() = newList.size\n-\n-            override fun areItemsTheSame(\n-                oldItemPosition: Int,\n-                newItemPosition: Int,\n-            ) = oldList[oldItemPosition].folderName == newList[newItemPosition].folderName\n-\n-            override fun areContentsTheSame(\n-                oldItemPosition: Int,\n-                newItemPosition: Int,\n-            ) = oldList[oldItemPosition] == newList[newItemPosition]\n-\n-        }\n-\n         var onFullyDrawnListener: (() -> Unit)? = null\n-        private fun reportFullyDrawn() {\n+        fun reportFullyDrawn() {\n             onFullyDrawnListener?.invoke()\n","improvement-type":"Complex Method"}],"change-level":"warning","is-hotspot?":false,"line":139,"what-changed":"QueueBoard.addQueue has a cyclomatic complexity of 14, threshold = 9","how-to-fix":"There are many reasons for Complex Method. Sometimes, another design approach is beneficial such as a) modeling state using an explicit state machine rather than conditionals, or b) using table lookup rather than long chains of logic. In other scenarios, the function can be split using [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html). Just make sure you extract natural and cohesive functions. Complex Methods can also be addressed by identifying complex conditional expressions and then using the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring.","change-type":"introduced"},{"method":"QueueBoard.addQueue","why-it-occurs":"A Bumpy Road is a function that contains multiple chunks of nested conditional logic inside the same function. The deeper the nesting and the more bumps, the lower the code health.\n\nA bumpy code road represents a lack of encapsulation which becomes an obstacle to comprehension. In imperative languages there’s also an increased risk for feature entanglement, which leads to complex state management. CodeScene considers the following rules for the code health impact: 1) The deeper the nested conditional logic of each bump, the higher the tax on our working memory. 2) The more bumps inside a function, the more expensive it is to refactor as each bump represents a missing abstraction. 3) The larger each bump – that is, the more lines of code it spans – the harder it is to build up a mental model of the function. The nesting depth for what is considered a bump is  levels of conditionals.","name":"Bumpy Road Ahead","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":139,"what-changed":"QueueBoard.addQueue has 3 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function","how-to-fix":"Bumpy Road implementations indicate a lack of encapsulation. Check out the detailed description of the [Bumpy Road code health issue](https://codescene.com/blog/bumpy-road-code-complexity-in-context/).\n\nA Bumpy Road often suggests that the function/method does too many things. The first refactoring step is to identify the different possible responsibilities of the function. Consider extracting those responsibilities into smaller, cohesive, and well-named functions. The [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring is the primary response.","change-type":"introduced"},{"method":"QueueBoard.renameQueue","why-it-occurs":"A Bumpy Road is a function that contains multiple chunks of nested conditional logic inside the same function. The deeper the nesting and the more bumps, the lower the code health.\n\nA bumpy code road represents a lack of encapsulation which becomes an obstacle to comprehension. In imperative languages there’s also an increased risk for feature entanglement, which leads to complex state management. CodeScene considers the following rules for the code health impact: 1) The deeper the nested conditional logic of each bump, the higher the tax on our working memory. 2) The more bumps inside a function, the more expensive it is to refactor as each bump represents a missing abstraction. 3) The larger each bump – that is, the more lines of code it spans – the harder it is to build up a mental model of the function. The nesting depth for what is considered a bump is  levels of conditionals.","name":"Bumpy Road Ahead","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":308,"what-changed":"QueueBoard.renameQueue has 3 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function","how-to-fix":"Bumpy Road implementations indicate a lack of encapsulation. Check out the detailed description of the [Bumpy Road code health issue](https://codescene.com/blog/bumpy-road-code-complexity-in-context/).\n\nA Bumpy Road often suggests that the function/method does too many things. The first refactoring step is to identify the different possible responsibilities of the function. Consider extracting those responsibilities into smaller, cohesive, and well-named functions. The [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring is the primary response.","change-type":"introduced"},{"method":"QueueBoard.setCurrQueue","why-it-occurs":"A Bumpy Road is a function that contains multiple chunks of nested conditional logic inside the same function. The deeper the nesting and the more bumps, the lower the code health.\n\nA bumpy code road represents a lack of encapsulation which becomes an obstacle to comprehension. In imperative languages there’s also an increased risk for feature entanglement, which leads to complex state management. CodeScene considers the following rules for the code health impact: 1) The deeper the nested conditional logic of each bump, the higher the tax on our working memory. 2) The more bumps inside a function, the more expensive it is to refactor as each bump represents a missing abstraction. 3) The larger each bump – that is, the more lines of code it spans – the harder it is to build up a mental model of the function. The nesting depth for what is considered a bump is  levels of conditionals.","name":"Bumpy Road Ahead","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":341,"what-changed":"QueueBoard.setCurrQueue has 2 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function","how-to-fix":"Bumpy Road implementations indicate a lack of encapsulation. Check out the detailed description of the [Bumpy Road code health issue](https://codescene.com/blog/bumpy-road-code-complexity-in-context/).\n\nA Bumpy Road often suggests that the function/method does too many things. The first refactoring step is to identify the different possible responsibilities of the function. Consider extracting those responsibilities into smaller, cohesive, and well-named functions. The [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring is the primary response.","change-type":"introduced"},{"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 72 % of all functions have primitive types as arguments.","name":"Primitive Obsession","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":[{"diff":"diff --git a/primitive-obsession.ts b/primitive-obsession.ts\nindex 38bae186cc..24116eddcc 100644\n--- a/primitive-obsession.ts\n+++ b/primitive-obsession.ts\n@@ -1,8 +1,8 @@\n-// Problem: It's hard to know what this function does, and what values are valid as parameters.\n-function getPopularRepositories(String baseURL, String query, Integer pages, Integer pageSize, String sortorder): Json {\n-\tlet pages == null ? 10 : pages\n-\tlet pageSize == null ? 10 : pageSize\n-  return httpClient.get(`${baseURL}?q=${query}&pages=${pages}&pageSize=${pageSize}&sortorder=${sortorder}`)\n+// Refactoring: extract the pagination & API logic into a class, and it will\n+// attract validation and other logic related to the specific query. It's now\n+// easier to use and to maintain the getPopularRepositories function!\n+function getPopularRepositories(query: PaginatedRepoQuery): Json {\n+  return httpClient.get(query.getURL())\n     .map(json => json.repositories)\n     .filter(repository => repositry.stargazersCount > 1000)\n }\n","language":"kotlin","improvement-type":"Primitive Obsession"}],"change-level":"warning","is-hotspot?":false,"what-changed":"In this module, 72.4% of all function arguments are primitive types, threshold = 30.0%","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","change-type":"introduced"},{"method":"QueueBoard.addQueue","why-it-occurs":"Functions with many arguments indicate either a) low cohesion where the function has too many responsibilities, or b) a missing abstraction that encapsulates those arguments.\n\nThe threshold for the Kotlin language is 4 function arguments.","name":"Excess Number of Function Arguments","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":[{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"3","loc-deleted":"21","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"9.1914109204282"},"author-email":"nift4@protonmail.com","commit-full-message":"nobody ever used it, and nobody ever will use it.","commit-date":"2026-01-03T22:46:51Z","current-rev":"fc1ce7df","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt","previous-rev":"789a8a8b","commit-title":"Remove Walaoke extension support","language":"Kotlin","id":"ee69b3c88fdb6663c468412eddd279a0b76b7ccf","model-score":0.45,"author-id":null,"project-id":64193,"delta-file-score":0.5577275,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt b/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt\nindex b4f21f50..afeb8d1b 100644\n--- a/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt\n+++ b/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt\n@@ -25,8 +25,2 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n     private var highlightTextColor = 0\n-    private var defaultTextColorM = 0\n-    private var highlightTextColorM = 0\n-    private var defaultTextColorF = 0\n-    private var highlightTextColorF = 0\n-    private var defaultTextColorD = 0\n-    private var highlightTextColorD = 0\n     private var lyrics: SemanticLyrics? = null\n@@ -70,5 +64,3 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n             newView!!.updateTextColor(\n-                defaultTextColor, highlightTextColor, defaultTextColorM,\n-                highlightTextColorM, defaultTextColorF, highlightTextColorF, defaultTextColorD,\n-                highlightTextColorD\n+                defaultTextColor, highlightTextColor\n             )\n@@ -126,5 +118,3 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n     fun updateTextColor(\n-        newColor: Int, newHighlightColor: Int, newColorM: Int,\n-        newHighlightColorM: Int, newColorF: Int, newHighlightColorF: Int,\n-        newColorD: Int, newHighlightColorD: Int\n+        newColor: Int, newHighlightColor: Int\n     ) {\n@@ -132,13 +122,5 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n         highlightTextColor = newHighlightColor\n-        defaultTextColorM = newColorM\n-        highlightTextColorM = newHighlightColorM\n-        defaultTextColorF = newColorF\n-        highlightTextColorF = newHighlightColorF\n-        defaultTextColorD = newColorD\n-        highlightTextColorD = newHighlightColorD\n         adapter?.updateTextColor(defaultTextColor, highlightTextColor)\n         newView?.updateTextColor(\n-            defaultTextColor, highlightTextColor, defaultTextColorM,\n-            highlightTextColorM, defaultTextColorF, highlightTextColorF, defaultTextColorD,\n-            highlightTextColorD\n+            defaultTextColor, highlightTextColor\n         )\n","improvement-type":"Excess Number of Function Arguments"},{"architectural-component-id":null,"author-name":"Light summer","training-data":{"loc-added":"79","loc-deleted":"84","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"93428659+lightsummer233@users.noreply.github.com","commit-full-message":"","commit-date":"2025-09-20T14:47:22Z","current-rev":"296bf3c","filename":"libPhonograph/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt","previous-rev":"a38b6fe","commit-title":"libPhonograph: Changes from Gramophone","language":"Kotlin","id":"db7b374615169a97822a31080fb78af0fd8d9410","model-score":0.22,"author-id":null,"project-id":64193,"delta-file-score":0.61278176,"diff":"diff --git a/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt b/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt\nindex 97fc6f4..2a44247 100644\n--- a/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt\n+++ b/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt\n@@ -10,2 +10,3 @@ import android.os.Build\n import android.os.Handler\n+import android.os.ext.SdkExtensions\n import androidx.annotation.ChecksSdkIntAtLeast\n@@ -13,5 +14,6 @@ import androidx.annotation.RequiresApi\n import androidx.core.content.ContextCompat\n+import androidx.core.net.toFile\n+import androidx.media3.common.MediaItem\n import kotlinx.coroutines.CoroutineScope\n import kotlinx.coroutines.ExperimentalCoroutinesApi\n-import kotlinx.coroutines.channels.BufferOverflow\n import kotlinx.coroutines.channels.ProducerScope\n@@ -19,13 +21,3 @@ import kotlinx.coroutines.channels.awaitClose\n import kotlinx.coroutines.flow.Flow\n-import kotlinx.coroutines.flow.MutableSharedFlow\n-import kotlinx.coroutines.flow.SharedFlow\n-import kotlinx.coroutines.flow.SharingCommand\n-import kotlinx.coroutines.flow.SharingStarted\n-import kotlinx.coroutines.flow.StateFlow\n import kotlinx.coroutines.flow.callbackFlow\n-import kotlinx.coroutines.flow.collect\n-import kotlinx.coroutines.flow.distinctUntilChanged\n-import kotlinx.coroutines.flow.emptyFlow\n-import kotlinx.coroutines.flow.flatMapLatest\n-import kotlinx.coroutines.flow.map\n import kotlinx.coroutines.launch\n@@ -33,2 +25,4 @@ import java.io.File\n import java.util.concurrent.atomic.AtomicLong\n+import kotlin.contracts.ExperimentalContracts\n+import kotlin.contracts.contract\n import kotlin.experimental.ExperimentalTypeInference\n@@ -61,3 +55,3 @@ abstract class ContentObserverCompat(handler: Handler?) : ContentObserver(handle\n \n-    abstract override fun onChange(selfChange: Boolean, uris: Collection<Uri?>, flags: Int)\n+    abstract override fun onChange(selfChange: Boolean, uris: Collection<Uri>, flags: Int)\n     abstract override fun deliverSelfNotifications(): Boolean\n@@ -70,3 +64,3 @@ internal fun versioningCallbackFlow(\n     val versionTracker = AtomicLong()\n-    return callbackFlow<Long> { block(versionTracker::incrementAndGet) }\n+    return callbackFlow { block(versionTracker::incrementAndGet) }\n }\n@@ -80,5 +74,5 @@ internal fun contentObserverVersioningFlow(\n         val listener = object : ContentObserverCompat(null) {\n-            override fun onChange(selfChange: Boolean, uris: Collection<Uri?>, flags: Int) {\n+            override fun onChange(selfChange: Boolean, uris: Collection<Uri>, flags: Int) {\n                 // TODO can we use those uris and flags for incremental reload at least on newer\n-                //  platform versions?\n+                //  platform versions? completely since R+, Q has no flags, before we get meh deletion handling\n                 scope.launch {\n@@ -92,4 +86,5 @@ internal fun contentObserverVersioningFlow(\n         }\n-        // TODO is content observer reliable if process gets cached? or are we forced to re-register\n-        //  and reload everything when regaining active state since Android 13?\n+        // Notifications may get delayed while we are frozen, but they do not get lost. Though, if\n+        // too many of them pile up, we will get killed for eating too much space with our async\n+        // binder transactions and we will have to restart in a new process later.\n         context.contentResolver.registerContentObserver(uri, notifyForDescendants, listener)\n@@ -102,35 +97,5 @@ internal fun contentObserverVersioningFlow(\n \n-internal fun <T> MutableSharedFlow<T>.collectOtherFlowWhenBeingCollected(\n-    scope: CoroutineScope, flow: Flow<*>\n-): MutableSharedFlow<T> {\n-    scope.launch {\n-        subscriptionCount\n-            .map { count -> count > 0 }\n-            .distinctUntilChanged()\n-            .collect { hasCollectors ->\n-                if (hasCollectors) {\n-                    flow.collect()\n-                }\n-            }\n-    }\n-    return this\n-}\n-\n-// https://bladecoder.medium.com/smarter-shared-kotlin-flows-d6b75fc66754\n-internal inline fun <T> sharedFlow(\n-    scope: CoroutineScope,\n-    replay: Int = 0,\n-    extraBufferCapacity: Int = 0,\n-    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,\n-    producer: (subscriptionCount: StateFlow<Int>) -> Flow<T>\n-): SharedFlow<T> {\n-    val shared = MutableSharedFlow<T>(replay, extraBufferCapacity, onBufferOverflow)\n-    val f = producer(shared.subscriptionCount)\n-    scope.launch { f.collect(shared) }\n-    return shared\n-}\n-\n fun File.toUriCompat(): Uri {\n     val tmp = Uri.fromFile(this)\n-    return if (tmp.scheme != \"file\") // This ONLY happens on Samsung and Ximi devices...\n+    return if (tmp.scheme != \"file\") // weird os bug workaround, found on Samsung and Xiaomi\n         tmp.buildUpon().scheme(\"file\").build()\n@@ -139,39 +104,12 @@ fun File.toUriCompat(): Uri {\n \n-// https://bladecoder.medium.com/smarter-shared-kotlin-flows-d6b75fc66754\n-@OptIn(ExperimentalCoroutinesApi::class)\n-internal fun <T> Flow<T>.flowWhileShared(\n-    subscriptionCount: StateFlow<Int>,\n-    started: SharingStarted\n-): Flow<T> {\n-    return started.command(subscriptionCount)\n-        .distinctUntilChanged()\n-        .flatMapLatest {\n-            when (it) {\n-                SharingCommand.START -> this\n-                SharingCommand.STOP,\n-                SharingCommand.STOP_AND_RESET_REPLAY_CACHE -> emptyFlow()\n-            }\n-        }\n+fun MediaItem.getUri(): Uri? {\n+    return localConfiguration?.uri\n }\n \n-@Suppress(\"NOTHING_TO_INLINE\")\n-internal inline fun Cursor.getColumnIndexOrNull(columnName: String): Int? =\n-    getColumnIndex(columnName).let { if (it == -1) null else it }\n-\n-@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)\n-@Suppress(\"NOTHING_TO_INLINE\")\n-internal inline fun hasImprovedMediaStore(): Boolean =\n-    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R\n-\n-@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)\n-@Suppress(\"NOTHING_TO_INLINE\")\n-internal inline fun hasScopedStorageV2(): Boolean =\n-    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R\n+fun MediaItem.getFile(): File? {\n+    return getUri()?.toFile()\n+}\n \n-@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU)\n @Suppress(\"NOTHING_TO_INLINE\")\n-internal inline fun hasScopedStorageWithMediaTypes(): Boolean =\n-    Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU\n-\n-internal fun Context.hasAudioPermission() =\n+inline fun Context.hasAudioPermission() =\n     hasScopedStorageWithMediaTypes() && ContextCompat.checkSelfPermission(\n@@ -190,5 +128,25 @@ internal fun Context.hasAudioPermission() =\n @RequiresApi(Build.VERSION_CODES.TIRAMISU)\n-internal fun Context.hasImagePermission() =\n-    checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) ==\n-            PackageManager.PERMISSION_GRANTED\n+fun Context.hasImagePermission() =\n+    checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED\n+\n+@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)\n+@Suppress(\"NOTHING_TO_INLINE\")\n+inline fun hasImprovedMediaStore(): Boolean =\n+    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R\n+\n+@Suppress(\"NOTHING_TO_INLINE\")\n+inline fun hasMarkIsFavouriteStatus(): Boolean =\n+    Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA ||\n+            (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&\n+                    SdkExtensions.getExtensionVersion(Build.VERSION_CODES.R) >= 16)\n+\n+@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)\n+@Suppress(\"NOTHING_TO_INLINE\")\n+inline fun hasScopedStorageV2(): Boolean =\n+    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R\n+\n+@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU)\n+@Suppress(\"NOTHING_TO_INLINE\")\n+inline fun hasScopedStorageWithMediaTypes(): Boolean =\n+    Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU\n \n@@ -216,2 +174,39 @@ internal inline fun Cursor.getIntOrNullIfThrow(index: Int): Int? =\n         null\n-    }\n\\ No newline at end of file\n+    }\n+\n+@Suppress(\"NOTHING_TO_INLINE\")\n+internal inline fun Cursor.getColumnIndexOrNull(columnName: String): Int? =\n+    getColumnIndex(columnName).let { if (it == -1) null else it }\n+\n+// From https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-util/src/commonMain/kotlin/androidx/compose/ui/util/\n+\n+/**\n+ * Iterates through a [List] using the index and calls [action] for each item. This does not\n+ * allocate an iterator like [Iterable.forEach].\n+ *\n+ * **Do not use for collections that come from public APIs**, since they may not support random\n+ * access in an efficient way, and this method may actually be a lot slower. Only use for\n+ * collections that are created by code we control and are known to support random access.\n+ */\n+@Suppress(\"BanInlineOptIn\")\n+@OptIn(ExperimentalContracts::class)\n+inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {\n+    contract { callsInPlace(action) }\n+    for (index in indices) {\n+        val item = get(index)\n+        action(item)\n+    }\n+}\n+\n+/**\n+ * Returns a list containing all elements that are not null\n+ *\n+ * **Do not use for collections that come from public APIs**, since they may not support random\n+ * access in an efficient way, and this method may actually be a lot slower. Only use for\n+ * collections that are created by code we control and are known to support random access.\n+ */\n+fun <T : Any> List<T?>.fastFilterNotNull(): List<T> {\n+    val target = ArrayList<T>(size)\n+    fastForEach { if ((it) != null) target += (it) }\n+    return target\n+}\n","improvement-type":"Excess Number of Function Arguments"}],"change-level":"warning","is-hotspot?":false,"line":139,"what-changed":"QueueBoard.addQueue has 6 arguments, max arguments = 4","how-to-fix":"Start by investigating the responsibilities of the function. Make sure it doesn't do too many things, in which case it should be split into smaller and more cohesive functions. Consider the refactoring [INTRODUCE PARAMETER OBJECT](https://refactoring.com/catalog/introduceParameterObject.html) to encapsulate arguments that refer to the same logical concept.","change-type":"introduced"},{"method":"PlaylistQueueSheet.init","why-it-occurs":"A Bumpy Road is a function that contains multiple chunks of nested conditional logic inside the same function. The deeper the nesting and the more bumps, the lower the code health.\n\nA bumpy code road represents a lack of encapsulation which becomes an obstacle to comprehension. In imperative languages there’s also an increased risk for feature entanglement, which leads to complex state management. CodeScene considers the following rules for the code health impact: 1) The deeper the nested conditional logic of each bump, the higher the tax on our working memory. 2) The more bumps inside a function, the more expensive it is to refactor as each bump represents a missing abstraction. 3) The larger each bump – that is, the more lines of code it spans – the harder it is to build up a mental model of the function. The nesting depth for what is considered a bump is  levels of conditionals.","name":"Bumpy Road Ahead","file":"app/src/main/java/org/akanework/gramophone/ui/components/PlaylistQueueSheet.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":73,"what-changed":"PlaylistQueueSheet.init has 2 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function","how-to-fix":"Bumpy Road implementations indicate a lack of encapsulation. Check out the detailed description of the [Bumpy Road code health issue](https://codescene.com/blog/bumpy-road-code-complexity-in-context/).\n\nA Bumpy Road often suggests that the function/method does too many things. The first refactoring step is to identify the different possible responsibilities of the function. Consider extracting those responsibilities into smaller, cohesive, and well-named functions. The [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring is the primary response.","change-type":"introduced"},{"why-it-occurs":"Duplicated code often leads to code that's harder to change since the same logical change has to be done in multiple functions. More duplication gives lower code health.","name":"Code Duplication","file":"app/src/main/java/org/akanework/gramophone/ui/fragments/compose/MultiQueue.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":747,"what-changed":"The module contains 4 functions with similar structure: MqState.detach,MqState.detach,MqState.removeQueue,MqState.resetHead","how-to-fix":"A certain degree of duplicated code might be acceptable. The problems start when it is the same behavior that is duplicated across the functions in the module, ie. a violation of the Don't Repeat Yourself (DRY) principle. DRY violations lead to code that is changed together in predictable patterns, which is both expensive and risky. DRY violations can be identified using CodeScene's X-Ray analysis to detect clusters of change coupled functions with high code similarity. [Read More](https://codescene.com/blog/software-revolution-part3/)\n\nOnce you have identified the similarities across functions, look to extract and encapsulate the concept that varies into its own function(s). These shared abstractions can then be re-used, which minimizes the amount of duplication and simplifies change.","change-type":"introduced"},{"method":"ActionBar","why-it-occurs":"Overly long functions make the code harder to read. The recommended maximum function length for the Kotlin language is 70 lines of code. Severity: Brain Method - Complex Method - Long Method.","name":"Large Method","file":"app/src/main/java/org/akanework/gramophone/ui/fragments/compose/MultiQueue.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":346,"what-changed":"ActionBar has 119 lines, threshold = 70","how-to-fix":"We recommend to be careful here -- just splitting long functions don't necessarily make the code easier to read. Instead, look for natural chunks inside the functions that expresses a specific task or concern. Often, such concerns are indicated by a Code Comment followed by an if-statement. Use the [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring to encapsulate that concern.","change-type":"introduced"},{"method":"BoxScope.pager","why-it-occurs":"Overly long functions make the code harder to read. The recommended maximum function length for the Kotlin language is 70 lines of code. Severity: Brain Method - Complex Method - Long Method.","name":"Large Method","file":"app/src/main/java/org/akanework/gramophone/ui/fragments/compose/MultiQueue.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":491,"what-changed":"BoxScope.pager has 74 lines, threshold = 70","how-to-fix":"We recommend to be careful here -- just splitting long functions don't necessarily make the code easier to read. Instead, look for natural chunks inside the functions that expresses a specific task or concern. Often, such concerns are indicated by a Code Comment followed by an if-statement. Use the [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring to encapsulate that concern.","change-type":"introduced"},{"method":"MqListItem","why-it-occurs":"Functions with many arguments indicate either a) low cohesion where the function has too many responsibilities, or b) a missing abstraction that encapsulates those arguments.\n\nThe threshold for the Kotlin language is 4 function arguments.","name":"Excess Number of Function Arguments","file":"app/src/main/java/org/akanework/gramophone/ui/fragments/compose/MultiQueue.kt","refactoring-examples":[{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"3","loc-deleted":"21","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"9.1914109204282"},"author-email":"nift4@protonmail.com","commit-full-message":"nobody ever used it, and nobody ever will use it.","commit-date":"2026-01-03T22:46:51Z","current-rev":"fc1ce7df","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt","previous-rev":"789a8a8b","commit-title":"Remove Walaoke extension support","language":"Kotlin","id":"ee69b3c88fdb6663c468412eddd279a0b76b7ccf","model-score":0.45,"author-id":null,"project-id":64193,"delta-file-score":0.5577275,"diff":"diff --git a/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt b/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt\nindex b4f21f50..afeb8d1b 100644\n--- a/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt\n+++ b/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt\n@@ -25,8 +25,2 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n     private var highlightTextColor = 0\n-    private var defaultTextColorM = 0\n-    private var highlightTextColorM = 0\n-    private var defaultTextColorF = 0\n-    private var highlightTextColorF = 0\n-    private var defaultTextColorD = 0\n-    private var highlightTextColorD = 0\n     private var lyrics: SemanticLyrics? = null\n@@ -70,5 +64,3 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n             newView!!.updateTextColor(\n-                defaultTextColor, highlightTextColor, defaultTextColorM,\n-                highlightTextColorM, defaultTextColorF, highlightTextColorF, defaultTextColorD,\n-                highlightTextColorD\n+                defaultTextColor, highlightTextColor\n             )\n@@ -126,5 +118,3 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n     fun updateTextColor(\n-        newColor: Int, newHighlightColor: Int, newColorM: Int,\n-        newHighlightColorM: Int, newColorF: Int, newHighlightColorF: Int,\n-        newColorD: Int, newHighlightColorD: Int\n+        newColor: Int, newHighlightColor: Int\n     ) {\n@@ -132,13 +122,5 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n         highlightTextColor = newHighlightColor\n-        defaultTextColorM = newColorM\n-        highlightTextColorM = newHighlightColorM\n-        defaultTextColorF = newColorF\n-        highlightTextColorF = newHighlightColorF\n-        defaultTextColorD = newColorD\n-        highlightTextColorD = newHighlightColorD\n         adapter?.updateTextColor(defaultTextColor, highlightTextColor)\n         newView?.updateTextColor(\n-            defaultTextColor, highlightTextColor, defaultTextColorM,\n-            highlightTextColorM, defaultTextColorF, highlightTextColorF, defaultTextColorD,\n-            highlightTextColorD\n+            defaultTextColor, highlightTextColor\n         )\n","improvement-type":"Excess Number of Function Arguments"},{"architectural-component-id":null,"author-name":"Light summer","training-data":{"loc-added":"79","loc-deleted":"84","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"93428659+lightsummer233@users.noreply.github.com","commit-full-message":"","commit-date":"2025-09-20T14:47:22Z","current-rev":"296bf3c","filename":"libPhonograph/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt","previous-rev":"a38b6fe","commit-title":"libPhonograph: Changes from Gramophone","language":"Kotlin","id":"db7b374615169a97822a31080fb78af0fd8d9410","model-score":0.22,"author-id":null,"project-id":64193,"delta-file-score":0.61278176,"diff":"diff --git a/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt b/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt\nindex 97fc6f4..2a44247 100644\n--- a/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt\n+++ b/libPhonograph/src/main/java/uk/akane/libphonograph/Extensions.kt\n@@ -10,2 +10,3 @@ import android.os.Build\n import android.os.Handler\n+import android.os.ext.SdkExtensions\n import androidx.annotation.ChecksSdkIntAtLeast\n@@ -13,5 +14,6 @@ import androidx.annotation.RequiresApi\n import androidx.core.content.ContextCompat\n+import androidx.core.net.toFile\n+import androidx.media3.common.MediaItem\n import kotlinx.coroutines.CoroutineScope\n import kotlinx.coroutines.ExperimentalCoroutinesApi\n-import kotlinx.coroutines.channels.BufferOverflow\n import kotlinx.coroutines.channels.ProducerScope\n@@ -19,13 +21,3 @@ import kotlinx.coroutines.channels.awaitClose\n import kotlinx.coroutines.flow.Flow\n-import kotlinx.coroutines.flow.MutableSharedFlow\n-import kotlinx.coroutines.flow.SharedFlow\n-import kotlinx.coroutines.flow.SharingCommand\n-import kotlinx.coroutines.flow.SharingStarted\n-import kotlinx.coroutines.flow.StateFlow\n import kotlinx.coroutines.flow.callbackFlow\n-import kotlinx.coroutines.flow.collect\n-import kotlinx.coroutines.flow.distinctUntilChanged\n-import kotlinx.coroutines.flow.emptyFlow\n-import kotlinx.coroutines.flow.flatMapLatest\n-import kotlinx.coroutines.flow.map\n import kotlinx.coroutines.launch\n@@ -33,2 +25,4 @@ import java.io.File\n import java.util.concurrent.atomic.AtomicLong\n+import kotlin.contracts.ExperimentalContracts\n+import kotlin.contracts.contract\n import kotlin.experimental.ExperimentalTypeInference\n@@ -61,3 +55,3 @@ abstract class ContentObserverCompat(handler: Handler?) : ContentObserver(handle\n \n-    abstract override fun onChange(selfChange: Boolean, uris: Collection<Uri?>, flags: Int)\n+    abstract override fun onChange(selfChange: Boolean, uris: Collection<Uri>, flags: Int)\n     abstract override fun deliverSelfNotifications(): Boolean\n@@ -70,3 +64,3 @@ internal fun versioningCallbackFlow(\n     val versionTracker = AtomicLong()\n-    return callbackFlow<Long> { block(versionTracker::incrementAndGet) }\n+    return callbackFlow { block(versionTracker::incrementAndGet) }\n }\n@@ -80,5 +74,5 @@ internal fun contentObserverVersioningFlow(\n         val listener = object : ContentObserverCompat(null) {\n-            override fun onChange(selfChange: Boolean, uris: Collection<Uri?>, flags: Int) {\n+            override fun onChange(selfChange: Boolean, uris: Collection<Uri>, flags: Int) {\n                 // TODO can we use those uris and flags for incremental reload at least on newer\n-                //  platform versions?\n+                //  platform versions? completely since R+, Q has no flags, before we get meh deletion handling\n                 scope.launch {\n@@ -92,4 +86,5 @@ internal fun contentObserverVersioningFlow(\n         }\n-        // TODO is content observer reliable if process gets cached? or are we forced to re-register\n-        //  and reload everything when regaining active state since Android 13?\n+        // Notifications may get delayed while we are frozen, but they do not get lost. Though, if\n+        // too many of them pile up, we will get killed for eating too much space with our async\n+        // binder transactions and we will have to restart in a new process later.\n         context.contentResolver.registerContentObserver(uri, notifyForDescendants, listener)\n@@ -102,35 +97,5 @@ internal fun contentObserverVersioningFlow(\n \n-internal fun <T> MutableSharedFlow<T>.collectOtherFlowWhenBeingCollected(\n-    scope: CoroutineScope, flow: Flow<*>\n-): MutableSharedFlow<T> {\n-    scope.launch {\n-        subscriptionCount\n-            .map { count -> count > 0 }\n-            .distinctUntilChanged()\n-            .collect { hasCollectors ->\n-                if (hasCollectors) {\n-                    flow.collect()\n-                }\n-            }\n-    }\n-    return this\n-}\n-\n-// https://bladecoder.medium.com/smarter-shared-kotlin-flows-d6b75fc66754\n-internal inline fun <T> sharedFlow(\n-    scope: CoroutineScope,\n-    replay: Int = 0,\n-    extraBufferCapacity: Int = 0,\n-    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,\n-    producer: (subscriptionCount: StateFlow<Int>) -> Flow<T>\n-): SharedFlow<T> {\n-    val shared = MutableSharedFlow<T>(replay, extraBufferCapacity, onBufferOverflow)\n-    val f = producer(shared.subscriptionCount)\n-    scope.launch { f.collect(shared) }\n-    return shared\n-}\n-\n fun File.toUriCompat(): Uri {\n     val tmp = Uri.fromFile(this)\n-    return if (tmp.scheme != \"file\") // This ONLY happens on Samsung and Ximi devices...\n+    return if (tmp.scheme != \"file\") // weird os bug workaround, found on Samsung and Xiaomi\n         tmp.buildUpon().scheme(\"file\").build()\n@@ -139,39 +104,12 @@ fun File.toUriCompat(): Uri {\n \n-// https://bladecoder.medium.com/smarter-shared-kotlin-flows-d6b75fc66754\n-@OptIn(ExperimentalCoroutinesApi::class)\n-internal fun <T> Flow<T>.flowWhileShared(\n-    subscriptionCount: StateFlow<Int>,\n-    started: SharingStarted\n-): Flow<T> {\n-    return started.command(subscriptionCount)\n-        .distinctUntilChanged()\n-        .flatMapLatest {\n-            when (it) {\n-                SharingCommand.START -> this\n-                SharingCommand.STOP,\n-                SharingCommand.STOP_AND_RESET_REPLAY_CACHE -> emptyFlow()\n-            }\n-        }\n+fun MediaItem.getUri(): Uri? {\n+    return localConfiguration?.uri\n }\n \n-@Suppress(\"NOTHING_TO_INLINE\")\n-internal inline fun Cursor.getColumnIndexOrNull(columnName: String): Int? =\n-    getColumnIndex(columnName).let { if (it == -1) null else it }\n-\n-@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)\n-@Suppress(\"NOTHING_TO_INLINE\")\n-internal inline fun hasImprovedMediaStore(): Boolean =\n-    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R\n-\n-@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)\n-@Suppress(\"NOTHING_TO_INLINE\")\n-internal inline fun hasScopedStorageV2(): Boolean =\n-    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R\n+fun MediaItem.getFile(): File? {\n+    return getUri()?.toFile()\n+}\n \n-@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU)\n @Suppress(\"NOTHING_TO_INLINE\")\n-internal inline fun hasScopedStorageWithMediaTypes(): Boolean =\n-    Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU\n-\n-internal fun Context.hasAudioPermission() =\n+inline fun Context.hasAudioPermission() =\n     hasScopedStorageWithMediaTypes() && ContextCompat.checkSelfPermission(\n@@ -190,5 +128,25 @@ internal fun Context.hasAudioPermission() =\n @RequiresApi(Build.VERSION_CODES.TIRAMISU)\n-internal fun Context.hasImagePermission() =\n-    checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) ==\n-            PackageManager.PERMISSION_GRANTED\n+fun Context.hasImagePermission() =\n+    checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED\n+\n+@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)\n+@Suppress(\"NOTHING_TO_INLINE\")\n+inline fun hasImprovedMediaStore(): Boolean =\n+    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R\n+\n+@Suppress(\"NOTHING_TO_INLINE\")\n+inline fun hasMarkIsFavouriteStatus(): Boolean =\n+    Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA ||\n+            (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&\n+                    SdkExtensions.getExtensionVersion(Build.VERSION_CODES.R) >= 16)\n+\n+@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)\n+@Suppress(\"NOTHING_TO_INLINE\")\n+inline fun hasScopedStorageV2(): Boolean =\n+    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R\n+\n+@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU)\n+@Suppress(\"NOTHING_TO_INLINE\")\n+inline fun hasScopedStorageWithMediaTypes(): Boolean =\n+    Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU\n \n@@ -216,2 +174,39 @@ internal inline fun Cursor.getIntOrNullIfThrow(index: Int): Int? =\n         null\n-    }\n\\ No newline at end of file\n+    }\n+\n+@Suppress(\"NOTHING_TO_INLINE\")\n+internal inline fun Cursor.getColumnIndexOrNull(columnName: String): Int? =\n+    getColumnIndex(columnName).let { if (it == -1) null else it }\n+\n+// From https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-util/src/commonMain/kotlin/androidx/compose/ui/util/\n+\n+/**\n+ * Iterates through a [List] using the index and calls [action] for each item. This does not\n+ * allocate an iterator like [Iterable.forEach].\n+ *\n+ * **Do not use for collections that come from public APIs**, since they may not support random\n+ * access in an efficient way, and this method may actually be a lot slower. Only use for\n+ * collections that are created by code we control and are known to support random access.\n+ */\n+@Suppress(\"BanInlineOptIn\")\n+@OptIn(ExperimentalContracts::class)\n+inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {\n+    contract { callsInPlace(action) }\n+    for (index in indices) {\n+        val item = get(index)\n+        action(item)\n+    }\n+}\n+\n+/**\n+ * Returns a list containing all elements that are not null\n+ *\n+ * **Do not use for collections that come from public APIs**, since they may not support random\n+ * access in an efficient way, and this method may actually be a lot slower. Only use for\n+ * collections that are created by code we control and are known to support random access.\n+ */\n+fun <T : Any> List<T?>.fastFilterNotNull(): List<T> {\n+    val target = ArrayList<T>(size)\n+    fastForEach { if ((it) != null) target += (it) }\n+    return target\n+}\n","improvement-type":"Excess Number of Function Arguments"}],"change-level":"warning","is-hotspot?":false,"line":97,"what-changed":"MqListItem has 9 arguments, max arguments = 4","how-to-fix":"Start by investigating the responsibilities of the function. Make sure it doesn't do too many things, in which case it should be split into smaller and more cohesive functions. Consider the refactoring [INTRODUCE PARAMETER OBJECT](https://refactoring.com/catalog/introduceParameterObject.html) to encapsulate arguments that refer to the same logical concept.","change-type":"introduced"}]},"positive-impact-count":0,"repo":"Gramophone","code-health":7.297174578418916,"version":"3.0","authors":["mikooomich"],"directives":{"added":[],"removed":[]},"positive-findings":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"notices":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"external-review-provider":"GitHub"},"analysistime":"2026-05-23T19:58:01.000Z","project-name":"Gramophone","repository":"https://github.com/FoedusProgramme/Gramophone.git"}}