{"results":{"result":{"added-files":{"code-health":9.54673804969694,"old-code-health":0.0,"files":[{"file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","loc":359,"code-health":9.022772285419025},{"file":"app/src/main/java/org/akanework/gramophone/ui/components/ComposeComponentsTemp.kt","loc":415,"code-health":10.0}]},"external-review-url":"https://github.com/FoedusProgramme/Gramophone/pull/865","old-code-health":6.899798486181131,"modified-files":{"code-health":6.844893351873204,"old-code-health":6.899798486181131,"files":[{"file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneExtensions.kt","loc":676,"old-loc":543,"code-health":8.031638343271364,"old-code-health":8.283981080161325},{"file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","loc":1382,"old-loc":1306,"code-health":4.688431645926911,"old-code-health":4.826729491574492},{"file":"app/src/main/java/org/akanework/gramophone/ui/adapters/BaseDecorAdapter.kt","loc":260,"old-loc":251,"code-health":8.983831645881306,"old-code-health":8.611108519496959},{"file":"app/src/main/java/org/akanework/gramophone/ui/adapters/SongAdapter.kt","loc":347,"old-loc":346,"code-health":8.719209493841293,"old-code-health":8.719209493841293},{"file":"app/src/main/java/org/akanework/gramophone/ui/components/PlaylistQueueSheet.kt","loc":392,"old-loc":239,"code-health":8.614866363843692,"old-code-health":9.536386775820924},{"file":"app/src/main/java/org/akanework/gramophone/ui/fragments/settings/ExperimentalSettingsFragment.kt","loc":88,"old-loc":86,"code-health":10.0,"old-code-health":10.0}]},"removed-files":{"code-health":0.0,"old-code-health":0.0,"files":[]},"external-review-id":"865","analysis-time":"2026-04-08T14:46:30Z","negative-impact-count":5,"suppressions":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"affected-hotspots":3,"commits":["fb485e47158fb4806e378ee1658bca4d1f878f8d","0d5efed4d76a860a1a1070f7b33307fd7e477d6f","7b0bd1b959a8da7bb70de8a7fa8a1fd88e84886b","336b980464f8e33a913e6c04711c7cb73824664d","6e8bf07bd4fdfcac6e91fe04b4883808a55cf2f4","7709eef2e501e0a087a720b9677a0bc3ff74052f","826f39575eae695ca7a04ebcd26b6668f60ba46c","16ddc71c31f8742d346d56d8594a29b4be1ac53f","4304106aaa0a737f5fcba64d912430c0c3a8a71c"],"is-negative-review":true,"negative-findings":{"number-of-types":3,"number-of-files-touched":3,"findings":[{"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, 54 % of all functions have primitive types as arguments.","name":"Primitive Obsession","file":"app/src/main/java/org/akanework/gramophone/logic/GramophoneExtensions.kt","refactoring-examples":[{"diff":"diff --git a/primitive-obsession.ts b/primitive-obsession.ts\nindex 38bae186cc..24116eddcc 100644\n--- a/primitive-obsession.ts\n+++ b/primitive-obsession.ts\n@@ -1,8 +1,8 @@\n-// Problem: It's hard to know what this function does, and what values are valid as parameters.\n-function getPopularRepositories(String baseURL, String query, Integer pages, Integer pageSize, String sortorder): Json {\n-\tlet pages == null ? 10 : pages\n-\tlet pageSize == null ? 10 : pageSize\n-  return httpClient.get(`${baseURL}?q=${query}&pages=${pages}&pageSize=${pageSize}&sortorder=${sortorder}`)\n+// Refactoring: extract the pagination & API logic into a class, and it will\n+// attract validation and other logic related to the specific query. It's now\n+// easier to use and to maintain the getPopularRepositories function!\n+function getPopularRepositories(query: PaginatedRepoQuery): Json {\n+  return httpClient.get(query.getURL())\n     .map(json => json.repositories)\n     .filter(repository => repositry.stargazersCount > 1000)\n }\n","language":"kotlin","improvement-type":"Primitive Obsession"}],"change-level":"warning","is-hotspot?":true,"what-changed":"In this module, 53.8% of all function arguments are primitive types, threshold = 30.0%","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","change-type":"introduced"},{"method":"GramophonePlaybackService.onCreate","why-it-occurs":"A Complex Method has a high cyclomatic complexity. The recommended threshold for the Kotlin language is a cyclomatic complexity lower than 9.","name":"Complex Method","file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","refactoring-examples":[{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"21","loc-deleted":"11","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.95517096544394"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2025-11-08T13:49:28Z","current-rev":"9595076b","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt","previous-rev":"9b7f9b9c","commit-title":"-remove some cruft from new lyrics -remove hardcoded assumptions that speed=1 in service -support speed!=1 in old lyrics -update gradient timing in new lyrics to use real bounds","language":"Kotlin","id":"91764f0765165200a607ffcd616eeacfff91c9c9","model-score":0.49,"author-id":null,"project-id":64193,"delta-file-score":0.13901214,"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 0a74a20f..b4f21f50 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@@ -45,18 +45,27 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n         newView = null\n+        val cb = object : NewLyricsView.Callbacks {\n+            // TODO https://github.com/androidx/media/issues/1578\n+            override fun getCurrentPosition(): ULong =\n+                GramophonePlaybackService.instanceForWidgetAndLyricsOnly\n+                    ?.endedWorkaroundPlayer?.currentPosition?.toULong()\n+                    ?: (context as MainActivity).getPlayer()?.currentPosition?.toULong() ?: 0uL\n+\n+            override fun seekTo(position: ULong) {\n+                (context as MainActivity).getPlayer()?.seekTo(position.toLong())\n+            }\n+\n+            override fun setPlayWhenReady(play: Boolean) {\n+                (context as MainActivity).getPlayer()?.playWhenReady = play\n+            }\n+\n+            override fun speed(): Float {\n+                return (context as MainActivity).getPlayer()?.playbackParameters?.speed ?: 1f\n+            }\n+        }\n         if (prefs.getBooleanStrict(\"lyric_ui\", false)) {\n             inflate(context, R.layout.lyric_view_v2, this)\n-            newView = findViewById(R.id.lyric_view)\n-            newView?.setPadding(oldPaddingLeft, oldPaddingTop, oldPaddingRight, oldPaddingBottom)\n-            newView?.instance = object : NewLyricsView.Callbacks {\n-                // TODO https://github.com/androidx/media/issues/1578\n-                override fun getCurrentPosition(): ULong =\n-                    GramophonePlaybackService.instanceForWidgetAndLyricsOnly\n-                        ?.endedWorkaroundPlayer?.currentPosition?.toULong()\n-                        ?: (context as MainActivity).getPlayer()?.currentPosition?.toULong() ?: 0uL\n-\n-                override fun seekTo(position: ULong) {\n-                    (context as MainActivity).getPlayer()?.seekTo(position.toLong())\n-                }\n-            }\n-            newView?.updateTextColor(\n+            newView = findViewById(R.id.lyric_view)!!\n+            newView!!.setPadding(oldPaddingLeft, oldPaddingTop, oldPaddingRight, oldPaddingBottom)\n+            newView!!.instance = cb\n+            newView!!.updateTextColor(\n                 defaultTextColor, highlightTextColor, defaultTextColorM,\n@@ -65,3 +74,3 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n             )\n-            newView?.updateLyrics(lyrics)\n+            newView!!.updateLyrics(lyrics)\n         } else {\n@@ -74,3 +83,4 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n             recyclerView!!.addItemDecoration(LyricPaddingDecoration(context))\n-            adapter?.updateLyrics(lyrics)\n+            adapter!!.callback = cb\n+            adapter!!.updateLyrics(lyrics)\n         }\n@@ -90,6 +100,6 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n     override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {\n-        if ((key == \"lyric_center\" || key == \"lyric_bold\") && adapter != null)\n+        if (key == \"lyric_center\" || key == \"lyric_bold\")\n             adapter?.onPrefsChanged()\n-        else if (key == \"lyric_center\" || key == \"lyric_bold\" || key == \"lyric_no_animation\" ||\n-            key == \"lyric_char_scaling\" || key == \"translation_auto_word\")\n+        if (key == \"lyric_center\" || key == \"lyric_bold\" || key == \"lyric_no_animation\" ||\n+            key == \"translation_auto_word\")\n             newView?.onPrefsChanged(key)\n","improvement-type":"Complex Method"},{"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.0","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.3009901,"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":268,"what-changed":"GramophonePlaybackService.onCreate already has high cyclomatic complexity, and now it increases in Lines of Code from 312 to 313","how-to-fix":"There are many reasons for Complex Method. Sometimes, another design approach is beneficial such as a) modeling state using an explicit state machine rather than conditionals, or b) using table lookup rather than long chains of logic. In other scenarios, the function can be split using [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html). Just make sure you extract natural and cohesive functions. Complex Methods can also be addressed by identifying complex conditional expressions and then using the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring.","change-type":"degraded"},{"method":"GramophonePlaybackService.onCustomCommand","why-it-occurs":"A Complex Method has a high cyclomatic complexity. The recommended threshold for the Kotlin language is a cyclomatic complexity lower than 9.","name":"Complex Method","file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","refactoring-examples":[{"architectural-component-id":null,"author-name":"Nick","training-data":{"loc-added":"21","loc-deleted":"11","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.95517096544394"},"author-email":"nift4@protonmail.com","commit-full-message":"","commit-date":"2025-11-08T13:49:28Z","current-rev":"9595076b","filename":"Gramophone/app/src/main/java/org/akanework/gramophone/ui/components/LyricsView.kt","previous-rev":"9b7f9b9c","commit-title":"-remove some cruft from new lyrics -remove hardcoded assumptions that speed=1 in service -support speed!=1 in old lyrics -update gradient timing in new lyrics to use real bounds","language":"Kotlin","id":"91764f0765165200a607ffcd616eeacfff91c9c9","model-score":0.49,"author-id":null,"project-id":64193,"delta-file-score":0.13901214,"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 0a74a20f..b4f21f50 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@@ -45,18 +45,27 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n         newView = null\n+        val cb = object : NewLyricsView.Callbacks {\n+            // TODO https://github.com/androidx/media/issues/1578\n+            override fun getCurrentPosition(): ULong =\n+                GramophonePlaybackService.instanceForWidgetAndLyricsOnly\n+                    ?.endedWorkaroundPlayer?.currentPosition?.toULong()\n+                    ?: (context as MainActivity).getPlayer()?.currentPosition?.toULong() ?: 0uL\n+\n+            override fun seekTo(position: ULong) {\n+                (context as MainActivity).getPlayer()?.seekTo(position.toLong())\n+            }\n+\n+            override fun setPlayWhenReady(play: Boolean) {\n+                (context as MainActivity).getPlayer()?.playWhenReady = play\n+            }\n+\n+            override fun speed(): Float {\n+                return (context as MainActivity).getPlayer()?.playbackParameters?.speed ?: 1f\n+            }\n+        }\n         if (prefs.getBooleanStrict(\"lyric_ui\", false)) {\n             inflate(context, R.layout.lyric_view_v2, this)\n-            newView = findViewById(R.id.lyric_view)\n-            newView?.setPadding(oldPaddingLeft, oldPaddingTop, oldPaddingRight, oldPaddingBottom)\n-            newView?.instance = object : NewLyricsView.Callbacks {\n-                // TODO https://github.com/androidx/media/issues/1578\n-                override fun getCurrentPosition(): ULong =\n-                    GramophonePlaybackService.instanceForWidgetAndLyricsOnly\n-                        ?.endedWorkaroundPlayer?.currentPosition?.toULong()\n-                        ?: (context as MainActivity).getPlayer()?.currentPosition?.toULong() ?: 0uL\n-\n-                override fun seekTo(position: ULong) {\n-                    (context as MainActivity).getPlayer()?.seekTo(position.toLong())\n-                }\n-            }\n-            newView?.updateTextColor(\n+            newView = findViewById(R.id.lyric_view)!!\n+            newView!!.setPadding(oldPaddingLeft, oldPaddingTop, oldPaddingRight, oldPaddingBottom)\n+            newView!!.instance = cb\n+            newView!!.updateTextColor(\n                 defaultTextColor, highlightTextColor, defaultTextColorM,\n@@ -65,3 +74,3 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n             )\n-            newView?.updateLyrics(lyrics)\n+            newView!!.updateLyrics(lyrics)\n         } else {\n@@ -74,3 +83,4 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n             recyclerView!!.addItemDecoration(LyricPaddingDecoration(context))\n-            adapter?.updateLyrics(lyrics)\n+            adapter!!.callback = cb\n+            adapter!!.updateLyrics(lyrics)\n         }\n@@ -90,6 +100,6 @@ class LyricsView(context: Context, attrs: AttributeSet?) : FrameLayout(context,\n     override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {\n-        if ((key == \"lyric_center\" || key == \"lyric_bold\") && adapter != null)\n+        if (key == \"lyric_center\" || key == \"lyric_bold\")\n             adapter?.onPrefsChanged()\n-        else if (key == \"lyric_center\" || key == \"lyric_bold\" || key == \"lyric_no_animation\" ||\n-            key == \"lyric_char_scaling\" || key == \"translation_auto_word\")\n+        if (key == \"lyric_center\" || key == \"lyric_bold\" || key == \"lyric_no_animation\" ||\n+            key == \"translation_auto_word\")\n             newView?.onPrefsChanged(key)\n","improvement-type":"Complex Method"},{"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.0","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.3009901,"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":815,"what-changed":"GramophonePlaybackService.onCustomCommand has a cyclomatic complexity of 11, threshold = 9","how-to-fix":"There are many reasons for Complex Method. Sometimes, another design approach is beneficial such as a) modeling state using an explicit state machine rather than conditionals, or b) using table lookup rather than long chains of logic. In other scenarios, the function can be split using [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html). Just make sure you extract natural and cohesive functions. Complex Methods can also be addressed by identifying complex conditional expressions and then using the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring.","change-type":"introduced"},{"method":"QueueBoard.renameQueue","why-it-occurs":"A Bumpy Road is a function that contains multiple chunks of nested conditional logic inside the same function. The deeper the nesting and the more bumps, the lower the code health.\n\nA bumpy code road represents a lack of encapsulation which becomes an obstacle to comprehension. In imperative languages there’s also an increased risk for feature entanglement, which leads to complex state management. CodeScene considers the following rules for the code health impact: 1) The deeper the nested conditional logic of each bump, the higher the tax on our working memory. 2) The more bumps inside a function, the more expensive it is to refactor as each bump represents a missing abstraction. 3) The larger each bump – that is, the more lines of code it spans – the harder it is to build up a mental model of the function. The nesting depth for what is considered a bump is  levels of conditionals.","name":"Bumpy Road Ahead","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":316,"what-changed":"QueueBoard.renameQueue has 3 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function","how-to-fix":"Bumpy Road implementations indicate a lack of encapsulation. Check out the detailed description of the [Bumpy Road code health issue](https://codescene.com/blog/bumpy-road-code-complexity-in-context/).\n\nA Bumpy Road often suggests that the function/method does too many things. The first refactoring step is to identify the different possible responsibilities of the function. Consider extracting those responsibilities into smaller, cohesive, and well-named functions. The [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring is the primary response.","change-type":"introduced"},{"method":"QueueBoard.setCurrQueue","why-it-occurs":"A Bumpy Road is a function that contains multiple chunks of nested conditional logic inside the same function. The deeper the nesting and the more bumps, the lower the code health.\n\nA bumpy code road represents a lack of encapsulation which becomes an obstacle to comprehension. In imperative languages there’s also an increased risk for feature entanglement, which leads to complex state management. CodeScene considers the following rules for the code health impact: 1) The deeper the nested conditional logic of each bump, the higher the tax on our working memory. 2) The more bumps inside a function, the more expensive it is to refactor as each bump represents a missing abstraction. 3) The larger each bump – that is, the more lines of code it spans – the harder it is to build up a mental model of the function. The nesting depth for what is considered a bump is  levels of conditionals.","name":"Bumpy Road Ahead","file":"app/src/main/java/org/akanework/gramophone/logic/QueueBoard.kt","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":349,"what-changed":"QueueBoard.setCurrQueue has 3 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function","how-to-fix":"Bumpy Road implementations indicate a lack of encapsulation. Check out the detailed description of the [Bumpy Road code health issue](https://codescene.com/blog/bumpy-road-code-complexity-in-context/).\n\nA Bumpy Road often suggests that the function/method does too many things. The first refactoring step is to identify the different possible responsibilities of the function. Consider extracting those responsibilities into smaller, cohesive, and well-named functions. The [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring is the primary response.","change-type":"introduced"}]},"positive-impact-count":3,"repo":"Gramophone","code-health":7.378505956138469,"version":"3.0","authors":["mikooomich"],"directives":{"added":[],"removed":[]},"positive-findings":{"number-of-types":3,"number-of-files-touched":2,"findings":[{"method":"GramophonePlaybackService.onCustomCommand","why-it-occurs":"Overly long functions make the code harder to read. The recommended maximum function length for the Kotlin language is 70 lines of code. Severity: Brain Method - Complex Method - Long Method.","name":"Large Method","file":"app/src/main/java/org/akanework/gramophone/logic/GramophonePlaybackService.kt","change-level":"improvement","is-hotspot?":true,"line":793,"what-changed":"GramophonePlaybackService.onCustomCommand is no longer above the threshold for lines of code","how-to-fix":"We recommend to be careful here -- just splitting long functions don't necessarily make the code easier to read. Instead, look for natural chunks inside the functions that expresses a specific task or concern. Often, such concerns are indicated by a Code Comment followed by an if-statement. Use the [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html) refactoring to encapsulate that concern.","change-type":"fixed"},{"method":"BaseDecorAdapter.onBindViewHolder","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/ui/adapters/BaseDecorAdapter.kt","change-level":"improvement","is-hotspot?":false,"line":60,"what-changed":"BaseDecorAdapter.onBindViewHolder decreases in cyclomatic complexity from 26 to 24, 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"},{"method":"BaseDecorAdapter.onBindViewHolder","why-it-occurs":"A Bumpy Road is a function that contains multiple chunks of nested conditional logic inside the same function. The deeper the nesting and the more bumps, the lower the code health.\n\nA bumpy code road represents a lack of encapsulation which becomes an obstacle to comprehension. In imperative languages there’s also an increased risk for feature entanglement, which leads to complex state management. CodeScene considers the following rules for the code health impact: 1) The deeper the nested conditional logic of each bump, the higher the tax on our working memory. 2) The more bumps inside a function, the more expensive it is to refactor as each bump represents a missing abstraction. 3) The larger each bump – that is, the more lines of code it spans – the harder it is to build up a mental model of the function. The nesting depth for what is considered a bump is  levels of conditionals.","name":"Bumpy Road Ahead","file":"app/src/main/java/org/akanework/gramophone/ui/adapters/BaseDecorAdapter.kt","change-level":"improvement","is-hotspot?":false,"line":60,"what-changed":"BaseDecorAdapter.onBindViewHolder decreases from 5 to 3 logical blocks with deeply nested code, 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":"improved"}]},"notices":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"external-review-provider":"GitHub"},"analysistime":"2026-04-08T14:46:29.000Z","project-name":"Gramophone","repository":"https://github.com/FoedusProgramme/Gramophone.git"}}