{"results":{"result":{"added-files":{"code-health":8.061015202871632,"old-code-health":0.0,"files":[{"file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneAlbumArtProvider.kt","loc":34,"code-health":9.6882083290695},{"file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneLibrarySessionCallback.kt","loc":365,"code-health":7.843307693014887},{"file":"app/src/main/java/org/akanework/gramophone/logic/utils/ArtCacheManager.kt","loc":112,"code-health":9.536386775820924},{"file":"app/src/main/java/org/akanework/gramophone/logic/utils/ArtResolver.kt","loc":260,"code-health":7.518311582243415}]},"external-review-url":"https://github.com/FoedusProgramme/Gramophone/pull/890","old-code-health":6.006549124503919,"modified-files":{"code-health":5.976419194713489,"old-code-health":6.006549124503919,"files":[{"file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","loc":1318,"old-loc":1305,"code-health":4.746362251076446,"old-code-health":4.81837345166433},{"file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneApplication.kt","loc":291,"old-loc":353,"code-health":8.284494733084642,"old-code-health":7.763192747917738},{"file":"app/src/main/java/org/akanework/gramophone/ui/fragments/ViewPagerFragment.kt","loc":236,"old-loc":233,"code-health":10.0,"old-code-health":10.0}]},"removed-files":{"code-health":0.0,"old-code-health":0.0,"files":[]},"external-review-id":"890","analysis-time":"2026-04-28T01:08:57Z","negative-impact-count":17,"suppressions":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"affected-hotspots":2,"commits":["77a7262a33f865972cf46c93fd598fad52435654","90045d6f85a51d48c5e518b949f9f04c6bc7a375","e405f419a7228cb31f63358eecb7d32d6271dc74","5f40cb634490b3cdfde4ff45c039631acaf3fe75","a41575fb0b72ac18b16360f60f04dcb391196d71"],"is-negative-review":true,"negative-findings":{"number-of-types":6,"number-of-files-touched":4,"findings":[{"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":269,"what-changed":"GramophonePlaybackService.onCreate already has high cyclomatic complexity, and now it increases in Lines of Code from 311 to 341","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":"GramophoneLibrarySessionCallback.onGetItem","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/GramophoneLibrarySessionCallback.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":161,"what-changed":"GramophoneLibrarySessionCallback.onGetItem has a cyclomatic complexity of 21, 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":"GramophoneLibrarySessionCallback.onAddMediaItems","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/GramophoneLibrarySessionCallback.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":318,"what-changed":"GramophoneLibrarySessionCallback.onAddMediaItems has a cyclomatic complexity of 17, 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":"GramophoneLibrarySessionCallback.onGetChildren","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/GramophoneLibrarySessionCallback.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":83,"what-changed":"GramophoneLibrarySessionCallback.onGetChildren 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"},{"why-it-occurs":"Overall Code Complexity is measured by the mean cyclomatic complexity across all functions in the file. The lower the number, the better.\n\nCyclomatic complexity is a function level metric that measures the number of logical branches (if-else, loops, etc.). Cyclomatic complexity is a rough complexity measure, but useful as a way of estimating the minimum number of unit tests you would need. As such, prefer functions with low cyclomatic complexity (2-3 branches).","name":"Overall Code Complexity","file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneLibrarySessionCallback.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"what-changed":"This module has a mean cyclomatic complexity of 4.93 across 15 functions. The mean complexity threshold is 4","how-to-fix":"You address the overall cyclomatic complexity by a) modularizing the code, and b) abstract away the complexity. Let's look at some examples:\n\nModularizing the Code: Do an X-Ray and inspect the local hotspots. Are there any complex conditional expressions? If yes, then do a [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring. Extract the conditional logic into a separate function and put a good name on that function. This clarifies the intent and makes the original function easier to read. Repeat until all complex conditional expressions have been simplified.\n\n","change-type":"introduced"},{"method":"GramophoneLibrarySessionCallback.onGetChildren","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/GramophoneLibrarySessionCallback.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":83,"what-changed":"GramophoneLibrarySessionCallback.onGetChildren 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":"GramophoneLibrarySessionCallback.onGetSearchResult","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/GramophoneLibrarySessionCallback.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":284,"what-changed":"GramophoneLibrarySessionCallback.onGetSearchResult 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":"ArtCacheManager.trimCacheIfNeeded","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/utils/ArtCacheManager.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":109,"what-changed":"ArtCacheManager.trimCacheIfNeeded 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"},{"method":"ArtResolver.openResourceStream","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/utils/ArtResolver.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":132,"what-changed":"ArtResolver.openResourceStream has a cyclomatic complexity of 13, 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":"ArtResolver.getResolutionList","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/utils/ArtResolver.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":66,"what-changed":"ArtResolver.getResolutionList has a cyclomatic complexity of 12, 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":"ArtResolver.decodeAndResize","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/utils/ArtResolver.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":193,"what-changed":"ArtResolver.decodeAndResize has a cyclomatic complexity of 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":"introduced"},{"method":"ArtResolver.extractSongThumbnail","why-it-occurs":"A complex conditional is an expression inside a branch such as an <code>if</code>-statmeent which consists of multiple, logical operations. Example: <code>if (x.started() && y.running())</code>.Complex conditionals make the code even harder to read, and contribute to the Complex Method code smell. Encapsulate them.","name":"Complex Conditional","file":"app/src/main/java/org/akanework/gramophone/logic/utils/ArtResolver.kt","refactoring-examples":[{"diff":"diff --git a/complex_conditional.js b/complex_conditional.js\nindex c43da09584..94259ce874 100644\n--- a/complex_conditional.js\n+++ b/complex_conditional.js\n@@ -1,16 +1,34 @@\n function messageReceived(message, timeReceived) {\n-   // Ignore all messages which aren't from known customers:\n-   if (!message.sender &&\n-       customers.getId(message.name) == null) {\n+   // Refactoring #1: encapsulate the business rule in a\n+   // function. A clear name replaces the need for the comment:\n+   if (!knownCustomer(message)) {\n      log('spam received -- ignoring');\n      return;\n    }\n \n-  // Provide an auto-reply when outside business hours:\n-  if ((timeReceived.getHours() > 17) ||\n-      (timeReceived.getHours() < 8)) {\n+  // Refactoring #2: encapsulate the business rule.\n+  // Again, note how a clear function name replaces the\n+  // need for a code comment:\n+  if (outsideBusinessHours(timeReceived)) {\n     return autoReplyTo(message);\n   }\n \n   pingAgentFor(message);\n+}\n+\n+function outsideBusinessHours(timeReceived) {\n+  // Refactoring #3: replace magic numbers with\n+  // symbols that communicate with the code reader:\n+  const closingHour = 17;\n+  const openingHour = 8;\n+\n+  const hours = timeReceived.getHours();\n+\n+  // Refactoring #4: simple conditional rules can\n+  // be further clarified by introducing a variable:\n+  const afterClosing = hours > closingHour;\n+  const beforeOpening = hours < openingHour;\n+\n+  // Yeah -- look how clear the business rule is now!\n+  return afterClosing || beforeOpening;\n }\n\\ No newline at end of file\n","language":"kotlin","improvement-type":"Complex Conditional"}],"change-level":"warning","is-hotspot?":false,"line":286,"what-changed":"ArtResolver.extractSongThumbnail has 1 complex conditionals with 3 branches, threshold = 2","how-to-fix":"Apply the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring so that the complex conditional is encapsulated in a separate function with a good name that captures the business rule. Optionally, for simple expressions, introduce a new variable which holds the result of the complex conditional.","change-type":"introduced"},{"method":"ArtResolver.getResolutionList","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/utils/ArtResolver.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":66,"what-changed":"ArtResolver.getResolutionList 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"},{"method":"ArtResolver.openResourceStream","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/utils/ArtResolver.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":132,"what-changed":"ArtResolver.openResourceStream 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"},{"method":"ArtResolver.decodeAndResize","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/utils/ArtResolver.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":193,"what-changed":"ArtResolver.decodeAndResize 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":"Overall Code Complexity is measured by the mean cyclomatic complexity across all functions in the file. The lower the number, the better.\n\nCyclomatic complexity is a function level metric that measures the number of logical branches (if-else, loops, etc.). Cyclomatic complexity is a rough complexity measure, but useful as a way of estimating the minimum number of unit tests you would need. As such, prefer functions with low cyclomatic complexity (2-3 branches).","name":"Overall Code Complexity","file":"app/src/main/java/org/akanework/gramophone/logic/utils/ArtResolver.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"what-changed":"This module has a mean cyclomatic complexity of 5.45 across 11 functions. The mean complexity threshold is 4","how-to-fix":"You address the overall cyclomatic complexity by a) modularizing the code, and b) abstract away the complexity. Let's look at some examples:\n\nModularizing the Code: Do an X-Ray and inspect the local hotspots. Are there any complex conditional expressions? If yes, then do a [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring. Extract the conditional logic into a separate function and put a good name on that function. This clarifies the intent and makes the original function easier to read. Repeat until all complex conditional expressions have been simplified.\n\n","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, 65 % of all functions have primitive types as arguments.","name":"Primitive Obsession","file":"app/src/main/java/org/akanework/gramophone/logic/utils/ArtResolver.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, 65.2% 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"}]},"positive-impact-count":2,"repo":"Gramophone","code-health":6.5908012750995475,"version":"3.0","authors":["Nathan Banks"],"directives":{"added":[],"removed":[]},"positive-findings":{"number-of-types":2,"number-of-files-touched":2,"findings":[{"name":"Overall Code Complexity","file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","change-type":"improved","change-level":"improvement","is-hotspot?":true,"why-it-occurs":"Overall Code Complexity is measured by the mean cyclomatic complexity across all functions in the file. The lower the number, the better.\n\nCyclomatic complexity is a function level metric that measures the number of logical branches (if-else, loops, etc.). Cyclomatic complexity is a rough complexity measure, but useful as a way of estimating the minimum number of unit tests you would need. As such, prefer functions with low cyclomatic complexity (2-3 branches).","how-to-fix":"You address the overall cyclomatic complexity by a) modularizing the code, and b) abstract away the complexity. Let's look at some examples:\n\nModularizing the Code: Do an X-Ray and inspect the local hotspots. Are there any complex conditional expressions? If yes, then do a [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring. Extract the conditional logic into a separate function and put a good name on that function. This clarifies the intent and makes the original function easier to read. Repeat until all complex conditional expressions have been simplified.\n\n","what-changed":"The mean cyclomatic complexity decreases from 4.91 to 4.73, threshold = 4"},{"method":"GramophoneApplication.newImageLoader","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/GramophoneApplication.kt","change-level":"improvement","is-hotspot?":true,"line":255,"what-changed":"GramophoneApplication.newImageLoader decreases in cyclomatic complexity from 27 to 16, 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":"improved"}]},"notices":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"external-review-provider":"GitHub"},"analysistime":"2026-04-28T01:08:57.000Z","project-name":"Gramophone","repository":"https://github.com/FoedusProgramme/Gramophone.git"}}