forked from 956tris/MetroFuse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit-15bf160.diff
More file actions
1247 lines (1195 loc) · 63 KB
/
commit-15bf160.diff
File metadata and controls
1247 lines (1195 loc) · 63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/app/src/main/kotlin/com/metrolist/music/App.kt b/app/src/main/kotlin/com/metrolist/music/App.kt
index 34a3db32fc..b990b78f24 100644
--- a/app/src/main/kotlin/com/metrolist/music/App.kt
+++ b/app/src/main/kotlin/com/metrolist/music/App.kt
@@ -82,6 +82,11 @@ class App :
Timber.plant(Timber.DebugTree())
+ // Pre-read Coil cache size on background to avoid runBlocking in newImageLoader
+ applicationScope.launch(Dispatchers.IO) {
+ cachedCoilCacheSize = dataStore.data.map { it[MaxImageCacheSizeKey] ?: 512 }.first()
+ }
+
// تهيئة إعدادات التطبيق عند الإقلاع
applicationScope.launch {
initializeSettings()
@@ -250,11 +255,13 @@ class App :
}
}
+ @Volatile
+ private var cachedCoilCacheSize: Int? = null
+
override fun newImageLoader(context: PlatformContext): ImageLoader {
- val cacheSize =
- runBlocking {
- dataStore.data.map { it[MaxImageCacheSizeKey] ?: 512 }.first()
- }
+ val cacheSize = cachedCoilCacheSize ?: runBlocking {
+ dataStore.data.map { it[MaxImageCacheSizeKey] ?: 512 }.first()
+ }
return ImageLoader
.Builder(this)
.apply {
@@ -264,7 +271,7 @@ class App :
memoryCache {
MemoryCache
.Builder()
- .maxSizePercent(context, 0.25)
+ .maxSizePercent(context, 0.15)
.build()
}
if (cacheSize == 0) {
diff --git a/app/src/main/kotlin/com/metrolist/music/MainActivity.kt b/app/src/main/kotlin/com/metrolist/music/MainActivity.kt
index 9b9094432b..7bff7f693d 100644
--- a/app/src/main/kotlin/com/metrolist/music/MainActivity.kt
+++ b/app/src/main/kotlin/com/metrolist/music/MainActivity.kt
@@ -77,6 +77,7 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -409,6 +410,43 @@ class MainActivity : ComponentActivity() {
}
}
+ // Defer migration and version tracking to avoid blocking first frame
+ lifecycleScope.launch(Dispatchers.IO) {
+ val preferences = dataStore.data.first()
+ val currentVersion = BuildConfig.VERSION_NAME
+
+ // SimpMusic Removal Migration
+ if (preferences[SimpMusicMigrationDoneKey] != true) {
+ dataStore.edit { settings ->
+ val currentOrder = settings[LyricsProviderOrderKey] ?: ""
+ if (currentOrder.contains("SimpMusic")) {
+ val orderList =
+ currentOrder
+ .split(",")
+ .map { it.trim() }
+ .filter { it.isNotBlank() && it != "SimpMusic" }
+ .toMutableList()
+ if (orderList.isEmpty()) {
+ settings[LyricsProviderOrderKey] = ""
+ } else {
+ settings[LyricsProviderOrderKey] = orderList.joinToString(",")
+ }
+ }
+ if (settings[PreferredLyricsProviderKey] == "SIMPMUSIC") {
+ settings[PreferredLyricsProviderKey] = PreferredLyricsProvider.LRCLIB.name
+ }
+ settings[SimpMusicMigrationDoneKey] = true
+ settings[LastSeenVersionKey] = currentVersion
+ }
+ }
+ }
+
+ lifecycleScope.launch(Dispatchers.IO) {
+ dataStore.edit { settings ->
+ settings[LastSeenVersionKey] = BuildConfig.VERSION_NAME
+ }
+ }
+
setContent {
MetrolistApp(
latestVersionName = latestVersionName,
@@ -539,6 +577,8 @@ class MainActivity : ComponentActivity() {
mutableStateOf(selectedThemeColor)
}
+ val themeColorCache = remember { mutableMapOf<String, Color>() }
+
LaunchedEffect(selectedThemeColor) {
if (!enableDynamicTheme) {
themeColor = selectedThemeColor
@@ -552,32 +592,43 @@ class MainActivity : ComponentActivity() {
return@LaunchedEffect
}
- playerConnection.service.currentMediaMetadata.collectLatest { song ->
- if (song?.thumbnailUrl != null) {
- withContext(Dispatchers.IO) {
- try {
- val result =
- imageLoader.execute(
- ImageRequest
- .Builder(this@MainActivity)
- .data(song.thumbnailUrl)
- .allowHardware(false)
- .memoryCachePolicy(CachePolicy.ENABLED)
- .diskCachePolicy(CachePolicy.ENABLED)
- .networkCachePolicy(CachePolicy.ENABLED)
- .crossfade(false)
- .build(),
- )
- themeColor = result.image?.toBitmap()?.extractThemeColor() ?: selectedThemeColor
- } catch (e: Exception) {
- // Fallback to default on error
- themeColor = selectedThemeColor
+ playerConnection.service.currentMediaMetadata
+ .distinctUntilChanged { old, new -> old?.id == new?.id }
+ .collectLatest { song ->
+ if (song?.thumbnailUrl != null) {
+ val cached = themeColorCache[song.thumbnailUrl]
+ if (cached != null) {
+ withFrameNanos { }
+ themeColor = cached
+ return@collectLatest
}
+ withContext(Dispatchers.IO) {
+ try {
+ val result =
+ imageLoader.execute(
+ ImageRequest
+ .Builder(this@MainActivity)
+ .data(song.thumbnailUrl)
+ .allowHardware(false)
+ .memoryCachePolicy(CachePolicy.ENABLED)
+ .diskCachePolicy(CachePolicy.ENABLED)
+ .networkCachePolicy(CachePolicy.ENABLED)
+ .crossfade(false)
+ .build(),
+ )
+ val extractedColor = result.image?.toBitmap()?.extractThemeColor() ?: selectedThemeColor
+ themeColorCache[song.thumbnailUrl] = extractedColor
+ withFrameNanos { }
+ themeColor = extractedColor
+ } catch (e: Exception) {
+ withFrameNanos { }
+ themeColor = selectedThemeColor
+ }
+ }
+ } else {
+ themeColor = selectedThemeColor
}
- } else {
- themeColor = selectedThemeColor
}
- }
}
MetrolistTheme(
@@ -606,40 +657,6 @@ class MainActivity : ComponentActivity() {
if (lastSeenVersion != currentVersion) {
showChangelog.value = true
}
-
- // SimpMusic Removal Migration
- if (dataStore.data.first()[SimpMusicMigrationDoneKey] != true) {
- dataStore.edit { settings ->
- val currentOrder = settings[LyricsProviderOrderKey] ?: ""
- if (currentOrder.contains("SimpMusic")) {
- // If the old order only contained SimpMusic, reset to default order
- // Otherwise remove SimpMusic and keep the rest
- val orderList =
- currentOrder
- .split(",")
- .map { it.trim() }
- .filter { it.isNotBlank() && it != "SimpMusic" }
- .toMutableList()
-
- if (orderList.isEmpty()) {
- settings[LyricsProviderOrderKey] = ""
- } else {
- settings[LyricsProviderOrderKey] = orderList.joinToString(",")
- }
- }
-
- // Reset preferred provider if it was SimpMusic
- if (settings[PreferredLyricsProviderKey] == "SIMPMUSIC") {
- settings[PreferredLyricsProviderKey] = PreferredLyricsProvider.LRCLIB.name
- }
-
- settings[SimpMusicMigrationDoneKey] = true
- }
- }
-
- dataStore.edit { settings ->
- settings[LastSeenVersionKey] = currentVersion
- }
}
val homeViewModel: HomeViewModel = hiltViewModel()
@@ -656,12 +673,19 @@ class MainActivity : ComponentActivity() {
Screens.MainScreens
}
}
+ val routeIndexMap = remember(navigationItems) {
+ navigationItems.mapIndexed { i, s -> s.route to i }.toMap()
+ }
val (slimNav) = rememberPreference(SlimNavBarKey, defaultValue = false)
val (useNewMiniPlayerDesign) = rememberPreference(UseNewMiniPlayerDesignKey, defaultValue = true)
- val defaultOpenTab =
- remember {
- dataStore[DefaultOpenTabKey].toEnum(defaultValue = NavigationTab.HOME)
+ val (defaultOpenTabInt) = rememberPreference(DefaultOpenTabKey, defaultValue = NavigationTab.HOME.name)
+ val defaultOpenTab = remember(defaultOpenTabInt) {
+ try {
+ NavigationTab.valueOf(defaultOpenTabInt)
+ } catch (_: IllegalArgumentException) {
+ NavigationTab.HOME
}
+ }
val tabOpenedFromShortcut =
remember {
when (intent?.action) {
@@ -1233,16 +1257,9 @@ class MainActivity : ComponentActivity() {
NavigationTab.LIBRARY -> Screens.Library
else -> Screens.Home
}.route,
- // Enter Transition - smoother with smaller offset and longer duration
enterTransition = {
- val currentRouteIndex =
- navigationItems.indexOfFirst {
- it.route == targetState.destination.route
- }
- val previousRouteIndex =
- navigationItems.indexOfFirst {
- it.route == initialState.destination.route
- }
+ val currentRouteIndex = routeIndexMap[targetState.destination.route] ?: -1
+ val previousRouteIndex = routeIndexMap[initialState.destination.route] ?: -1
if (currentRouteIndex == -1 || currentRouteIndex > previousRouteIndex) {
slideInHorizontally { it / 8 } + fadeIn(tween(200))
@@ -1250,16 +1267,9 @@ class MainActivity : ComponentActivity() {
slideInHorizontally { -it / 8 } + fadeIn(tween(200))
}
},
- // Exit Transition - smoother with smaller offset and longer duration
exitTransition = {
- val currentRouteIndex =
- navigationItems.indexOfFirst {
- it.route == initialState.destination.route
- }
- val targetRouteIndex =
- navigationItems.indexOfFirst {
- it.route == targetState.destination.route
- }
+ val currentRouteIndex = routeIndexMap[initialState.destination.route] ?: -1
+ val targetRouteIndex = routeIndexMap[targetState.destination.route] ?: -1
if (targetRouteIndex == -1 || targetRouteIndex > currentRouteIndex) {
slideOutHorizontally { -it / 8 } + fadeOut(tween(200))
@@ -1267,16 +1277,9 @@ class MainActivity : ComponentActivity() {
slideOutHorizontally { it / 8 } + fadeOut(tween(200))
}
},
- // Pop Enter Transition - smoother with smaller offset and longer duration
popEnterTransition = {
- val currentRouteIndex =
- navigationItems.indexOfFirst {
- it.route == targetState.destination.route
- }
- val previousRouteIndex =
- navigationItems.indexOfFirst {
- it.route == initialState.destination.route
- }
+ val currentRouteIndex = routeIndexMap[targetState.destination.route] ?: -1
+ val previousRouteIndex = routeIndexMap[initialState.destination.route] ?: -1
if (previousRouteIndex != -1 && previousRouteIndex < currentRouteIndex) {
slideInHorizontally { it / 8 } + fadeIn(tween(200))
@@ -1284,16 +1287,9 @@ class MainActivity : ComponentActivity() {
slideInHorizontally { -it / 8 } + fadeIn(tween(200))
}
},
- // Pop Exit Transition - smoother with smaller offset and longer duration
popExitTransition = {
- val currentRouteIndex =
- navigationItems.indexOfFirst {
- it.route == initialState.destination.route
- }
- val targetRouteIndex =
- navigationItems.indexOfFirst {
- it.route == targetState.destination.route
- }
+ val currentRouteIndex = routeIndexMap[initialState.destination.route] ?: -1
+ val targetRouteIndex = routeIndexMap[targetState.destination.route] ?: -1
if (currentRouteIndex != -1 && currentRouteIndex < targetRouteIndex) {
slideOutHorizontally { -it / 8 } + fadeOut(tween(200))
diff --git a/app/src/main/kotlin/com/metrolist/music/constants/Dimensions.kt b/app/src/main/kotlin/com/metrolist/music/constants/Dimensions.kt
index 041e1b94bc..5bec328b1e 100644
--- a/app/src/main/kotlin/com/metrolist/music/constants/Dimensions.kt
+++ b/app/src/main/kotlin/com/metrolist/music/constants/Dimensions.kt
@@ -39,7 +39,7 @@ val PlayerHorizontalPadding = 32.dp
val NavigationBarAnimationSpec = spring<Dp>(
dampingRatio = Spring.DampingRatioNoBouncy,
- stiffness = Spring.StiffnessLow
+ stiffness = Spring.StiffnessMediumLow
)
val BottomSheetAnimationSpec = spring<Dp>(
diff --git a/app/src/main/kotlin/com/metrolist/music/listentogether/ListenTogetherClient.kt b/app/src/main/kotlin/com/metrolist/music/listentogether/ListenTogetherClient.kt
index 09bbb70a67..e7e0f83f52 100644
--- a/app/src/main/kotlin/com/metrolist/music/listentogether/ListenTogetherClient.kt
+++ b/app/src/main/kotlin/com/metrolist/music/listentogether/ListenTogetherClient.kt
@@ -311,7 +311,7 @@ class ListenTogetherClient
ensureNotificationChannel()
observeAppLifecycle()
// Load persisted session info asynchronously after construction to avoid calling log() before flows are initialized
- CoroutineScope(Dispatchers.IO + SupervisorJob()).launch {
+ scope.launch {
loadPersistedSession()
observeNetworkChanges()
}
diff --git a/app/src/main/kotlin/com/metrolist/music/playback/MusicService.kt b/app/src/main/kotlin/com/metrolist/music/playback/MusicService.kt
index 595aea9ece..50432c4096 100644
--- a/app/src/main/kotlin/com/metrolist/music/playback/MusicService.kt
+++ b/app/src/main/kotlin/com/metrolist/music/playback/MusicService.kt
@@ -229,6 +229,7 @@ import java.io.ObjectOutputStream
import java.time.LocalDateTime
import javax.inject.Inject
import kotlin.random.Random
+import java.util.Collections
private const val INSTANT_SILENCE_SKIP_STEP_MS = 15_000L
private const val INSTANT_SILENCE_SKIP_SETTLE_MS = 350L
@@ -415,8 +416,30 @@ class MusicService :
private var retryCount = 0
private var silenceSkipJob: Job? = null
+ // Cached preferences to avoid runBlocking DataStore reads in hot paths
+ @Volatile
+ private var cachedPersistentQueue = true
+ @Volatile
+ private var cachedAutoplay = true
+ @Volatile
+ private var cachedDisableLoadMoreWhenRepeatAll = false
+ @Volatile
+ private var cachedHideExplicit = false
+ @Volatile
+ private var cachedHideVideoSongs = false
+ @Volatile
+ private var cachedShufflePlaylistFirst = false
+ @Volatile
+ private var cachedAutoLoadMore = true
+
// URL cache for stream URLs - class-level so it can be invalidated on errors
- private val songUrlCache = HashMap<String, Pair<String, Long>>()
+ private val songUrlCache = Collections.synchronizedMap(
+ object : LinkedHashMap<String, Pair<String, Long>>(0, 0.75f, true) {
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Pair<String, Long>>): Boolean {
+ return size > 500
+ }
+ }
+ )
// Flag to bypass cache when quality changes - forces fresh stream fetch
private val bypassCacheForQualityChange = mutableSetOf<String>()
@@ -935,6 +958,29 @@ class MusicService :
crossfadeGapless = gapless
}
+ // Observe and cache common preferences to avoid runBlocking reads in playback callbacks
+ scope.launch {
+ dataStore.data.map { it[PersistentQueueKey] ?: true }.distinctUntilChanged().collect { cachedPersistentQueue = it }
+ }
+ scope.launch {
+ dataStore.data.map { it[AutoplayKey] ?: true }.distinctUntilChanged().collect { cachedAutoplay = it }
+ }
+ scope.launch {
+ dataStore.data.map { it[DisableLoadMoreWhenRepeatAllKey] ?: false }.distinctUntilChanged().collect { cachedDisableLoadMoreWhenRepeatAll = it }
+ }
+ scope.launch {
+ dataStore.data.map { it[HideExplicitKey] ?: false }.distinctUntilChanged().collect { cachedHideExplicit = it }
+ }
+ scope.launch {
+ dataStore.data.map { it[HideVideoSongsKey] ?: false }.distinctUntilChanged().collect { cachedHideVideoSongs = it }
+ }
+ scope.launch {
+ dataStore.data.map { it[ShufflePlaylistFirstKey] ?: false }.distinctUntilChanged().collect { cachedShufflePlaylistFirst = it }
+ }
+ scope.launch {
+ dataStore.data.map { it[AutoLoadMoreKey] ?: true }.distinctUntilChanged().collect { cachedAutoLoadMore = it }
+ }
+
if (dataStore.get(PersistentQueueKey, true)) {
val queueFile = filesDir.resolve(PERSISTENT_QUEUE_FILE)
if (queueFile.exists()) {
@@ -1023,7 +1069,7 @@ class MusicService :
scope.launch {
while (isActive) {
delay(15.seconds)
- if (dataStore.get(PersistentQueueKey, true)) {
+ if (cachedPersistentQueue) {
saveQueueToDisk()
}
// Also save episode position periodically
@@ -1039,7 +1085,7 @@ class MusicService :
scope.launch {
while (isActive) {
delay(10.seconds)
- if (dataStore.get(PersistentQueueKey, true) && player.isPlaying) {
+ if (cachedPersistentQueue && player.isPlaying) {
saveQueueToDisk()
}
}
@@ -1550,8 +1596,8 @@ class MusicService :
songs
.filter { it.id != currentMediaId }
.map { it.toMediaItem() }
- .filterExplicit(dataStore.get(HideExplicitKey, false))
- .filterVideoSongs(dataStore.get(HideVideoSongsKey, false))
+ .filterExplicit(cachedHideExplicit)
+ .filterVideoSongs(cachedHideVideoSongs)
if (radioItems.isNotEmpty()) {
val itemCount = player.mediaItemCount
@@ -1560,11 +1606,10 @@ class MusicService :
}
player.addMediaItems(currentIndex + 1, radioItems)
if (player.shuffleModeEnabled) {
- val shufflePlaylistFirst = dataStore.get(ShufflePlaylistFirstKey, false)
applyShuffleOrder(
player.currentMediaItemIndex,
player.mediaItemCount,
- shufflePlaylistFirst,
+ cachedShufflePlaylistFirst,
)
}
}
@@ -2220,8 +2265,7 @@ class MusicService :
// Force Repeat One if the player ignored it and auto-advanced
if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO) {
- val repeatMode = runBlocking { dataStore.get(RepeatModeKey, REPEAT_MODE_OFF) }
- if (repeatMode == REPEAT_MODE_ONE &&
+ if (player.repeatMode == REPEAT_MODE_ONE &&
previousMediaItemIndex != C.INDEX_UNSET &&
previousMediaItemIndex != player.currentMediaItemIndex
) {
@@ -2260,32 +2304,31 @@ class MusicService :
}
// Auto load more songs from queue
- if (dataStore.get(AutoLoadMoreKey, true) &&
+ if (cachedAutoLoadMore &&
reason != Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT &&
player.mediaItemCount - player.currentMediaItemIndex <= 5 &&
currentQueue.hasNextPage() &&
- !(dataStore.get(DisableLoadMoreWhenRepeatAllKey, false) && player.repeatMode == REPEAT_MODE_ALL)
+ !(cachedDisableLoadMoreWhenRepeatAll && player.repeatMode == REPEAT_MODE_ALL)
) {
scope.launch(SilentHandler) {
val mediaItems =
withContext(Dispatchers.IO) {
currentQueue
.nextPage()
- .filterExplicit(dataStore.get(HideExplicitKey, false))
- .filterVideoSongs(dataStore.get(HideVideoSongsKey, false))
+ .filterExplicit(cachedHideExplicit)
+ .filterVideoSongs(cachedHideVideoSongs)
}
if (player.playbackState != STATE_IDLE && mediaItems.isNotEmpty()) {
player.addMediaItems(mediaItems)
if (player.shuffleModeEnabled) {
- val shufflePlaylistFirst = dataStore.get(ShufflePlaylistFirstKey, false)
- applyShuffleOrder(player.currentMediaItemIndex, player.mediaItemCount, shufflePlaylistFirst)
+ applyShuffleOrder(player.currentMediaItemIndex, player.mediaItemCount, cachedShufflePlaylistFirst)
}
}
}
}
// Save state when media item changes
- if (dataStore.get(PersistentQueueKey, true)) {
+ if (cachedPersistentQueue) {
saveQueueToDisk()
}
}
@@ -2300,7 +2343,7 @@ class MusicService :
return
}
- val repeatMode = runBlocking { dataStore.get(RepeatModeKey, REPEAT_MODE_OFF) }
+ val repeatMode = player.repeatMode
// Handle Repeat All mode
if (repeatMode == REPEAT_MODE_ALL && player.mediaItemCount > 0) {
@@ -2319,8 +2362,7 @@ class MusicService :
}
// Handle autoplay - check if there's a next item to play
- val autoplay = runBlocking { dataStore.get(AutoplayKey, true) }
- if (autoplay && player.hasNextMediaItem()) {
+ if (cachedAutoplay && player.hasNextMediaItem()) {
player.seekToNextMediaItem()
player.prepare()
if (castConnectionHandler?.isCasting?.value != true) {
@@ -2330,7 +2372,7 @@ class MusicService :
}
// Save state when playback state changes (but not during silence skipping)
- if (dataStore.get(PersistentQueueKey, true) && !isSilenceSkipping) {
+ if (cachedPersistentQueue && !isSilenceSkipping) {
saveQueueToDisk()
}
@@ -2478,7 +2520,7 @@ class MusicService :
}
// Save state when shuffle mode changes
- if (dataStore.get(PersistentQueueKey, true)) {
+ if (cachedPersistentQueue) {
saveQueueToDisk()
}
}
@@ -2492,7 +2534,7 @@ class MusicService :
}
// Save state when repeat mode changes
- if (dataStore.get(PersistentQueueKey, true)) {
+ if (cachedPersistentQueue) {
saveQueueToDisk()
}
}
diff --git a/app/src/main/kotlin/com/metrolist/music/ui/component/CreatePlaylistDialog.kt b/app/src/main/kotlin/com/metrolist/music/ui/component/CreatePlaylistDialog.kt
index 5df4ae12fc..d8092718b7 100644
--- a/app/src/main/kotlin/com/metrolist/music/ui/component/CreatePlaylistDialog.kt
+++ b/app/src/main/kotlin/com/metrolist/music/ui/component/CreatePlaylistDialog.kt
@@ -115,23 +115,25 @@ fun CreatePlaylistDialog(
Switch(
checked = syncedPlaylist,
onCheckedChange = {
- val isYtmSyncEnabled = context.isSyncEnabled()
- if (!isSignedIn && !syncedPlaylist) {
- Toast
- .makeText(
- context,
- notLoggedInYoutubeStr,
- Toast.LENGTH_SHORT,
- ).show()
- } else if (!isYtmSyncEnabled) {
- Toast
- .makeText(
- context,
- syncDisabledStr,
- Toast.LENGTH_SHORT,
- ).show()
- } else {
- syncedPlaylist = !syncedPlaylist
+ coroutineScope.launch {
+ val isYtmSyncEnabled = withContext(Dispatchers.IO) { context.isSyncEnabled() }
+ if (!isSignedIn && !syncedPlaylist) {
+ Toast
+ .makeText(
+ context,
+ notLoggedInYoutubeStr,
+ Toast.LENGTH_SHORT,
+ ).show()
+ } else if (!isYtmSyncEnabled) {
+ Toast
+ .makeText(
+ context,
+ syncDisabledStr,
+ Toast.LENGTH_SHORT,
+ ).show()
+ } else {
+ syncedPlaylist = !syncedPlaylist
+ }
}
},
)
diff --git a/app/src/main/kotlin/com/metrolist/music/ui/component/ExperimentalLyrics.kt b/app/src/main/kotlin/com/metrolist/music/ui/component/ExperimentalLyrics.kt
index d6613dc8ca..2d764a2a19 100644
--- a/app/src/main/kotlin/com/metrolist/music/ui/component/ExperimentalLyrics.kt
+++ b/app/src/main/kotlin/com/metrolist/music/ui/component/ExperimentalLyrics.kt
@@ -53,6 +53,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.withFrameNanos
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
@@ -344,7 +345,7 @@ fun ExperimentalLyrics(
var lastUpdateTime = System.currentTimeMillis()
while (isActive) {
- delay(16)
+ withFrameNanos { _ -> }
val now = System.currentTimeMillis()
val sliderPosition = sliderPositionProvider()
isSeeking = sliderPosition != null
diff --git a/app/src/main/kotlin/com/metrolist/music/ui/component/LyricsLine.kt b/app/src/main/kotlin/com/metrolist/music/ui/component/LyricsLine.kt
index 702e9e2a46..b9c162a593 100644
--- a/app/src/main/kotlin/com/metrolist/music/ui/component/LyricsLine.kt
+++ b/app/src/main/kotlin/com/metrolist/music/ui/component/LyricsLine.kt
@@ -44,6 +44,7 @@ import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.drawscope.withTransform
+import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
@@ -511,7 +512,10 @@ private fun WordLevelLyrics(
Canvas(modifier = Modifier
.fillMaxWidth()
.height(with(density) { layoutResult.size.height.toDp() })
- .graphicsLayer(clip = false)
+ .graphicsLayer(
+ clip = false,
+ compositingStrategy = CompositingStrategy.Offscreen,
+ )
) {
if (mainText.isEmpty()) return@Canvas
if (!isActiveLine) {
diff --git a/app/src/main/kotlin/com/metrolist/music/ui/component/SpeedDialGridItem.kt b/app/src/main/kotlin/com/metrolist/music/ui/component/SpeedDialGridItem.kt
index 4a98ebe18a..d12be81458 100644
--- a/app/src/main/kotlin/com/metrolist/music/ui/component/SpeedDialGridItem.kt
+++ b/app/src/main/kotlin/com/metrolist/music/ui/component/SpeedDialGridItem.kt
@@ -46,7 +46,7 @@ fun SpeedDialGridItem(
) {
// Thumbnail
ItemThumbnail(
- thumbnailUrl = item.thumbnail?.resize(1080, 1080),
+ thumbnailUrl = item.thumbnail?.resize(200, 200),
isActive = isActive,
isPlaying = isPlaying,
shape = if (item is ArtistItem) CircleShape else RoundedCornerShape(ThumbnailCornerRadius),
diff --git a/app/src/main/kotlin/com/metrolist/music/ui/menu/SelectionSongsMenu.kt b/app/src/main/kotlin/com/metrolist/music/ui/menu/SelectionSongsMenu.kt
index 31aedabbd4..5bce99c940 100644
--- a/app/src/main/kotlin/com/metrolist/music/ui/menu/SelectionSongsMenu.kt
+++ b/app/src/main/kotlin/com/metrolist/music/ui/menu/SelectionSongsMenu.kt
@@ -66,7 +66,6 @@ import com.metrolist.music.ui.component.NewAction
import com.metrolist.music.ui.component.NewActionGrid
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
-import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.time.LocalDateTime
@@ -692,13 +691,10 @@ fun SelectionMediaMetadataMenu(
AddToPlaylistDialog(
isVisible = showChoosePlaylistDialog,
onGetSong = {
- songSelection.map {
- runBlocking {
- withContext(Dispatchers.IO) {
- database.insert(it)
- }
- }
- it.id
+ // Safe: AddToPlaylistDialog wraps this lambda in withContext(Dispatchers.IO)
+ songSelection.map { song ->
+ database.insert(song)
+ song.id
}
},
onGetSongIds = { songSelection.map { it.id } },
diff --git a/app/src/main/kotlin/com/metrolist/music/ui/screens/HomeScreen.kt b/app/src/main/kotlin/com/metrolist/music/ui/screens/HomeScreen.kt
index 70cdf4faf0..4ccec7e21d 100644
--- a/app/src/main/kotlin/com/metrolist/music/ui/screens/HomeScreen.kt
+++ b/app/src/main/kotlin/com/metrolist/music/ui/screens/HomeScreen.kt
@@ -35,6 +35,7 @@ import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.items
+import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
@@ -675,6 +676,8 @@ fun HomeScreen(
val innerTubeCookie by rememberPreference(InnerTubeCookieKey, "")
val (randomizeHomeOrder) = rememberPreference(RandomizeHomeOrderKey, true)
+ LaunchedEffect(Unit) { viewModel.loadHomeData() }
+
val shouldShowWrappedCard by viewModel.showWrappedCard.collectAsStateWithLifecycle()
val wrappedState by viewModel.wrappedManager.state.collectAsStateWithLifecycle()
val isWrappedDataReady = wrappedState.isDataReady
@@ -1211,7 +1214,7 @@ fun HomeScreen(
.only(WindowInsetsSides.Horizontal)
.asPaddingValues(),
) {
- items(savedPodcastShows) { podcast ->
+ items(savedPodcastShows, key = { it.id }) { podcast ->
ytGridItem(podcast)
}
}
@@ -1236,7 +1239,7 @@ fun HomeScreen(
.only(WindowInsetsSides.Horizontal)
.asPaddingValues(),
) {
- items(episodesForLater) { episode ->
+ items(episodesForLater, key = { it.id }) { episode ->
ytGridItem(episode)
}
}
@@ -1259,7 +1262,7 @@ fun HomeScreen(
.only(WindowInsetsSides.Horizontal)
.asPaddingValues(),
) {
- items(featuredPodcasts) { podcast ->
+ items(featuredPodcasts, key = { it.id }) { podcast ->
ytGridItem(podcast)
}
}
@@ -1331,7 +1334,6 @@ fun HomeScreen(
}
}
},
- modifier = Modifier.animateItem(),
)
}
@@ -1342,7 +1344,7 @@ fun HomeScreen(
.only(WindowInsetsSides.Horizontal)
.asPaddingValues(),
) {
- items(sectionData.items) { item ->
+ items(sectionData.items, key = { it.id }) { item ->
ytGridItem(item)
}
}
@@ -1421,7 +1423,6 @@ fun HomeScreen(
item(key = "speed_dial_title") {
NavigationTitle(
title = stringResource(R.string.speed_dial),
- modifier = Modifier.animateItem(),
)
}
@@ -1445,8 +1446,7 @@ fun HomeScreen(
Column(
modifier =
Modifier
- .fillMaxWidth()
- .animateItem(),
+ .fillMaxWidth(),
) {
HorizontalPager(
state = pagerState,
@@ -1737,7 +1737,6 @@ fun HomeScreen(
val quickPicksTitle = stringResource(R.string.quick_picks)
NavigationTitle(
title = quickPicksTitle,
- modifier = Modifier.animateItem(),
onPlayAllClick =
if (!isListenTogetherGuest) {
{
@@ -1766,12 +1765,11 @@ fun HomeScreen(
modifier =
Modifier
.fillMaxWidth()
- .height(ListItemHeight * 4)
- .animateItem(),
- ) {
- items(
- items = quickPicks.distinctBy { it.id },
- key = { "home_quickpick_${it.id}" },
+ .height(ListItemHeight * 4),
+ ) {
+ items(
+ items = quickPicks.distinctBy { it.id },
+ key = { "home_quickpick_${it.id}" },
) { originalSong ->
// fetch song from database to keep updated
val song by database
@@ -1842,7 +1840,6 @@ fun HomeScreen(
item(key = "community_playlists_title") {
NavigationTitle(
title = stringResource(R.string.from_the_community),
- modifier = Modifier.animateItem(),
)
}
@@ -1850,7 +1847,6 @@ fun HomeScreen(
LazyRow(
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
- modifier = Modifier.animateItem(),
) {
items(playlists) { item ->
CommunityPlaylistCard(
@@ -1949,14 +1945,13 @@ fun HomeScreen(
item(key = "keep_listening_title") {
NavigationTitle(
title = stringResource(R.string.keep_listening),
- modifier = Modifier.animateItem(),
)
}
item(key = "keep_listening_list") {
val rows = if (keepListening.size > 6) 2 else 1
LazyHorizontalGrid(
- state = rememberLazyGridState(),
+ state = remember("keep_listening_grid") { LazyGridState() },
rows = GridCells.Fixed(rows),
contentPadding =
WindowInsets.systemBars
@@ -1975,9 +1970,9 @@ fun HomeScreen(
.toDp() * 2
}
) * rows,
- ).animateItem(),
+ ),
) {
- items(keepListening) {
+ items(keepListening, key = { it.id }) {
localGridItem(it)
}
}
@@ -2022,7 +2017,6 @@ fun HomeScreen(
onClick = {
navController.navigate("account")
},
- modifier = Modifier.animateItem(),
)
}
@@ -2032,7 +2026,6 @@ fun HomeScreen(
WindowInsets.systemBars
.only(WindowInsetsSides.Horizontal)
.asPaddingValues(),
- modifier = Modifier.animateItem(),
) {
items(
items = accountPlaylists.distinctBy { it.id },
@@ -2051,7 +2044,6 @@ fun HomeScreen(
val forgottenFavoritesTitle = stringResource(R.string.forgotten_favorites)
NavigationTitle(
title = forgottenFavoritesTitle,
- modifier = Modifier.animateItem(),
onPlayAllClick =
if (!isListenTogetherGuest) {
{
@@ -2085,11 +2077,10 @@ fun HomeScreen(
modifier =
Modifier
.fillMaxWidth()
- .height(ListItemHeight * rows)
- .animateItem(),
- ) {
- items(
- items = forgottenFavorites.distinctBy { it.id },
+ .height(ListItemHeight * rows),
+ ) {
+ items(
+ items = forgottenFavorites.distinctBy { it.id },
key = { "home_forgotten_${it.id}" },
) { originalSong ->
val song by database
@@ -2201,7 +2192,6 @@ fun HomeScreen(
is Playlist -> {}
}
},
- modifier = Modifier.animateItem(),
)
}
@@ -2211,9 +2201,8 @@ fun HomeScreen(
WindowInsets.systemBars
.only(WindowInsetsSides.Horizontal)
.asPaddingValues(),
- modifier = Modifier.animateItem(),
) {
- items(recommendation.items) { item ->
+ items(recommendation.items, key = { it.id }) { item ->
ytGridItem(item)
}
}
@@ -2301,7 +2290,6 @@ fun HomeScreen(
} else {
null
},
- modifier = Modifier.animateItem(),
)
}
@@ -2309,7 +2297,7 @@ fun HomeScreen(
// Render songs as a horizontal scrollable list (like Quick picks in YouTube Music)
item(key = "home_section_list_${section.index}") {
LazyHorizontalGrid(
- state = rememberLazyGridState(),
+ state = remember("section_${section.index}_grid") { LazyGridState() },
rows = GridCells.Fixed(4),
contentPadding =
WindowInsets.systemBars
@@ -2318,8 +2306,7 @@ fun HomeScreen(
modifier =
Modifier
.fillMaxWidth()
- .height(ListItemHeight * 4)
- .animateItem(),
+ .height(ListItemHeight * 4),
) {
items(
items = sectionSongs.distinctBy { it.id },
@@ -2385,7 +2372,6 @@ fun HomeScreen(
WindowInsets.systemBars
.only(WindowInsetsSides.Horizontal)
.asPaddingValues(),
- modifier = Modifier.animateItem(),
) {
items(
items = sectionData.items.distinctBy { it.id },
@@ -2411,7 +2397,6 @@ fun HomeScreen(
onClick = {
navController.navigate("mood_and_genres")
},
- modifier = Modifier.animateItem(),
)
}
item(key = "mood_and_genres_list") {
@@ -2420,10 +2405,9 @@ fun HomeScreen(
contentPadding = PaddingValues(6.dp),
modifier =
Modifier
- .height((MoodAndGenresButtonHeight + 12.dp) * 4 + 12.dp)
- .animateItem(),
+ .height((MoodAndGenresButtonHeight + 12.dp) * 4 + 12.dp),
) {
- items(moodAndGenres) {
+ items(moodAndGenres, key = { it.title }) {
MoodAndGenresButton(
title = it.title,
onClick = {
@@ -2448,7 +2432,6 @@ fun HomeScreen(
if (isLoading && homePage?.sections.isNullOrEmpty()) {
item(key = "loading_shimmer") {
ShimmerHost(
- modifier = Modifier.animateItem(),
) {
repeat(2) {
TextPlaceholder(
diff --git a/app/src/main/kotlin/com/metrolist/music/ui/screens/playlist/LocalPlaylistScreen.kt b/app/src/main/kotlin/com/metrolist/music/ui/screens/playlist/LocalPlaylistScreen.kt
index 3617eb1287..ad984d6e80 100644
--- a/app/src/main/kotlin/com/metrolist/music/ui/screens/playlist/LocalPlaylistScreen.kt
+++ b/app/src/main/kotlin/com/metrolist/music/ui/screens/playlist/LocalPlaylistScreen.kt
@@ -65,10 +65,8 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
-import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
-import androidx.compose.runtime.toMutableStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
@@ -222,16 +220,12 @@ fun LocalPlaylistScreen(
}
}
- var inSelectMode by rememberSaveable { mutableStateOf(false) }
+ var inSelectMode by remember { mutableStateOf(false) }
val selection =
- rememberSaveable(
- saver =
- listSaver<MutableList<Int>, Int>(
- save = { it.toList() },
- restore = { it.toMutableStateList() },
- ),
- ) { mutableStateListOf() }
- var selectionAnchorMapId by rememberSaveable { mutableStateOf<Int?>(null) }
+ remember {
+ mutableStateListOf<Int>()
+ }
+ var selectionAnchorMapId by remember { mutableStateOf<Int?>(null) }
val onExitSelectionMode = {
inSelectMode = false
selection.clear()