From 9dbdd6bd5abbb09cb1e3c8d0af57ec696de310b7 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 19:59:56 +0330 Subject: [PATCH 01/70] Add AndroidX Media3 playback dependencies --- app/build.gradle.kts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 9eb327d..de4bd8a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -24,3 +24,8 @@ android { jvmTarget = "17" } } + +dependencies { + implementation("androidx.media3:media3-exoplayer:1.5.1") + implementation("androidx.media3:media3-session:1.5.1") +} From 7eccab01d765c7d239ae6d7e12fbaae598476e85 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 19:59:59 +0330 Subject: [PATCH 02/70] Declare media playback foreground service --- app/src/main/AndroidManifest.xml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 2c49eed..2f69909 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,5 +1,8 @@ + + + + + + + + From ee9066893e957f480dd0b2f1ad052024726c9261 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:00:06 +0330 Subject: [PATCH 03/70] Add Media3 foreground playback service --- .../java/com/movemusic/app/PlaybackService.kt | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 app/src/main/java/com/movemusic/app/PlaybackService.kt diff --git a/app/src/main/java/com/movemusic/app/PlaybackService.kt b/app/src/main/java/com/movemusic/app/PlaybackService.kt new file mode 100644 index 0000000..b1af25e --- /dev/null +++ b/app/src/main/java/com/movemusic/app/PlaybackService.kt @@ -0,0 +1,42 @@ +package com.movemusic.app + +import android.content.Intent +import androidx.media3.common.AudioAttributes +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.session.MediaSession +import androidx.media3.session.MediaSessionService + +class PlaybackService : MediaSessionService() { + private var player: ExoPlayer? = null + private var mediaSession: MediaSession? = null + + override fun onCreate() { + super.onCreate() + + val exoPlayer = ExoPlayer.Builder(this).build().apply { + setAudioAttributes(AudioAttributes.DEFAULT, true) + setHandleAudioBecomingNoisy(true) + } + player = exoPlayer + mediaSession = MediaSession.Builder(this, exoPlayer).build() + } + + override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = + mediaSession + + override fun onTaskRemoved(rootIntent: Intent?) { + if (player?.isPlaying != true) { + stopSelf() + } + } + + override fun onDestroy() { + mediaSession?.run { + player.release() + release() + } + mediaSession = null + player = null + super.onDestroy() + } +} From f4888491fec5b6cbcb1c5c70a32a6815363915d2 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:00:29 +0330 Subject: [PATCH 04/70] Connect player UI to background media session --- .../java/com/movemusic/app/MainActivity.kt | 123 ++++++++++++------ 1 file changed, 83 insertions(+), 40 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index fbee71e..79dbf25 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -4,9 +4,9 @@ import android.Manifest import android.app.Activity import android.app.AlertDialog import android.content.ContentUris +import android.content.ComponentName import android.content.Context import android.content.pm.PackageManager -import android.media.MediaPlayer import android.media.MediaMetadataRetriever import android.graphics.BitmapFactory import android.graphics.Color @@ -22,6 +22,12 @@ import android.view.View import android.widget.* import org.json.JSONArray import org.json.JSONObject +import androidx.media3.common.MediaItem +import androidx.media3.common.MediaMetadata +import androidx.media3.common.Player +import androidx.media3.session.MediaController +import androidx.media3.session.SessionToken +import com.google.common.util.concurrent.ListenableFuture data class Song(val id: Long, val title: String, val artist: String, val uri: Uri) @@ -36,7 +42,9 @@ class MainActivity : Activity() { private val songs = mutableListOf() private var currentPlaylist = "همه آهنگ‌ها" private var displayedSongCount = 50 - private var player: MediaPlayer? = null + private var player: MediaController? = null + private var controllerFuture: ListenableFuture? = null + private var pendingSong: Song? = null private var playbackQueue: List = emptyList() private var currentSongIndex = -1 private var shuffleEnabled = false @@ -57,9 +65,48 @@ class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) loadPlaylists() + connectPlaybackController() showPermissionOrLoad() } + private fun connectPlaybackController() { + val token = SessionToken(this, ComponentName(this, PlaybackService::class.java)) + val future = MediaController.Builder(this, token).buildAsync() + controllerFuture = future + future.addListener({ + try { + val controller = future.get() + if (isFinishing || isDestroyed) { + controller.release() + return@addListener + } + player = controller + controller.addListener(object : Player.Listener { + override fun onIsPlayingChanged(isPlaying: Boolean) { + updatePlayerControls() + } + + override fun onPlaybackStateChanged(playbackState: Int) { + updatePlayerControls() + if (playbackState == Player.STATE_ENDED && shuffleEnabled) { + playNextSong() + } + } + + override fun onPlayerError(error: androidx.media3.common.PlaybackException) { + toast("پخش این فایل ممکن نیست.") + } + }) + pendingSong?.let { + pendingSong = null + startSong(it) + } + } catch (_: Exception) { + toast("اتصال به سرویس پخش موسیقی برقرار نشد.") + } + }, java.util.concurrent.Executor { command -> runOnUiThread(command) }) + } + private fun showPermissionOrLoad() { val permission = if (Build.VERSION.SDK_INT >= 33) Manifest.permission.READ_MEDIA_AUDIO else Manifest.permission.READ_EXTERNAL_STORAGE @@ -363,38 +410,24 @@ class MainActivity : Activity() { } private fun startSong(song: Song) { + val controller = player + if (controller == null) { + pendingSong = song + return + } try { - // Detach callbacks before releasing the previous player so a late - // error from the old track cannot show a misleading message. - player?.setOnPreparedListener(null) - player?.setOnCompletionListener(null) - player?.setOnErrorListener(null) - player?.release() - - val newPlayer = MediaPlayer() - player = newPlayer - newPlayer.setOnPreparedListener { mp -> - if (player !== mp) return@setOnPreparedListener - try { - mp.start() - updatePlayerControls() - } catch (_: Exception) { - if (player === mp) toast("پخش این فایل ممکن نیست.") - } - } - newPlayer.setOnCompletionListener { mp -> - // Auto-advance only in shuffle mode. In normal mode, leave - // playback stopped at the end of the current track. - if (player === mp && shuffleEnabled) playNextSong() - } - newPlayer.setOnErrorListener { mp, _, _ -> - if (player === mp && currentSong?.id == song.id) { - toast("پخش این فایل ممکن نیست.") - } - true - } - newPlayer.setDataSource(this, song.uri) - newPlayer.prepareAsync() + val metadata = MediaMetadata.Builder() + .setTitle(song.title) + .setArtist(song.artist) + .build() + val item = MediaItem.Builder() + .setUri(song.uri) + .setMediaMetadata(metadata) + .build() + controller.setMediaItem(item) + controller.prepare() + controller.play() + updatePlayerControls() } catch (_: Exception) { toast("باز کردن فایل موسیقی ممکن نشد.") } @@ -454,10 +487,8 @@ class MainActivity : Activity() { override fun onProgressChanged(bar: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { val p = player ?: return - if (p.isPlaying || p.currentPosition >= 0) { - val duration = p.duration - if (duration > 0) p.seekTo(duration * progress / 1000) - } + val duration = p.duration + if (duration > 0) p.seekTo(duration * progress / 1000L) } } override fun onStartTrackingTouch(bar: SeekBar?) {} @@ -623,7 +654,12 @@ class MainActivity : Activity() { private fun togglePlayback() { val p = player ?: return try { - if (p.isPlaying) p.pause() else p.start() + if (p.isPlaying) { + p.pause() + } else { + if (p.playbackState == Player.STATE_ENDED) p.seekTo(0) + p.play() + } updatePlayerControls() } catch (_: Exception) {} } @@ -635,7 +671,7 @@ class MainActivity : Activity() { if (!playerScreenVisible) return try { val p = player - if (p != null && p.isPlaying && p.duration > 0) { + if (p != null && p.duration > 0) { seek.progress = (p.currentPosition * 1000L / p.duration).toInt() } } catch (_: Exception) {} @@ -716,5 +752,12 @@ class MainActivity : Activity() { } private fun toast(s: String) = Toast.makeText(this, s, Toast.LENGTH_SHORT).show() - override fun onDestroy() { uiHandler.removeCallbacksAndMessages(null); player?.release(); player = null; super.onDestroy() } + override fun onDestroy() { + uiHandler.removeCallbacksAndMessages(null) + pendingSong = null + player?.release() + player = null + controllerFuture = null + super.onDestroy() + } } From 0c0f7211cf3baab23c60a861d132a35699269fbb Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:00:37 +0330 Subject: [PATCH 05/70] Fix playback service player cleanup --- app/src/main/java/com/movemusic/app/PlaybackService.kt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/PlaybackService.kt b/app/src/main/java/com/movemusic/app/PlaybackService.kt index b1af25e..42dbac7 100644 --- a/app/src/main/java/com/movemusic/app/PlaybackService.kt +++ b/app/src/main/java/com/movemusic/app/PlaybackService.kt @@ -31,10 +31,8 @@ class PlaybackService : MediaSessionService() { } override fun onDestroy() { - mediaSession?.run { - player.release() - release() - } + mediaSession?.release() + player?.release() mediaSession = null player = null super.onDestroy() From 71f43dc9c58ebc10a7626aa23df8825d2da4f5db Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:01:10 +0330 Subject: [PATCH 06/70] Restore active track when reconnecting to playback service --- .../java/com/movemusic/app/MainActivity.kt | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 79dbf25..4f912be 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -96,17 +96,35 @@ class MainActivity : Activity() { override fun onPlayerError(error: androidx.media3.common.PlaybackException) { toast("پخش این فایل ممکن نیست.") } + + override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) { + restorePlaybackState() + } }) pendingSong?.let { pendingSong = null startSong(it) - } + } ?: restorePlaybackState() } catch (_: Exception) { toast("اتصال به سرویس پخش موسیقی برقرار نشد.") } }, java.util.concurrent.Executor { command -> runOnUiThread(command) }) } + private fun restorePlaybackState() { + val activeUri = player?.currentMediaItem?.localConfiguration?.uri ?: return + val song = songs.firstOrNull { it.uri == activeUri } ?: return + currentSong = song + if (playbackQueue.isEmpty()) playbackQueue = songs.toList() + currentSongIndex = playbackQueue.indexOfFirst { it.id == song.id } + miniPlayerHost?.let { host -> + host.removeAllViews() + host.visibility = View.VISIBLE + host.addView(buildMiniPlayerBar(), LinearLayout.LayoutParams(-1, -2)) + } + updatePlayerControls() + } + private fun showPermissionOrLoad() { val permission = if (Build.VERSION.SDK_INT >= 33) Manifest.permission.READ_MEDIA_AUDIO else Manifest.permission.READ_EXTERNAL_STORAGE @@ -164,6 +182,7 @@ class MainActivity : Activity() { songs.clear() songs.addAll(loadedSongs) displayedSongCount = 50 + restorePlaybackState() render() } } catch (e: Exception) { From 213fa72b7ab6e19d4e5a230a51e2b49814f9fc5a Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:01:16 +0330 Subject: [PATCH 07/70] Document background playback service --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 47a9a3c..2bff5a8 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,9 @@ A free, offline Android music-player starter project with a one-action **Move to - In a playlist, `انتقال به…` adds the selected track to the destination playlist and removes it from the source in the same operation. - Keeps the original audio file untouched. - Electric-blue on deep-black visual theme. +- Background playback managed by an AndroidX Media3 `MediaSessionService` and ExoPlayer. +- A media-session notification while playback is active, with system-managed playback controls. +- Audio-focus handling and automatic pause when headphones or Bluetooth audio devices are disconnected. ## Build Open this folder in Android Studio (Giraffe or newer), allow Gradle sync, then choose **Build > Build APK(s)**. @@ -15,4 +18,4 @@ Open this folder in Android Studio (Giraffe or newer), allow Gradle sync, then c Minimum Android: 8.0 (API 26). The project targets API 35. ## Important prototype limitation -Playlists are managed inside MoveMusic and do not modify playlists created by other music apps. This first prototype has basic playback and playlist management; background playback, notification/media controls, artwork, queue management, and robust error handling are not included yet. +Playlists are managed inside MoveMusic and do not modify playlists created by other music apps. Playback now runs in a foreground media service, so it can continue while the app is in the background or the screen is off. The media session provides the system media notification. Advanced queue editing, richer notification actions (such as app-managed next/previous controls), and comprehensive recovery from all playback errors remain future work. From 3cbc10c4dacdc6d17dbc8501e812372f84fcc21e Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:01:29 +0330 Subject: [PATCH 08/70] Release MediaController connection safely --- app/src/main/java/com/movemusic/app/MainActivity.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 4f912be..68fbd93 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -77,7 +77,7 @@ class MainActivity : Activity() { try { val controller = future.get() if (isFinishing || isDestroyed) { - controller.release() + MediaController.releaseFuture(future) return@addListener } player = controller @@ -774,7 +774,7 @@ class MainActivity : Activity() { override fun onDestroy() { uiHandler.removeCallbacksAndMessages(null) pendingSong = null - player?.release() + controllerFuture?.let { MediaController.releaseFuture(it) } player = null controllerFuture = null super.onDestroy() From 8248299bc0de9077cd8baa450087184f51a04ba9 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:01:45 +0330 Subject: [PATCH 09/70] Keep audio playback active with screen off --- app/src/main/java/com/movemusic/app/PlaybackService.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/src/main/java/com/movemusic/app/PlaybackService.kt b/app/src/main/java/com/movemusic/app/PlaybackService.kt index 42dbac7..4078f4d 100644 --- a/app/src/main/java/com/movemusic/app/PlaybackService.kt +++ b/app/src/main/java/com/movemusic/app/PlaybackService.kt @@ -2,6 +2,7 @@ package com.movemusic.app import android.content.Intent import androidx.media3.common.AudioAttributes +import androidx.media3.common.C import androidx.media3.exoplayer.ExoPlayer import androidx.media3.session.MediaSession import androidx.media3.session.MediaSessionService @@ -16,6 +17,7 @@ class PlaybackService : MediaSessionService() { val exoPlayer = ExoPlayer.Builder(this).build().apply { setAudioAttributes(AudioAttributes.DEFAULT, true) setHandleAudioBecomingNoisy(true) + setWakeMode(C.WAKE_MODE_LOCAL) } player = exoPlayer mediaSession = MediaSession.Builder(this, exoPlayer).build() From 0e5cfc4e3e21f2ba7faadc47be662190b0642615 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:02:01 +0330 Subject: [PATCH 10/70] Validate completed features on PR and release on main --- .github/workflows/build.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4ef91cc..a242de9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,7 +1,14 @@ name: Build and Release MoveMusic APK on: - # Build and publish only when explicitly requested after a feature is complete. + # Feature branches stay quiet while work is in progress. + # A completed PR is build-validated; merging to main publishes the release. + pull_request: + branches: + - main + push: + branches: + - main workflow_dispatch: jobs: From 421c9132a8ec8d12f2ee08c72f5bc61fe337b059 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:56:54 +0330 Subject: [PATCH 11/70] Provide full media queue for notification controls --- .../java/com/movemusic/app/MainActivity.kt | 60 +++++++++++-------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 68fbd93..32b06a6 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -88,9 +88,6 @@ class MainActivity : Activity() { override fun onPlaybackStateChanged(playbackState: Int) { updatePlayerControls() - if (playbackState == Player.STATE_ENDED && shuffleEnabled) { - playNextSong() - } } override fun onPlayerError(error: androidx.media3.common.PlaybackException) { @@ -117,10 +114,14 @@ class MainActivity : Activity() { currentSong = song if (playbackQueue.isEmpty()) playbackQueue = songs.toList() currentSongIndex = playbackQueue.indexOfFirst { it.id == song.id } - miniPlayerHost?.let { host -> - host.removeAllViews() - host.visibility = View.VISIBLE - host.addView(buildMiniPlayerBar(), LinearLayout.LayoutParams(-1, -2)) + if (playerScreenVisible) { + showPlayerScreen() + } else { + miniPlayerHost?.let { host -> + host.removeAllViews() + host.visibility = View.VISIBLE + host.addView(buildMiniPlayerBar(), LinearLayout.LayoutParams(-1, -2)) + } } updatePlayerControls() } @@ -435,15 +436,20 @@ class MainActivity : Activity() { return } try { - val metadata = MediaMetadata.Builder() - .setTitle(song.title) - .setArtist(song.artist) - .build() - val item = MediaItem.Builder() - .setUri(song.uri) - .setMediaMetadata(metadata) - .build() - controller.setMediaItem(item) + val items = playbackQueue.map { queuedSong -> + val metadata = MediaMetadata.Builder() + .setTitle(queuedSong.title) + .setArtist(queuedSong.artist) + .build() + MediaItem.Builder() + .setMediaId(queuedSong.id.toString()) + .setUri(queuedSong.uri) + .setMediaMetadata(metadata) + .build() + } + val selectedIndex = playbackQueue.indexOfFirst { it.id == song.id } + .takeIf { it >= 0 } ?: 0 + controller.setMediaItems(items, selectedIndex, 0L) controller.prepare() controller.play() updatePlayerControls() @@ -702,23 +708,25 @@ class MainActivity : Activity() { } private fun playPreviousSong() { + val controller = player ?: return if (playbackQueue.isEmpty() || currentSongIndex !in playbackQueue.indices) return - currentSongIndex = if (currentSongIndex <= 0) playbackQueue.lastIndex else currentSongIndex - 1 - currentSong = playbackQueue[currentSongIndex] - if (playerScreenVisible) showPlayerScreen() else render() - startSong(playbackQueue[currentSongIndex]) + if (shuffleEnabled && playbackQueue.size > 1) { + val target = (playbackQueue.indices.filter { it != currentSongIndex }).random() + controller.seekToMediaItem(target, 0L) + } else { + controller.seekToPreviousMediaItem() + } } private fun playNextSong(manual: Boolean = false) { + val controller = player ?: return if (playbackQueue.size < 2 || currentSongIndex !in playbackQueue.indices) return - currentSongIndex = if (shuffleEnabled) { - (playbackQueue.indices.filter { it != currentSongIndex }).random() + if (shuffleEnabled) { + val target = (playbackQueue.indices.filter { it != currentSongIndex }).random() + controller.seekToMediaItem(target, 0L) } else { - (currentSongIndex + 1) % playbackQueue.size + controller.seekToNextMediaItem() } - currentSong = playbackQueue[currentSongIndex] - if (playerScreenVisible) showPlayerScreen() else render() - startSong(playbackQueue[currentSongIndex]) } @Suppress("DEPRECATION") From 065acd33296d564064ff24c30b438c56b9999b5e Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:57:13 +0330 Subject: [PATCH 12/70] Reduce initial audio buffering delay --- app/src/main/java/com/movemusic/app/PlaybackService.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/PlaybackService.kt b/app/src/main/java/com/movemusic/app/PlaybackService.kt index 4078f4d..98c8893 100644 --- a/app/src/main/java/com/movemusic/app/PlaybackService.kt +++ b/app/src/main/java/com/movemusic/app/PlaybackService.kt @@ -4,6 +4,7 @@ import android.content.Intent import androidx.media3.common.AudioAttributes import androidx.media3.common.C import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.DefaultLoadControl import androidx.media3.session.MediaSession import androidx.media3.session.MediaSessionService @@ -14,7 +15,12 @@ class PlaybackService : MediaSessionService() { override fun onCreate() { super.onCreate() - val exoPlayer = ExoPlayer.Builder(this).build().apply { + val loadControl = DefaultLoadControl.Builder() + .setBufferDurationsMs(15_000, 50_000, 250, 500) + .build() + val exoPlayer = ExoPlayer.Builder(this) + .setLoadControl(loadControl) + .build().apply { setAudioAttributes(AudioAttributes.DEFAULT, true) setHandleAudioBecomingNoisy(true) setWakeMode(C.WAKE_MODE_LOCAL) From e37fcf7a300001b57772ab14bde029068e6ae0b4 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:57:16 +0330 Subject: [PATCH 13/70] Warm playback service and prepare queue off the UI thread --- .../java/com/movemusic/app/MainActivity.kt | 34 +++++++++++++------ 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 32b06a6..871c60f 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -45,6 +45,7 @@ class MainActivity : Activity() { private var player: MediaController? = null private var controllerFuture: ListenableFuture? = null private var pendingSong: Song? = null + private var playbackRequestToken = 0 private var playbackQueue: List = emptyList() private var currentSongIndex = -1 private var shuffleEnabled = false @@ -65,6 +66,7 @@ class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) loadPlaylists() + startService(Intent(this, PlaybackService::class.java)) connectPlaybackController() showPermissionOrLoad() } @@ -435,8 +437,15 @@ class MainActivity : Activity() { pendingSong = song return } - try { - val items = playbackQueue.map { queuedSong -> + val requestToken = ++playbackRequestToken + val queueSnapshot = playbackQueue.toList() + val selectedIndex = queueSnapshot.indexOfFirst { it.id == song.id } + .takeIf { it >= 0 } ?: 0 + + // Build potentially large playlists away from the UI thread. This + // prevents a long library from delaying the user's play request. + Thread { + val items = queueSnapshot.map { queuedSong -> val metadata = MediaMetadata.Builder() .setTitle(queuedSong.title) .setArtist(queuedSong.artist) @@ -447,15 +456,18 @@ class MainActivity : Activity() { .setMediaMetadata(metadata) .build() } - val selectedIndex = playbackQueue.indexOfFirst { it.id == song.id } - .takeIf { it >= 0 } ?: 0 - controller.setMediaItems(items, selectedIndex, 0L) - controller.prepare() - controller.play() - updatePlayerControls() - } catch (_: Exception) { - toast("باز کردن فایل موسیقی ممکن نشد.") - } + runOnUiThread { + if (requestToken != playbackRequestToken || player !== controller) return@runOnUiThread + try { + controller.setMediaItems(items, selectedIndex, 0L) + controller.prepare() + controller.play() + updatePlayerControls() + } catch (_: Exception) { + toast("باز کردن فایل موسیقی ممکن نشد.") + } + } + }.start() } private fun showPlayerScreen() { From 018e1a99b7975e6b422144be8ad3ad7453bf0ba7 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 20:57:31 +0330 Subject: [PATCH 14/70] Align feature workflow with manual release policy --- .github/workflows/build.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a242de9..4945920 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,14 +1,10 @@ name: Build and Release MoveMusic APK on: - # Feature branches stay quiet while work is in progress. - # A completed PR is build-validated; merging to main publishes the release. + # Validate completed pull requests without publishing an APK. pull_request: branches: - main - push: - branches: - - main workflow_dispatch: jobs: From 53e7152516091830f00a1f7fee6c25f53df61697 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 21:00:23 +0330 Subject: [PATCH 15/70] Fix Media3 controller compile errors --- app/src/main/java/com/movemusic/app/MainActivity.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 871c60f..3ea7056 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -5,6 +5,7 @@ import android.app.Activity import android.app.AlertDialog import android.content.ContentUris import android.content.ComponentName +import android.content.Intent import android.content.Context import android.content.pm.PackageManager import android.media.MediaMetadataRetriever @@ -724,7 +725,7 @@ class MainActivity : Activity() { if (playbackQueue.isEmpty() || currentSongIndex !in playbackQueue.indices) return if (shuffleEnabled && playbackQueue.size > 1) { val target = (playbackQueue.indices.filter { it != currentSongIndex }).random() - controller.seekToMediaItem(target, 0L) + controller.seekTo(target, 0L) } else { controller.seekToPreviousMediaItem() } From 5508968f0992262e8c1d2ee93880eb55fbb02bd8 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 21:02:52 +0330 Subject: [PATCH 16/70] Fix remaining unsupported MediaController seek call --- app/src/main/java/com/movemusic/app/MainActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 3ea7056..79da18b 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -736,7 +736,7 @@ class MainActivity : Activity() { if (playbackQueue.size < 2 || currentSongIndex !in playbackQueue.indices) return if (shuffleEnabled) { val target = (playbackQueue.indices.filter { it != currentSongIndex }).random() - controller.seekToMediaItem(target, 0L) + controller.seekTo(target, 0L) } else { controller.seekToNextMediaItem() } From 6ab9b450052020dd6740c81365732d1fe95a2816 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 21:12:14 +0330 Subject: [PATCH 17/70] Start selected track before building playback queue --- .../java/com/movemusic/app/MainActivity.kt | 62 +++++++++++++------ 1 file changed, 42 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 79da18b..06699ff 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -438,34 +438,56 @@ class MainActivity : Activity() { pendingSong = song return } + val requestToken = ++playbackRequestToken - val queueSnapshot = playbackQueue.toList() + val queueSnapshot = playbackQueue val selectedIndex = queueSnapshot.indexOfFirst { it.id == song.id } .takeIf { it >= 0 } ?: 0 - // Build potentially large playlists away from the UI thread. This - // prevents a long library from delaying the user's play request. + fun mediaItem(queuedSong: Song): MediaItem { + val metadata = MediaMetadata.Builder() + .setTitle(queuedSong.title) + .setArtist(queuedSong.artist) + .build() + return MediaItem.Builder() + .setMediaId(queuedSong.id.toString()) + .setUri(queuedSong.uri) + .setMediaMetadata(metadata) + .build() + } + + // Start the selected local file immediately. Never wait for the + // potentially large playlist to be converted into Media3 items. + try { + controller.setMediaItem(mediaItem(song)) + controller.prepare() + controller.play() + updatePlayerControls() + } catch (_: Exception) { + toast("باز کردن فایل موسیقی ممکن نشد.") + return + } + + // Populate the rest of the queue in the background while the selected + // track is already playing. Inserting before/after the current item + // preserves the active playback position. + if (queueSnapshot.size <= 1) return Thread { - val items = queueSnapshot.map { queuedSong -> - val metadata = MediaMetadata.Builder() - .setTitle(queuedSong.title) - .setArtist(queuedSong.artist) - .build() - MediaItem.Builder() - .setMediaId(queuedSong.id.toString()) - .setUri(queuedSong.uri) - .setMediaMetadata(metadata) - .build() - } + val previousItems = queueSnapshot.subList(0, selectedIndex).map(::mediaItem) + val nextItems = queueSnapshot.subList(selectedIndex + 1, queueSnapshot.size).map(::mediaItem) runOnUiThread { - if (requestToken != playbackRequestToken || player !== controller) return@runOnUiThread + if (requestToken != playbackRequestToken || player !== controller || + controller.currentMediaItem?.mediaId != song.id.toString()) return@runOnUiThread try { - controller.setMediaItems(items, selectedIndex, 0L) - controller.prepare() - controller.play() - updatePlayerControls() + if (previousItems.isNotEmpty()) { + controller.addMediaItems(0, previousItems) + } + if (nextItems.isNotEmpty()) { + controller.addMediaItems(controller.currentMediaItemIndex + 1, nextItems) + } } catch (_: Exception) { - toast("باز کردن فایل موسیقی ممکن نشد.") + // The current track is already playing; queue enrichment + // must never interrupt it. } } }.start() From 8a3a0e2bf3e56eced6aba484d997400fcaa0ba1c Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 21:32:14 +0330 Subject: [PATCH 18/70] Make playback controls respond immediately and reduce tap overhead --- .../main/java/com/movemusic/app/MainActivity.kt | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 06699ff..37ed159 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -114,11 +114,14 @@ class MainActivity : Activity() { private fun restorePlaybackState() { val activeUri = player?.currentMediaItem?.localConfiguration?.uri ?: return val song = songs.firstOrNull { it.uri == activeUri } ?: return + val songChanged = currentSong?.id != song.id currentSong = song - if (playbackQueue.isEmpty()) playbackQueue = songs.toList() + if (playbackQueue.isEmpty()) playbackQueue = songs currentSongIndex = playbackQueue.indexOfFirst { it.id == song.id } if (playerScreenVisible) { - showPlayerScreen() + // Avoid rebuilding the screen for the initial transition of the + // track that is already displayed. + if (songChanged) showPlayerScreen() } else { miniPlayerHost?.let { host -> host.removeAllViews() @@ -419,7 +422,8 @@ class MainActivity : Activity() { private fun play(song: Song) { playbackQueue = if (currentPlaylist == "همه آهنگ‌ها") { - songs.toList() + // Reuse the loaded library instead of copying it on every tap. + songs } else { // Use a hash set for membership checks. List.contains() here made // playlist startup increasingly slow as both library and playlist grew. @@ -705,7 +709,12 @@ class MainActivity : Activity() { } private fun updatePlayerControls() { - val icon = if (player?.isPlaying == true) android.R.drawable.ic_media_pause + val activePlayer = player + // Update optimistically from playWhenReady so the icon follows the + // user's command instead of waiting for decoder startup. + val shouldShowPause = activePlayer?.playWhenReady == true && + activePlayer.playbackState != Player.STATE_ENDED + val icon = if (shouldShowPause) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play playPauseButton?.setImageResource(icon) miniPlayPauseButton?.setImageResource(icon) From 91412743c03fd995958e63cdfdf34af5ffa086bc Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 21:54:39 +0330 Subject: [PATCH 19/70] Cache and downsample artwork; streamline back navigation --- .../java/com/movemusic/app/MainActivity.kt | 53 ++++++++++++++----- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 37ed159..f43fcb8 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -10,6 +10,9 @@ import android.content.Context import android.content.pm.PackageManager import android.media.MediaMetadataRetriever import android.graphics.BitmapFactory +import android.graphics.Bitmap +import android.util.LruCache +import java.util.concurrent.Executors import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.net.Uri @@ -63,6 +66,11 @@ class MainActivity : Activity() { private var songScrollView: ScrollView? = null private var isLoadingNextPage = false private var hasMoreSongs = false + private val artworkExecutor = Executors.newFixedThreadPool(2) + private val artworkCache = object : LruCache((Runtime.getRuntime().maxMemory() / 1024 / 8).toInt()) { + override fun sizeOf(key: Long, value: Bitmap): Int = value.byteCount / 1024 + } + private var artworkRequestToken = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -668,26 +676,41 @@ class MainActivity : Activity() { } private fun loadSongArtwork(song: Song, target: ImageView) { - Thread { - var bitmap: android.graphics.Bitmap? = null + val requestToken = ++artworkRequestToken + artworkCache.get(song.id)?.let { cached -> + target.setImageBitmap(cached) + target.scaleType = ImageView.ScaleType.CENTER_CROP + return + } + artworkExecutor.execute { + var bitmap: Bitmap? = null + var retriever: MediaMetadataRetriever? = null try { - val retriever = MediaMetadataRetriever() + retriever = MediaMetadataRetriever() retriever.setDataSource(this, song.uri) val bytes = retriever.embeddedPicture - if (bytes != null) bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) - retriever.release() - } catch (_: Exception) {} + if (bytes != null) { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + val targetSize = (resources.displayMetrics.widthPixels * 0.78f).toInt() + var sample = 1 + while (bounds.outWidth / (sample * 2) >= targetSize && bounds.outHeight / (sample * 2) >= targetSize) sample *= 2 + bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample }) + bitmap?.let { artworkCache.put(song.id, it) } + } + } catch (_: Exception) { + } finally { + try { retriever?.release() } catch (_: Exception) {} + } + val result = bitmap runOnUiThread { - if (playerScreenVisible && currentSong?.id == song.id && bitmap != null) { - target.setImageBitmap(bitmap) - } else if (bitmap == null && playerScreenVisible && currentSong?.id == song.id) { - target.setImageResource(android.R.drawable.ic_media_play) - target.scaleType = ImageView.ScaleType.CENTER + if (!isFinishing && playerScreenVisible && artworkRequestToken == requestToken && currentSong?.id == song.id) { + if (result != null) { target.setImageBitmap(result); target.scaleType = ImageView.ScaleType.CENTER_CROP } + else { target.setImageResource(android.R.drawable.ic_media_play); target.scaleType = ImageView.ScaleType.CENTER } } } - }.start() + } } - private fun playerControl(iconRes: Int, size: Int, action: () -> Unit): ImageButton = ImageButton(this).apply { setImageResource(iconRes) @@ -783,6 +806,7 @@ class MainActivity : Activity() { miniPlayPauseButton = null // Restore the existing home view instead of rebuilding every song row. // This preserves the exact scroll position and avoids a long UI-thread pass. + homeRoot?.let { setContentView(it) } ?: render() miniPlayerHost?.let { host -> host.removeAllViews() if (currentSong != null) { @@ -792,7 +816,6 @@ class MainActivity : Activity() { host.visibility = View.GONE } } - homeRoot?.let { setContentView(it) } ?: render() } else { super.onBackPressed() } @@ -825,6 +848,8 @@ class MainActivity : Activity() { private fun toast(s: String) = Toast.makeText(this, s, Toast.LENGTH_SHORT).show() override fun onDestroy() { uiHandler.removeCallbacksAndMessages(null) + artworkExecutor.shutdownNow() + artworkCache.evictAll() pendingSong = null controllerFuture?.let { MediaController.releaseFuture(it) } player = null From 2c0cec408405f05eaf6e6936b3550ca06cff711e Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:10:35 +0330 Subject: [PATCH 20/70] Improve album artwork loading and caching --- .../java/com/movemusic/app/MainActivity.kt | 141 +++++++++++++++--- 1 file changed, 117 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index f43fcb8..bdd1491 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -12,7 +12,12 @@ import android.media.MediaMetadataRetriever import android.graphics.BitmapFactory import android.graphics.Bitmap import android.util.LruCache -import java.util.concurrent.Executors +import java.io.File +import java.io.FileOutputStream +import java.util.concurrent.Future +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.net.Uri @@ -33,7 +38,7 @@ import androidx.media3.session.MediaController import androidx.media3.session.SessionToken import com.google.common.util.concurrent.ListenableFuture -data class Song(val id: Long, val title: String, val artist: String, val uri: Uri) +data class Song(val id: Long, val title: String, val artist: String, val albumId: Long, val uri: Uri) class MainActivity : Activity() { private val blue = 0xFF168BFF.toInt() @@ -66,11 +71,21 @@ class MainActivity : Activity() { private var songScrollView: ScrollView? = null private var isLoadingNextPage = false private var hasMoreSongs = false - private val artworkExecutor = Executors.newFixedThreadPool(2) - private val artworkCache = object : LruCache((Runtime.getRuntime().maxMemory() / 1024 / 8).toInt()) { - override fun sizeOf(key: Long, value: Bitmap): Int = value.byteCount / 1024 + // A small bounded worker pool prevents rapid track changes from building + // an unbounded queue of slow metadata-extraction jobs. + private val artworkExecutor = ThreadPoolExecutor( + 2, 2, 0L, TimeUnit.MILLISECONDS, + LinkedBlockingQueue(2), + ThreadPoolExecutor.DiscardOldestPolicy() + ) + private val artworkCache = object : LruCache( + (Runtime.getRuntime().maxMemory() / 1024 / 8).toInt().coerceAtLeast(1024) + ) { + override fun sizeOf(key: String, value: Bitmap): Int = (value.byteCount / 1024).coerceAtLeast(1) } + private val artworkCacheDir by lazy { File(cacheDir, "artwork").apply { mkdirs() } } private var artworkRequestToken = 0 + private var artworkTask: Future<*>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -169,6 +184,7 @@ class MainActivity : Activity() { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, + MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.IS_MUSIC ) contentResolver.query( @@ -181,6 +197,7 @@ class MainActivity : Activity() { val idCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID) val titleCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE) val artistCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST) + val albumIdCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID) while (cursor.moveToNext()) { val id = cursor.getLong(idCol) loadedSongs.add( @@ -188,6 +205,7 @@ class MainActivity : Activity() { id, cursor.getString(titleCol) ?: "بدون عنوان", cursor.getString(artistCol) ?: "هنرمند نامشخص", + cursor.getLong(albumIdCol), ContentUris.withAppendedId(collection, id) ) ) @@ -675,38 +693,112 @@ class MainActivity : Activity() { setOnClickListener { action() } } + private fun artworkKey(song: Song): String = + if (song.albumId > 0L) "album_${song.albumId}" else "song_${song.id}" + + private fun decodeArtwork(bytes: ByteArray, targetSize: Int): Bitmap? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null + + // Decode close to the rendered size; CENTER_CROP handles the final fit. + var sample = 1 + while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= targetSize) { + sample *= 2 + } + return BitmapFactory.decodeByteArray( + bytes, 0, bytes.size, + BitmapFactory.Options().apply { + inSampleSize = sample + inPreferredConfig = Bitmap.Config.RGB_565 + } + ) + } + + private fun readArtworkBytes(song: Song): ByteArray? { + // Android's MediaStore album-art provider is much cheaper than opening + // and parsing the whole audio file with MediaMetadataRetriever. + if (song.albumId > 0L) { + val albumArtUri = Uri.parse("content://media/external/audio/albumart/${song.albumId}") + try { + contentResolver.openInputStream(albumArtUri)?.use { return it.readBytes() } + } catch (_: Exception) { + // Some devices do not expose album art through this provider. + } + } + + // Fallback for files whose artwork is embedded but not indexed by MediaStore. + var retriever: MediaMetadataRetriever? = null + return try { + retriever = MediaMetadataRetriever() + retriever.setDataSource(this, song.uri) + retriever.embeddedPicture + } catch (_: Exception) { + null + } finally { + try { retriever?.release() } catch (_: Exception) {} + } + } + private fun loadSongArtwork(song: Song, target: ImageView) { val requestToken = ++artworkRequestToken - artworkCache.get(song.id)?.let { cached -> + val key = artworkKey(song) + target.tag = requestToken + artworkCache.get(key)?.let { cached -> target.setImageBitmap(cached) target.scaleType = ImageView.ScaleType.CENTER_CROP return } - artworkExecutor.execute { + + // Cancel obsolete work before submitting the newest request. This is + // important when users skip through tracks quickly. + artworkTask?.cancel(true) + val requestedSize = (resources.displayMetrics.widthPixels * 0.78f).toInt().coerceAtLeast(1) + artworkTask = artworkExecutor.submit { var bitmap: Bitmap? = null - var retriever: MediaMetadataRetriever? = null try { - retriever = MediaMetadataRetriever() - retriever.setDataSource(this, song.uri) - val bytes = retriever.embeddedPicture - if (bytes != null) { - val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) - val targetSize = (resources.displayMetrics.widthPixels * 0.78f).toInt() - var sample = 1 - while (bounds.outWidth / (sample * 2) >= targetSize && bounds.outHeight / (sample * 2) >= targetSize) sample *= 2 - bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample }) - bitmap?.let { artworkCache.put(song.id, it) } + val diskFile = File(artworkCacheDir, "$key.img") + if (diskFile.isFile && diskFile.length() > 0L) { + bitmap = decodeArtwork(diskFile.readBytes(), requestedSize) } + + if (bitmap == null) { + val bytes = readArtworkBytes(song) + if (bytes != null && bytes.isNotEmpty()) { + bitmap = decodeArtwork(bytes, requestedSize) + if (bitmap != null) { + val tempFile = File(artworkCacheDir, "$key.tmp") + try { + FileOutputStream(tempFile).use { it.write(bytes) } + val finalFile = File(artworkCacheDir, "$key.img") + if (!tempFile.renameTo(finalFile)) { + tempFile.copyTo(finalFile, overwrite = true) + tempFile.delete() + } + } catch (_: Exception) { + tempFile.delete() + } + } + } + } + + if (Thread.currentThread().isInterrupted) return@submit + bitmap?.let { artworkCache.put(key, it) } } catch (_: Exception) { - } finally { - try { retriever?.release() } catch (_: Exception) {} + bitmap = null } + val result = bitmap runOnUiThread { - if (!isFinishing && playerScreenVisible && artworkRequestToken == requestToken && currentSong?.id == song.id) { - if (result != null) { target.setImageBitmap(result); target.scaleType = ImageView.ScaleType.CENTER_CROP } - else { target.setImageResource(android.R.drawable.ic_media_play); target.scaleType = ImageView.ScaleType.CENTER } + if (!isFinishing && !isDestroyed && target.tag == requestToken && + artworkRequestToken == requestToken && currentSong?.id == song.id) { + if (result != null) { + target.setImageBitmap(result) + target.scaleType = ImageView.ScaleType.CENTER_CROP + } else { + target.setImageResource(android.R.drawable.ic_media_play) + target.scaleType = ImageView.ScaleType.CENTER + } } } } @@ -848,6 +940,7 @@ class MainActivity : Activity() { private fun toast(s: String) = Toast.makeText(this, s, Toast.LENGTH_SHORT).show() override fun onDestroy() { uiHandler.removeCallbacksAndMessages(null) + artworkTask?.cancel(true) artworkExecutor.shutdownNow() artworkCache.evictAll() pendingSong = null From f1f7ce808c2b5ee1bf939b6585558d3888e716f3 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:10:48 +0330 Subject: [PATCH 21/70] Run APK workflow only on manual request --- .github/workflows/build.yml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4945920..e0a3589 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,10 +1,7 @@ name: Build and Release MoveMusic APK on: - # Validate completed pull requests without publishing an APK. - pull_request: - branches: - - main + # Build/release only when explicitly requested after the feature is complete. workflow_dispatch: jobs: @@ -52,7 +49,7 @@ jobs: release: name: Publish GitHub Release needs: build - if: github.event_name != 'pull_request' + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest permissions: contents: write From 97aa628ae13143b558919deb68c8703e12b83f62 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:11:02 +0330 Subject: [PATCH 22/70] Add embedded artwork fallback for invalid album art --- .../java/com/movemusic/app/MainActivity.kt | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index bdd1491..1585f39 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -718,15 +718,17 @@ class MainActivity : Activity() { private fun readArtworkBytes(song: Song): ByteArray? { // Android's MediaStore album-art provider is much cheaper than opening // and parsing the whole audio file with MediaMetadataRetriever. - if (song.albumId > 0L) { - val albumArtUri = Uri.parse("content://media/external/audio/albumart/${song.albumId}") - try { - contentResolver.openInputStream(albumArtUri)?.use { return it.readBytes() } - } catch (_: Exception) { - // Some devices do not expose album art through this provider. - } + if (song.albumId <= 0L) return null + val albumArtUri = Uri.parse("content://media/external/audio/albumart/${song.albumId}") + return try { + contentResolver.openInputStream(albumArtUri)?.use { it.readBytes() } + } catch (_: Exception) { + // Some devices do not expose album art through this provider. + null } + } + private fun readEmbeddedArtworkBytes(song: Song): ByteArray? { // Fallback for files whose artwork is embedded but not indexed by MediaStore. var retriever: MediaMetadataRetriever? = null return try { @@ -763,11 +765,16 @@ class MainActivity : Activity() { } if (bitmap == null) { - val bytes = readArtworkBytes(song) - if (bytes != null && bytes.isNotEmpty()) { - bitmap = decodeArtwork(bytes, requestedSize) - if (bitmap != null) { - val tempFile = File(artworkCacheDir, "$key.tmp") + var bytes = readArtworkBytes(song) + bitmap = bytes?.takeIf { it.isNotEmpty() }?.let { decodeArtwork(it, requestedSize) } + if (bitmap == null) { + // If MediaStore returned an unreadable image, try the + // original file's embedded artwork before giving up. + bytes = readEmbeddedArtworkBytes(song) + bitmap = bytes?.takeIf { it.isNotEmpty() }?.let { decodeArtwork(it, requestedSize) } + } + if (bitmap != null && bytes != null) { + val tempFile = File(artworkCacheDir, "$key.tmp") try { FileOutputStream(tempFile).use { it.write(bytes) } val finalFile = File(artworkCacheDir, "$key.img") From a94f34a0a17162b0e5c203eb33faddfc08128880 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:11:06 +0330 Subject: [PATCH 23/70] Add multi-layer artwork loading and caching --- .../java/com/movemusic/app/ArtworkLoader.kt | 136 ++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 app/src/main/java/com/movemusic/app/ArtworkLoader.kt diff --git a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt new file mode 100644 index 0000000..b97517b --- /dev/null +++ b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt @@ -0,0 +1,136 @@ +package com.movemusic.app + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.media.MediaMetadataRetriever +import android.net.Uri +import android.provider.MediaStore +import android.util.LruCache +import java.io.File +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.Executors + +/** + * Artwork pipeline: memory cache -> persistent disk cache -> MediaStore album + * artwork -> embedded artwork fallback. All I/O and decoding stay off the UI + * thread, and simultaneous requests for one album share a single decode. + */ +internal class ArtworkLoader(context: Context) { + private val appContext = context.applicationContext + private val diskDirectory = File(appContext.cacheDir, "artwork").apply { mkdirs() } + private val executor = Executors.newFixedThreadPool(2) + private val memoryCache = object : LruCache( + (Runtime.getRuntime().maxMemory() / 1024 / 8).toInt() + ) { + override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount / 1024 + } + private val pending = ConcurrentHashMap Unit>>() + + fun load(song: Song, targetSize: Int, callback: (Bitmap?) -> Unit) { + val key = if (song.albumId > 0) "album_\${song.albumId}" else "song_\${song.id}" + memoryCache.get(key)?.let { callback(it); return } + + var shouldStart = false + synchronized(pending) { + val listeners = pending[key] + if (listeners != null) listeners.add(callback) + else { + pending[key] = mutableListOf(callback) + shouldStart = true + } + } + if (!shouldStart) return + + executor.execute { + val bitmap = try { + loadFromDisk(key, targetSize) + ?: loadFromMediaStore(song.albumId, targetSize) + ?: loadEmbedded(song, targetSize) + } catch (_: Exception) { null } + + if (bitmap != null) { + memoryCache.put(key, bitmap) + saveToDisk(key, bitmap) + } + val listeners = synchronized(pending) { pending.remove(key).orEmpty() } + listeners.forEach { listener -> try { listener(bitmap) } catch (_: Exception) {} } + } + } + + private fun loadFromDisk(key: String, targetSize: Int): Bitmap? { + val file = File(diskDirectory, "$key.webp") + if (!file.isFile || file.length() == 0L) return null + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeFile(file.absolutePath, bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null + return BitmapFactory.decodeFile(file.absolutePath, BitmapFactory.Options().apply { + inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, targetSize) + inPreferredConfig = Bitmap.Config.RGB_565 + }) + } + + private fun loadFromMediaStore(albumId: Long, targetSize: Int): Bitmap? { + if (albumId <= 0) return null + val uri = Uri.parse("content://media/external/audio/albumart/$albumId") + val bytes = appContext.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: return null + return decode(bytes, targetSize) + } + + private fun loadEmbedded(song: Song, targetSize: Int): Bitmap? { + val retriever = MediaMetadataRetriever() + return try { + retriever.setDataSource(appContext, song.uri) + retriever.embeddedPicture?.let { decode(it, targetSize) } + } finally { + try { retriever.release() } catch (_: Exception) {} + } + } + + private fun decode(bytes: ByteArray, targetSize: Int): Bitmap? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null + return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { + inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, targetSize) + inPreferredConfig = Bitmap.Config.RGB_565 + }) + } + + private fun sampleSize(width: Int, height: Int, targetSize: Int): Int { + var sample = 1 + while (maxOf(width, height) / (sample * 2) >= targetSize) sample *= 2 + return sample + } + + private fun saveToDisk(key: String, bitmap: Bitmap) { + try { + val file = File(diskDirectory, "$key.webp") + val temp = File(diskDirectory, "$key.tmp") + temp.outputStream().use { bitmap.compress(Bitmap.CompressFormat.WEBP, 92, it) } + if (!temp.renameTo(file)) { + temp.copyTo(file, overwrite = true) + temp.delete() + } + trimDiskCache() + } catch (_: Exception) {} + } + + private fun trimDiskCache() { + val files = diskDirectory.listFiles()?.filter { it.isFile } ?: return + var total = files.sumOf { it.length() } + val maxBytes = 64L * 1024L * 1024L + if (total <= maxBytes) return + files.sortedBy { it.lastModified() }.forEach { file -> + if (total <= maxBytes) return + val size = file.length() + if (file.delete()) total -= size + } + } + + fun close() { + executor.shutdownNow() + memoryCache.evictAll() + synchronized(pending) { pending.clear() } + } +} From f599ef19f6c6cb1b78a64b06172d92fffb44dc51 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:11:09 +0330 Subject: [PATCH 24/70] Integrate album-aware artwork pipeline --- .../java/com/movemusic/app/MainActivity.kt | 65 +++---------------- 1 file changed, 9 insertions(+), 56 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 1585f39..05f4d4b 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -744,63 +744,16 @@ class MainActivity : Activity() { private fun loadSongArtwork(song: Song, target: ImageView) { val requestToken = ++artworkRequestToken - val key = artworkKey(song) - target.tag = requestToken - artworkCache.get(key)?.let { cached -> - target.setImageBitmap(cached) - target.scaleType = ImageView.ScaleType.CENTER_CROP - return - } - - // Cancel obsolete work before submitting the newest request. This is - // important when users skip through tracks quickly. - artworkTask?.cancel(true) - val requestedSize = (resources.displayMetrics.widthPixels * 0.78f).toInt().coerceAtLeast(1) - artworkTask = artworkExecutor.submit { - var bitmap: Bitmap? = null - try { - val diskFile = File(artworkCacheDir, "$key.img") - if (diskFile.isFile && diskFile.length() > 0L) { - bitmap = decodeArtwork(diskFile.readBytes(), requestedSize) - } - - if (bitmap == null) { - var bytes = readArtworkBytes(song) - bitmap = bytes?.takeIf { it.isNotEmpty() }?.let { decodeArtwork(it, requestedSize) } - if (bitmap == null) { - // If MediaStore returned an unreadable image, try the - // original file's embedded artwork before giving up. - bytes = readEmbeddedArtworkBytes(song) - bitmap = bytes?.takeIf { it.isNotEmpty() }?.let { decodeArtwork(it, requestedSize) } - } - if (bitmap != null && bytes != null) { - val tempFile = File(artworkCacheDir, "$key.tmp") - try { - FileOutputStream(tempFile).use { it.write(bytes) } - val finalFile = File(artworkCacheDir, "$key.img") - if (!tempFile.renameTo(finalFile)) { - tempFile.copyTo(finalFile, overwrite = true) - tempFile.delete() - } - } catch (_: Exception) { - tempFile.delete() - } - } - } - } + target.setImageResource(android.R.drawable.ic_media_play) + target.scaleType = ImageView.ScaleType.CENTER + val targetSize = (resources.displayMetrics.widthPixels * 0.78f).toInt().coerceAtLeast(256) - if (Thread.currentThread().isInterrupted) return@submit - bitmap?.let { artworkCache.put(key, it) } - } catch (_: Exception) { - bitmap = null - } - - val result = bitmap + artworkLoader.load(song, targetSize) { bitmap -> runOnUiThread { - if (!isFinishing && !isDestroyed && target.tag == requestToken && + if (!isFinishing && !isDestroyed && playerScreenVisible && artworkRequestToken == requestToken && currentSong?.id == song.id) { - if (result != null) { - target.setImageBitmap(result) + if (bitmap != null) { + target.setImageBitmap(bitmap) target.scaleType = ImageView.ScaleType.CENTER_CROP } else { target.setImageResource(android.R.drawable.ic_media_play) @@ -810,6 +763,7 @@ class MainActivity : Activity() { } } } + private fun playerControl(iconRes: Int, size: Int, action: () -> Unit): ImageButton = ImageButton(this).apply { setImageResource(iconRes) @@ -948,8 +902,7 @@ class MainActivity : Activity() { override fun onDestroy() { uiHandler.removeCallbacksAndMessages(null) artworkTask?.cancel(true) - artworkExecutor.shutdownNow() - artworkCache.evictAll() + if (artworkLoaderDelegate.isInitialized()) artworkLoader.close() pendingSong = null controllerFuture?.let { MediaController.releaseFuture(it) } player = null From db2dd32148f670e59a341dd6384150c386a510e8 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:11:33 +0330 Subject: [PATCH 25/70] Consolidate artwork loading through repository --- .../java/com/movemusic/app/MainActivity.kt | 76 +------------------ 1 file changed, 2 insertions(+), 74 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 05f4d4b..b827126 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -8,16 +8,6 @@ import android.content.ComponentName import android.content.Intent import android.content.Context import android.content.pm.PackageManager -import android.media.MediaMetadataRetriever -import android.graphics.BitmapFactory -import android.graphics.Bitmap -import android.util.LruCache -import java.io.File -import java.io.FileOutputStream -import java.util.concurrent.Future -import java.util.concurrent.LinkedBlockingQueue -import java.util.concurrent.ThreadPoolExecutor -import java.util.concurrent.TimeUnit import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.net.Uri @@ -71,21 +61,9 @@ class MainActivity : Activity() { private var songScrollView: ScrollView? = null private var isLoadingNextPage = false private var hasMoreSongs = false - // A small bounded worker pool prevents rapid track changes from building - // an unbounded queue of slow metadata-extraction jobs. - private val artworkExecutor = ThreadPoolExecutor( - 2, 2, 0L, TimeUnit.MILLISECONDS, - LinkedBlockingQueue(2), - ThreadPoolExecutor.DiscardOldestPolicy() - ) - private val artworkCache = object : LruCache( - (Runtime.getRuntime().maxMemory() / 1024 / 8).toInt().coerceAtLeast(1024) - ) { - override fun sizeOf(key: String, value: Bitmap): Int = (value.byteCount / 1024).coerceAtLeast(1) - } - private val artworkCacheDir by lazy { File(cacheDir, "artwork").apply { mkdirs() } } + private val artworkLoaderDelegate = lazy { ArtworkLoader(this) } + private val artworkLoader by artworkLoaderDelegate private var artworkRequestToken = 0 - private var artworkTask: Future<*>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -693,55 +671,6 @@ class MainActivity : Activity() { setOnClickListener { action() } } - private fun artworkKey(song: Song): String = - if (song.albumId > 0L) "album_${song.albumId}" else "song_${song.id}" - - private fun decodeArtwork(bytes: ByteArray, targetSize: Int): Bitmap? { - val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) - if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null - - // Decode close to the rendered size; CENTER_CROP handles the final fit. - var sample = 1 - while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= targetSize) { - sample *= 2 - } - return BitmapFactory.decodeByteArray( - bytes, 0, bytes.size, - BitmapFactory.Options().apply { - inSampleSize = sample - inPreferredConfig = Bitmap.Config.RGB_565 - } - ) - } - - private fun readArtworkBytes(song: Song): ByteArray? { - // Android's MediaStore album-art provider is much cheaper than opening - // and parsing the whole audio file with MediaMetadataRetriever. - if (song.albumId <= 0L) return null - val albumArtUri = Uri.parse("content://media/external/audio/albumart/${song.albumId}") - return try { - contentResolver.openInputStream(albumArtUri)?.use { it.readBytes() } - } catch (_: Exception) { - // Some devices do not expose album art through this provider. - null - } - } - - private fun readEmbeddedArtworkBytes(song: Song): ByteArray? { - // Fallback for files whose artwork is embedded but not indexed by MediaStore. - var retriever: MediaMetadataRetriever? = null - return try { - retriever = MediaMetadataRetriever() - retriever.setDataSource(this, song.uri) - retriever.embeddedPicture - } catch (_: Exception) { - null - } finally { - try { retriever?.release() } catch (_: Exception) {} - } - } - private fun loadSongArtwork(song: Song, target: ImageView) { val requestToken = ++artworkRequestToken target.setImageResource(android.R.drawable.ic_media_play) @@ -901,7 +830,6 @@ class MainActivity : Activity() { private fun toast(s: String) = Toast.makeText(this, s, Toast.LENGTH_SHORT).show() override fun onDestroy() { uiHandler.removeCallbacksAndMessages(null) - artworkTask?.cancel(true) if (artworkLoaderDelegate.isInitialized()) artworkLoader.close() pendingSong = null controllerFuture?.let { MediaController.releaseFuture(it) } From 6e7ba684f586237d7fd3be72ce625878b35d5baa Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:11:36 +0330 Subject: [PATCH 26/70] Fix artwork cache keys From 2c1f30a974b7843dc0d94a3658e6aa4b46ebe278 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:11:57 +0330 Subject: [PATCH 27/70] Optimize artwork delivery and cache key --- app/src/main/java/com/movemusic/app/ArtworkLoader.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt index b97517b..ec16086 100644 --- a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt +++ b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt @@ -49,12 +49,12 @@ internal class ArtworkLoader(context: Context) { ?: loadEmbedded(song, targetSize) } catch (_: Exception) { null } - if (bitmap != null) { - memoryCache.put(key, bitmap) - saveToDisk(key, bitmap) - } + if (bitmap != null) memoryCache.put(key, bitmap) val listeners = synchronized(pending) { pending.remove(key).orEmpty() } + // Deliver as soon as decoding finishes; disk persistence must not + // delay the visible cover on the main thread. listeners.forEach { listener -> try { listener(bitmap) } catch (_: Exception) {} } + if (bitmap != null) saveToDisk(key, bitmap) } } From 4aab2ea0fc0b16e38b831dc17651042f300674fd Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:12:23 +0330 Subject: [PATCH 28/70] Correct album artwork cache key interpolation --- app/src/main/java/com/movemusic/app/ArtworkLoader.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt index ec16086..d711cd3 100644 --- a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt +++ b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt @@ -28,7 +28,7 @@ internal class ArtworkLoader(context: Context) { private val pending = ConcurrentHashMap Unit>>() fun load(song: Song, targetSize: Int, callback: (Bitmap?) -> Unit) { - val key = if (song.albumId > 0) "album_\${song.albumId}" else "song_\${song.id}" + val key = if (song.albumId > 0) "album_${song.albumId}" else "song_${song.id}" memoryCache.get(key)?.let { callback(it); return } var shouldStart = false From 8c690a692b3d3a1b9bea7aaa581e0ffe293ff04e Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:12:27 +0330 Subject: [PATCH 29/70] Prioritize current artwork requests --- .../java/com/movemusic/app/ArtworkLoader.kt | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt index d711cd3..e656b33 100644 --- a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt +++ b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt @@ -9,7 +9,9 @@ import android.provider.MediaStore import android.util.LruCache import java.io.File import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.Executors +import java.util.concurrent.LinkedBlockingDeque +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit /** * Artwork pipeline: memory cache -> persistent disk cache -> MediaStore album @@ -19,7 +21,14 @@ import java.util.concurrent.Executors internal class ArtworkLoader(context: Context) { private val appContext = context.applicationContext private val diskDirectory = File(appContext.cacheDir, "artwork").apply { mkdirs() } - private val executor = Executors.newFixedThreadPool(2) + // Keep at most the currently requested album queued. Rapid track skipping + // must not leave a long tail of obsolete artwork decodes ahead of the UI. + private val executor = ThreadPoolExecutor( + 2, 2, 0L, TimeUnit.MILLISECONDS, LinkedBlockingDeque() + ) + private inner class ArtworkTask(val key: String, val work: () -> Unit) : Runnable { + override fun run() = work() + } private val memoryCache = object : LruCache( (Runtime.getRuntime().maxMemory() / 1024 / 8).toInt() ) { @@ -34,15 +43,25 @@ internal class ArtworkLoader(context: Context) { var shouldStart = false synchronized(pending) { val listeners = pending[key] - if (listeners != null) listeners.add(callback) - else { + if (listeners != null) { + listeners.add(callback) + } else { + // Remove queued jobs for albums that are no longer displayed. + // Already-running decodes are allowed to finish and populate cache. + val obsoleteKeys = pending.keys.filter { it != key } + obsoleteKeys.forEach { obsoleteKey -> + pending.remove(obsoleteKey) + executor.queue.removeIf { task -> + task is ArtworkTask && task.key == obsoleteKey + } + } pending[key] = mutableListOf(callback) shouldStart = true } } if (!shouldStart) return - executor.execute { + executor.execute(ArtworkTask(key) { val bitmap = try { loadFromDisk(key, targetSize) ?: loadFromMediaStore(song.albumId, targetSize) @@ -55,7 +74,7 @@ internal class ArtworkLoader(context: Context) { // delay the visible cover on the main thread. listeners.forEach { listener -> try { listener(bitmap) } catch (_: Exception) {} } if (bitmap != null) saveToDisk(key, bitmap) - } + }) } private fun loadFromDisk(key: String, targetSize: Int): Bitmap? { From f8ad8315b24adac9bef6da034d6d1ef3b17b3fca Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:28:47 +0330 Subject: [PATCH 30/70] Add prioritized artwork prefetch support --- .../java/com/movemusic/app/ArtworkLoader.kt | 62 ++++++++++++++----- 1 file changed, 46 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt index e656b33..8783f1f 100644 --- a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt +++ b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt @@ -26,7 +26,11 @@ internal class ArtworkLoader(context: Context) { private val executor = ThreadPoolExecutor( 2, 2, 0L, TimeUnit.MILLISECONDS, LinkedBlockingDeque() ) - private inner class ArtworkTask(val key: String, val work: () -> Unit) : Runnable { + private inner class ArtworkTask( + val key: String, + val isPrefetch: Boolean, + val work: () -> Unit + ) : Runnable { override fun run() = work() } private val memoryCache = object : LruCache( @@ -37,31 +41,51 @@ internal class ArtworkLoader(context: Context) { private val pending = ConcurrentHashMap Unit>>() fun load(song: Song, targetSize: Int, callback: (Bitmap?) -> Unit) { + request(song, targetSize, callback, false) + } + + /** + * Warm the caches for a small number of likely-to-be-opened tracks. + * Prefetch tasks are queued behind user-requested artwork and are discarded + * when a fresh on-demand request needs the worker queue. + */ + fun prefetch(song: Song, targetSize: Int) { + request(song, targetSize, null, true) + } + + private fun request( + song: Song, + targetSize: Int, + callback: ((Bitmap?) -> Unit)?, + isPrefetch: Boolean + ) { val key = if (song.albumId > 0) "album_${song.albumId}" else "song_${song.id}" - memoryCache.get(key)?.let { callback(it); return } + memoryCache.get(key)?.let { callback?.invoke(it); return } var shouldStart = false synchronized(pending) { val listeners = pending[key] if (listeners != null) { - listeners.add(callback) + if (callback != null) listeners.add(callback) } else { - // Remove queued jobs for albums that are no longer displayed. - // Already-running decodes are allowed to finish and populate cache. - val obsoleteKeys = pending.keys.filter { it != key } - obsoleteKeys.forEach { obsoleteKey -> - pending.remove(obsoleteKey) - executor.queue.removeIf { task -> - task is ArtworkTask && task.key == obsoleteKey - } + if (!isPrefetch) { + // User-visible artwork always takes precedence over queued + // speculative work. Running jobs finish and warm the cache. + val queuedPrefetchKeys = executor.queue.filter { + it is ArtworkTask && it.isPrefetch + }.map { (it as ArtworkTask).key }.toSet() + executor.queue.removeIf { it is ArtworkTask && it.isPrefetch } + queuedPrefetchKeys.forEach { pending.remove(it) } + } + pending[key] = mutableListOf<(Bitmap?) -> Unit>().also { + if (callback != null) it.add(callback) } - pending[key] = mutableListOf(callback) shouldStart = true } } if (!shouldStart) return - executor.execute(ArtworkTask(key) { + val task = ArtworkTask(key, isPrefetch) { val bitmap = try { loadFromDisk(key, targetSize) ?: loadFromMediaStore(song.albumId, targetSize) @@ -70,11 +94,17 @@ internal class ArtworkLoader(context: Context) { if (bitmap != null) memoryCache.put(key, bitmap) val listeners = synchronized(pending) { pending.remove(key).orEmpty() } - // Deliver as soon as decoding finishes; disk persistence must not - // delay the visible cover on the main thread. listeners.forEach { listener -> try { listener(bitmap) } catch (_: Exception) {} } if (bitmap != null) saveToDisk(key, bitmap) - }) + } + + if (isPrefetch) { + executor.execute(task) + } else { + // Put the requested artwork at the front of the waiting queue. + if (executor.poolSize < executor.corePoolSize) executor.execute(task) + else executor.queue.offerFirst(task) + } } private fun loadFromDisk(key: String, targetSize: Int): Bitmap? { From e32947ddf2dbf7c051b3b14afc75a322f8f15043 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:29:00 +0330 Subject: [PATCH 31/70] Prefetch artwork for visible song pages --- .../main/java/com/movemusic/app/MainActivity.kt | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index b827126..307c12a 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -299,6 +299,22 @@ class MainActivity : Activity() { }) page.forEach { song -> addSongRow(song) } this.hasMoreSongs = hasMoreSongs + scheduleArtworkPrefetch(page) + } + + /** + * Warm a tiny batch after the list settles. This keeps initial rendering + * and scrolling responsive while making the first few player screens ready. + */ + private fun scheduleArtworkPrefetch(items: List) { + if (items.isEmpty()) return + val candidates = items.take(4) + uiHandler.postDelayed({ + if (isFinishing || isDestroyed || playerScreenVisible) return@postDelayed + val targetSize = (resources.displayMetrics.widthPixels * 0.78f) + .toInt().coerceAtLeast(256) + candidates.forEach { artworkLoader.prefetch(it, targetSize) } + }, 350L) } private fun addSongRow(song: Song) { @@ -361,6 +377,7 @@ class MainActivity : Activity() { val batch = nextPage.take(50) hasMoreSongs = nextPage.size > 50 displayedSongCount += batch.size + scheduleArtworkPrefetch(batch) // Add rows in small UI batches instead of rebuilding the whole list. // This keeps scrolling responsive while the next page is appended. From a9abf249e182ab51ee39e9bbc8004c139ed10509 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:56:18 +0330 Subject: [PATCH 32/70] Experiment with Coil for player artwork --- .../java/com/movemusic/app/MainActivity.kt | 48 ++++--------------- 1 file changed, 9 insertions(+), 39 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 307c12a..bea77f3 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -27,6 +27,7 @@ import androidx.media3.common.Player import androidx.media3.session.MediaController import androidx.media3.session.SessionToken import com.google.common.util.concurrent.ListenableFuture +import coil3.load data class Song(val id: Long, val title: String, val artist: String, val albumId: Long, val uri: Uri) @@ -61,9 +62,6 @@ class MainActivity : Activity() { private var songScrollView: ScrollView? = null private var isLoadingNextPage = false private var hasMoreSongs = false - private val artworkLoaderDelegate = lazy { ArtworkLoader(this) } - private val artworkLoader by artworkLoaderDelegate - private var artworkRequestToken = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -299,22 +297,6 @@ class MainActivity : Activity() { }) page.forEach { song -> addSongRow(song) } this.hasMoreSongs = hasMoreSongs - scheduleArtworkPrefetch(page) - } - - /** - * Warm a tiny batch after the list settles. This keeps initial rendering - * and scrolling responsive while making the first few player screens ready. - */ - private fun scheduleArtworkPrefetch(items: List) { - if (items.isEmpty()) return - val candidates = items.take(4) - uiHandler.postDelayed({ - if (isFinishing || isDestroyed || playerScreenVisible) return@postDelayed - val targetSize = (resources.displayMetrics.widthPixels * 0.78f) - .toInt().coerceAtLeast(256) - candidates.forEach { artworkLoader.prefetch(it, targetSize) } - }, 350L) } private fun addSongRow(song: Song) { @@ -377,7 +359,6 @@ class MainActivity : Activity() { val batch = nextPage.take(50) hasMoreSongs = nextPage.size > 50 displayedSongCount += batch.size - scheduleArtworkPrefetch(batch) // Add rows in small UI batches instead of rebuilding the whole list. // This keeps scrolling responsive while the next page is appended. @@ -689,24 +670,14 @@ class MainActivity : Activity() { } private fun loadSongArtwork(song: Song, target: ImageView) { - val requestToken = ++artworkRequestToken - target.setImageResource(android.R.drawable.ic_media_play) - target.scaleType = ImageView.ScaleType.CENTER - val targetSize = (resources.displayMetrics.widthPixels * 0.78f).toInt().coerceAtLeast(256) - - artworkLoader.load(song, targetSize) { bitmap -> - runOnUiThread { - if (!isFinishing && !isDestroyed && playerScreenVisible && - artworkRequestToken == requestToken && currentSong?.id == song.id) { - if (bitmap != null) { - target.setImageBitmap(bitmap) - target.scaleType = ImageView.ScaleType.CENTER_CROP - } else { - target.setImageResource(android.R.drawable.ic_media_play) - target.scaleType = ImageView.ScaleType.CENTER - } - } - } + // Match Chocola's MediaStore URI convention and let Coil own image + // loading, request lifecycle, decoding and memory caching. + val artworkUri = Uri.withAppendedPath(song.uri, "albumart") + target.scaleType = ImageView.ScaleType.CENTER_CROP + target.load(artworkUri) { + placeholder(android.R.drawable.ic_media_play) + error(android.R.drawable.ic_media_play) + crossfade(false) } } @@ -847,7 +818,6 @@ class MainActivity : Activity() { private fun toast(s: String) = Toast.makeText(this, s, Toast.LENGTH_SHORT).show() override fun onDestroy() { uiHandler.removeCallbacksAndMessages(null) - if (artworkLoaderDelegate.isInitialized()) artworkLoader.close() pendingSong = null controllerFuture?.let { MediaController.releaseFuture(it) } player = null From b75849908b7970b2b1689c1fed6955132d10c7e9 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:56:21 +0330 Subject: [PATCH 33/70] Add Coil image loading dependency --- app/build.gradle.kts | 1 + 1 file changed, 1 insertion(+) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index de4bd8a..f892e9b 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -26,6 +26,7 @@ android { } dependencies { + implementation("io.coil-kt.coil3:coil:3.6.3") implementation("androidx.media3:media3-exoplayer:1.5.1") implementation("androidx.media3:media3-session:1.5.1") } From 5b380309960a06431fded66fb06871b7ed25c9da Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 22:56:23 +0330 Subject: [PATCH 34/70] Remove custom artwork loader in Coil experiment --- .../java/com/movemusic/app/ArtworkLoader.kt | 185 ------------------ 1 file changed, 185 deletions(-) delete mode 100644 app/src/main/java/com/movemusic/app/ArtworkLoader.kt diff --git a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt b/app/src/main/java/com/movemusic/app/ArtworkLoader.kt deleted file mode 100644 index 8783f1f..0000000 --- a/app/src/main/java/com/movemusic/app/ArtworkLoader.kt +++ /dev/null @@ -1,185 +0,0 @@ -package com.movemusic.app - -import android.content.Context -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.media.MediaMetadataRetriever -import android.net.Uri -import android.provider.MediaStore -import android.util.LruCache -import java.io.File -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.LinkedBlockingDeque -import java.util.concurrent.ThreadPoolExecutor -import java.util.concurrent.TimeUnit - -/** - * Artwork pipeline: memory cache -> persistent disk cache -> MediaStore album - * artwork -> embedded artwork fallback. All I/O and decoding stay off the UI - * thread, and simultaneous requests for one album share a single decode. - */ -internal class ArtworkLoader(context: Context) { - private val appContext = context.applicationContext - private val diskDirectory = File(appContext.cacheDir, "artwork").apply { mkdirs() } - // Keep at most the currently requested album queued. Rapid track skipping - // must not leave a long tail of obsolete artwork decodes ahead of the UI. - private val executor = ThreadPoolExecutor( - 2, 2, 0L, TimeUnit.MILLISECONDS, LinkedBlockingDeque() - ) - private inner class ArtworkTask( - val key: String, - val isPrefetch: Boolean, - val work: () -> Unit - ) : Runnable { - override fun run() = work() - } - private val memoryCache = object : LruCache( - (Runtime.getRuntime().maxMemory() / 1024 / 8).toInt() - ) { - override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount / 1024 - } - private val pending = ConcurrentHashMap Unit>>() - - fun load(song: Song, targetSize: Int, callback: (Bitmap?) -> Unit) { - request(song, targetSize, callback, false) - } - - /** - * Warm the caches for a small number of likely-to-be-opened tracks. - * Prefetch tasks are queued behind user-requested artwork and are discarded - * when a fresh on-demand request needs the worker queue. - */ - fun prefetch(song: Song, targetSize: Int) { - request(song, targetSize, null, true) - } - - private fun request( - song: Song, - targetSize: Int, - callback: ((Bitmap?) -> Unit)?, - isPrefetch: Boolean - ) { - val key = if (song.albumId > 0) "album_${song.albumId}" else "song_${song.id}" - memoryCache.get(key)?.let { callback?.invoke(it); return } - - var shouldStart = false - synchronized(pending) { - val listeners = pending[key] - if (listeners != null) { - if (callback != null) listeners.add(callback) - } else { - if (!isPrefetch) { - // User-visible artwork always takes precedence over queued - // speculative work. Running jobs finish and warm the cache. - val queuedPrefetchKeys = executor.queue.filter { - it is ArtworkTask && it.isPrefetch - }.map { (it as ArtworkTask).key }.toSet() - executor.queue.removeIf { it is ArtworkTask && it.isPrefetch } - queuedPrefetchKeys.forEach { pending.remove(it) } - } - pending[key] = mutableListOf<(Bitmap?) -> Unit>().also { - if (callback != null) it.add(callback) - } - shouldStart = true - } - } - if (!shouldStart) return - - val task = ArtworkTask(key, isPrefetch) { - val bitmap = try { - loadFromDisk(key, targetSize) - ?: loadFromMediaStore(song.albumId, targetSize) - ?: loadEmbedded(song, targetSize) - } catch (_: Exception) { null } - - if (bitmap != null) memoryCache.put(key, bitmap) - val listeners = synchronized(pending) { pending.remove(key).orEmpty() } - listeners.forEach { listener -> try { listener(bitmap) } catch (_: Exception) {} } - if (bitmap != null) saveToDisk(key, bitmap) - } - - if (isPrefetch) { - executor.execute(task) - } else { - // Put the requested artwork at the front of the waiting queue. - if (executor.poolSize < executor.corePoolSize) executor.execute(task) - else executor.queue.offerFirst(task) - } - } - - private fun loadFromDisk(key: String, targetSize: Int): Bitmap? { - val file = File(diskDirectory, "$key.webp") - if (!file.isFile || file.length() == 0L) return null - val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeFile(file.absolutePath, bounds) - if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null - return BitmapFactory.decodeFile(file.absolutePath, BitmapFactory.Options().apply { - inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, targetSize) - inPreferredConfig = Bitmap.Config.RGB_565 - }) - } - - private fun loadFromMediaStore(albumId: Long, targetSize: Int): Bitmap? { - if (albumId <= 0) return null - val uri = Uri.parse("content://media/external/audio/albumart/$albumId") - val bytes = appContext.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: return null - return decode(bytes, targetSize) - } - - private fun loadEmbedded(song: Song, targetSize: Int): Bitmap? { - val retriever = MediaMetadataRetriever() - return try { - retriever.setDataSource(appContext, song.uri) - retriever.embeddedPicture?.let { decode(it, targetSize) } - } finally { - try { retriever.release() } catch (_: Exception) {} - } - } - - private fun decode(bytes: ByteArray, targetSize: Int): Bitmap? { - val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) - if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null - return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { - inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, targetSize) - inPreferredConfig = Bitmap.Config.RGB_565 - }) - } - - private fun sampleSize(width: Int, height: Int, targetSize: Int): Int { - var sample = 1 - while (maxOf(width, height) / (sample * 2) >= targetSize) sample *= 2 - return sample - } - - private fun saveToDisk(key: String, bitmap: Bitmap) { - try { - val file = File(diskDirectory, "$key.webp") - val temp = File(diskDirectory, "$key.tmp") - temp.outputStream().use { bitmap.compress(Bitmap.CompressFormat.WEBP, 92, it) } - if (!temp.renameTo(file)) { - temp.copyTo(file, overwrite = true) - temp.delete() - } - trimDiskCache() - } catch (_: Exception) {} - } - - private fun trimDiskCache() { - val files = diskDirectory.listFiles()?.filter { it.isFile } ?: return - var total = files.sumOf { it.length() } - val maxBytes = 64L * 1024L * 1024L - if (total <= maxBytes) return - files.sortedBy { it.lastModified() }.forEach { file -> - if (total <= maxBytes) return - val size = file.length() - if (file.delete()) total -= size - } - } - - fun close() { - executor.shutdownNow() - memoryCache.evictAll() - synchronized(pending) { pending.clear() } - } -} From cc1103dbf3dd7f7b4e33182f0c3297c991f77331 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 23:07:16 +0330 Subject: [PATCH 35/70] Use Coil 3.0.4 compatible with current Android toolchain --- app/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f892e9b..51aa64e 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -26,7 +26,7 @@ android { } dependencies { - implementation("io.coil-kt.coil3:coil:3.6.3") + implementation("io.coil-kt.coil3:coil:3.0.4") implementation("androidx.media3:media3-exoplayer:1.5.1") implementation("androidx.media3:media3-session:1.5.1") } From 39a89649e9ba96df39412657a2b64a861d84dcdb Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 23:14:18 +0330 Subject: [PATCH 36/70] Use Coil 3 ImageView loading API compatible with Coil 3.0.4 --- app/src/main/java/com/movemusic/app/MainActivity.kt | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index bea77f3..2f1b0c4 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -674,11 +674,7 @@ class MainActivity : Activity() { // loading, request lifecycle, decoding and memory caching. val artworkUri = Uri.withAppendedPath(song.uri, "albumart") target.scaleType = ImageView.ScaleType.CENTER_CROP - target.load(artworkUri) { - placeholder(android.R.drawable.ic_media_play) - error(android.R.drawable.ic_media_play) - crossfade(false) - } + target.load(artworkUri) } private fun playerControl(iconRes: Int, size: Int, action: () -> Unit): ImageButton = From 716d9b292acba0ae75190693f7ffefe397a1e8d3 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 23:40:12 +0330 Subject: [PATCH 37/70] Optimize Coil artwork sizing and prefetch adjacent tracks --- .../java/com/movemusic/app/MainActivity.kt | 40 +++++++++++++++++-- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 2f1b0c4..a95217f 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -28,6 +28,9 @@ import androidx.media3.session.MediaController import androidx.media3.session.SessionToken import com.google.common.util.concurrent.ListenableFuture import coil3.load +import coil3.SingletonImageLoader +import coil3.request.ImageRequest +import coil3.size.Precision data class Song(val id: Long, val title: String, val artist: String, val albumId: Long, val uri: Uri) @@ -117,6 +120,7 @@ class MainActivity : Activity() { currentSong = song if (playbackQueue.isEmpty()) playbackQueue = songs currentSongIndex = playbackQueue.indexOfFirst { it.id == song.id } + if (songChanged) prefetchAdjacentArtwork(currentSongIndex) if (playerScreenVisible) { // Avoid rebuilding the screen for the initial transition of the // track that is already displayed. @@ -434,6 +438,7 @@ class MainActivity : Activity() { } currentSongIndex = playbackQueue.indexOfFirst { it.id == song.id } currentSong = song + prefetchAdjacentArtwork(currentSongIndex) showPlayerScreen() startSong(song) } @@ -669,12 +674,39 @@ class MainActivity : Activity() { setOnClickListener { action() } } + private fun artworkUri(song: Song): Uri = + Uri.withAppendedPath(song.uri, "albumart") + private fun loadSongArtwork(song: Song, target: ImageView) { - // Match Chocola's MediaStore URI convention and let Coil own image - // loading, request lifecycle, decoding and memory caching. - val artworkUri = Uri.withAppendedPath(song.uri, "albumart") + // INEXACT lets Coil reuse a larger cached bitmap and avoid decoding + // beyond the source image's native dimensions. ImageView scales it. target.scaleType = ImageView.ScaleType.CENTER_CROP - target.load(artworkUri) + target.load(artworkUri(song)) { + precision(Precision.INEXACT) + } + } + + private fun prefetchAdjacentArtwork(index: Int) { + if (index !in playbackQueue.indices) return + + // Match the player cover's requested dimensions so the prefetched + // result is reusable when the user opens the adjacent track. + val size = (resources.displayMetrics.widthPixels * 0.78f) + .toInt() + .coerceAtLeast(1) + val imageLoader = SingletonImageLoader.get(applicationContext) + + listOf(index - 1, index + 1) + .filter { it in playbackQueue.indices } + .distinct() + .forEach { adjacentIndex -> + val request = ImageRequest.Builder(applicationContext) + .data(artworkUri(playbackQueue[adjacentIndex])) + .size(size, size) + .precision(Precision.INEXACT) + .build() + imageLoader.enqueue(request) + } } private fun playerControl(iconRes: Int, size: Int, action: () -> Unit): ImageButton = From 9b8fbff97e8b324bebd4896d8cb87c41c855cb21 Mon Sep 17 00:00:00 2001 From: Soebb Date: Sun, 8 Nov 2026 23:57:26 +0330 Subject: [PATCH 38/70] Add touch-activated fast scroll bar to song list --- .../java/com/movemusic/app/MainActivity.kt | 126 +++++++++++++++++- 1 file changed, 125 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index a95217f..bcf1041 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -9,6 +9,8 @@ import android.content.Intent import android.content.Context import android.content.pm.PackageManager import android.graphics.Color +import android.graphics.Canvas +import android.graphics.Paint import android.graphics.drawable.GradientDrawable import android.net.Uri import android.os.Handler @@ -17,6 +19,7 @@ import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.view.Gravity +import android.view.MotionEvent import android.view.View import android.widget.* import org.json.JSONArray @@ -63,6 +66,7 @@ class MainActivity : Activity() { private var homeRoot: View? = null private var miniPlayerHost: LinearLayout? = null private var songScrollView: ScrollView? = null + private var fastScrollOverlay: FastScrollOverlay? = null private var isLoadingNextPage = false private var hasMoreSongs = false @@ -247,9 +251,27 @@ class MainActivity : Activity() { isFillViewport = true addView(body) } - root.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f)) + val scrollContainer = FrameLayout(this) + scrollContainer.addView( + scroll, + FrameLayout.LayoutParams(-1, -1) + ) + val fastScroller = FastScrollOverlay(scroll).apply { + visibility = View.GONE + } + scrollContainer.addView( + fastScroller, + FrameLayout.LayoutParams( + (30 * resources.displayMetrics.density).toInt(), + -1, + Gravity.END + ) + ) + root.addView(scrollContainer, LinearLayout.LayoutParams(-1, 0, 1f)) songScrollView = scroll + fastScrollOverlay = fastScroller scroll.setOnScrollChangeListener { _, _, scrollY, _, _ -> + fastScroller.invalidate() val contentHeight = scroll.getChildAt(0)?.height ?: 0 if (hasMoreSongs && !isLoadingNextPage && contentHeight > 0 && scrollY + scroll.height >= contentHeight - scroll.height / 2) { @@ -267,6 +289,108 @@ class MainActivity : Activity() { refreshBody() } + private inner class FastScrollOverlay( + private val scrollView: ScrollView + ) : View(this@MainActivity) { + private val density = resources.displayMetrics.density + private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = 0x55808080 + strokeWidth = 2.5f * density + strokeCap = Paint.Cap.ROUND + } + private val thumbPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = 0xFFBDBDBD.toInt() + strokeWidth = 4f * density + strokeCap = Paint.Cap.ROUND + } + private val hideTask = Runnable { + visibility = View.GONE + } + private var dragging = false + private var dragOffset = 0f + + private val trackInset get() = 8f * density + private val minimumThumb get() = 38f * density + + init { + isClickable = true + setLayerType(View.LAYER_TYPE_SOFTWARE, null) + } + + private fun scrollRange(): Int { + val contentHeight = scrollView.getChildAt(0)?.height ?: 0 + return (contentHeight - scrollView.height).coerceAtLeast(0) + } + + private fun thumbHeight(): Float { + if (height <= 0) return minimumThumb + val contentHeight = (scrollView.getChildAt(0)?.height ?: 0).coerceAtLeast(1) + return (height.toFloat() * scrollView.height / contentHeight) + .coerceAtLeast(minimumThumb) + .coerceAtMost(height.toFloat()) + } + + private fun thumbTop(): Float { + val available = (height - thumbHeight()).coerceAtLeast(0f) + val range = scrollRange() + return if (range == 0) 0f else available * scrollView.scrollY / range + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + if (scrollRange() <= 0 || height <= 0) return + val centerX = width - 7f * density + val top = trackInset + val bottom = height - trackInset + canvas.drawLine(centerX, top, centerX, bottom, trackPaint) + val thumb = thumbHeight() + val thumbTop = thumbTop().coerceIn(top, (bottom - thumb).coerceAtLeast(top)) + canvas.drawLine(centerX, thumbTop, centerX, thumbTop + thumb, thumbPaint) + } + + private fun moveTo(y: Float) { + val range = scrollRange() + if (range <= 0) return + val available = (height - thumbHeight()).coerceAtLeast(1f) + val top = (y - dragOffset - thumbHeight() / 2f) + .coerceIn(0f, available) + scrollView.scrollTo(0, (top / available * range).toInt()) + invalidate() + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + uiHandler.removeCallbacks(hideTask) + visibility = View.VISIBLE + val currentTop = thumbTop() + val currentBottom = currentTop + thumbHeight() + dragging = true + dragOffset = if (event.y in currentTop..currentBottom) { + event.y - currentTop - thumbHeight() / 2f + } else { + 0f + } + moveTo(event.y) + parent?.requestDisallowInterceptTouchEvent(true) + return true + } + MotionEvent.ACTION_MOVE -> { + if (dragging) moveTo(event.y) + return true + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + dragging = false + parent?.requestDisallowInterceptTouchEvent(false) + uiHandler.removeCallbacks(hideTask) + uiHandler.postDelayed(hideTask, 1_000L) + return true + } + } + return true + } + } + private fun refreshBody() { body.removeAllViews() body.addView(label(currentPlaylist, 18, white)) From 4da885e3e15d4b236a2b76687539ba14c2f4f266 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 00:16:36 +0330 Subject: [PATCH 39/70] Enable full-library fast scrolling across paginated song list --- .../java/com/movemusic/app/MainActivity.kt | 57 ++++++++++++++++--- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index bcf1041..e170c54 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -67,6 +67,8 @@ class MainActivity : Activity() { private var miniPlayerHost: LinearLayout? = null private var songScrollView: ScrollView? = null private var fastScrollOverlay: FastScrollOverlay? = null + private var songRowsStartIndex = 0 + private var pendingFastScrollIndex = -1 private var isLoadingNextPage = false private var hasMoreSongs = false @@ -322,18 +324,27 @@ class MainActivity : Activity() { return (contentHeight - scrollView.height).coerceAtLeast(0) } + private fun totalSongCount(): Int { + val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null + else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() + return songs.count { playlistIds == null || it.id in playlistIds } + } + private fun thumbHeight(): Float { if (height <= 0) return minimumThumb - val contentHeight = (scrollView.getChildAt(0)?.height ?: 0).coerceAtLeast(1) - return (height.toFloat() * scrollView.height / contentHeight) + val estimatedContentHeight = (totalSongCount() * 72f * density) + .coerceAtLeast(height.toFloat()) + return (height.toFloat() * height / estimatedContentHeight) .coerceAtLeast(minimumThumb) .coerceAtMost(height.toFloat()) } private fun thumbTop(): Float { val available = (height - thumbHeight()).coerceAtLeast(0f) - val range = scrollRange() - return if (range == 0) 0f else available * scrollView.scrollY / range + val total = totalSongCount() + if (total <= 1) return 0f + val firstVisibleIndex = scrollView.scrollY / (72f * density) + return available * (firstVisibleIndex / (total - 1f)).coerceIn(0f, 1f) } override fun onDraw(canvas: Canvas) { @@ -349,12 +360,17 @@ class MainActivity : Activity() { } private fun moveTo(y: Float) { - val range = scrollRange() - if (range <= 0) return val available = (height - thumbHeight()).coerceAtLeast(1f) val top = (y - dragOffset - thumbHeight() / 2f) .coerceIn(0f, available) - scrollView.scrollTo(0, (top / available * range).toInt()) + val fraction = (top / available).coerceIn(0f, 1f) + val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null + else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() + val totalSongs = songs.count { playlistIds == null || it.id in playlistIds } + if (totalSongs > 0) { + val targetIndex = (fraction * (totalSongs - 1)).toInt() + scrollToSongIndex(targetIndex) + } invalidate() } @@ -423,6 +439,7 @@ class MainActivity : Activity() { refreshBody() toast(if (shuffleEnabled) "پخش تصادفی فعال شد." else "پخش تصادفی غیرفعال شد.") }) + songRowsStartIndex = body.childCount page.forEach { song -> addSongRow(song) } this.hasMoreSongs = hasMoreSongs } @@ -501,11 +518,37 @@ class MainActivity : Activity() { uiHandler.post { appendChunk() } } else { isLoadingNextPage = false + if (pendingFastScrollIndex >= 0) { + val target = pendingFastScrollIndex + pendingFastScrollIndex = -1 + scrollToSongIndex(target) + } } } appendChunk() } + private fun scrollToSongIndex(index: Int) { + val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null + else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() + val totalSongs = songs.count { playlistIds == null || it.id in playlistIds } + if (totalSongs == 0) return + val target = index.coerceIn(0, totalSongs - 1) + + if (target >= displayedSongCount && hasMoreSongs) { + pendingFastScrollIndex = target + if (!isLoadingNextPage) loadNextSongsPage() + return + } + if (isLoadingNextPage) { + pendingFastScrollIndex = target + return + } + + val row = body.getChildAt(songRowsStartIndex + target) ?: return + songScrollView?.scrollTo(0, row.top) + } + private fun moveSong(song: Song) { val destinations = playlists.keys.filter { it != currentPlaylist }.toTypedArray() if (destinations.isEmpty()) { toast("اول یک پلی‌لیست دیگر بساز."); return } From 0c7abd6b81c86ab9df7773ae00cbfd277d99a464 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 00:32:28 +0330 Subject: [PATCH 40/70] Add live search across song titles and artists --- .../java/com/movemusic/app/MainActivity.kt | 129 ++++++++++++------ 1 file changed, 91 insertions(+), 38 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index e170c54..a12cb41 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -69,6 +69,9 @@ class MainActivity : Activity() { private var fastScrollOverlay: FastScrollOverlay? = null private var songRowsStartIndex = 0 private var pendingFastScrollIndex = -1 + private var searchQuery = "" + private var searchField: EditText? = null + private var searchContainer: LinearLayout? = null private var isLoadingNextPage = false private var hasMoreSongs = false @@ -247,7 +250,42 @@ class MainActivity : Activity() { nav.addView(button("همه آهنگ‌ها") { currentPlaylist = "همه آهنگ‌ها"; displayedSongCount = 50; refreshBody() }) nav.addView(button("پلی‌لیست‌ها") { showPlaylistChooser() }) nav.addView(button("+ جدید") { createPlaylist() }) + nav.addView(button("⌕ جست‌وجو") { toggleSearch() }) root.addView(nav) + searchContainer = LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + visibility = View.GONE + setPadding(0, 6, 0, 6) + } + searchField = EditText(this).apply { + hint = "نام آهنگ یا خواننده…" + textSize = 14f + singleLine = true + setTextColor(white) + setHintTextColor(muted) + setCompoundDrawablePadding(8) + addTextChangedListener(object : android.text.TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { + searchQuery = s?.toString()?.trim().orEmpty() + displayedSongCount = 50 + pendingFastScrollIndex = -1 + songScrollView?.scrollTo(0, 0) + if (::body.isInitialized) refreshBody() + } + override fun afterTextChanged(s: android.text.Editable?) {} + }) + } + searchContainer?.addView(searchField, LinearLayout.LayoutParams(0, -2, 1f)) + searchContainer?.addView(button("✕") { + searchField?.text?.clear() + searchContainer?.visibility = View.GONE + searchField?.clearFocus() + val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager + imm.hideSoftInputFromWindow(searchField?.windowToken, 0) + }) + root.addView(searchContainer) body = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } val scroll = ScrollView(this).apply { isFillViewport = true @@ -291,6 +329,30 @@ class MainActivity : Activity() { refreshBody() } + private fun toggleSearch() { + val container = searchContainer ?: return + if (container.visibility == View.VISIBLE) { + searchField?.requestFocus() + } else { + container.visibility = View.VISIBLE + searchField?.requestFocus() + val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager + imm.showSoftInput(searchField, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT) + } + } + + private fun visibleSongSource(): List { + val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null + else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() + val source = songs.asSequence().filter { playlistIds == null || it.id in playlistIds } + val query = searchQuery.trim() + return if (query.isEmpty()) source.toList() + else source.filter { + it.title.contains(query, ignoreCase = true) || + it.artist.contains(query, ignoreCase = true) + }.toList() + } + private inner class FastScrollOverlay( private val scrollView: ScrollView ) : View(this@MainActivity) { @@ -325,9 +387,7 @@ class MainActivity : Activity() { } private fun totalSongCount(): Int { - val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null - else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() - return songs.count { playlistIds == null || it.id in playlistIds } + return visibleSongSource().size } private fun thumbHeight(): Float { @@ -364,9 +424,7 @@ class MainActivity : Activity() { val top = (y - dragOffset - thumbHeight() / 2f) .coerceIn(0f, available) val fraction = (top / available).coerceIn(0f, 1f) - val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null - else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() - val totalSongs = songs.count { playlistIds == null || it.id in playlistIds } + val totalSongs = visibleSongSource().size if (totalSongs > 0) { val targetIndex = (fraction * (totalSongs - 1)).toInt() scrollToSongIndex(targetIndex) @@ -409,19 +467,14 @@ class MainActivity : Activity() { private fun refreshBody() { body.removeAllViews() - body.addView(label(currentPlaylist, 18, white)) - // Only collect the current page (plus one item to detect whether - // another page exists). Avoid filtering the entire music library on - // every return from the player screen. - val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null - else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() - val pageWithExtra = songs.asSequence() - .filter { playlistIds == null || it.id in playlistIds } - .take(displayedSongCount + 1) - .toList() - val hasMoreSongs = pageWithExtra.size > displayedSongCount - val page = pageWithExtra.take(displayedSongCount) - if (currentPlaylist != "همه آهنگ‌ها") { + body.addView(label( + if (searchQuery.isEmpty()) currentPlaylist else "نتایج جست‌وجو", + 18, white + )) + val allVisibleSongs = visibleSongSource() + val page = allVisibleSongs.take(displayedSongCount) + this.hasMoreSongs = allVisibleSongs.size > displayedSongCount + if (currentPlaylist != "همه آهنگ‌ها" && searchQuery.isEmpty()) { body.addView(button("افزودن همه آهنگ‌ها به این پلی‌لیست") { val target = playlists[currentPlaylist] ?: return@button val existingIds = target.toHashSet() @@ -433,15 +486,22 @@ class MainActivity : Activity() { else "${newSongs.size} آهنگ به پلی‌لیست اضافه شد.") }) } - if (page.isEmpty()) body.addView(label("اینجا هنوز آهنگی نیست.", 13, muted)) - body.addView(button(if (shuffleEnabled) "پخش تصادفی: روشن" else "پخش تصادفی: خاموش") { - shuffleEnabled = !shuffleEnabled - refreshBody() - toast(if (shuffleEnabled) "پخش تصادفی فعال شد." else "پخش تصادفی غیرفعال شد.") - }) + if (page.isEmpty()) { + body.addView(label( + if (searchQuery.isEmpty()) "اینجا هنوز آهنگی نیست." else "نتیجه‌ای پیدا نشد.", + 13, muted + )) + } + if (searchQuery.isEmpty()) { + body.addView(button(if (shuffleEnabled) "پخش تصادفی: روشن" else "پخش تصادفی: خاموش") { + shuffleEnabled = !shuffleEnabled + refreshBody() + toast(if (shuffleEnabled) "پخش تصادفی فعال شد." else "پخش تصادفی غیرفعال شد.") + }) + } songRowsStartIndex = body.childCount page.forEach { song -> addSongRow(song) } - this.hasMoreSongs = hasMoreSongs + fastScrollOverlay?.invalidate() } private fun addSongRow(song: Song) { @@ -494,15 +554,9 @@ class MainActivity : Activity() { private fun loadNextSongsPage() { if (!hasMoreSongs || isLoadingNextPage) return isLoadingNextPage = true - val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null - else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() - val nextPage = songs.asSequence() - .filter { playlistIds == null || it.id in playlistIds } - .drop(displayedSongCount) - .take(51) - .toList() - val batch = nextPage.take(50) - hasMoreSongs = nextPage.size > 50 + val nextPage = visibleSongSource().drop(displayedSongCount).take(50).toList() + val batch = nextPage + hasMoreSongs = visibleSongSource().size > displayedSongCount + batch.size displayedSongCount += batch.size // Add rows in small UI batches instead of rebuilding the whole list. @@ -529,9 +583,8 @@ class MainActivity : Activity() { } private fun scrollToSongIndex(index: Int) { - val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null - else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() - val totalSongs = songs.count { playlistIds == null || it.id in playlistIds } + val visibleSongs = visibleSongSource() + val totalSongs = visibleSongs.size if (totalSongs == 0) return val target = index.coerceIn(0, totalSongs - 1) From 0e3d866f8ac5a148d860e154877b3706a7329e87 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 00:38:07 +0330 Subject: [PATCH 41/70] Fix EditText single-line configuration for search --- app/src/main/java/com/movemusic/app/MainActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index a12cb41..8759c1e 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -261,7 +261,7 @@ class MainActivity : Activity() { searchField = EditText(this).apply { hint = "نام آهنگ یا خواننده…" textSize = 14f - singleLine = true + setSingleLine(true) setTextColor(white) setHintTextColor(muted) setCompoundDrawablePadding(8) From 0a29f2d0105473f8bd3993fc6047d1ffee4d0af9 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:03:32 +0330 Subject: [PATCH 42/70] Support combined multi-term song and artist search --- .../main/java/com/movemusic/app/MainActivity.kt | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 8759c1e..ab9aa8d 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -345,11 +345,18 @@ class MainActivity : Activity() { val playlistIds = if (currentPlaylist == "همه آهنگ‌ها") null else (playlists[currentPlaylist] ?: mutableListOf()).toHashSet() val source = songs.asSequence().filter { playlistIds == null || it.id in playlistIds } - val query = searchQuery.trim() - return if (query.isEmpty()) source.toList() - else source.filter { - it.title.contains(query, ignoreCase = true) || - it.artist.contains(query, ignoreCase = true) + val terms = searchQuery.trim() + .split(Regex("\\s+")) + .filter { it.isNotBlank() } + return if (terms.isEmpty()) source.toList() + else source.filter { song -> + // Every search term must match either the title or artist. + // This supports combined queries such as "song name artist" + // and multiple artist names stored in the same artist field. + terms.all { term -> + song.title.contains(term, ignoreCase = true) || + song.artist.contains(term, ignoreCase = true) + } }.toList() } From 2ee63adb82cc80b1da3fbfc3689d820f67008440 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:07:10 +0330 Subject: [PATCH 43/70] Fix fast scroller touch interaction --- .../main/java/com/movemusic/app/MainActivity.kt | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index ab9aa8d..ad13635 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -297,12 +297,12 @@ class MainActivity : Activity() { FrameLayout.LayoutParams(-1, -1) ) val fastScroller = FastScrollOverlay(scroll).apply { - visibility = View.GONE + visibility = View.VISIBLE } scrollContainer.addView( fastScroller, FrameLayout.LayoutParams( - (30 * resources.displayMetrics.density).toInt(), + (48 * resources.displayMetrics.density).toInt(), -1, Gravity.END ) @@ -375,16 +375,22 @@ class MainActivity : Activity() { strokeCap = Paint.Cap.ROUND } private val hideTask = Runnable { - visibility = View.GONE + indicatorVisible = false + invalidate() } private var dragging = false + private var indicatorVisible = false private var dragOffset = 0f private val trackInset get() = 8f * density private val minimumThumb get() = 38f * density init { + // Keep a transparent touch strip attached: a GONE view cannot receive + // ACTION_DOWN, so the fast scroller could never be grabbed by the user. isClickable = true + isFocusable = true + setBackgroundColor(Color.TRANSPARENT) setLayerType(View.LAYER_TYPE_SOFTWARE, null) } @@ -416,7 +422,7 @@ class MainActivity : Activity() { override fun onDraw(canvas: Canvas) { super.onDraw(canvas) - if (scrollRange() <= 0 || height <= 0) return + if (!indicatorVisible || scrollRange() <= 0 || height <= 0) return val centerX = width - 7f * density val top = trackInset val bottom = height - trackInset @@ -443,7 +449,8 @@ class MainActivity : Activity() { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { uiHandler.removeCallbacks(hideTask) - visibility = View.VISIBLE + indicatorVisible = true + invalidate() val currentTop = thumbTop() val currentBottom = currentTop + thumbHeight() dragging = true From bc9fc33b681026a4ffb730261134ae861279c786 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:19:29 +0330 Subject: [PATCH 44/70] Improve fast scroller responsiveness and drag performance --- .../java/com/movemusic/app/MainActivity.kt | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index ad13635..16f24b2 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -69,6 +69,7 @@ class MainActivity : Activity() { private var fastScrollOverlay: FastScrollOverlay? = null private var songRowsStartIndex = 0 private var pendingFastScrollIndex = -1 + private var visibleSongsCache: List = emptyList() private var searchQuery = "" private var searchField: EditText? = null private var searchContainer: LinearLayout? = null @@ -381,6 +382,7 @@ class MainActivity : Activity() { private var dragging = false private var indicatorVisible = false private var dragOffset = 0f + private var lastTargetIndex = -1 private val trackInset get() = 8f * density private val minimumThumb get() = 38f * density @@ -391,7 +393,6 @@ class MainActivity : Activity() { isClickable = true isFocusable = true setBackgroundColor(Color.TRANSPARENT) - setLayerType(View.LAYER_TYPE_SOFTWARE, null) } private fun scrollRange(): Int { @@ -399,25 +400,23 @@ class MainActivity : Activity() { return (contentHeight - scrollView.height).coerceAtLeast(0) } - private fun totalSongCount(): Int { - return visibleSongSource().size - } + private fun totalSongCount(): Int = visibleSongsCache.size private fun thumbHeight(): Float { if (height <= 0) return minimumThumb - val estimatedContentHeight = (totalSongCount() * 72f * density) - .coerceAtLeast(height.toFloat()) - return (height.toFloat() * height / estimatedContentHeight) + val range = scrollRange() + if (range <= 0) return height.toFloat() + // Derive thumb size from the real ScrollView range, not a guessed row height. + return (height.toFloat() * height / (height + range)) .coerceAtLeast(minimumThumb) .coerceAtMost(height.toFloat()) } private fun thumbTop(): Float { val available = (height - thumbHeight()).coerceAtLeast(0f) - val total = totalSongCount() - if (total <= 1) return 0f - val firstVisibleIndex = scrollView.scrollY / (72f * density) - return available * (firstVisibleIndex / (total - 1f)).coerceIn(0f, 1f) + val range = scrollRange() + if (range <= 0) return 0f + return available * (scrollView.scrollY.toFloat() / range).coerceIn(0f, 1f) } override fun onDraw(canvas: Canvas) { @@ -437,10 +436,13 @@ class MainActivity : Activity() { val top = (y - dragOffset - thumbHeight() / 2f) .coerceIn(0f, available) val fraction = (top / available).coerceIn(0f, 1f) - val totalSongs = visibleSongSource().size + val totalSongs = totalSongCount() if (totalSongs > 0) { val targetIndex = (fraction * (totalSongs - 1)).toInt() - scrollToSongIndex(targetIndex) + if (targetIndex != lastTargetIndex) { + lastTargetIndex = targetIndex + scrollToSongIndex(targetIndex) + } } invalidate() } @@ -454,6 +456,7 @@ class MainActivity : Activity() { val currentTop = thumbTop() val currentBottom = currentTop + thumbHeight() dragging = true + lastTargetIndex = -1 dragOffset = if (event.y in currentTop..currentBottom) { event.y - currentTop - thumbHeight() / 2f } else { @@ -486,6 +489,7 @@ class MainActivity : Activity() { 18, white )) val allVisibleSongs = visibleSongSource() + visibleSongsCache = allVisibleSongs val page = allVisibleSongs.take(displayedSongCount) this.hasMoreSongs = allVisibleSongs.size > displayedSongCount if (currentPlaylist != "همه آهنگ‌ها" && searchQuery.isEmpty()) { @@ -568,16 +572,16 @@ class MainActivity : Activity() { private fun loadNextSongsPage() { if (!hasMoreSongs || isLoadingNextPage) return isLoadingNextPage = true - val nextPage = visibleSongSource().drop(displayedSongCount).take(50).toList() + val nextPage = visibleSongsCache.drop(displayedSongCount).take(50) val batch = nextPage - hasMoreSongs = visibleSongSource().size > displayedSongCount + batch.size + hasMoreSongs = visibleSongsCache.size > displayedSongCount + batch.size displayedSongCount += batch.size // Add rows in small UI batches instead of rebuilding the whole list. // This keeps scrolling responsive while the next page is appended. var index = 0 fun appendChunk() { - val end = minOf(index + 10, batch.size) + val end = minOf(index + 20, batch.size) while (index < end) { addSongRow(batch[index]) index++ @@ -597,8 +601,7 @@ class MainActivity : Activity() { } private fun scrollToSongIndex(index: Int) { - val visibleSongs = visibleSongSource() - val totalSongs = visibleSongs.size + val totalSongs = visibleSongsCache.size if (totalSongs == 0) return val target = index.coerceIn(0, totalSongs - 1) From b969ca6f68529f58d69474a1cde1d6dc4d5d12e9 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:19:38 +0330 Subject: [PATCH 45/70] Calibrate fast scroller against full song list --- .../java/com/movemusic/app/MainActivity.kt | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 16f24b2..9bb1de7 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -402,21 +402,27 @@ class MainActivity : Activity() { private fun totalSongCount(): Int = visibleSongsCache.size + private fun estimatedRowHeight(): Float { + val loaded = displayedSongCount.coerceAtLeast(1) + val contentHeight = scrollView.getChildAt(0)?.height ?: 0 + return (contentHeight.toFloat() / loaded).coerceAtLeast(1f) + } + + private fun estimatedContentHeight(): Float { + return (totalSongCount() * estimatedRowHeight()).coerceAtLeast(height.toFloat()) + } + private fun thumbHeight(): Float { if (height <= 0) return minimumThumb - val range = scrollRange() - if (range <= 0) return height.toFloat() - // Derive thumb size from the real ScrollView range, not a guessed row height. - return (height.toFloat() * height / (height + range)) + return (height.toFloat() * height / estimatedContentHeight()) .coerceAtLeast(minimumThumb) .coerceAtMost(height.toFloat()) } private fun thumbTop(): Float { val available = (height - thumbHeight()).coerceAtLeast(0f) - val range = scrollRange() - if (range <= 0) return 0f - return available * (scrollView.scrollY.toFloat() / range).coerceIn(0f, 1f) + val estimatedRange = (estimatedContentHeight() - height).coerceAtLeast(1f) + return available * (scrollView.scrollY.toFloat() / estimatedRange).coerceIn(0f, 1f) } override fun onDraw(canvas: Canvas) { From 1d761848508e60375a5dc43879c8a77f3094d89b Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:30:15 +0330 Subject: [PATCH 46/70] Keep fast scrolling moving while loading distant songs --- .../java/com/movemusic/app/MainActivity.kt | 57 +++++++++++-------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 9bb1de7..34bafd0 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -578,32 +578,43 @@ class MainActivity : Activity() { private fun loadNextSongsPage() { if (!hasMoreSongs || isLoadingNextPage) return isLoadingNextPage = true - val nextPage = visibleSongsCache.drop(displayedSongCount).take(50) - val batch = nextPage - hasMoreSongs = visibleSongsCache.size > displayedSongCount + batch.size - displayedSongCount += batch.size - - // Add rows in small UI batches instead of rebuilding the whole list. - // This keeps scrolling responsive while the next page is appended. - var index = 0 - fun appendChunk() { - val end = minOf(index + 20, batch.size) - while (index < end) { - addSongRow(batch[index]) - index++ - } - if (index < batch.size) { - uiHandler.post { appendChunk() } + + // Normal list scrolling appends one page. During fast-scroll dragging, + // keep extending directly toward the latest requested index instead of + // stopping after each 50-row page. + fun appendNextChunk() { + val requestedTarget = pendingFastScrollIndex + val targetLimit = if (requestedTarget >= displayedSongCount) { + (requestedTarget + 1).coerceAtMost(visibleSongsCache.size) } else { - isLoadingNextPage = false - if (pendingFastScrollIndex >= 0) { - val target = pendingFastScrollIndex - pendingFastScrollIndex = -1 - scrollToSongIndex(target) - } + (displayedSongCount + 50).coerceAtMost(visibleSongsCache.size) + } + val end = minOf(displayedSongCount + 20, targetLimit) + while (displayedSongCount < end) { + addSongRow(visibleSongsCache[displayedSongCount]) + displayedSongCount++ + } + + hasMoreSongs = displayedSongCount < visibleSongsCache.size + fastScrollOverlay?.invalidate() + + if (pendingFastScrollIndex >= displayedSongCount && + displayedSongCount < visibleSongsCache.size) { + // Continue toward the finger's most recent position without + // waiting for another drag event or starting a new page cycle. + uiHandler.post { appendNextChunk() } + return + } + + isLoadingNextPage = false + if (pendingFastScrollIndex >= 0) { + val target = pendingFastScrollIndex + pendingFastScrollIndex = -1 + scrollToSongIndex(target) } } - appendChunk() + + appendNextChunk() } private fun scrollToSongIndex(index: Int) { From 6031c092f43822c41bf0d649883c60f739208a81 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:40:31 +0330 Subject: [PATCH 47/70] Replace paged song list with RecyclerView virtualization --- .../java/com/movemusic/app/MainActivity.kt | 264 +++++------------- 1 file changed, 77 insertions(+), 187 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 34bafd0..04207c8 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -22,6 +22,8 @@ import android.view.Gravity import android.view.MotionEvent import android.view.View import android.widget.* +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.LinearLayoutManager import org.json.JSONArray import org.json.JSONObject import androidx.media3.common.MediaItem @@ -65,16 +67,13 @@ class MainActivity : Activity() { private lateinit var header: TextView private var homeRoot: View? = null private var miniPlayerHost: LinearLayout? = null - private var songScrollView: ScrollView? = null + private var songRecyclerView: RecyclerView? = null + private var songAdapter: SongAdapter? = null private var fastScrollOverlay: FastScrollOverlay? = null - private var songRowsStartIndex = 0 - private var pendingFastScrollIndex = -1 private var visibleSongsCache: List = emptyList() private var searchQuery = "" private var searchField: EditText? = null private var searchContainer: LinearLayout? = null - private var isLoadingNextPage = false - private var hasMoreSongs = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -270,9 +269,7 @@ class MainActivity : Activity() { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { searchQuery = s?.toString()?.trim().orEmpty() - displayedSongCount = 50 - pendingFastScrollIndex = -1 - songScrollView?.scrollTo(0, 0) + songRecyclerView?.scrollToPosition(0) if (::body.isInitialized) refreshBody() } override fun afterTextChanged(s: android.text.Editable?) {} @@ -288,37 +285,28 @@ class MainActivity : Activity() { }) root.addView(searchContainer) body = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } - val scroll = ScrollView(this).apply { - isFillViewport = true - addView(body) - } - val scrollContainer = FrameLayout(this) - scrollContainer.addView( - scroll, - FrameLayout.LayoutParams(-1, -1) - ) - val fastScroller = FastScrollOverlay(scroll).apply { - visibility = View.VISIBLE - } - scrollContainer.addView( - fastScroller, - FrameLayout.LayoutParams( - (48 * resources.displayMetrics.density).toInt(), - -1, - Gravity.END - ) - ) - root.addView(scrollContainer, LinearLayout.LayoutParams(-1, 0, 1f)) - songScrollView = scroll + root.addView(body, LinearLayout.LayoutParams(-1, -2)) + val listContainer = FrameLayout(this) + val recycler = RecyclerView(this).apply { + layoutManager = LinearLayoutManager(this@MainActivity) + itemAnimator = null + setHasFixedSize(false) + } + songAdapter = SongAdapter() + recycler.adapter = songAdapter + listContainer.addView(recycler, FrameLayout.LayoutParams(-1, -1)) + val fastScroller = FastScrollOverlay(recycler).apply { visibility = View.VISIBLE } + listContainer.addView(fastScroller, FrameLayout.LayoutParams( + (48 * resources.displayMetrics.density).toInt(), -1, Gravity.END + )) + root.addView(listContainer, LinearLayout.LayoutParams(-1, 0, 1f)) + songRecyclerView = recycler fastScrollOverlay = fastScroller - scroll.setOnScrollChangeListener { _, _, scrollY, _, _ -> - fastScroller.invalidate() - val contentHeight = scroll.getChildAt(0)?.height ?: 0 - if (hasMoreSongs && !isLoadingNextPage && contentHeight > 0 && - scrollY + scroll.height >= contentHeight - scroll.height / 2) { - loadNextSongsPage() + recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + fastScroller.invalidate() } - } + }) val miniHost = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } if (currentSong != null) miniHost.addView(buildMiniPlayerBar(), LinearLayout.LayoutParams(-1, -2)) else miniHost.visibility = View.GONE @@ -362,7 +350,7 @@ class MainActivity : Activity() { } private inner class FastScrollOverlay( - private val scrollView: ScrollView + private val recyclerView: RecyclerView ) : View(this@MainActivity) { private val density = resources.displayMetrics.density private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { @@ -375,107 +363,69 @@ class MainActivity : Activity() { strokeWidth = 4f * density strokeCap = Paint.Cap.ROUND } - private val hideTask = Runnable { - indicatorVisible = false - invalidate() - } + private val hideTask = Runnable { indicatorVisible = false; invalidate() } private var dragging = false private var indicatorVisible = false private var dragOffset = 0f - private var lastTargetIndex = -1 - private val trackInset get() = 8f * density private val minimumThumb get() = 38f * density init { - // Keep a transparent touch strip attached: a GONE view cannot receive - // ACTION_DOWN, so the fast scroller could never be grabbed by the user. isClickable = true isFocusable = true setBackgroundColor(Color.TRANSPARENT) } - private fun scrollRange(): Int { - val contentHeight = scrollView.getChildAt(0)?.height ?: 0 - return (contentHeight - scrollView.height).coerceAtLeast(0) - } - - private fun totalSongCount(): Int = visibleSongsCache.size - - private fun estimatedRowHeight(): Float { - val loaded = displayedSongCount.coerceAtLeast(1) - val contentHeight = scrollView.getChildAt(0)?.height ?: 0 - return (contentHeight.toFloat() / loaded).coerceAtLeast(1f) - } - - private fun estimatedContentHeight(): Float { - return (totalSongCount() * estimatedRowHeight()).coerceAtLeast(height.toFloat()) - } - + private fun totalCount() = visibleSongsCache.size private fun thumbHeight(): Float { if (height <= 0) return minimumThumb - return (height.toFloat() * height / estimatedContentHeight()) - .coerceAtLeast(minimumThumb) - .coerceAtMost(height.toFloat()) + val count = totalCount().coerceAtLeast(1) + val visible = (recyclerView.height / (56f * density)).toInt().coerceAtLeast(1) + return (height.toFloat() * visible / count).coerceAtLeast(minimumThumb).coerceAtMost(height.toFloat()) + } + private fun currentPosition(): Int { + val manager = recyclerView.layoutManager as? LinearLayoutManager ?: return 0 + return manager.findFirstVisibleItemPosition().coerceAtLeast(0) } - private fun thumbTop(): Float { val available = (height - thumbHeight()).coerceAtLeast(0f) - val estimatedRange = (estimatedContentHeight() - height).coerceAtLeast(1f) - return available * (scrollView.scrollY.toFloat() / estimatedRange).coerceIn(0f, 1f) + val maxIndex = (totalCount() - 1).coerceAtLeast(1) + return available * (currentPosition().toFloat() / maxIndex).coerceIn(0f, 1f) } - override fun onDraw(canvas: Canvas) { super.onDraw(canvas) - if (!indicatorVisible || scrollRange() <= 0 || height <= 0) return - val centerX = width - 7f * density + if (!indicatorVisible || totalCount() <= 0 || height <= 0) return + val x = width - 7f * density val top = trackInset val bottom = height - trackInset - canvas.drawLine(centerX, top, centerX, bottom, trackPaint) + canvas.drawLine(x, top, x, bottom, trackPaint) val thumb = thumbHeight() val thumbTop = thumbTop().coerceIn(top, (bottom - thumb).coerceAtLeast(top)) - canvas.drawLine(centerX, thumbTop, centerX, thumbTop + thumb, thumbPaint) + canvas.drawLine(x, thumbTop, x, thumbTop + thumb, thumbPaint) } - private fun moveTo(y: Float) { val available = (height - thumbHeight()).coerceAtLeast(1f) - val top = (y - dragOffset - thumbHeight() / 2f) - .coerceIn(0f, available) + val top = (y - dragOffset - thumbHeight() / 2f).coerceIn(0f, available) val fraction = (top / available).coerceIn(0f, 1f) - val totalSongs = totalSongCount() - if (totalSongs > 0) { - val targetIndex = (fraction * (totalSongs - 1)).toInt() - if (targetIndex != lastTargetIndex) { - lastTargetIndex = targetIndex - scrollToSongIndex(targetIndex) - } - } + val count = totalCount() + if (count > 0) recyclerView.scrollToPosition((fraction * (count - 1)).toInt()) invalidate() } - override fun onTouchEvent(event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { uiHandler.removeCallbacks(hideTask) indicatorVisible = true - invalidate() - val currentTop = thumbTop() - val currentBottom = currentTop + thumbHeight() + val top = thumbTop() + val bottom = top + thumbHeight() dragging = true - lastTargetIndex = -1 - dragOffset = if (event.y in currentTop..currentBottom) { - event.y - currentTop - thumbHeight() / 2f - } else { - 0f - } + dragOffset = if (event.y in top..bottom) event.y - top - thumbHeight() / 2f else 0f moveTo(event.y) parent?.requestDisallowInterceptTouchEvent(true) + invalidate() return true } - MotionEvent.ACTION_MOVE -> { - if (dragging) moveTo(event.y) - return true - } + MotionEvent.ACTION_MOVE -> { if (dragging) moveTo(event.y); return true } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { dragging = false parent?.requestDisallowInterceptTouchEvent(false) @@ -496,8 +446,6 @@ class MainActivity : Activity() { )) val allVisibleSongs = visibleSongSource() visibleSongsCache = allVisibleSongs - val page = allVisibleSongs.take(displayedSongCount) - this.hasMoreSongs = allVisibleSongs.size > displayedSongCount if (currentPlaylist != "همه آهنگ‌ها" && searchQuery.isEmpty()) { body.addView(button("افزودن همه آهنگ‌ها به این پلی‌لیست") { val target = playlists[currentPlaylist] ?: return@button @@ -510,12 +458,6 @@ class MainActivity : Activity() { else "${newSongs.size} آهنگ به پلی‌لیست اضافه شد.") }) } - if (page.isEmpty()) { - body.addView(label( - if (searchQuery.isEmpty()) "اینجا هنوز آهنگی نیست." else "نتیجه‌ای پیدا نشد.", - 13, muted - )) - } if (searchQuery.isEmpty()) { body.addView(button(if (shuffleEnabled) "پخش تصادفی: روشن" else "پخش تصادفی: خاموش") { shuffleEnabled = !shuffleEnabled @@ -523,12 +465,30 @@ class MainActivity : Activity() { toast(if (shuffleEnabled) "پخش تصادفی فعال شد." else "پخش تصادفی غیرفعال شد.") }) } - songRowsStartIndex = body.childCount - page.forEach { song -> addSongRow(song) } + songAdapter?.setSongs(allVisibleSongs) + songRecyclerView?.scrollToPosition(0) fastScrollOverlay?.invalidate() } - private fun addSongRow(song: Song) { + private inner class SongAdapter : RecyclerView.Adapter() { + private var items: List = emptyList() + inner class SongHolder(val container: FrameLayout) : RecyclerView.ViewHolder(container) + fun setSongs(songs: List) { + items = songs + notifyDataSetChanged() + } + override fun getItemCount() = items.size + override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): SongHolder { + return SongHolder(FrameLayout(this@MainActivity)) + } + override fun onBindViewHolder(holder: SongHolder, position: Int) { + val song = items[position] + holder.container.removeAllViews() + holder.container.addView(buildSongRow(song), FrameLayout.LayoutParams(-1, -2)) + } + } + + private fun buildSongRow(song: Song): View { val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL gravity = Gravity.CENTER_VERTICAL @@ -540,30 +500,21 @@ class MainActivity : Activity() { gravity = Gravity.CENTER_VERTICAL } details.addView(TextView(this).apply { - text = song.title - textSize = 14f - setTextColor(white) - maxLines = 1 - ellipsize = android.text.TextUtils.TruncateAt.END + text = song.title; textSize = 14f; setTextColor(white) + maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END }) details.addView(TextView(this).apply { - text = song.artist - textSize = 11f - setTextColor(muted) - maxLines = 1 - ellipsize = android.text.TextUtils.TruncateAt.END + text = song.artist; textSize = 11f; setTextColor(muted) + maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END }) row.addView(details, LinearLayout.LayoutParams(0, -2, 1f)) val actions = LinearLayout(this).apply { - orientation = LinearLayout.HORIZONTAL - gravity = Gravity.CENTER_VERTICAL + orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL } if (currentPlaylist != "همه آهنگ‌ها") { actions.addView(button("انتقال") { moveSong(song) }) actions.addView(button("حذف") { - playlists[currentPlaylist]?.remove(song.id) - savePlaylists() - refreshBody() + playlists[currentPlaylist]?.remove(song.id); savePlaylists(); refreshBody() }) } else { actions.addView(button("+ لیست") { addSong(song) }) @@ -572,68 +523,7 @@ class MainActivity : Activity() { row.isClickable = true row.isFocusable = true row.setOnClickListener { play(song) } - body.addView(row, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = 3 }) - } - - private fun loadNextSongsPage() { - if (!hasMoreSongs || isLoadingNextPage) return - isLoadingNextPage = true - - // Normal list scrolling appends one page. During fast-scroll dragging, - // keep extending directly toward the latest requested index instead of - // stopping after each 50-row page. - fun appendNextChunk() { - val requestedTarget = pendingFastScrollIndex - val targetLimit = if (requestedTarget >= displayedSongCount) { - (requestedTarget + 1).coerceAtMost(visibleSongsCache.size) - } else { - (displayedSongCount + 50).coerceAtMost(visibleSongsCache.size) - } - val end = minOf(displayedSongCount + 20, targetLimit) - while (displayedSongCount < end) { - addSongRow(visibleSongsCache[displayedSongCount]) - displayedSongCount++ - } - - hasMoreSongs = displayedSongCount < visibleSongsCache.size - fastScrollOverlay?.invalidate() - - if (pendingFastScrollIndex >= displayedSongCount && - displayedSongCount < visibleSongsCache.size) { - // Continue toward the finger's most recent position without - // waiting for another drag event or starting a new page cycle. - uiHandler.post { appendNextChunk() } - return - } - - isLoadingNextPage = false - if (pendingFastScrollIndex >= 0) { - val target = pendingFastScrollIndex - pendingFastScrollIndex = -1 - scrollToSongIndex(target) - } - } - - appendNextChunk() - } - - private fun scrollToSongIndex(index: Int) { - val totalSongs = visibleSongsCache.size - if (totalSongs == 0) return - val target = index.coerceIn(0, totalSongs - 1) - - if (target >= displayedSongCount && hasMoreSongs) { - pendingFastScrollIndex = target - if (!isLoadingNextPage) loadNextSongsPage() - return - } - if (isLoadingNextPage) { - pendingFastScrollIndex = target - return - } - - val row = body.getChildAt(songRowsStartIndex + target) ?: return - songScrollView?.scrollTo(0, row.top) + return row } private fun moveSong(song: Song) { From 6610c69051eef92a6b163b93d8f2521f7b4d850c Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:40:36 +0330 Subject: [PATCH 48/70] Add RecyclerView dependency for virtualized library list --- app/build.gradle.kts | 1 + 1 file changed, 1 insertion(+) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 51aa64e..f19b73d 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -29,4 +29,5 @@ dependencies { implementation("io.coil-kt.coil3:coil:3.0.4") implementation("androidx.media3:media3-exoplayer:1.5.1") implementation("androidx.media3:media3-session:1.5.1") + implementation("androidx.recyclerview:recyclerview:1.3.2") } From e949b9287a02d53f95d1606d30bcc3245129d01c Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:43:28 +0330 Subject: [PATCH 49/70] Include WAV files in music library scan --- app/src/main/java/com/movemusic/app/MainActivity.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 04207c8..b71dd44 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -179,7 +179,9 @@ class MainActivity : Activity() { contentResolver.query( collection, projection, - "${MediaStore.Audio.Media.IS_MUSIC} != 0", + """${MediaStore.Audio.Media.IS_MUSIC} != 0 + OR ${MediaStore.Audio.Media.MIME_TYPE} IN ('audio/wav', 'audio/x-wav', 'audio/vnd.wave', 'audio/wave') + OR ${MediaStore.Audio.Media.DISPLAY_NAME} LIKE '%.wav'""".trimIndent(), null, "${MediaStore.Audio.Media.TITLE} COLLATE NOCASE ASC" )?.use { cursor -> From af956594b4b7db3ab54cd1a3fc5ef9738d05bc20 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 01:52:00 +0330 Subject: [PATCH 50/70] Fix song rows to fill RecyclerView width --- app/src/main/java/com/movemusic/app/MainActivity.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index b71dd44..5157714 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -481,7 +481,14 @@ class MainActivity : Activity() { } override fun getItemCount() = items.size override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): SongHolder { - return SongHolder(FrameLayout(this@MainActivity)) + val container = FrameLayout(this@MainActivity).apply { + // RecyclerView items must occupy the full available row width. + layoutParams = RecyclerView.LayoutParams( + RecyclerView.LayoutParams.MATCH_PARENT, + RecyclerView.LayoutParams.WRAP_CONTENT + ) + } + return SongHolder(container) } override fun onBindViewHolder(holder: SongHolder, position: Int) { val song = items[position] From 1389d836e94be8fddc3ae49b5000259c447c1dde Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 14:38:41 +0330 Subject: [PATCH 51/70] Restore full playback queue for lock-screen controls --- .../java/com/movemusic/app/MainActivity.kt | 36 ++++--------------- 1 file changed, 7 insertions(+), 29 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 5157714..6335d01 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -604,10 +604,13 @@ class MainActivity : Activity() { } val requestToken = ++playbackRequestToken - val queueSnapshot = playbackQueue + val queueSnapshot = playbackQueue.ifEmpty { listOf(song) } val selectedIndex = queueSnapshot.indexOfFirst { it.id == song.id } .takeIf { it >= 0 } ?: 0 + // Publish the complete queue to Media3 immediately. Android's + // MediaSession uses the available previous/next items to expose the + // three standard lock-screen controls: previous, play/pause, next. fun mediaItem(queuedSong: Song): MediaItem { val metadata = MediaMetadata.Builder() .setTitle(queuedSong.title) @@ -620,41 +623,16 @@ class MainActivity : Activity() { .build() } - // Start the selected local file immediately. Never wait for the - // potentially large playlist to be converted into Media3 items. try { - controller.setMediaItem(mediaItem(song)) + val mediaItems = queueSnapshot.map(::mediaItem) + if (requestToken != playbackRequestToken || player !== controller) return + controller.setMediaItems(mediaItems, selectedIndex, 0L) controller.prepare() controller.play() updatePlayerControls() } catch (_: Exception) { toast("باز کردن فایل موسیقی ممکن نشد.") - return } - - // Populate the rest of the queue in the background while the selected - // track is already playing. Inserting before/after the current item - // preserves the active playback position. - if (queueSnapshot.size <= 1) return - Thread { - val previousItems = queueSnapshot.subList(0, selectedIndex).map(::mediaItem) - val nextItems = queueSnapshot.subList(selectedIndex + 1, queueSnapshot.size).map(::mediaItem) - runOnUiThread { - if (requestToken != playbackRequestToken || player !== controller || - controller.currentMediaItem?.mediaId != song.id.toString()) return@runOnUiThread - try { - if (previousItems.isNotEmpty()) { - controller.addMediaItems(0, previousItems) - } - if (nextItems.isNotEmpty()) { - controller.addMediaItems(controller.currentMediaItemIndex + 1, nextItems) - } - } catch (_: Exception) { - // The current track is already playing; queue enrichment - // must never interrupt it. - } - } - }.start() } private fun showPlayerScreen() { From 727c3716e5ef0aba2bed9832307e2a7fb4401f7e Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 14:52:04 +0330 Subject: [PATCH 52/70] Start playback immediately and build remaining queue in background --- .../java/com/movemusic/app/MainActivity.kt | 46 +++++++++++++++++-- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 6335d01..9d18ce5 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -608,9 +608,6 @@ class MainActivity : Activity() { val selectedIndex = queueSnapshot.indexOfFirst { it.id == song.id } .takeIf { it >= 0 } ?: 0 - // Publish the complete queue to Media3 immediately. Android's - // MediaSession uses the available previous/next items to expose the - // three standard lock-screen controls: previous, play/pause, next. fun mediaItem(queuedSong: Song): MediaItem { val metadata = MediaMetadata.Builder() .setTitle(queuedSong.title) @@ -623,16 +620,55 @@ class MainActivity : Activity() { .build() } + // Start playback with only the selected track and its immediate + // neighbours. This exposes previous/next to MediaSession straight + // away without building the entire library on the UI thread. + val firstIndex = (selectedIndex - 1).coerceAtLeast(0) + val lastIndex = (selectedIndex + 1).coerceAtMost(queueSnapshot.lastIndex) + val initialItems = (firstIndex..lastIndex).map { mediaItem(queueSnapshot[it]) } + val initialCurrentIndex = selectedIndex - firstIndex + try { - val mediaItems = queueSnapshot.map(::mediaItem) if (requestToken != playbackRequestToken || player !== controller) return - controller.setMediaItems(mediaItems, selectedIndex, 0L) + controller.setMediaItems(initialItems, initialCurrentIndex, 0L) controller.prepare() controller.play() updatePlayerControls() } catch (_: Exception) { toast("باز کردن فایل موسیقی ممکن نشد.") + return } + + // Build the remaining queue off the main thread. Insert it around + // the currently playing item so playback position and lock-screen + // controls remain intact. + if (firstIndex == 0 && lastIndex == queueSnapshot.lastIndex) return + Thread { + try { + val previousItems = (0 until firstIndex) + .map { mediaItem(queueSnapshot[it]) } + val nextItems = ((lastIndex + 1)..queueSnapshot.lastIndex) + .map { mediaItem(queueSnapshot[it]) } + + runOnUiThread { + if (requestToken != playbackRequestToken || player !== controller || + controller.currentMediaItem?.mediaId != song.id.toString()) return@runOnUiThread + try { + if (previousItems.isNotEmpty()) { + controller.addMediaItems(0, previousItems) + } + if (nextItems.isNotEmpty()) { + controller.addMediaItems(controller.currentMediaItemIndex + 1, nextItems) + } + } catch (_: Exception) { + // The selected track is already playing; queue + // completion must not interrupt it. + } + } + } catch (_: Exception) { + // Keep current playback running if queue preparation fails. + } + }.start() } private fun showPlayerScreen() { From c905568be0eb66d29c7e04e84451dbaf3b08c95d Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 15:12:06 +0330 Subject: [PATCH 53/70] Move song actions away from fast scroller and add confirmed file deletion --- .../java/com/movemusic/app/MainActivity.kt | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 9d18ce5..270ee31 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -3,6 +3,7 @@ package com.movemusic.app import android.Manifest import android.app.Activity import android.app.AlertDialog +import android.app.RecoverableSecurityException import android.content.ContentUris import android.content.ComponentName import android.content.Intent @@ -74,6 +75,7 @@ class MainActivity : Activity() { private var searchQuery = "" private var searchField: EditText? = null private var searchContainer: LinearLayout? = null + private val deleteRequestCode = 4102 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -293,6 +295,8 @@ class MainActivity : Activity() { layoutManager = LinearLayoutManager(this@MainActivity) itemAnimator = null setHasFixedSize(false) + setPadding(paddingLeft, paddingTop, (56 * resources.displayMetrics.density).toInt(), paddingBottom) + clipToPadding = false } songAdapter = SongAdapter() recycler.adapter = songAdapter @@ -527,6 +531,7 @@ class MainActivity : Activity() { }) } else { actions.addView(button("+ لیست") { addSong(song) }) + actions.addView(button("حذف") { confirmDeleteSong(song) }) } row.addView(actions) row.isClickable = true @@ -559,6 +564,57 @@ class MainActivity : Activity() { }.show() } + private fun confirmDeleteSong(song: Song) { + AlertDialog.Builder(this) + .setTitle("حذف آهنگ") + .setMessage("آیا مطمئنی می‌خواهی «" + song.title + "» را برای همیشه از گوشی حذف کنی؟") + .setNegativeButton("انصراف", null) + .setPositiveButton("حذف") { _, _ -> requestSongDeletion(song) } + .show() + } + + private fun requestSongDeletion(song: Song) { + try { + if (Build.VERSION.SDK_INT >= 30) { + val request = MediaStore.createDeleteRequest(contentResolver, listOf(song.uri)) + startIntentSenderForResult(request.intentSender, deleteRequestCode, null, 0, 0, 0) + } else { + val deleted = contentResolver.delete(song.uri, null, null) + if (deleted > 0) onSongDeleted(song) else toast("حذف آهنگ انجام نشد.") + } + } catch (e: RecoverableSecurityException) { + if (Build.VERSION.SDK_INT == 29) { + try { + startIntentSenderForResult(e.userAction.actionIntent.intentSender, deleteRequestCode, null, 0, 0, 0) + } catch (_: Exception) { toast("درخواست مجوز حذف باز نشد.") } + } else toast("حذف آهنگ ممکن نشد.") + } catch (_: Exception) { + toast("حذف آهنگ ممکن نشد.") + } + } + + private fun onSongDeleted(song: Song) { + songs.removeAll { it.id == song.id } + playlists.values.forEach { it.remove(song.id) } + savePlaylists() + if (currentSong?.id == song.id) { + try { player?.stop() } catch (_: Exception) {} + currentSong = null + playbackQueue = emptyList() + currentSongIndex = -1 + miniPlayerHost?.removeAllViews() + miniPlayerHost?.visibility = View.GONE + } else playbackQueue = playbackQueue.filterNot { it.id == song.id } + refreshBody() + toast("آهنگ از گوشی حذف شد.") + } + + @Suppress("DEPRECATION") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + if (requestCode == deleteRequestCode && resultCode == RESULT_OK) loadSongsAsync() + } + private fun showPlaylistChooser() { val names = playlists.keys.toMutableList() names.add(0, "همه آهنگ‌ها") From 8208e06dd95a8dbbface304ee9da90f853c297ba Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 15:32:36 +0330 Subject: [PATCH 54/70] Handle each MediaStore deletion confirmation independently --- app/src/main/java/com/movemusic/app/MainActivity.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 270ee31..7f557af 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -76,6 +76,7 @@ class MainActivity : Activity() { private var searchField: EditText? = null private var searchContainer: LinearLayout? = null private val deleteRequestCode = 4102 + private var pendingDeletionSong: Song? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -576,6 +577,7 @@ class MainActivity : Activity() { private fun requestSongDeletion(song: Song) { try { if (Build.VERSION.SDK_INT >= 30) { + pendingDeletionSong = song val request = MediaStore.createDeleteRequest(contentResolver, listOf(song.uri)) startIntentSenderForResult(request.intentSender, deleteRequestCode, null, 0, 0, 0) } else { @@ -612,7 +614,12 @@ class MainActivity : Activity() { @Suppress("DEPRECATION") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) - if (requestCode == deleteRequestCode && resultCode == RESULT_OK) loadSongsAsync() + if (requestCode == deleteRequestCode) { + val deletedSong = pendingDeletionSong + pendingDeletionSong = null + if (resultCode == RESULT_OK && deletedSong != null) onSongDeleted(deletedSong) + else if (resultCode != RESULT_OK) toast("حذف آهنگ لغو شد.") + } } private fun showPlaylistChooser() { From 7bda92b8089e463c98a5db82169a875a49523661 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 15:38:38 +0330 Subject: [PATCH 55/70] Align and enlarge song action buttons; remove footer hint --- .../java/com/movemusic/app/MainActivity.kt | 37 +++++++++++++++---- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 7f557af..d1756dc 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -296,7 +296,7 @@ class MainActivity : Activity() { layoutManager = LinearLayoutManager(this@MainActivity) itemAnimator = null setHasFixedSize(false) - setPadding(paddingLeft, paddingTop, (56 * resources.displayMetrics.density).toInt(), paddingBottom) + setPadding(paddingLeft, paddingTop, (36 * resources.displayMetrics.density).toInt(), paddingBottom) clipToPadding = false } songAdapter = SongAdapter() @@ -304,7 +304,7 @@ class MainActivity : Activity() { listContainer.addView(recycler, FrameLayout.LayoutParams(-1, -1)) val fastScroller = FastScrollOverlay(recycler).apply { visibility = View.VISIBLE } listContainer.addView(fastScroller, FrameLayout.LayoutParams( - (48 * resources.displayMetrics.density).toInt(), -1, Gravity.END + (32 * resources.displayMetrics.density).toInt(), -1, Gravity.END )) root.addView(listContainer, LinearLayout.LayoutParams(-1, 0, 1f)) songRecyclerView = recycler @@ -319,7 +319,6 @@ class MainActivity : Activity() { else miniHost.visibility = View.GONE root.addView(miniHost, LinearLayout.LayoutParams(-1, -2)) miniPlayerHost = miniHost - root.addView(label("برای انتقال، آهنگ را انتخاب کن و «انتقال به…» را بزن.", 10, muted)) homeRoot = root setContentView(root) refreshBody() @@ -526,13 +525,13 @@ class MainActivity : Activity() { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL } if (currentPlaylist != "همه آهنگ‌ها") { - actions.addView(button("انتقال") { moveSong(song) }) - actions.addView(button("حذف") { + actions.addView(songActionButton("انتقال") { moveSong(song) }) + actions.addView(songActionButton("حذف") { playlists[currentPlaylist]?.remove(song.id); savePlaylists(); refreshBody() }) } else { - actions.addView(button("+ لیست") { addSong(song) }) - actions.addView(button("حذف") { confirmDeleteSong(song) }) + actions.addView(songActionButton("+ لیست") { addSong(song) }) + actions.addView(songActionButton("حذف") { confirmDeleteSong(song) }) } row.addView(actions) row.isClickable = true @@ -541,6 +540,30 @@ class MainActivity : Activity() { return row } + private fun songActionButton(text: String, action: () -> Unit) = TextView(this).apply { + this.text = text + textSize = 12f + setTextColor(white) + gravity = Gravity.CENTER + minHeight = (36 * resources.displayMetrics.density).toInt() + minWidth = 0 + setPadding( + (11 * resources.displayMetrics.density).toInt(), + (7 * resources.displayMetrics.density).toInt(), + (11 * resources.displayMetrics.density).toInt(), + (7 * resources.displayMetrics.density).toInt() + ) + background = android.graphics.drawable.GradientDrawable().apply { + setColor(blue) + cornerRadius = 7f * resources.displayMetrics.density + } + layoutParams = LinearLayout.LayoutParams(-2, -2).apply { + marginStart = (2 * resources.displayMetrics.density).toInt() + marginEnd = (2 * resources.displayMetrics.density).toInt() + } + setOnClickListener { action() } + } + private fun moveSong(song: Song) { val destinations = playlists.keys.filter { it != currentPlaylist }.toTypedArray() if (destinations.isEmpty()) { toast("اول یک پلی‌لیست دیگر بساز."); return } From 6d2d247a01070c1808aa465a349375eb0f8d4c13 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 15:50:59 +0330 Subject: [PATCH 56/70] Fix delete permission flow and bring song actions beside fast scroller --- .../java/com/movemusic/app/MainActivity.kt | 41 +++++++++++-------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index d1756dc..7b3730f 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -23,6 +23,8 @@ import android.view.Gravity import android.view.MotionEvent import android.view.View import android.widget.* +import androidx.activity.result.IntentSenderRequest +import androidx.activity.result.contract.ActivityResultContracts import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.LinearLayoutManager import org.json.JSONArray @@ -75,8 +77,18 @@ class MainActivity : Activity() { private var searchQuery = "" private var searchField: EditText? = null private var searchContainer: LinearLayout? = null - private val deleteRequestCode = 4102 private var pendingDeletionSong: Song? = null + private val deletePermissionLauncher = registerForActivityResult( + ActivityResultContracts.StartIntentSenderForResult() + ) { result -> + val deletedSong = pendingDeletionSong + pendingDeletionSong = null + if (result.resultCode == RESULT_OK && deletedSong != null) { + onSongDeleted(deletedSong) + } else if (result.resultCode != RESULT_OK) { + toast("حذف آهنگ لغو شد.") + } + } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -296,7 +308,7 @@ class MainActivity : Activity() { layoutManager = LinearLayoutManager(this@MainActivity) itemAnimator = null setHasFixedSize(false) - setPadding(paddingLeft, paddingTop, (36 * resources.displayMetrics.density).toInt(), paddingBottom) + setPadding(paddingLeft, paddingTop, (14 * resources.displayMetrics.density).toInt(), paddingBottom) clipToPadding = false } songAdapter = SongAdapter() @@ -304,7 +316,7 @@ class MainActivity : Activity() { listContainer.addView(recycler, FrameLayout.LayoutParams(-1, -1)) val fastScroller = FastScrollOverlay(recycler).apply { visibility = View.VISIBLE } listContainer.addView(fastScroller, FrameLayout.LayoutParams( - (32 * resources.displayMetrics.density).toInt(), -1, Gravity.END + (16 * resources.displayMetrics.density).toInt(), -1, Gravity.END )) root.addView(listContainer, LinearLayout.LayoutParams(-1, 0, 1f)) songRecyclerView = recycler @@ -418,6 +430,9 @@ class MainActivity : Activity() { invalidate() } override fun onTouchEvent(event: MotionEvent): Boolean { + // Keep the overlay's touch target limited to the scrollbar itself. + // The song action buttons can then sit close to it without being covered. + if (event.x < width - 12f * density) return false when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { uiHandler.removeCallbacks(hideTask) @@ -602,7 +617,9 @@ class MainActivity : Activity() { if (Build.VERSION.SDK_INT >= 30) { pendingDeletionSong = song val request = MediaStore.createDeleteRequest(contentResolver, listOf(song.uri)) - startIntentSenderForResult(request.intentSender, deleteRequestCode, null, 0, 0, 0) + deletePermissionLauncher.launch( + IntentSenderRequest.Builder(request.intentSender).build() + ) } else { val deleted = contentResolver.delete(song.uri, null, null) if (deleted > 0) onSongDeleted(song) else toast("حذف آهنگ انجام نشد.") @@ -610,7 +627,10 @@ class MainActivity : Activity() { } catch (e: RecoverableSecurityException) { if (Build.VERSION.SDK_INT == 29) { try { - startIntentSenderForResult(e.userAction.actionIntent.intentSender, deleteRequestCode, null, 0, 0, 0) + pendingDeletionSong = song + deletePermissionLauncher.launch( + IntentSenderRequest.Builder(e.userAction.actionIntent.intentSender).build() + ) } catch (_: Exception) { toast("درخواست مجوز حذف باز نشد.") } } else toast("حذف آهنگ ممکن نشد.") } catch (_: Exception) { @@ -634,17 +654,6 @@ class MainActivity : Activity() { toast("آهنگ از گوشی حذف شد.") } - @Suppress("DEPRECATION") - override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { - super.onActivityResult(requestCode, resultCode, data) - if (requestCode == deleteRequestCode) { - val deletedSong = pendingDeletionSong - pendingDeletionSong = null - if (resultCode == RESULT_OK && deletedSong != null) onSongDeleted(deletedSong) - else if (resultCode != RESULT_OK) toast("حذف آهنگ لغو شد.") - } - } - private fun showPlaylistChooser() { val names = playlists.keys.toMutableList() names.add(0, "همه آهنگ‌ها") From 040ca8e127a3712042657fe755e9a9b09c7623ed Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 15:51:28 +0330 Subject: [PATCH 57/70] Use ComponentActivity for reliable delete permission result handling --- app/src/main/java/com/movemusic/app/MainActivity.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 7b3730f..af1967d 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -23,6 +23,7 @@ import android.view.Gravity import android.view.MotionEvent import android.view.View import android.widget.* +import androidx.activity.ComponentActivity import androidx.activity.result.IntentSenderRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.recyclerview.widget.RecyclerView @@ -42,7 +43,7 @@ import coil3.size.Precision data class Song(val id: Long, val title: String, val artist: String, val albumId: Long, val uri: Uri) -class MainActivity : Activity() { +class MainActivity : ComponentActivity() { private val blue = 0xFF168BFF.toInt() private val bg = 0xFF05070B.toInt() private val panel = 0xFF111722.toInt() From f232cc3718afbc5acbc1e3b9518513405fc4d940 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 15:52:13 +0330 Subject: [PATCH 58/70] Add AndroidX Activity Result API dependency --- app/build.gradle.kts | 1 + 1 file changed, 1 insertion(+) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f19b73d..3ec6317 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -30,4 +30,5 @@ dependencies { implementation("androidx.media3:media3-exoplayer:1.5.1") implementation("androidx.media3:media3-session:1.5.1") implementation("androidx.recyclerview:recyclerview:1.3.2") + implementation("androidx.activity:activity-ktx:1.10.1") } From d5b741ee46a50539967799746196f39c69e4ddaf Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 15:56:20 +0330 Subject: [PATCH 59/70] Reuse song row views to reduce return-to-library rendering delay --- .../java/com/movemusic/app/MainActivity.kt | 124 +++++++++++------- 1 file changed, 79 insertions(+), 45 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index af1967d..17cdd64 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -494,66 +494,100 @@ class MainActivity : ComponentActivity() { private inner class SongAdapter : RecyclerView.Adapter() { private var items: List = emptyList() - inner class SongHolder(val container: FrameLayout) : RecyclerView.ViewHolder(container) + + inner class SongHolder( + val row: LinearLayout, + val titleView: TextView, + val artistView: TextView, + val addButton: TextView, + val transferButton: TextView, + val removeButton: TextView, + val deleteFileButton: TextView + ) : RecyclerView.ViewHolder(row) { + var boundSong: Song? = null + } + fun setSongs(songs: List) { items = songs notifyDataSetChanged() } + override fun getItemCount() = items.size + override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): SongHolder { - val container = FrameLayout(this@MainActivity).apply { - // RecyclerView items must occupy the full available row width. + val row = LinearLayout(this@MainActivity).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(10, 5, 6, 5) + setBackgroundColor(panel) layoutParams = RecyclerView.LayoutParams( RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT ) } - return SongHolder(container) + val details = LinearLayout(this@MainActivity).apply { + orientation = LinearLayout.VERTICAL + gravity = Gravity.CENTER_VERTICAL + } + val title = TextView(this@MainActivity).apply { + textSize = 14f + setTextColor(white) + maxLines = 1 + ellipsize = android.text.TextUtils.TruncateAt.END + } + val artist = TextView(this@MainActivity).apply { + textSize = 11f + setTextColor(muted) + maxLines = 1 + ellipsize = android.text.TextUtils.TruncateAt.END + } + details.addView(title) + details.addView(artist) + row.addView(details, LinearLayout.LayoutParams(0, -2, 1f)) + + val actions = LinearLayout(this@MainActivity).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + } + lateinit var holder: SongHolder + val add = songActionButton("+ لیست") { + holder.boundSong?.let { addSong(it) } + } + val transfer = songActionButton("انتقال") { + holder.boundSong?.let { moveSong(it) } + } + val remove = songActionButton("حذف") { + holder.boundSong?.let { song -> + playlists[currentPlaylist]?.remove(song.id) + savePlaylists() + refreshBody() + } + } + val deleteFile = songActionButton("حذف") { + holder.boundSong?.let { confirmDeleteSong(it) } + } + actions.addView(add) + actions.addView(transfer) + actions.addView(remove) + actions.addView(deleteFile) + row.addView(actions) + + holder = SongHolder(row, title, artist, add, transfer, remove, deleteFile) + row.setOnClickListener { holder.boundSong?.let { play(it) } } + return holder } + override fun onBindViewHolder(holder: SongHolder, position: Int) { val song = items[position] - holder.container.removeAllViews() - holder.container.addView(buildSongRow(song), FrameLayout.LayoutParams(-1, -2)) - } - } - - private fun buildSongRow(song: Song): View { - val row = LinearLayout(this).apply { - orientation = LinearLayout.HORIZONTAL - gravity = Gravity.CENTER_VERTICAL - setPadding(10, 5, 6, 5) - setBackgroundColor(panel) - } - val details = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - gravity = Gravity.CENTER_VERTICAL - } - details.addView(TextView(this).apply { - text = song.title; textSize = 14f; setTextColor(white) - maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END - }) - details.addView(TextView(this).apply { - text = song.artist; textSize = 11f; setTextColor(muted) - maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END - }) - row.addView(details, LinearLayout.LayoutParams(0, -2, 1f)) - val actions = LinearLayout(this).apply { - orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL - } - if (currentPlaylist != "همه آهنگ‌ها") { - actions.addView(songActionButton("انتقال") { moveSong(song) }) - actions.addView(songActionButton("حذف") { - playlists[currentPlaylist]?.remove(song.id); savePlaylists(); refreshBody() - }) - } else { - actions.addView(songActionButton("+ لیست") { addSong(song) }) - actions.addView(songActionButton("حذف") { confirmDeleteSong(song) }) + holder.boundSong = song + holder.titleView.text = song.title + holder.artistView.text = song.artist + val inAllSongs = currentPlaylist == "همه آهنگ‌ها" + holder.addButton.visibility = if (inAllSongs) View.VISIBLE else View.GONE + holder.deleteFileButton.visibility = if (inAllSongs) View.VISIBLE else View.GONE + holder.transferButton.visibility = if (inAllSongs) View.GONE else View.VISIBLE + holder.removeButton.visibility = if (inAllSongs) View.GONE else View.VISIBLE } - row.addView(actions) - row.isClickable = true - row.isFocusable = true - row.setOnClickListener { play(song) } - return row } private fun songActionButton(text: String, action: () -> Unit) = TextView(this).apply { From d4d936be376b2ff642fdeccf6343b6a299445c27 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 16:10:08 +0330 Subject: [PATCH 60/70] Fix permission callback Kotlin override signature --- app/src/main/java/com/movemusic/app/MainActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 17cdd64..038980f 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -170,7 +170,7 @@ class MainActivity : ComponentActivity() { } } - override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, results: IntArray) { + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, results: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, results) if (requestCode == 10 && results.firstOrNull() == PackageManager.PERMISSION_GRANTED) { loadSongsAsync() From e97f3f01bc93fd3e86438bf891fe468f8a210704 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 16:33:25 +0330 Subject: [PATCH 61/70] Reduce list right padding and batch playback queue updates --- .../java/com/movemusic/app/MainActivity.kt | 41 ++++++++++++++----- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 038980f..2cac232 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -309,7 +309,7 @@ class MainActivity : ComponentActivity() { layoutManager = LinearLayoutManager(this@MainActivity) itemAnimator = null setHasFixedSize(false) - setPadding(paddingLeft, paddingTop, (14 * resources.displayMetrics.density).toInt(), paddingBottom) + setPadding(paddingLeft, paddingTop, (7 * resources.displayMetrics.density).toInt(), paddingBottom) clipToPadding = false } songAdapter = SongAdapter() @@ -780,21 +780,42 @@ class MainActivity : ComponentActivity() { val nextItems = ((lastIndex + 1)..queueSnapshot.lastIndex) .map { mediaItem(queueSnapshot[it]) } - runOnUiThread { + // Add the rest of the queue in small UI-thread batches. + // A single large addMediaItems() call can block input handling + // (including the system Back button) while the first tracks load. + val batchSize = 40 + fun addPreviousBatch(endExclusive: Int) { if (requestToken != playbackRequestToken || player !== controller || - controller.currentMediaItem?.mediaId != song.id.toString()) return@runOnUiThread + controller.currentMediaItem?.mediaId != song.id.toString()) return try { - if (previousItems.isNotEmpty()) { - controller.addMediaItems(0, previousItems) - } - if (nextItems.isNotEmpty()) { - controller.addMediaItems(controller.currentMediaItemIndex + 1, nextItems) + if (endExclusive <= 0) { + addNextBatch(0) + return } + val start = (endExclusive - batchSize).coerceAtLeast(0) + controller.addMediaItems(0, previousItems.subList(start, endExclusive)) + uiHandler.post { addPreviousBatch(start) } } catch (_: Exception) { - // The selected track is already playing; queue - // completion must not interrupt it. + // Keep current playback running if queue completion fails. } } + fun addNextBatch(start: Int) { + if (requestToken != playbackRequestToken || player !== controller || + controller.currentMediaItem?.mediaId != song.id.toString()) return + try { + if (start >= nextItems.size) return + val end = (start + batchSize).coerceAtMost(nextItems.size) + val insertionIndex = controller.currentMediaItemIndex + 1 + + (start) + controller.addMediaItems(insertionIndex, nextItems.subList(start, end)) + uiHandler.post { addNextBatch(end) } + } catch (_: Exception) { + // Keep current playback running if queue completion fails. + } + } + runOnUiThread { + addPreviousBatch(previousItems.size) + } } catch (_: Exception) { // Keep current playback running if queue preparation fails. } From 4c846c3fce0a8ef6e49da0dcb5a515236d7493d7 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 16:40:28 +0330 Subject: [PATCH 62/70] Fix queue batch local function declaration order --- .../java/com/movemusic/app/MainActivity.kt | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 2cac232..a661e16 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -784,6 +784,20 @@ class MainActivity : ComponentActivity() { // A single large addMediaItems() call can block input handling // (including the system Back button) while the first tracks load. val batchSize = 40 + fun addNextBatch(start: Int) { + if (requestToken != playbackRequestToken || player !== controller || + controller.currentMediaItem?.mediaId != song.id.toString()) return + try { + if (start >= nextItems.size) return + val end = (start + batchSize).coerceAtMost(nextItems.size) + val insertionIndex = controller.currentMediaItemIndex + 1 + + (start) + controller.addMediaItems(insertionIndex, nextItems.subList(start, end)) + uiHandler.post { addNextBatch(end) } + } catch (_: Exception) { + // Keep current playback running if queue completion fails. + } + } fun addPreviousBatch(endExclusive: Int) { if (requestToken != playbackRequestToken || player !== controller || controller.currentMediaItem?.mediaId != song.id.toString()) return @@ -799,20 +813,6 @@ class MainActivity : ComponentActivity() { // Keep current playback running if queue completion fails. } } - fun addNextBatch(start: Int) { - if (requestToken != playbackRequestToken || player !== controller || - controller.currentMediaItem?.mediaId != song.id.toString()) return - try { - if (start >= nextItems.size) return - val end = (start + batchSize).coerceAtMost(nextItems.size) - val insertionIndex = controller.currentMediaItemIndex + 1 + - (start) - controller.addMediaItems(insertionIndex, nextItems.subList(start, end)) - uiHandler.post { addNextBatch(end) } - } catch (_: Exception) { - // Keep current playback running if queue completion fails. - } - } runOnUiThread { addPreviousBatch(previousItems.size) } From 4254eb8d48fc47bc57a01862f32e097daa624cb4 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 16:59:19 +0330 Subject: [PATCH 63/70] Improve queue batching responsiveness --- app/src/main/java/com/movemusic/app/MainActivity.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index a661e16..905270e 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -783,7 +783,7 @@ class MainActivity : ComponentActivity() { // Add the rest of the queue in small UI-thread batches. // A single large addMediaItems() call can block input handling // (including the system Back button) while the first tracks load. - val batchSize = 40 + val batchSize = 10 fun addNextBatch(start: Int) { if (requestToken != playbackRequestToken || player !== controller || controller.currentMediaItem?.mediaId != song.id.toString()) return @@ -793,7 +793,7 @@ class MainActivity : ComponentActivity() { val insertionIndex = controller.currentMediaItemIndex + 1 + (start) controller.addMediaItems(insertionIndex, nextItems.subList(start, end)) - uiHandler.post { addNextBatch(end) } + uiHandler.postDelayed({ addNextBatch(end) }, 40L) } catch (_: Exception) { // Keep current playback running if queue completion fails. } @@ -808,7 +808,7 @@ class MainActivity : ComponentActivity() { } val start = (endExclusive - batchSize).coerceAtLeast(0) controller.addMediaItems(0, previousItems.subList(start, endExclusive)) - uiHandler.post { addPreviousBatch(start) } + uiHandler.postDelayed({ addPreviousBatch(start) }, 40L) } catch (_: Exception) { // Keep current playback running if queue completion fails. } From fe229f851d54417599708fc73db7cc5175fd5104 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 17:13:56 +0330 Subject: [PATCH 64/70] Increase fast scroller touch area --- app/src/main/java/com/movemusic/app/MainActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 905270e..29cbbb5 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -317,7 +317,7 @@ class MainActivity : ComponentActivity() { listContainer.addView(recycler, FrameLayout.LayoutParams(-1, -1)) val fastScroller = FastScrollOverlay(recycler).apply { visibility = View.VISIBLE } listContainer.addView(fastScroller, FrameLayout.LayoutParams( - (16 * resources.displayMetrics.density).toInt(), -1, Gravity.END + (23 * resources.displayMetrics.density).toInt(), -1, Gravity.END )) root.addView(listContainer, LinearLayout.LayoutParams(-1, 0, 1f)) songRecyclerView = recycler From 9d0071646596e69ef9487f4f08c451057f42475b Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 17:34:29 +0330 Subject: [PATCH 65/70] Make fast scroller pixel-based and widen overlay to 30dp --- .../java/com/movemusic/app/MainActivity.kt | 51 ++++++++++++------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 29cbbb5..9db81cf 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -317,7 +317,7 @@ class MainActivity : ComponentActivity() { listContainer.addView(recycler, FrameLayout.LayoutParams(-1, -1)) val fastScroller = FastScrollOverlay(recycler).apply { visibility = View.VISIBLE } listContainer.addView(fastScroller, FrameLayout.LayoutParams( - (23 * resources.displayMetrics.density).toInt(), -1, Gravity.END + (30 * resources.displayMetrics.density).toInt(), -1, Gravity.END )) root.addView(listContainer, LinearLayout.LayoutParams(-1, 0, 1f)) songRecyclerView = recycler @@ -385,6 +385,7 @@ class MainActivity : ComponentActivity() { private val hideTask = Runnable { indicatorVisible = false; invalidate() } private var dragging = false private var indicatorVisible = false + // Distance from the finger to the top edge of the thumb. private var dragOffset = 0f private val trackInset get() = 8f * density private val minimumThumb get() = 38f * density @@ -396,21 +397,33 @@ class MainActivity : ComponentActivity() { } private fun totalCount() = visibleSongsCache.size + + // Use RecyclerView's pixel-based scroll metrics instead of item indexes. + // This accounts for partially visible rows and avoids the step-like motion + // caused by repeatedly jumping to integer adapter positions. + private fun scrollRange(): Int = + (recyclerView.computeVerticalScrollRange() - + recyclerView.computeVerticalScrollExtent()).coerceAtLeast(0) + private fun thumbHeight(): Float { if (height <= 0) return minimumThumb - val count = totalCount().coerceAtLeast(1) - val visible = (recyclerView.height / (56f * density)).toInt().coerceAtLeast(1) - return (height.toFloat() * visible / count).coerceAtLeast(minimumThumb).coerceAtMost(height.toFloat()) - } - private fun currentPosition(): Int { - val manager = recyclerView.layoutManager as? LinearLayoutManager ?: return 0 - return manager.findFirstVisibleItemPosition().coerceAtLeast(0) + val trackLength = (height - 2f * trackInset).coerceAtLeast(1f) + val range = recyclerView.computeVerticalScrollRange().coerceAtLeast(1) + val extent = recyclerView.computeVerticalScrollExtent().coerceAtLeast(1) + return (trackLength * extent / range) + .coerceAtLeast(minimumThumb) + .coerceAtMost(trackLength) } + private fun thumbTop(): Float { - val available = (height - thumbHeight()).coerceAtLeast(0f) - val maxIndex = (totalCount() - 1).coerceAtLeast(1) - return available * (currentPosition().toFloat() / maxIndex).coerceIn(0f, 1f) + val trackLength = (height - 2f * trackInset).coerceAtLeast(0f) + val available = (trackLength - thumbHeight()).coerceAtLeast(0f) + val range = scrollRange() + val fraction = if (range == 0) 0f else + (recyclerView.computeVerticalScrollOffset().toFloat() / range).coerceIn(0f, 1f) + return trackInset + available * fraction } + override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (!indicatorVisible || totalCount() <= 0 || height <= 0) return @@ -422,12 +435,16 @@ class MainActivity : ComponentActivity() { val thumbTop = thumbTop().coerceIn(top, (bottom - thumb).coerceAtLeast(top)) canvas.drawLine(x, thumbTop, x, thumbTop + thumb, thumbPaint) } + private fun moveTo(y: Float) { - val available = (height - thumbHeight()).coerceAtLeast(1f) - val top = (y - dragOffset - thumbHeight() / 2f).coerceIn(0f, available) - val fraction = (top / available).coerceIn(0f, 1f) - val count = totalCount() - if (count > 0) recyclerView.scrollToPosition((fraction * (count - 1)).toInt()) + val thumb = thumbHeight() + val trackLength = (height - 2f * trackInset).coerceAtLeast(0f) + val available = (trackLength - thumb).coerceAtLeast(1f) + val top = (y - dragOffset).coerceIn(trackInset, trackInset + available) + val fraction = ((top - trackInset) / available).coerceIn(0f, 1f) + val targetOffset = (fraction * scrollRange()).toInt() + val currentOffset = recyclerView.computeVerticalScrollOffset() + recyclerView.scrollBy(0, targetOffset - currentOffset) invalidate() } override fun onTouchEvent(event: MotionEvent): Boolean { @@ -441,7 +458,7 @@ class MainActivity : ComponentActivity() { val top = thumbTop() val bottom = top + thumbHeight() dragging = true - dragOffset = if (event.y in top..bottom) event.y - top - thumbHeight() / 2f else 0f + dragOffset = if (event.y in top..bottom) event.y - top else thumbHeight() / 2f moveTo(event.y) parent?.requestDisallowInterceptTouchEvent(true) invalidate() From 781b8dd9f5df54b17235cbf28b8e88f2a97db406 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 17:48:31 +0330 Subject: [PATCH 66/70] Improve fast scroller responsiveness and spacing --- .../java/com/movemusic/app/MainActivity.kt | 66 ++++++++++--------- 1 file changed, 36 insertions(+), 30 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 9db81cf..2089576 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -309,7 +309,11 @@ class MainActivity : ComponentActivity() { layoutManager = LinearLayoutManager(this@MainActivity) itemAnimator = null setHasFixedSize(false) - setPadding(paddingLeft, paddingTop, (7 * resources.displayMetrics.density).toInt(), paddingBottom) + // Reserve the scrollbar width plus a 4dp visual gap. + setPadding( + paddingLeft, paddingTop, + (39 * resources.displayMetrics.density).toInt(), paddingBottom + ) clipToPadding = false } songAdapter = SongAdapter() @@ -317,7 +321,7 @@ class MainActivity : ComponentActivity() { listContainer.addView(recycler, FrameLayout.LayoutParams(-1, -1)) val fastScroller = FastScrollOverlay(recycler).apply { visibility = View.VISIBLE } listContainer.addView(fastScroller, FrameLayout.LayoutParams( - (30 * resources.displayMetrics.density).toInt(), -1, Gravity.END + (35 * resources.displayMetrics.density).toInt(), -1, Gravity.END )) root.addView(listContainer, LinearLayout.LayoutParams(-1, 0, 1f)) songRecyclerView = recycler @@ -385,10 +389,10 @@ class MainActivity : ComponentActivity() { private val hideTask = Runnable { indicatorVisible = false; invalidate() } private var dragging = false private var indicatorVisible = false - // Distance from the finger to the top edge of the thumb. private var dragOffset = 0f private val trackInset get() = 8f * density private val minimumThumb get() = 38f * density + private val layoutManager get() = recyclerView.layoutManager as? LinearLayoutManager init { isClickable = true @@ -397,31 +401,27 @@ class MainActivity : ComponentActivity() { } private fun totalCount() = visibleSongsCache.size - - // Use RecyclerView's pixel-based scroll metrics instead of item indexes. - // This accounts for partially visible rows and avoids the step-like motion - // caused by repeatedly jumping to integer adapter positions. - private fun scrollRange(): Int = - (recyclerView.computeVerticalScrollRange() - - recyclerView.computeVerticalScrollExtent()).coerceAtLeast(0) + private fun visibleItemCount(): Int = (layoutManager?.childCount ?: 0).coerceAtLeast(1) + private fun maxFirstVisiblePosition(): Int = (totalCount() - visibleItemCount()).coerceAtLeast(0) private fun thumbHeight(): Float { if (height <= 0) return minimumThumb val trackLength = (height - 2f * trackInset).coerceAtLeast(1f) - val range = recyclerView.computeVerticalScrollRange().coerceAtLeast(1) - val extent = recyclerView.computeVerticalScrollExtent().coerceAtLeast(1) - return (trackLength * extent / range) - .coerceAtLeast(minimumThumb) - .coerceAtMost(trackLength) + val fraction = (visibleItemCount().toFloat() / totalCount().coerceAtLeast(1)).coerceIn(0f, 1f) + return (trackLength * fraction).coerceAtLeast(minimumThumb).coerceAtMost(trackLength) + } + + private fun currentScrollFraction(): Float { + val maxPosition = maxFirstVisiblePosition() + if (maxPosition == 0) return 0f + val first = layoutManager?.findFirstVisibleItemPosition() ?: 0 + return (first.toFloat() / maxPosition).coerceIn(0f, 1f) } private fun thumbTop(): Float { val trackLength = (height - 2f * trackInset).coerceAtLeast(0f) val available = (trackLength - thumbHeight()).coerceAtLeast(0f) - val range = scrollRange() - val fraction = if (range == 0) 0f else - (recyclerView.computeVerticalScrollOffset().toFloat() / range).coerceIn(0f, 1f) - return trackInset + available * fraction + return trackInset + available * currentScrollFraction() } override fun onDraw(canvas: Canvas) { @@ -432,25 +432,31 @@ class MainActivity : ComponentActivity() { val bottom = height - trackInset canvas.drawLine(x, top, x, bottom, trackPaint) val thumb = thumbHeight() - val thumbTop = thumbTop().coerceIn(top, (bottom - thumb).coerceAtLeast(top)) - canvas.drawLine(x, thumbTop, x, thumbTop + thumb, thumbPaint) + val topThumb = thumbTop().coerceIn(top, (bottom - thumb).coerceAtLeast(top)) + canvas.drawLine(x, topThumb, x, topThumb + thumb, thumbPaint) } private fun moveTo(y: Float) { - val thumb = thumbHeight() - val trackLength = (height - 2f * trackInset).coerceAtLeast(0f) - val available = (trackLength - thumb).coerceAtLeast(1f) + val manager = layoutManager ?: return + val count = totalCount() + if (count <= 0) return + val trackLength = (height - 2f * trackInset).coerceAtLeast(1f) + val available = (trackLength - thumbHeight()).coerceAtLeast(1f) val top = (y - dragOffset).coerceIn(trackInset, trackInset + available) val fraction = ((top - trackInset) / available).coerceIn(0f, 1f) - val targetOffset = (fraction * scrollRange()).toInt() - val currentOffset = recyclerView.computeVerticalScrollOffset() - recyclerView.scrollBy(0, targetOffset - currentOffset) + val maxPosition = maxFirstVisiblePosition() + val target = fraction * maxPosition + val position = target.toInt().coerceIn(0, count - 1) + val fractionWithinItem = target - position + val itemHeight = recyclerView.getChildAt(0)?.height?.takeIf { it > 0 } ?: 1 + val offset = -(fractionWithinItem * itemHeight).toInt() + // Seek by adapter position: pixel scroll metrics fluctuate during layout. + manager.scrollToPositionWithOffset(position, offset) invalidate() } + override fun onTouchEvent(event: MotionEvent): Boolean { - // Keep the overlay's touch target limited to the scrollbar itself. - // The song action buttons can then sit close to it without being covered. - if (event.x < width - 12f * density) return false + // The list reserves 39dp (35dp bar + 4dp gap), so the full width is safe to touch. when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { uiHandler.removeCallbacks(hideTask) From 143fbf066fae92546ed38a4326423d9020d59215 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 18:14:22 +0330 Subject: [PATCH 67/70] Bring song list content closer to fast scroller --- app/src/main/java/com/movemusic/app/MainActivity.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 2089576..7fa639e 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -309,10 +309,11 @@ class MainActivity : ComponentActivity() { layoutManager = LinearLayoutManager(this@MainActivity) itemAnimator = null setHasFixedSize(false) - // Reserve the scrollbar width plus a 4dp visual gap. + // Keep the list content edge 5dp away from the visible scrollbar stroke. + // The stroke is drawn 7dp from the overlay's right edge with a 2dp half-width. setPadding( paddingLeft, paddingTop, - (39 * resources.displayMetrics.density).toInt(), paddingBottom + (14 * resources.displayMetrics.density).toInt(), paddingBottom ) clipToPadding = false } From b7bdf724e749c86fd0a309d3872c9f28003e8610 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 18:22:05 +0330 Subject: [PATCH 68/70] Reduce fast scroller content gap to 2dp --- app/src/main/java/com/movemusic/app/MainActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/movemusic/app/MainActivity.kt b/app/src/main/java/com/movemusic/app/MainActivity.kt index 7fa639e..2bfec5d 100644 --- a/app/src/main/java/com/movemusic/app/MainActivity.kt +++ b/app/src/main/java/com/movemusic/app/MainActivity.kt @@ -313,7 +313,7 @@ class MainActivity : ComponentActivity() { // The stroke is drawn 7dp from the overlay's right edge with a 2dp half-width. setPadding( paddingLeft, paddingTop, - (14 * resources.displayMetrics.density).toInt(), paddingBottom + (11 * resources.displayMetrics.density).toInt(), paddingBottom ) clipToPadding = false } From dca7e3abd4296dedb72464ece87dbf6a21974bd2 Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 18:39:07 +0330 Subject: [PATCH 69/70] Stabilize lock-screen media controls without changing queue loading --- .../java/com/movemusic/app/PlaybackService.kt | 48 +++++++++++++++++-- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/PlaybackService.kt b/app/src/main/java/com/movemusic/app/PlaybackService.kt index 98c8893..80e0373 100644 --- a/app/src/main/java/com/movemusic/app/PlaybackService.kt +++ b/app/src/main/java/com/movemusic/app/PlaybackService.kt @@ -3,11 +3,30 @@ package com.movemusic.app import android.content.Intent import androidx.media3.common.AudioAttributes import androidx.media3.common.C +import androidx.media3.common.Player +import androidx.media3.common.ForwardingSimpleBasePlayer +import androidx.media3.common.UnstableApi import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.DefaultLoadControl +import androidx.media3.session.CommandButton import androidx.media3.session.MediaSession import androidx.media3.session.MediaSessionService +@OptIn(UnstableApi::class) +private class StableQueueControlsPlayer(player: Player) : ForwardingSimpleBasePlayer(player) { + override fun getState(): State { + val state = super.getState() + // Keep the lock-screen's previous/next slots stable while MainActivity + // appends the rest of a large playlist in small, non-blocking batches. + val commands = state.availableCommands.buildUpon() + .add(Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM) + .add(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM) + .build() + return state.buildUpon().setAvailableCommands(commands).build() + } +} + +@OptIn(UnstableApi::class) class PlaybackService : MediaSessionService() { private var player: ExoPlayer? = null private var mediaSession: MediaSession? = null @@ -21,12 +40,31 @@ class PlaybackService : MediaSessionService() { val exoPlayer = ExoPlayer.Builder(this) .setLoadControl(loadControl) .build().apply { - setAudioAttributes(AudioAttributes.DEFAULT, true) - setHandleAudioBecomingNoisy(true) - setWakeMode(C.WAKE_MODE_LOCAL) - } + setAudioAttributes(AudioAttributes.DEFAULT, true) + setHandleAudioBecomingNoisy(true) + setWakeMode(C.WAKE_MODE_LOCAL) + } player = exoPlayer - mediaSession = MediaSession.Builder(this, exoPlayer).build() + + val previousButton = CommandButton.Builder(CommandButton.ICON_PREVIOUS) + .setPlayerCommand(Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM) + .setDisplayName("Previous") + .setSlots(intArrayOf(CommandButton.SLOT_BACK)) + .build() + val playPauseButton = CommandButton.Builder(CommandButton.ICON_PLAY) + .setPlayerCommand(Player.COMMAND_PLAY_PAUSE) + .setDisplayName("Play/Pause") + .setSlots(intArrayOf(CommandButton.SLOT_CENTRAL)) + .build() + val nextButton = CommandButton.Builder(CommandButton.ICON_NEXT) + .setPlayerCommand(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM) + .setDisplayName("Next") + .setSlots(intArrayOf(CommandButton.SLOT_FORWARD)) + .build() + + mediaSession = MediaSession.Builder(this, StableQueueControlsPlayer(exoPlayer)) + .setMediaButtonPreferences(listOf(previousButton, playPauseButton, nextButton)) + .build() } override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = From d3fa6b7105d65630b41a6eb75d0386a4130b038e Mon Sep 17 00:00:00 2001 From: Soebb Date: Mon, 9 Nov 2026 18:48:06 +0330 Subject: [PATCH 70/70] Fix Media3 lock-screen command button API usage --- app/src/main/java/com/movemusic/app/PlaybackService.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/movemusic/app/PlaybackService.kt b/app/src/main/java/com/movemusic/app/PlaybackService.kt index 80e0373..e232d87 100644 --- a/app/src/main/java/com/movemusic/app/PlaybackService.kt +++ b/app/src/main/java/com/movemusic/app/PlaybackService.kt @@ -5,7 +5,7 @@ import androidx.media3.common.AudioAttributes import androidx.media3.common.C import androidx.media3.common.Player import androidx.media3.common.ForwardingSimpleBasePlayer -import androidx.media3.common.UnstableApi +import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.DefaultLoadControl import androidx.media3.session.CommandButton @@ -49,17 +49,17 @@ class PlaybackService : MediaSessionService() { val previousButton = CommandButton.Builder(CommandButton.ICON_PREVIOUS) .setPlayerCommand(Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM) .setDisplayName("Previous") - .setSlots(intArrayOf(CommandButton.SLOT_BACK)) + .setSlots(CommandButton.SLOT_BACK) .build() val playPauseButton = CommandButton.Builder(CommandButton.ICON_PLAY) .setPlayerCommand(Player.COMMAND_PLAY_PAUSE) .setDisplayName("Play/Pause") - .setSlots(intArrayOf(CommandButton.SLOT_CENTRAL)) + .setSlots(CommandButton.SLOT_CENTRAL) .build() val nextButton = CommandButton.Builder(CommandButton.ICON_NEXT) .setPlayerCommand(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM) .setDisplayName("Next") - .setSlots(intArrayOf(CommandButton.SLOT_FORWARD)) + .setSlots(CommandButton.SLOT_FORWARD) .build() mediaSession = MediaSession.Builder(this, StableQueueControlsPlayer(exoPlayer))