diff --git a/androidApp/build.gradle.kts b/androidApp/build.gradle.kts
index cbafbb790a..5c7a2edc28 100644
--- a/androidApp/build.gradle.kts
+++ b/androidApp/build.gradle.kts
@@ -275,4 +275,8 @@ if (!isFullBuild) {
tasks.named { it.contains("injectSentryDebugMetaPropertiesIntoAssetsRelease") }.configureEach {
finalizedBy(cleanSentryMetaTask)
}
-}
\ No newline at end of file
+}
+
+configurations.configureEach {
+ exclude(group = "com.charleskorn.kaml")
+}
diff --git a/androidApp/src/main/AndroidManifest.xml b/androidApp/src/main/AndroidManifest.xml
index 1a3a355216..ee3c154586 100644
--- a/androidApp/src/main/AndroidManifest.xml
+++ b/androidApp/src/main/AndroidManifest.xml
@@ -203,6 +203,15 @@
+
+
+
+
+
+
+
+
+
diff --git a/androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt b/androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt
index 1fbeae79d9..8a4aa2e169 100644
--- a/androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt
+++ b/androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt
@@ -1,6 +1,7 @@
package com.maxrave.simpmusic
import android.Manifest
+import android.app.SearchManager
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
@@ -9,6 +10,7 @@ import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.os.SystemClock
+import android.provider.MediaStore
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
@@ -111,14 +113,8 @@ class MainActivity : AppCompatActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
- Logger.d("MainActivity", "onNewIntent: $intent")
- viewModel.setIntent(
- GenericIntent(
- action = intent.action,
- data = (intent.data ?: intent.getStringExtra(Intent.EXTRA_TEXT)?.toUri())?.toKmpUriOrNull(),
- type = intent.type,
- ),
- )
+ setIntent(intent)
+ handleIntent(intent)
}
@ExperimentalFoundationApi
@@ -140,16 +136,7 @@ class MainActivity : AppCompatActivity() {
startMusicService()
}
Logger.d("MainActivity", "onCreate: ")
- val data = (intent?.data ?: intent?.getStringExtra(Intent.EXTRA_TEXT)?.toUri())?.toKmpUriOrNull()
- if (data != null) {
- viewModel.setIntent(
- GenericIntent(
- action = intent.action,
- data = data,
- type = intent.type,
- ),
- )
- }
+ handleIntent(intent)
Logger.d("Italy", "Key: ${Locale.ITALY.toLanguageTag()}")
// Check if the migration has already been done or not
@@ -338,6 +325,72 @@ class MainActivity : AppCompatActivity() {
private fun getString(key: String): String? = viewModel.getString(key)
+ private fun handleIntent(intent: Intent?) {
+ if (intent == null) return
+ Logger.d("MainActivity", "handleIntent: action=${intent.action}, data=${intent.data}")
+
+ // 1. Check for Media / Voice search actions from Gemini / Google Assistant
+ val action = intent.action
+ val isMediaPlayFromSearch = action == MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH ||
+ action == "android.intent.action.MEDIA_SEARCH" ||
+ action == Intent.ACTION_SEARCH
+
+ if (isMediaPlayFromSearch) {
+ val query = intent.getStringExtra(SearchManager.QUERY)
+ ?: intent.getStringExtra(Intent.EXTRA_TEXT)
+ ?: intent.getStringExtra(MediaStore.EXTRA_MEDIA_TITLE)
+ ?: intent.getStringExtra("query")
+
+ if (query.isNullOrBlank()) {
+ viewModel.playRecommendations()
+ } else {
+ val clean = query.trim().lowercase()
+ when {
+ clean.contains("recommandation") || clean.contains("recommendation") || clean.contains("pour moi") -> {
+ viewModel.playRecommendations()
+ }
+ clean.contains("hors ligne") || clean.contains("offline") || clean.contains("téléchargé") || clean.contains("telecharge") -> {
+ viewModel.playDownloaded()
+ }
+ clean.contains("favori") || clean.contains("favorite") || clean.contains("aimé") || clean.contains("liked") -> {
+ viewModel.playFavorites()
+ }
+ clean.contains("cache") -> {
+ viewModel.playCached()
+ }
+ clean.contains("pause") || clean.contains("stop") || clean.contains("arrête") || clean.contains("arrete") -> {
+ viewModel.pausePlayback()
+ }
+ clean.contains("reprend") || clean.contains("resume") || clean.contains("relance") || clean.contains("play") -> {
+ viewModel.resumePlayback()
+ }
+ clean.contains("suivant") || clean.contains("next") -> {
+ viewModel.skipNextTrack()
+ }
+ clean.contains("précédent") || clean.contains("precedent") || clean.contains("previous") -> {
+ viewModel.skipPreviousTrack()
+ }
+ else -> {
+ viewModel.searchAndPlay(query)
+ }
+ }
+ }
+ return
+ }
+
+ // 2. Generic and deep links
+ val data = (intent.data ?: intent.getStringExtra(Intent.EXTRA_TEXT)?.toUri())?.toKmpUriOrNull()
+ if (data != null) {
+ viewModel.setIntent(
+ GenericIntent(
+ action = intent.action,
+ data = data,
+ type = intent.type,
+ ),
+ )
+ }
+ }
+
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
viewModel.activityRecreate()
diff --git a/composeApp/src/commonMain/composeResources/values-fr/strings.xml b/composeApp/src/commonMain/composeResources/values-fr/strings.xml
index e18199e304..9bfe9143c0 100644
--- a/composeApp/src/commonMain/composeResources/values-fr/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values-fr/strings.xml
@@ -992,4 +992,22 @@
Impossible de charger les commentaires
Impossible de publier votre commentaire
Créez une chaîne YouTube pour laisser un commentaire
+ Générer les sous-titres
+ Génération des sous-titres…
+ Traduire les paroles
+ Traduction des paroles…
+ Échec de la traduction
+ Aucun sous-titre trouvé
+ Rechercher dans les paramètres…
+ Aucun paramètre trouvé
+ Par défaut du système
+ Assistant & Actions Gemini
+ Commandes vocales de l\'assistant et intégration AppFunctions
+ Lancer les recommandations
+ Démarrer la lecture de votre mix recommandé
+ Lire les musiques téléchargées
+ Écouter les titres enregistrés hors-ligne
+ Lire les favoris
+ Écouter vos titres aimés
+ Intents vocaux supportés : « Joue de la musique sur SimpMusic », « Joue [titre/artiste] », AppFunctions et liens simpmusic://action/...
diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 4ea19ff0df..3ef7e769d9 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -475,6 +475,10 @@
Belarusian
Kyrgyz
Macedonian
+ Kazakh
+ Mongolian
+ Greek
+ Georgian
Downloading the Japanese dictionary…
Japanese dictionary downloaded
Couldn't download the Japanese dictionary. Check your connection and select Japanese again to retry.
@@ -1151,4 +1155,22 @@
Sign-in could not be verified. Check your connection, or sign in again in this browser profile and refresh.
Refresh browser profiles
%1$s - song info
+ Generate subtitles
+ Generating subtitles…
+ Translate lyrics
+ Translating lyrics…
+ Translation failed
+ No subtitles found
+ Search settings…
+ No settings found
+ System default
+ Assistant & Gemini Actions
+ Voice assistant commands and AppFunctions integration
+ Play recommendations
+ Start playing your recommended mix
+ Play downloaded music
+ Play music saved offline
+ Play favorites
+ Play your liked tracks
+ Supported voice intents: \"Play music on SimpMusic\", \"Play [song/artist]\", AppFunctions, and custom scheme simpmusic://action/...
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt
index 1dba3cac8b..68454b17df 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt
@@ -379,6 +379,85 @@ fun App(
}
}
+ // Actions & Assistant commands: simpmusic://recommendations, simpmusic://offline, etc.
+ "recommendations", "recommandations" -> {
+ viewModel.playRecommendations()
+ }
+
+ "downloaded", "offline", "horsligne" -> {
+ viewModel.playDownloaded()
+ }
+
+ "favorites", "favoris" -> {
+ viewModel.playFavorites()
+ }
+
+ "cached" -> {
+ viewModel.playCached()
+ }
+
+ "pause" -> {
+ viewModel.pausePlayback()
+ }
+
+ "resume" -> {
+ viewModel.resumePlayback()
+ }
+
+ "next" -> {
+ viewModel.skipNextTrack()
+ }
+
+ "previous" -> {
+ viewModel.skipPreviousTrack()
+ }
+
+ "play" -> {
+ val type = data.getQueryParameter("type")?.lowercase()
+ val q = data.getQueryParameter("q") ?: data.getQueryParameter("query")
+ val action = data.getQueryParameter("action")?.lowercase()
+ when {
+ type == "recommendations" || type == "recommandations" || action == "recommendations" -> {
+ viewModel.playRecommendations()
+ }
+ type == "downloaded" || type == "offline" || type == "horsligne" || action == "downloaded" || action == "offline" -> {
+ viewModel.playDownloaded()
+ }
+ type == "favorites" || type == "favoris" || action == "favorites" -> {
+ viewModel.playFavorites()
+ }
+ type == "cached" || action == "cached" -> {
+ viewModel.playCached()
+ }
+ !q.isNullOrBlank() -> {
+ viewModel.searchAndPlay(q)
+ }
+ else -> {
+ viewModel.resumePlayback()
+ }
+ }
+ }
+
+ "action" -> {
+ val type = data.getQueryParameter("type")?.lowercase()
+ when (type) {
+ "recommendations", "recommandations" -> viewModel.playRecommendations()
+ "downloaded", "offline", "horsligne" -> viewModel.playDownloaded()
+ "favorites", "favoris" -> viewModel.playFavorites()
+ "cached" -> viewModel.playCached()
+ "pause" -> viewModel.pausePlayback()
+ "resume" -> viewModel.resumePlayback()
+ "next" -> viewModel.skipNextTrack()
+ "previous" -> viewModel.skipPreviousTrack()
+ else -> {
+ val q = data.getQueryParameter("q") ?: data.getQueryParameter("query")
+ if (!q.isNullOrBlank()) {
+ viewModel.searchAndPlay(q)
+ }
+ }
+ }
+ }
+
else -> {
viewModel.makeToast(getString(Res.string.this_link_is_not_supported))
}
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullscreenLyricsContent.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullscreenLyricsContent.kt
index 9be0c6fa1a..d889af4850 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullscreenLyricsContent.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullscreenLyricsContent.kt
@@ -104,6 +104,7 @@ import com.maxrave.simpmusic.ui.icon.MoreVert
import com.maxrave.simpmusic.ui.icon.PictureInPictureAlt
import com.maxrave.simpmusic.ui.icon.QueueMusic
import com.maxrave.simpmusic.ui.icon.Share
+import com.maxrave.simpmusic.ui.icon.Translate
import com.maxrave.simpmusic.ui.icon.AvTimer
import com.maxrave.simpmusic.ui.icon.SimpIcons
import com.maxrave.simpmusic.ui.icon.VolumeOff
@@ -133,6 +134,7 @@ import org.jetbrains.compose.resources.stringResource
import simpmusic.composeapp.generated.resources.Res
import simpmusic.composeapp.generated.resources.crossfading
import simpmusic.composeapp.generated.resources.share_lyrics
+import simpmusic.composeapp.generated.resources.translate_lyrics
import simpmusic.composeapp.generated.resources.unavailable
import kotlin.math.PI
import kotlin.math.cos
@@ -449,6 +451,15 @@ fun FullscreenLyricsContent(
// Share lyrics — only when there are lyrics to share.
if (screenDataState.lyricsData != null) {
+ IconButton(
+ onClick = { sharedViewModel.translateCurrentLyrics() },
+ ) {
+ Icon(
+ imageVector = SimpIcons.Translate,
+ contentDescription = stringResource(Res.string.translate_lyrics),
+ tint = Color.White,
+ )
+ }
IconButton(
onClick = { showShareLyricsSheet = true },
) {
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricsView.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricsView.kt
index 54eca64968..0a7b14dbc8 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricsView.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LyricsView.kt
@@ -418,6 +418,18 @@ private fun buildSyncedTranslatedWordsByLineIndex(
val _bt = bestTs
}
}
+ // Fallback: If time-based matching produced nothing or missed most lines while line count matches closely,
+ // fallback to line-index matching so translations never get dropped on timing drift.
+ if (result.isEmpty() || result.size < originalLines.size / 3) {
+ for (i in originalLines.indices) {
+ if (!result.containsKey(i)) {
+ val fallbackWords = translatedLines.getOrNull(i)?.words
+ if (!fallbackWords.isNullOrBlank()) {
+ result[i] = fallbackWords
+ }
+ }
+ }
+ }
return result
}
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt
index 15449a0d8d..3a0b1b3e39 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt
@@ -177,6 +177,8 @@ import com.maxrave.simpmusic.ui.icon.Speed
import com.maxrave.simpmusic.ui.icon.Sync
import com.maxrave.simpmusic.ui.icon.SyncDisabled
import com.maxrave.simpmusic.ui.icon.ThumbDownOutline
+import com.maxrave.simpmusic.ui.icon.Translate
+import com.maxrave.simpmusic.ui.icon.Subtitles
import com.maxrave.simpmusic.ui.icon.Tune
import com.maxrave.simpmusic.ui.icon.Update
import com.maxrave.simpmusic.ui.navigation.destination.list.AlbumDestination
@@ -216,6 +218,8 @@ import simpmusic.composeapp.generated.resources.can_not_be_empty
import simpmusic.composeapp.generated.resources.cancel
import simpmusic.composeapp.generated.resources.cancel_download
import simpmusic.composeapp.generated.resources.crop_cover
+import simpmusic.composeapp.generated.resources.generate_subtitles
+import simpmusic.composeapp.generated.resources.translate_lyrics
import simpmusic.composeapp.generated.resources.codec
import simpmusic.composeapp.generated.resources.copied_to_clipboard
import simpmusic.composeapp.generated.resources.create_new_queue_and_play
@@ -1372,6 +1376,10 @@ fun NowPlayingBottomSheet(
onRemoveFromCache: (() -> Unit)? = null,
/** Set while the song playing has no lyrics: adds Add lyrics under Main Lyrics Provider. */
onAddLyrics: (() -> Unit)? = null,
+ /** Triggered on demand to translate lyrics */
+ onTranslateLyrics: (() -> Unit)? = null,
+ /** Triggered on demand to generate or fetch subtitles */
+ onGenerateSubtitles: (() -> Unit)? = null,
/** Set when opened from a queue row: adds that row's move and delete actions at the top. */
queuePosition: QueuePosition? = null,
/**
@@ -1887,6 +1895,24 @@ fun NowPlayingBottomSheet(
onAddLyrics()
}
}
+ if (onTranslateLyrics != null) {
+ ActionButton(
+ icon = SimpIcons.Translate,
+ text = Res.string.translate_lyrics,
+ ) {
+ hideModalBottomSheet()
+ onTranslateLyrics()
+ }
+ }
+ if (onGenerateSubtitles != null) {
+ ActionButton(
+ icon = SimpIcons.Subtitles,
+ text = Res.string.generate_subtitles,
+ ) {
+ hideModalBottomSheet()
+ onGenerateSubtitles()
+ }
+ }
Crossfade(targetState = setSleepTimerEnable) {
val sleepTimerState = uiState.sleepTimer
if (it) {
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/Translate.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/Translate.kt
new file mode 100644
index 0000000000..27d91a8688
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/Translate.kt
@@ -0,0 +1,80 @@
+package com.maxrave.simpmusic.ui.icon
+
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.PathFillType
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.StrokeJoin
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.graphics.vector.path
+import androidx.compose.ui.unit.dp
+
+@Suppress("CheckReturnValue")
+val SimpIcons.Translate: ImageVector
+ get() {
+ if (_Translate != null) {
+ return _Translate!!
+ }
+ _Translate =
+ ImageVector.Builder(
+ name = "Translate",
+ defaultWidth = 24.dp,
+ defaultHeight = 24.dp,
+ viewportWidth = 24f,
+ viewportHeight = 24f,
+ ).apply {
+ path(
+ fill = SolidColor(Color.Black),
+ fillAlpha = 1f,
+ stroke = null,
+ strokeAlpha = 1f,
+ strokeLineWidth = 1f,
+ strokeLineCap = StrokeCap.Butt,
+ strokeLineJoin = StrokeJoin.Bevel,
+ strokeLineMiter = 1f,
+ pathFillType = PathFillType.Companion.NonZero,
+ ) {
+ moveTo(12.87f, 15.07f)
+ lineToRelative(-2.54f, -2.51f)
+ lineToRelative(0.03f, -0.03f)
+ curveToRelative(1.74f, -1.94f, 2.98f, -4.17f, 3.71f, -6.53f)
+ horizontalLineTo(17f)
+ verticalLineTo(4f)
+ horizontalLineToRelative(-7f)
+ verticalLineTo(2f)
+ horizontalLineTo(8f)
+ verticalLineToRelative(2f)
+ horizontalLineTo(1f)
+ verticalLineToRelative(1.99f)
+ horizontalLineToRelative(11.17f)
+ curveTo(11.5f, 7.92f, 10.44f, 9.75f, 9f, 11.35f)
+ curveTo(8.07f, 10.32f, 7.3f, 9.19f, 6.69f, 8f)
+ horizontalLineToRelative(-2f)
+ curveToRelative(0.73f, 1.63f, 1.73f, 3.17f, 2.98f, 4.56f)
+ lineToRelative(-5.09f, 5.02f)
+ lineTo(4f, 19f)
+ lineToRelative(5f, -5f)
+ lineToRelative(3.11f, 3.11f)
+ lineToRelative(0.76f, -2.04f)
+ close()
+ moveTo(18.5f, 10f)
+ horizontalLineToRelative(-2f)
+ lineTo(12f, 22f)
+ horizontalLineToRelative(2f)
+ lineToRelative(1.12f, -3f)
+ horizontalLineToRelative(4.75f)
+ lineTo(21f, 22f)
+ horizontalLineToRelative(2f)
+ lineToRelative(-4.5f, -12f)
+ close()
+ moveTo(15.88f, 17f)
+ lineToRelative(1.62f, -4.33f)
+ lineTo(19.12f, 17f)
+ horizontalLineToRelative(-3.24f)
+ close()
+ }
+ }.build()
+ return _Translate!!
+ }
+
+private var _Translate: ImageVector? = null
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt
index 2c17b7c0cd..6ca0dcd05d 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt
@@ -61,6 +61,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -138,6 +139,7 @@ import com.maxrave.simpmusic.ui.component.SettingGroup
import com.maxrave.simpmusic.ui.component.SettingItem
import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew
import com.maxrave.simpmusic.ui.icon.Close
+import com.maxrave.simpmusic.ui.icon.Search
import com.maxrave.simpmusic.ui.icon.Error
import com.maxrave.simpmusic.ui.icon.PeopleAlt
import com.maxrave.simpmusic.ui.icon.PlaylistAdd
@@ -177,9 +179,22 @@ import kotlinx.datetime.format.FormatStringsInDatetimeFormats
import kotlinx.datetime.format.byUnicodePattern
import org.jetbrains.compose.resources.getString
import org.jetbrains.compose.resources.stringResource
+import org.jetbrains.compose.resources.StringResource
import org.koin.compose.koinInject
import org.koin.compose.viewmodel.koinViewModel
import simpmusic.composeapp.generated.resources.Res
+import simpmusic.composeapp.generated.resources.search_settings
+import simpmusic.composeapp.generated.resources.no_settings_found
+import simpmusic.composeapp.generated.resources.system_default
+import simpmusic.composeapp.generated.resources.assistant_and_ai
+import simpmusic.composeapp.generated.resources.assistant_and_ai_description
+import simpmusic.composeapp.generated.resources.play_recommendations_action
+import simpmusic.composeapp.generated.resources.play_recommendations_description
+import simpmusic.composeapp.generated.resources.play_downloaded_action
+import simpmusic.composeapp.generated.resources.play_downloaded_description
+import simpmusic.composeapp.generated.resources.play_favorites_action
+import simpmusic.composeapp.generated.resources.play_favorites_description
+import simpmusic.composeapp.generated.resources.voice_commands_info
import simpmusic.composeapp.generated.resources.base_url
import simpmusic.composeapp.generated.resources.configured
import simpmusic.composeapp.generated.resources.custom_base_url
@@ -358,6 +373,10 @@ import simpmusic.composeapp.generated.resources.romanization_japanese_dict_faile
import simpmusic.composeapp.generated.resources.romanization_korean
import simpmusic.composeapp.generated.resources.romanization_kyrgyz
import simpmusic.composeapp.generated.resources.romanization_macedonian
+import simpmusic.composeapp.generated.resources.romanization_kazakh
+import simpmusic.composeapp.generated.resources.romanization_mongolian
+import simpmusic.composeapp.generated.resources.romanization_greek
+import simpmusic.composeapp.generated.resources.romanization_georgian
import simpmusic.composeapp.generated.resources.romanization_punjabi
import simpmusic.composeapp.generated.resources.romanization_russian
import simpmusic.composeapp.generated.resources.romanization_serbian
@@ -658,6 +677,12 @@ fun SettingScreen(
var showThirdPartyLibraries by rememberSaveable {
mutableStateOf(false)
}
+ var searchQuery by rememberSaveable {
+ mutableStateOf("")
+ }
+ var isSearchActive by rememberSaveable {
+ mutableStateOf(false)
+ }
LaunchedEffect(true) {
viewModel.getAllGoogleAccount()
@@ -668,6 +693,43 @@ fun SettingScreen(
viewModel.getThumbCacheSize(platformContext)
}
+
+ val normalizedSearchQuery = searchQuery.trim().lowercase()
+ val sectionStringsCache = remember {
+ mutableStateMapOf>()
+ }
+ LaunchedEffect(Unit) {
+ for ((section, resList) in settingSectionKeywords) {
+ val list = mutableListOf()
+ for (res in resList) {
+ try {
+ list.add(getString(res).lowercase())
+ } catch (e: Exception) {
+ // ignore
+ }
+ }
+ sectionStringsCache[section] = list
+ }
+ }
+
+ val matchingSections by remember(normalizedSearchQuery, sectionStringsCache.size) {
+ derivedStateOf {
+ if (normalizedSearchQuery.isEmpty()) {
+ settingSectionKeywords.keys
+ } else {
+ val matches = mutableSetOf()
+ for ((section, strings) in sectionStringsCache) {
+ if (strings.any { it.contains(normalizedSearchQuery) }) {
+ matches.add(section)
+ }
+ }
+ matches
+ }
+ }
+ }
+ fun isSectionVisible(key: String): Boolean =
+ normalizedSearchQuery.isEmpty() || key in matchingSections
+
val settingListState = rememberLazyListState()
// The toolbar is part of the list and scrolls away with it; a pinned, frosted copy takes over
// once the Devices group has gone under it — Playlist's and Artist's way. The group's height
@@ -716,6 +778,13 @@ fun SettingScreen(
// where the pinned copy appears; the list's top padding already clears the status bar.
SettingTopBar(
onBack = { navController.navigateUp() },
+ searchQuery = searchQuery,
+ onSearchQueryChange = { searchQuery = it },
+ isSearchActive = isSearchActive,
+ onToggleSearch = {
+ isSearchActive = !isSearchActive
+ if (!isSearchActive) searchQuery = ""
+ },
windowInsets = WindowInsets(0),
modifier =
Modifier.layout { measurable, constraints ->
@@ -725,6 +794,7 @@ fun SettingScreen(
layout(constraints.maxWidth, placeable.height) { placeable.place(-bleed, 0) }
},
)
+ if (isSectionVisible("user_interface")) {
// Above every section, and inside item 0 rather than an item of its own, for the
// glow reason above.
SettingGroup(
@@ -892,6 +962,10 @@ fun SettingScreen(
RomanizationLanguage.BELARUSIAN to stringResource(Res.string.romanization_belarusian),
RomanizationLanguage.KYRGYZ to stringResource(Res.string.romanization_kyrgyz),
RomanizationLanguage.MACEDONIAN to stringResource(Res.string.romanization_macedonian),
+ RomanizationLanguage.KAZAKH to stringResource(Res.string.romanization_kazakh),
+ RomanizationLanguage.MONGOLIAN to stringResource(Res.string.romanization_mongolian),
+ RomanizationLanguage.GREEK to stringResource(Res.string.romanization_greek),
+ RomanizationLanguage.GEORGIAN to stringResource(Res.string.romanization_georgian),
)
val romanizationSelected = RomanizationLanguage.parse(romanizationStored)
SettingItem(
@@ -1001,9 +1075,11 @@ fun SettingScreen(
switch = (enableLiquidGlass to { viewModel.setEnableLiquidGlass(it) }),
)
}
+ }
}
}
- item(key = "content") {
+ if (isSectionVisible("content")) {
+ item(key = "content") {
SettingGroup(title = stringResource(Res.string.content)) {
SettingItem(
title = stringResource(Res.string.youtube_account),
@@ -1464,8 +1540,10 @@ fun SettingScreen(
}
}
}
+ }
if (getPlatform() == Platform.Android) {
- item(key = "audio") {
+ if (isSectionVisible("audio")) {
+ item(key = "audio") {
SettingGroup(title = stringResource(Res.string.audio)) {
SettingItem(
title = stringResource(Res.string.normalize_volume),
@@ -1525,7 +1603,9 @@ fun SettingScreen(
}
}
}
- item(key = "playback") {
+ }
+ if (isSectionVisible("playback")) {
+ item(key = "playback") {
SettingGroup(title = stringResource(Res.string.playback)) {
// Under Playback rather than Audio because that whole group sits inside an
// Android-only branch — "Open system equalizer" is an Android feature — and this
@@ -1707,10 +1787,12 @@ fun SettingScreen(
}
}
}
+ }
// Deliberately not part of "storage" further down, which is Android-only: tracking and the
// rows it leaves behind exist on Desktop just the same. The switch that produces the history
// and the button that erases it belong together.
- item(key = "listening_history") {
+ if (isSectionVisible("listening_history")) {
+ item(key = "listening_history") {
SettingGroup(title = stringResource(Res.string.listening_history)) {
SettingItem(
title = stringResource(Res.string.local_tracking_title),
@@ -1740,7 +1822,9 @@ fun SettingScreen(
)
}
}
- item(key = "lyrics") {
+ }
+ if (isSectionVisible("lyrics")) {
+ item(key = "lyrics") {
SettingGroup(title = stringResource(Res.string.lyrics)) {
SettingItem(
title = stringResource(Res.string.main_lyrics_provider),
@@ -1827,26 +1911,47 @@ fun SettingScreen(
},
)
+ val defaultLangLabel = stringResource(Res.string.system_default)
+ val currentTransLangDisplay = if (translationLanguage.isNullOrEmpty()) {
+ defaultLangLabel
+ } else {
+ SUPPORTED_LANGUAGE.getLanguageFromCode(
+ if (translationLanguage!!.length == 2) {
+ SUPPORTED_LANGUAGE.codes.firstOrNull { it.startsWith(translationLanguage!!) } ?: translationLanguage
+ } else translationLanguage
+ )
+ }
SettingItem(
title = stringResource(Res.string.translation_language),
- subtitle = translationLanguage ?: "",
+ subtitle = currentTransLangDisplay,
onClick = {
+ val languageOptions = listOf(defaultLangLabel to "") + SUPPORTED_LANGUAGE.items.mapIndexed { index, item ->
+ val fullCode = SUPPORTED_LANGUAGE.codes.getOrNull(index) ?: ""
+ val twoLetter = fullCode.substringBefore("-")
+ item.toString() to twoLetter
+ }
+ val currentSelectedCode = translationLanguage ?: ""
viewModel.setAlertData(
SettingAlertState(
title = runBlocking { getString(Res.string.translation_language) },
- textField =
- SettingAlertState.TextFieldData(
- label = runBlocking { getString(Res.string.translation_language) },
- value = translationLanguage ?: "",
- verifyCodeBlock = {
- (it.length == 2 && it.isTwoLetterCode()) to
- runBlocking { getString(Res.string.invalid_language_code) }
- },
+ selectOne =
+ SettingAlertState.SelectData(
+ listSelect =
+ languageOptions.map { (label, code) ->
+ val isSelected = if (code.isEmpty()) {
+ currentSelectedCode.isEmpty()
+ } else {
+ currentSelectedCode.equals(code, ignoreCase = true)
+ }
+ isSelected to label
+ },
),
message = runBlocking { getString(Res.string.translation_language_message) },
confirm =
runBlocking { getString(Res.string.change) } to { state ->
- viewModel.setTranslationLanguage(state.textField?.value ?: "")
+ val selectedLabel = state.selectOne?.getSelected()
+ val matchedCode = languageOptions.firstOrNull { it.first == selectedLabel }?.second ?: ""
+ viewModel.setTranslationLanguage(matchedCode)
},
dismiss = runBlocking { getString(Res.string.cancel) },
),
@@ -1854,26 +1959,46 @@ fun SettingScreen(
},
isEnable = true,
)
+ val currentSubLangDisplay = if (youtubeSubtitleLanguage.isEmpty()) {
+ defaultLangLabel
+ } else {
+ SUPPORTED_LANGUAGE.getLanguageFromCode(
+ if (youtubeSubtitleLanguage.length == 2) {
+ SUPPORTED_LANGUAGE.codes.firstOrNull { it.startsWith(youtubeSubtitleLanguage) } ?: youtubeSubtitleLanguage
+ } else youtubeSubtitleLanguage
+ )
+ }
SettingItem(
title = stringResource(Res.string.youtube_subtitle_language),
- subtitle = youtubeSubtitleLanguage,
+ subtitle = currentSubLangDisplay,
onClick = {
+ val languageOptions = listOf(defaultLangLabel to "") + SUPPORTED_LANGUAGE.items.mapIndexed { index, item ->
+ val fullCode = SUPPORTED_LANGUAGE.codes.getOrNull(index) ?: ""
+ val twoLetter = fullCode.substringBefore("-")
+ item.toString() to twoLetter
+ }
+ val currentSelectedCode = youtubeSubtitleLanguage
viewModel.setAlertData(
SettingAlertState(
title = runBlocking { getString(Res.string.youtube_subtitle_language) },
- textField =
- SettingAlertState.TextFieldData(
- label = runBlocking { getString(Res.string.youtube_subtitle_language) },
- value = youtubeSubtitleLanguage,
- verifyCodeBlock = {
- (it.length == 2 && it.isTwoLetterCode()) to
- runBlocking { getString(Res.string.invalid_language_code) }
- },
+ selectOne =
+ SettingAlertState.SelectData(
+ listSelect =
+ languageOptions.map { (label, code) ->
+ val isSelected = if (code.isEmpty()) {
+ currentSelectedCode.isEmpty()
+ } else {
+ currentSelectedCode.equals(code, ignoreCase = true)
+ }
+ isSelected to label
+ },
),
message = runBlocking { getString(Res.string.youtube_subtitle_language_message) },
confirm =
runBlocking { getString(Res.string.change) } to { state ->
- viewModel.setYoutubeSubtitleLanguage(state.textField?.value ?: "")
+ val selectedLabel = state.selectOne?.getSelected()
+ val matchedCode = languageOptions.firstOrNull { it.first == selectedLabel }?.second ?: ""
+ viewModel.setYoutubeSubtitleLanguage(matchedCode)
},
dismiss = runBlocking { getString(Res.string.cancel) },
),
@@ -1940,7 +2065,9 @@ fun SettingScreen(
)
}
}
- item(key = "AI") {
+ }
+ if (isSectionVisible("AI")) {
+ item(key = "AI") {
SettingGroup(title = stringResource(Res.string.ai)) {
SettingItem(
title = stringResource(Res.string.ai_provider),
@@ -2123,7 +2250,46 @@ fun SettingScreen(
)
}
}
- item(key = "spotify") {
+ }
+ if (isSectionVisible("assistant_and_ai")) {
+ item(key = "assistant_and_ai") {
+ SettingGroup(
+ title = stringResource(Res.string.assistant_and_ai),
+ footer = {
+ Text(
+ text = stringResource(Res.string.voice_commands_info),
+ style = typo().bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
+ )
+ },
+ ) {
+ SettingItem(
+ title = stringResource(Res.string.play_recommendations_action),
+ subtitle = stringResource(Res.string.play_recommendations_description),
+ onClick = {
+ sharedViewModel.playRecommendations()
+ },
+ )
+ SettingItem(
+ title = stringResource(Res.string.play_downloaded_action),
+ subtitle = stringResource(Res.string.play_downloaded_description),
+ onClick = {
+ sharedViewModel.playDownloaded()
+ },
+ )
+ SettingItem(
+ title = stringResource(Res.string.play_favorites_action),
+ subtitle = stringResource(Res.string.play_favorites_description),
+ onClick = {
+ sharedViewModel.playFavorites()
+ },
+ )
+ }
+ }
+ }
+ if (isSectionVisible("spotify")) {
+ item(key = "spotify") {
SettingGroup(title = stringResource(Res.string.spotify)) {
SettingItem(
// The title follows the state: a row that still reads "Log in" while logged in
@@ -2172,7 +2338,9 @@ fun SettingScreen(
)
}
}
- item(key = "discord") {
+ }
+ if (isSectionVisible("discord")) {
+ item(key = "discord") {
SettingGroup(title = stringResource(Res.string.discord_integration)) {
SettingItem(
title =
@@ -2205,10 +2373,12 @@ fun SettingScreen(
)
}
}
+ }
// Hidden entirely when the build carries no Last.fm credentials — a FOSS build, or a full
// build whose local.properties has no key.
if (viewModel.lastfmAvailable) {
- item(key = "lastfm") {
+ if (isSectionVisible("lastfm")) {
+ item(key = "lastfm") {
SettingGroup(title = stringResource(Res.string.lastfm_integration)) {
SettingItem(
title =
@@ -2242,7 +2412,9 @@ fun SettingScreen(
}
}
}
- item(key = "sponsor_block") {
+ }
+ if (isSectionVisible("sponsor_block")) {
+ item(key = "sponsor_block") {
SettingGroup(
title = stringResource(Res.string.sponsorBlock),
// The project's note sits under the card, where a grouped list keeps its explanations.
@@ -2317,8 +2489,10 @@ fun SettingScreen(
)
}
}
+ }
if (getPlatform() == Platform.Android) {
- item(key = "storage") {
+ if (isSectionVisible("storage")) {
+ item(key = "storage") {
SettingGroup(title = stringResource(Res.string.storage)) {
SettingItem(
title = stringResource(Res.string.player_cache),
@@ -2624,7 +2798,9 @@ fun SettingScreen(
}
}
}
- item(key = "backup") {
+ }
+ if (isSectionVisible("backup")) {
+ item(key = "backup") {
SettingGroup(
title = stringResource(Res.string.backup),
footer = {
@@ -2788,7 +2964,9 @@ fun SettingScreen(
)
}
}
- item(key = "about_us") {
+ }
+ if (isSectionVisible("about_us")) {
+ item(key = "about_us") {
SettingGroup(title = stringResource(Res.string.about_us)) {
SettingItem(
title = stringResource(Res.string.version),
@@ -2888,7 +3066,9 @@ fun SettingScreen(
)
}
}
- item(key = "developer_option") {
+ }
+ if (isSectionVisible("developer_option")) {
+ item(key = "developer_option") {
SettingGroup(title = stringResource(Res.string.developer_option)) {
SettingItem(
title = stringResource(Res.string.app_log),
@@ -2899,6 +3079,7 @@ fun SettingScreen(
)
}
}
+ }
item(key = "end") {
EndOfPage()
}
@@ -3518,6 +3699,13 @@ fun SettingScreen(
) {
SettingTopBar(
onBack = { navController.navigateUp() },
+ searchQuery = searchQuery,
+ onSearchQueryChange = { searchQuery = it },
+ isSearchActive = isSearchActive,
+ onToggleSearch = {
+ isSearchActive = !isSearchActive
+ if (!isSearchActive) searchQuery = ""
+ },
// The house recipe from AlbumScreen's bars, thinned: ultraThin's built-in tint stacked
// on this page's dark ground read as a solid lid. 0.3 keeps the blur doing the work and
// the tint only settling legibility.
@@ -3530,19 +3718,66 @@ fun SettingScreen(
* The page's toolbar. Drawn twice, the way Playlist and Artist draw theirs: once inside the list,
* where it scrolls away with the content, and once pinned above it.
*/
+private val settingSectionKeywords: Map> = mapOf(
+ "user_interface" to listOf(Res.string.custom_color, Res.string.enable_liquid_glass_effect, Res.string.enable_liquid_glass_effect_description, Res.string.login_sync_android_description, Res.string.login_sync_android_title, Res.string.login_sync_desktop_description, Res.string.login_sync_desktop_title, Res.string.login_sync_section, Res.string.lyrics_romanization, Res.string.lyrics_romanization_description, Res.string.lyrics_style, Res.string.lyrics_style_apple_music, Res.string.lyrics_style_classic, Res.string.now_playing_style, Res.string.now_playing_style_apple_music, Res.string.now_playing_style_m3_expressive, Res.string.now_playing_style_soundcloud, Res.string.now_playing_style_spotify, Res.string.requires_android_12, Res.string.romanization_belarusian, Res.string.romanization_bulgarian, Res.string.romanization_chinese, Res.string.romanization_hindi, Res.string.romanization_japanese, Res.string.romanization_japanese_dict_downloading, Res.string.romanization_japanese_dict_failed, Res.string.romanization_korean, Res.string.romanization_kyrgyz, Res.string.romanization_macedonian, Res.string.romanization_punjabi, Res.string.romanization_russian, Res.string.romanization_serbian, Res.string.romanization_ukrainian, Res.string.theme, Res.string.theme_color, Res.string.theme_color_custom, Res.string.theme_color_default, Res.string.theme_color_wallpaper, Res.string.theme_mode_dark, Res.string.theme_mode_light, Res.string.theme_mode_system, Res.string.user_interface),
+ "content" to listOf(Res.string.auto_download_liked_songs, Res.string.auto_download_liked_songs_description, Res.string.change_language_warning, Res.string.content, Res.string.content_country, Res.string.download_quality, Res.string.http, Res.string.invalid_host, Res.string.invalid_language_code, Res.string.invalid_port, Res.string.keep_your_youtube_playlist_offline, Res.string.keep_your_youtube_playlist_offline_description, Res.string.language, Res.string.manage_your_youtube_accounts, Res.string.original_audio, Res.string.play_explicit_content, Res.string.play_explicit_content_description, Res.string.play_video_for_video_track_instead_of_audio_only, Res.string.preferred_audio_language, Res.string.preferred_audio_language_message, Res.string.proxy, Res.string.proxy_description, Res.string.proxy_host, Res.string.proxy_host_message, Res.string.proxy_password, Res.string.proxy_password_message, Res.string.proxy_port, Res.string.proxy_port_message, Res.string.proxy_type, Res.string.proxy_username, Res.string.proxy_username_message, Res.string.quality, Res.string.radio_audio_only, Res.string.radio_audio_only_description, Res.string.send_back_listening_data_to_google, Res.string.smart_downloads, Res.string.smart_downloads_description, Res.string.smart_downloads_needs_local_tracking, Res.string.smart_downloads_size, Res.string.smart_downloads_size_value, Res.string.socks, Res.string.such_as_music_video_lyrics_video_podcasts_and_more, Res.string.sync_follow_to_youtube, Res.string.sync_follow_to_youtube_description, Res.string.video_download_quality, Res.string.video_quality, Res.string.youtube_account),
+ "audio" to listOf(Res.string.audio, Res.string.balance_media_loudness, Res.string.equalizer_type, Res.string.equalizer_type_built_in, Res.string.equalizer_type_system, Res.string.normalize_volume, Res.string.not_available_while_casting, Res.string.open_system_equalizer, Res.string.skip_no_music_part, Res.string.skip_silent, Res.string.use_your_system_equalizer),
+ "playback" to listOf(Res.string.audio_delay, Res.string.audio_delay_description, Res.string.audio_reverb, Res.string.audio_reverb_description, Res.string.crossfade, Res.string.crossfade_auto, Res.string.crossfade_description, Res.string.crossfade_dj_mode, Res.string.crossfade_dj_mode_description, Res.string.crossfade_duration, Res.string.crossfade_skip_album, Res.string.crossfade_skip_album_description, Res.string.equalizer, Res.string.equalizer_description, Res.string.kill_service_on_exit, Res.string.kill_service_on_exit_description, Res.string.not_available_while_casting, Res.string.playback, Res.string.save_playback_state, Res.string.save_shuffle_and_repeat_mode),
+ "listening_history" to listOf(Res.string.clear_listening_history, Res.string.clear_listening_history_confirm, Res.string.clear_listening_history_description, Res.string.listening_history, Res.string.local_tracking_description, Res.string.local_tracking_title),
+ "lyrics" to listOf(Res.string.anonymous, Res.string.better_lyrics, Res.string.contributor_email, Res.string.contributor_name, Res.string.help_build_lyrics_database, Res.string.help_build_lyrics_database_description, Res.string.invalid, Res.string.lrclib, Res.string.lyrics, Res.string.lyrics_offset, Res.string.lyrics_offset_invalid, Res.string.lyrics_offset_message, Res.string.lyrics_offset_value, Res.string.main_lyrics_provider, Res.string.simpmusic_lyrics, Res.string.system_default, Res.string.translation_language, Res.string.translation_language_message, Res.string.unknown, Res.string.youtube_subtitle_language, Res.string.youtube_subtitle_language_message, Res.string.youtube_transcript),
+ "AI" to listOf(Res.string.ai, Res.string.ai_api_key, Res.string.ai_provider, Res.string.base_url, Res.string.custom_ai_model_id, Res.string.custom_base_url, Res.string.custom_base_url_message, Res.string.custom_headers, Res.string.custom_headers_json, Res.string.custom_headers_message, Res.string.custom_model_id_messages, Res.string.default_models, Res.string.gemini, Res.string.headers_json, Res.string.invalid, Res.string.invalid_api_key, Res.string.invalid_json_format, Res.string.invalid_url_format, Res.string.openai, Res.string.openai_api_compatible, Res.string.unknown, Res.string.use_ai_translation, Res.string.use_ai_translation_description),
+ "assistant_and_ai" to listOf(Res.string.assistant_and_ai, Res.string.play_downloaded_action, Res.string.play_downloaded_description, Res.string.play_favorites_action, Res.string.play_favorites_description, Res.string.play_recommendations_action, Res.string.play_recommendations_description, Res.string.voice_commands_info),
+ "spotify" to listOf(Res.string.animated_artwork_info, Res.string.canvas_info, Res.string.enable_animated_artwork, Res.string.enable_canvas, Res.string.enable_spotify_lyrics, Res.string.intro_login_to_spotify, Res.string.log_in_to_spotify, Res.string.log_out_from_spotify, Res.string.logged_in, Res.string.spotify, Res.string.spotify_lyrícs_info),
+ "discord" to listOf(Res.string.discord_integration, Res.string.enable_rich_presence, Res.string.intro_login_to_discord, Res.string.log_in_to_discord, Res.string.log_out_from_discord, Res.string.logged_in, Res.string.rich_presence_info),
+ "lastfm" to listOf(Res.string.enable_scrobbling, Res.string.intro_login_to_lastfm, Res.string.lastfm_integration, Res.string.log_in_to_lastfm, Res.string.log_out_from_lastfm, Res.string.logged_in_as, Res.string.scrobbling_info),
+ "sponsor_block" to listOf(Res.string.categories_sponsor_block, Res.string.enable_sponsor_block, Res.string.skip_sponsor_part_of_video, Res.string.sponsorBlock, Res.string.sponsor_block_intro, Res.string.what_segments_will_be_skipped),
+ "storage" to listOf(Res.string.clear_canvas_cache, Res.string.clear_downloaded_cache, Res.string.clear_player_cache, Res.string.clear_thumbnail_cache, Res.string.database, Res.string.downloaded_cache, Res.string.free_space, Res.string.limit_player_cache, Res.string.other_app, Res.string.player_cache, Res.string.spotify_canvas_cache, Res.string.storage, Res.string.thumbnail_cache),
+ "backup" to listOf(Res.string.auto_backup, Res.string.auto_backup_description, Res.string.backup, Res.string.backup_downloaded, Res.string.backup_downloaded_description, Res.string.backup_frequency, Res.string.daily, Res.string.import_data, Res.string.import_data_intro, Res.string.import_playlists_from_other_apps, Res.string.keep_backups, Res.string.keep_backups_format, Res.string.last_backup, Res.string.monthly, Res.string.never, Res.string.restore_your_data, Res.string.restore_your_saved_data, Res.string.save_all_your_playlist_data, Res.string.weekly),
+ "about_us" to listOf(Res.string.about_us, Res.string.author, Res.string.auto_check_for_update, Res.string.auto_check_for_update_description, Res.string.blog_notification_description, Res.string.blog_notification_title, Res.string.buy_me_a_coffee, Res.string.check_for_update, Res.string.description_and_licenses, Res.string.developer_blog, Res.string.developer_blog_tagline, Res.string.donation, Res.string.follow_me_on_x, Res.string.maxrave_dev, Res.string.third_party_libraries, Res.string.update_channel, Res.string.version, Res.string.version_format),
+ "developer_option" to listOf(Res.string.app_log, Res.string.app_log_description, Res.string.developer_option),
+)
+
+
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SettingTopBar(
onBack: () -> Unit,
+ searchQuery: String = "",
+ onSearchQueryChange: (String) -> Unit = {},
+ isSearchActive: Boolean = false,
+ onToggleSearch: () -> Unit = {},
modifier: Modifier = Modifier,
windowInsets: WindowInsets = TopAppBarDefaults.windowInsets,
) {
TopAppBar(
title = {
- Text(
- text = stringResource(Res.string.settings),
- style = typo().titleMedium,
- )
+ if (isSearchActive) {
+ TextField(
+ value = searchQuery,
+ onValueChange = onSearchQueryChange,
+ placeholder = {
+ Text(
+ text = stringResource(Res.string.search_settings),
+ style = typo().bodyMedium,
+ )
+ },
+ singleLine = true,
+ textStyle = typo().bodyMedium,
+ colors =
+ androidx.compose.material3.TextFieldDefaults.colors(
+ focusedContainerColor = Color.Transparent,
+ unfocusedContainerColor = Color.Transparent,
+ focusedIndicatorColor = Color.Transparent,
+ unfocusedIndicatorColor = Color.Transparent,
+ ),
+ modifier = Modifier.fillMaxWidth(),
+ )
+ } else {
+ Text(
+ text = stringResource(Res.string.settings),
+ style = typo().titleMedium,
+ )
+ }
},
navigationIcon = {
Box(Modifier.padding(horizontal = 5.dp)) {
@@ -3552,7 +3787,23 @@ private fun SettingTopBar(
true,
tint = MaterialTheme.colorScheme.onSurface,
) {
- onBack()
+ if (isSearchActive) {
+ onToggleSearch()
+ } else {
+ onBack()
+ }
+ }
+ }
+ },
+ actions = {
+ Box(Modifier.padding(horizontal = 5.dp)) {
+ RippleIconButton(
+ if (isSearchActive) SimpIcons.Close else SimpIcons.Search,
+ Modifier.size(32.dp),
+ true,
+ tint = MaterialTheme.colorScheme.onSurface,
+ ) {
+ onToggleSearch()
}
}
},
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/FullscreenPlayer.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/FullscreenPlayer.kt
index 1ad3f4e8e3..70e6d1df44 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/FullscreenPlayer.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/FullscreenPlayer.kt
@@ -96,6 +96,7 @@ import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.koinInject
import simpmusic.composeapp.generated.resources.Res
+import simpmusic.composeapp.generated.resources.generate_subtitles
import simpmusic.composeapp.generated.resources.five_seconds
@OptIn(ExperimentalMaterial3Api::class)
@@ -700,7 +701,13 @@ fun FullscreenPlayer(
CircleShape,
),
onClick = {
- shouldShowSubtitle = !shouldShowSubtitle
+ if (nowPlayingState.lyricsData == null && !shouldShowSubtitle) {
+ // If subtitles/lyrics are absent, trigger generating/fetching subtitles
+ sharedViewModel.fetchOrGenerateSubtitles()
+ shouldShowSubtitle = true
+ } else {
+ shouldShowSubtitle = !shouldShowSubtitle
+ }
},
) {
Crossfade(shouldShowSubtitle) {
@@ -708,7 +715,7 @@ fun FullscreenPlayer(
Icon(
imageVector = SimpIcons.SubtitlesOff,
tint = Color.White,
- contentDescription = "",
+ contentDescription = stringResource(Res.string.generate_subtitles),
modifier =
Modifier
.size(24.dp),
@@ -717,7 +724,7 @@ fun FullscreenPlayer(
Icon(
imageVector = SimpIcons.Subtitles,
tint = Color.White,
- contentDescription = "",
+ contentDescription = stringResource(Res.string.generate_subtitles),
modifier =
Modifier
.size(24.dp),
@@ -776,6 +783,11 @@ fun FullscreenPlayer(
} else {
null
},
+ onTranslateLyrics =
+ if (nowPlayingState.lyricsData != null) {
+ { sharedViewModel.translateCurrentLyrics() }
+ } else null,
+ onGenerateSubtitles = { sharedViewModel.fetchOrGenerateSubtitles() },
)
}
addLyricsFor?.let { (videoId, title, artist) ->
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/NowPlayingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/NowPlayingScreen.kt
index 9a39bee9d3..fdf2ba5373 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/NowPlayingScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/NowPlayingScreen.kt
@@ -720,6 +720,7 @@ fun NowPlayingScreenContent(
},
onShowFullscreenLyrics = { showFullscreenLyrics = true },
onShowVoteDialog = { showVoteDialog = true },
+ onTranslateLyrics = { sharedViewModel.translateCurrentLyrics() },
onLyricsOffsetChange = { sharedViewModel.setLyricsOffsetMs(it) },
onEnterFullscreenVideo = {
onDismiss()
@@ -848,6 +849,11 @@ fun NowPlayingScreenContent(
?.let { song ->
{ addLyricsFor = arrayListOf(song.videoId, song.title, song.artistName?.joinToString(", ").orEmpty()) }
},
+ onTranslateLyrics =
+ if (screenDataState.lyricsData != null) {
+ { sharedViewModel.translateCurrentLyrics() }
+ } else null,
+ onGenerateSubtitles = { sharedViewModel.fetchOrGenerateSubtitles() },
youTubeDislike =
when {
!isUserLoggedIn -> null
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentState.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentState.kt
index b081d726ce..aa55cb8b5e 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentState.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentState.kt
@@ -179,6 +179,7 @@ class NowPlayingContentActions(
val onWriteComment: (draft: String) -> Unit,
val onShowFullscreenLyrics: () -> Unit,
val onShowVoteDialog: () -> Unit,
+ val onTranslateLyrics: () -> Unit = {},
/** Writes the lyrics timing offset — the same value Settings › Lyrics edits. */
val onLyricsOffsetChange: (Int) -> Unit,
val onEnterFullscreenVideo: () -> Unit,
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricsView.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricsView.kt
index f06aec7422..4276bb6ba8 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricsView.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricsView.kt
@@ -58,6 +58,7 @@ import com.maxrave.simpmusic.ui.icon.Share
import com.maxrave.simpmusic.ui.icon.AvTimer
import com.maxrave.simpmusic.ui.icon.SimpIcons
import com.maxrave.simpmusic.ui.icon.ThumbsUpDown
+import com.maxrave.simpmusic.ui.icon.Translate
import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentActions
import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentState
import com.maxrave.simpmusic.ui.screen.player.content.canVote
@@ -297,6 +298,8 @@ internal fun AppleMusicLyricsView(
if (lyricsData.canVote()) {
AppleMusicFloatingCircleButton(icon = SimpIcons.ThumbsUpDown, onClick = { actions.onShowVoteDialog() })
}
+ // Translate lyrics button
+ AppleMusicFloatingCircleButton(icon = SimpIcons.Translate, onClick = { actions.onTranslateLyrics() })
AppleMusicFloatingCircleButton(icon = SimpIcons.Share, onClick = { showShareSheet = true })
AppleMusicFloatingCircleButton(icon = SimpIcons.OpenInFull, onClick = { actions.onShowFullscreenLyrics() })
}
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/AppLinks.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/AppLinks.kt
index 09db55f548..3abfc632d0 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/AppLinks.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/AppLinks.kt
@@ -7,7 +7,11 @@ import com.maxrave.simpmusic.getPlatform
// Every path the deep-link router in App.kt opens; anything else gets its "link not supported" toast.
// A path added there must be added here too, or no launch banner can point at it.
-private val APP_LINK_PATHS = setOf("notification", "watch", "playlist", "channel", "c", "album", "library", "analytics", "taste", "recognize")
+private val APP_LINK_PATHS = setOf(
+ "notification", "watch", "playlist", "channel", "c", "album", "library", "analytics", "taste", "recognize",
+ "play", "recommendations", "recommandations", "downloaded", "offline", "horsligne", "favorites", "favoris",
+ "cached", "pause", "resume", "next", "previous", "action"
+)
/**
* Whether the screen a `simpmusic://` link opens exists for this user right now. Analytics, the
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/LyricsTranslator.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/LyricsTranslator.kt
new file mode 100644
index 0000000000..c19a72f2c3
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/LyricsTranslator.kt
@@ -0,0 +1,117 @@
+package com.maxrave.simpmusic.utils
+
+import com.maxrave.domain.data.model.metadata.Line
+import com.maxrave.domain.data.model.metadata.Lyrics
+import com.maxrave.logger.Logger
+import io.ktor.client.HttpClient
+import io.ktor.client.engine.cio.CIO
+import io.ktor.client.request.forms.submitForm
+import io.ktor.client.request.get
+import io.ktor.client.request.header
+import io.ktor.client.statement.bodyAsText
+import io.ktor.http.Parameters
+import io.ktor.http.encodeURLParameter
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+
+object LyricsTranslator {
+ private const val TAG = "LyricsTranslator"
+ private val client = HttpClient(CIO)
+ private val json = Json { ignoreUnknownKeys = true }
+
+ suspend fun translateLyrics(
+ lyrics: Lyrics,
+ targetLanguage: String,
+ ): Result = runCatching {
+ val originalLines = lyrics.lines.orEmpty()
+ if (originalLines.isEmpty()) {
+ throw IllegalArgumentException("Empty lyrics")
+ }
+
+ val nonBlankLines = originalLines.mapIndexedNotNull { index, line ->
+ val w = line.words.trim()
+ if (w.isNotEmpty() && w != "♫") index to w else null
+ }
+
+ if (nonBlankLines.isEmpty()) {
+ throw IllegalArgumentException("No translatable words")
+ }
+
+ val textToTranslate = nonBlankLines.joinToString("\n") { it.second }
+
+ // Try Google Translate public client with POST (avoids URL length limits & 403 blocks)
+ val translatedText = translateWithGoogle(textToTranslate, targetLanguage)
+ ?: translateWithMyMemory(textToTranslate, targetLanguage)
+ ?: throw IllegalStateException("All translation providers failed")
+
+ val translatedLinesList = translatedText.lines()
+ val indexToTranslatedWord = mutableMapOf()
+ nonBlankLines.forEachIndexed { i, (origIndex, _) ->
+ val trans = translatedLinesList.getOrNull(i)?.trim()
+ if (!trans.isNullOrEmpty()) {
+ indexToTranslatedWord[origIndex] = trans
+ }
+ }
+
+ val resultLines = originalLines.mapIndexed { index, origLine ->
+ val translatedWord = indexToTranslatedWord[index] ?: origLine.words
+ Line(
+ endTimeMs = origLine.endTimeMs,
+ startTimeMs = origLine.startTimeMs,
+ words = translatedWord,
+ syllables = emptyList(),
+ )
+ }
+
+ Lyrics(
+ error = false,
+ lines = ArrayList(resultLines),
+ syncType = lyrics.syncType,
+ )
+ }
+
+ private suspend fun translateWithGoogle(text: String, targetLanguage: String): String? {
+ return runCatching {
+ val response = client.submitForm(
+ url = "https://translate.googleapis.com/translate_a/single?client=gtx&dt=t",
+ formParameters = Parameters.build {
+ append("sl", "auto")
+ append("tl", targetLanguage)
+ append("q", text)
+ },
+ ) {
+ header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
+ }.bodyAsText()
+
+ val jsonElement = json.parseToJsonElement(response)
+ val parts = jsonElement.jsonArray[0].jsonArray
+ val sb = StringBuilder()
+ for (p in parts) {
+ val partStr = p.jsonArray.getOrNull(0)?.jsonPrimitive?.content
+ if (partStr != null) {
+ sb.append(partStr)
+ }
+ }
+ sb.toString()
+ }.onFailure {
+ Logger.w(TAG, "Google translate failed: ${it.message}")
+ }.getOrNull()
+ }
+
+ private suspend fun translateWithMyMemory(text: String, targetLanguage: String): String? {
+ return runCatching {
+ val encoded = text.encodeURLParameter()
+ val url = "https://api.mymemory.translated.net/get?q=$encoded&langpair=autodetect|$targetLanguage"
+ val response = client.get(url) {
+ header("User-Agent", "SimpMusic/2.5.0")
+ }.bodyAsText()
+
+ val jsonElement = json.parseToJsonElement(response)
+ jsonElement.jsonObject["responseData"]?.jsonObject?.get("translatedText")?.jsonPrimitive?.content
+ }.onFailure {
+ Logger.w(TAG, "MyMemory translate failed: ${it.message}")
+ }.getOrNull()
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt
index 4dd5884e5c..d7b0d620f4 100644
--- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt
@@ -38,6 +38,7 @@ import com.maxrave.domain.extension.isSong
import com.maxrave.domain.extension.isVideo
import com.maxrave.domain.extension.toGenericMediaItem
import com.maxrave.domain.manager.DataStoreManager
+import com.maxrave.domain.data.model.ai.AiMusicAction
import com.maxrave.domain.data.model.lyrics.RomanizationLanguage
import com.maxrave.domain.manager.DataStoreManager.Values.FALSE
import com.maxrave.domain.manager.DataStoreManager.Values.TRUE
@@ -54,15 +55,18 @@ import com.maxrave.domain.mediaservice.handler.addToQueueBlock
import com.maxrave.domain.repository.AlbumRepository
import com.maxrave.domain.repository.CacheRepository
import com.maxrave.domain.repository.DiscordRepository
+import com.maxrave.domain.repository.HomeRepository
import com.maxrave.domain.repository.LocalPlaylistRepository
import com.maxrave.domain.repository.LyricsCanvasRepository
import com.maxrave.domain.repository.PlaylistRepository
+import com.maxrave.domain.repository.SearchRepository
import com.maxrave.domain.repository.SongRepository
import com.maxrave.domain.repository.StreamRepository
import com.maxrave.domain.repository.UpdateRepository
import com.maxrave.domain.utils.Resource
import com.maxrave.domain.utils.YouTubeLikeStatus
import com.maxrave.domain.utils.isEndlessQueueId
+import com.maxrave.domain.utils.toArrayListTrack
import com.maxrave.domain.utils.toListName
import com.maxrave.domain.utils.toLyrics
import com.maxrave.domain.utils.toLyricsEntity
@@ -117,6 +121,7 @@ import simpmusic.composeapp.generated.resources.added_local_playlist
import simpmusic.composeapp.generated.resources.added_to_queue
import simpmusic.composeapp.generated.resources.added_to_youtube_liked
import simpmusic.composeapp.generated.resources.disliked
+import simpmusic.composeapp.generated.resources.downloaded
import simpmusic.composeapp.generated.resources.error
import simpmusic.composeapp.generated.resources.discord_login_failed
import simpmusic.composeapp.generated.resources.lastfm_login_failed
@@ -126,6 +131,10 @@ import simpmusic.composeapp.generated.resources.removed_from_youtube_liked
import simpmusic.composeapp.generated.resources.shared
import simpmusic.composeapp.generated.resources.updated
import simpmusic.composeapp.generated.resources.vote_submitted
+import simpmusic.composeapp.generated.resources.generating_subtitles
+import simpmusic.composeapp.generated.resources.translating_lyrics
+import simpmusic.composeapp.generated.resources.translation_failed
+import androidx.compose.ui.text.intl.Locale
import java.io.FileOutputStream
import kotlin.math.abs
import kotlin.reflect.KClass
@@ -155,6 +164,8 @@ class SharedViewModel(
var showedUpdateDialog: Boolean = false
private val appIdentity: AppIdentity by inject()
+ private val homeRepository: HomeRepository by inject()
+ private val searchRepository: SearchRepository by inject()
private val _isCheckingUpdate = MutableStateFlow(false)
val isCheckingUpdate: StateFlow = _isCheckingUpdate
@@ -1877,73 +1888,163 @@ class SharedViewModel(
}
}
- private suspend fun getAITranslationLyrics(
+ suspend fun getAITranslationLyrics(
videoId: String,
lyrics: Lyrics,
+ force: Boolean = false,
) {
- Logger.d(tag, "Get AI Translation Lyrics for $videoId")
- if (dataStoreManager.useAITranslation.first() == TRUE &&
- dataStoreManager.aiApiKey.first().isNotEmpty() &&
- dataStoreManager.enableTranslateLyric.first() == FALSE
- ) {
- val savedTranslatedLyrics =
- lyricsCanvasRepository
- .getSavedTranslatedLyrics(
- videoId,
- dataStoreManager.translationLanguage.first(),
- ).firstOrNull()
- if (savedTranslatedLyrics != null) {
- Logger.d(tag, "Get Saved Translated Lyrics")
- updateLyrics(
+ Logger.d(tag, "Get AI Translation Lyrics for $videoId (force=$force)")
+ val targetLang = dataStoreManager.translationLanguage.first().ifEmpty {
+ Locale.current.language
+ }
+
+ val savedTranslatedLyrics =
+ lyricsCanvasRepository
+ .getSavedTranslatedLyrics(
videoId,
- 0,
- savedTranslatedLyrics.toLyrics(),
- true,
- LyricsProvider.AI,
- )
+ targetLang,
+ ).firstOrNull()
+ if (savedTranslatedLyrics != null && !force) {
+ Logger.d(tag, "Get Saved Translated Lyrics")
+ updateLyrics(
+ videoId,
+ 0,
+ savedTranslatedLyrics.toLyrics(),
+ true,
+ LyricsProvider.AI,
+ )
+ return
+ }
+
+ // Convert RICH_SYNCED to LINE_SYNCED before sending to translation
+ val lyricsForAi =
+ if (lyrics.syncType == "RICH_SYNCED") {
+ lyrics.toSyncedLyrics()
} else {
- // Convert RICH_SYNCED to LINE_SYNCED before sending to AI
- // AI should only work with line-level or plain lyrics
- val lyricsForAi =
- if (lyrics.syncType == "RICH_SYNCED") {
- lyrics.toSyncedLyrics()
+ lyrics
+ }
+
+ // 1. If AI API key is configured and enabled, try AI first
+ val hasAiKey = dataStoreManager.aiApiKey.first().isNotEmpty()
+ if (hasAiKey) {
+ var aiSuccess = false
+ lyricsCanvasRepository
+ .getAITranslationLyrics(
+ lyricsForAi,
+ targetLang,
+ ).cancellable()
+ .collectLatest {
+ val data = it.data
+ if (it is Resource.Success && data != null) {
+ Logger.d(tag, "Get AI Translate Lyrics Success")
+ aiSuccess = true
+ lyricsCanvasRepository.insertTranslatedLyrics(
+ TranslatedLyricsEntity(
+ videoId = videoId,
+ language = targetLang,
+ error = false,
+ lines = data.lines,
+ syncType = data.syncType,
+ ),
+ )
+ updateLyrics(
+ videoId,
+ 0,
+ data,
+ true,
+ LyricsProvider.AI,
+ )
} else {
- lyrics
+ Logger.w(tag, "Get AI Translate Lyrics Error: ${it.message}")
}
- lyricsCanvasRepository
- .getAITranslationLyrics(
- lyricsForAi,
- dataStoreManager.translationLanguage.first(),
- ).cancellable()
- .collectLatest {
- val data = it.data
- when (it) {
- is Resource.Success if (data != null) -> {
- Logger.d(tag, "Get AI Translate Lyrics Success")
- lyricsCanvasRepository.insertTranslatedLyrics(
- TranslatedLyricsEntity(
- videoId = videoId,
- language = dataStoreManager.translationLanguage.first(),
- error = false,
- lines = data.lines,
- syncType = data.syncType,
- ),
- )
- updateLyrics(
- videoId,
- 0,
- data,
- true,
- LyricsProvider.AI,
- )
- }
+ }
+ if (aiSuccess) return
+ }
- else -> {
- Logger.w(tag, "Get AI Translate Lyrics Error: ${it.message}")
- }
+ // 2. Direct online translation fallback (Google Translate / MyMemory)
+ val onlineResult = com.maxrave.simpmusic.utils.LyricsTranslator.translateLyrics(lyricsForAi, targetLang)
+ onlineResult.onSuccess { translatedLyrics ->
+ Logger.d(tag, "Online Lyrics Translation Success")
+ lyricsCanvasRepository.insertTranslatedLyrics(
+ TranslatedLyricsEntity(
+ videoId = videoId,
+ language = targetLang,
+ error = false,
+ lines = translatedLyrics.lines,
+ syncType = translatedLyrics.syncType,
+ ),
+ )
+ updateLyrics(
+ videoId,
+ 0,
+ translatedLyrics,
+ true,
+ LyricsProvider.AI,
+ )
+ }.onFailure { err ->
+ Logger.e(tag, "Online Lyrics Translation Error: ${err.message}")
+ if (force) {
+ makeToast(getString(Res.string.translation_failed))
+ }
+ }
+ }
+
+ /**
+ * Request on-demand lyrics translation for current song.
+ */
+ fun translateCurrentLyrics() {
+ viewModelScope.launch {
+ val song = nowPlayingState.value?.songEntity ?: return@launch
+ val lyricsData = nowPlayingScreenData.value.lyricsData?.lyrics ?: return@launch
+ makeToast(getString(Res.string.translating_lyrics))
+ getAITranslationLyrics(song.videoId, lyricsData, force = true)
+ }
+ }
+
+ /**
+ * Request on-demand subtitles / captions for current song.
+ */
+ fun fetchOrGenerateSubtitles() {
+ viewModelScope.launch {
+ val song = nowPlayingState.value?.songEntity ?: return@launch
+ val duration = (timeline.value.total / 1000).toInt()
+ val artist = song.artistName?.firstOrNull() ?: ""
+ makeToast(getString(Res.string.generating_subtitles))
+ lyricsCanvasRepository
+ .getYouTubeCaption(dataStoreManager.youtubeSubtitleLanguage.first(), song.videoId)
+ .cancellable()
+ .collect { response ->
+ val data = response.data
+ if (response is Resource.Success && data != null) {
+ val lyrics = data.first
+ val translatedLyrics = data.second
+ insertLyrics(lyrics.toLyricsEntity(song.videoId))
+ updateLyrics(
+ song.videoId,
+ duration,
+ lyrics,
+ false,
+ LyricsProvider.YOUTUBE,
+ )
+ if (translatedLyrics != null) {
+ updateLyrics(
+ song.videoId,
+ duration,
+ translatedLyrics,
+ true,
+ LyricsProvider.YOUTUBE,
+ )
+ } else {
+ getAITranslationLyrics(
+ song.videoId,
+ lyrics,
+ )
}
+ } else {
+ // YouTube captions not available: fallback to full lyrics cascade (SimpMusic, LRCLIB, BetterLyrics, Spotify)
+ getSimpMusicLyrics(song.videoId, song, artist, duration)
}
- }
+ }
}
}
@@ -2350,6 +2451,201 @@ class SharedViewModel(
fun isUserLoggedInFlow(): Flow = dataStoreManager.cookie.map { it.isNotEmpty() }
fun isCombineFavoriteAndYTLiked(): Boolean = runBlocking { dataStoreManager.combineLocalAndYouTubeLiked.first() == TRUE }
+
+ // --- Gemini / Voice Assistant Actions ---
+
+ fun playRecommendations() {
+ viewModelScope.launch {
+ try {
+ showLoadingDialog()
+ val homeData = homeRepository.getHomeData(viewString = "views", songString = "songs").firstOrNull()
+ val shelves = (homeData as? Resource.Success)?.data?.second.orEmpty()
+ val tracks = shelves.firstOrNull { shelf ->
+ shelf.contents.any { it?.videoId != null }
+ }?.contents?.mapNotNull { it?.toTrack() }
+
+ if (!tracks.isNullOrEmpty()) {
+ val trackList = ArrayList(tracks)
+ val first = trackList.first()
+ setQueueData(
+ QueueData.Data(
+ listTracks = trackList,
+ firstPlayedTrack = first,
+ playlistId = null,
+ playlistName = "Recommandations",
+ playlistType = PlaylistType.RADIO,
+ continuation = null,
+ ),
+ )
+ loadMediaItemFromTrack(first, Config.SONG_CLICK, 0)
+ } else {
+ playFavorites()
+ }
+ } catch (e: Exception) {
+ Logger.e("SharedViewModel", "Error playing recommendations: ${e.message}")
+ playFavorites()
+ } finally {
+ hideLoadingDialog()
+ }
+ }
+ }
+
+ fun playDownloaded() {
+ viewModelScope.launch {
+ try {
+ showLoadingDialog()
+ val downloadedSongs = songRepository.getDownloadedSongs().firstOrNull().orEmpty()
+ if (downloadedSongs.isNotEmpty()) {
+ val tracks = downloadedSongs.toArrayListTrack()
+ val first = tracks.first()
+ setQueueData(
+ QueueData.Data(
+ listTracks = tracks,
+ firstPlayedTrack = first,
+ playlistId = null,
+ playlistName = getString(Res.string.downloaded),
+ playlistType = PlaylistType.LOCAL_PLAYLIST,
+ continuation = null,
+ ),
+ )
+ loadMediaItemFromTrack(first, Config.PLAYLIST_CLICK, 0)
+ } else {
+ makeToast(getString(Res.string.error))
+ }
+ } catch (e: Exception) {
+ Logger.e("SharedViewModel", "Error playing downloaded: ${e.message}")
+ } finally {
+ hideLoadingDialog()
+ }
+ }
+ }
+
+ fun playOffline() = playDownloaded()
+
+ fun playFavorites() {
+ viewModelScope.launch {
+ try {
+ showLoadingDialog()
+ val likedSongs = songRepository.getLikedSongs().firstOrNull().orEmpty()
+ if (likedSongs.isNotEmpty()) {
+ val tracks = likedSongs.toArrayListTrack()
+ val first = tracks.first()
+ setQueueData(
+ QueueData.Data(
+ listTracks = tracks,
+ firstPlayedTrack = first,
+ playlistId = null,
+ playlistName = "Favoris",
+ playlistType = PlaylistType.LOCAL_PLAYLIST,
+ continuation = null,
+ ),
+ )
+ loadMediaItemFromTrack(first, Config.PLAYLIST_CLICK, 0)
+ } else {
+ makeToast(getString(Res.string.error))
+ }
+ } catch (e: Exception) {
+ Logger.e("SharedViewModel", "Error playing favorites: ${e.message}")
+ } finally {
+ hideLoadingDialog()
+ }
+ }
+ }
+
+ fun playCached() {
+ viewModelScope.launch {
+ try {
+ showLoadingDialog()
+ val cachedKeys = cacheRepository.getAllCacheKeys(Config.PLAYER_CACHE)
+ val songs = if (cachedKeys.isNotEmpty()) {
+ songRepository.getSongsByListVideoId(cachedKeys).firstOrNull().orEmpty()
+ } else emptyList()
+
+ if (songs.isNotEmpty()) {
+ val tracks = songs.toArrayListTrack()
+ val first = tracks.first()
+ setQueueData(
+ QueueData.Data(
+ listTracks = tracks,
+ firstPlayedTrack = first,
+ playlistId = null,
+ playlistName = "Cache",
+ playlistType = PlaylistType.LOCAL_PLAYLIST,
+ continuation = null,
+ ),
+ )
+ loadMediaItemFromTrack(first, Config.PLAYLIST_CLICK, 0)
+ } else {
+ makeToast(getString(Res.string.error))
+ }
+ } catch (e: Exception) {
+ Logger.e("SharedViewModel", "Error playing cached: ${e.message}")
+ } finally {
+ hideLoadingDialog()
+ }
+ }
+ }
+
+ fun searchAndPlay(query: String) {
+ viewModelScope.launch {
+ try {
+ showLoadingDialog()
+ val result = searchRepository.getSearchDataSong(query).firstOrNull { it is Resource.Success }
+ val songs = (result as? Resource.Success)?.data.orEmpty()
+ if (songs.isNotEmpty()) {
+ val tracks = songs.map { it.toTrack() }.toCollection(ArrayList())
+ val first = tracks.first()
+ setQueueData(
+ QueueData.Data(
+ listTracks = tracks,
+ firstPlayedTrack = first,
+ playlistId = "RDAMVM${first.videoId}",
+ playlistName = query,
+ playlistType = PlaylistType.RADIO,
+ continuation = null,
+ ),
+ )
+ loadMediaItemFromTrack(first, Config.SONG_CLICK, 0)
+ } else {
+ makeToast(getString(Res.string.error))
+ }
+ } catch (e: Exception) {
+ Logger.e("SharedViewModel", "Error search and play: ${e.message}")
+ } finally {
+ hideLoadingDialog()
+ }
+ }
+ }
+
+ fun pausePlayback() {
+ mediaPlayerHandler.player.pause()
+ }
+
+ fun resumePlayback() {
+ mediaPlayerHandler.player.play()
+ }
+
+ fun skipNextTrack() {
+ mediaPlayerHandler.player.seekToNext()
+ }
+
+ fun skipPreviousTrack() {
+ mediaPlayerHandler.player.seekToPrevious()
+ }
+
+ fun executeAiAction(action: AiMusicAction) {
+ when (action) {
+ is AiMusicAction.PlayRecommendations -> playRecommendations()
+ is AiMusicAction.PlayDownloaded, is AiMusicAction.PlayOffline -> playDownloaded()
+ is AiMusicAction.PlayFavorites -> playFavorites()
+ is AiMusicAction.PlayCached -> playCached()
+ is AiMusicAction.SearchAndPlay -> searchAndPlay(action.query)
+ is AiMusicAction.Pause -> pausePlayback()
+ is AiMusicAction.Resume -> resumePlayback()
+ is AiMusicAction.Next -> skipNextTrack()
+ is AiMusicAction.Previous -> skipPreviousTrack()
+ }
+ }
}
sealed class UIEvent {
diff --git a/core b/core
index 8413a257cb..aa5008cc09 160000
--- a/core
+++ b/core
@@ -1 +1 @@
-Subproject commit 8413a257cbe45d102a9f101f2760e35b549e4d9e
+Subproject commit aa5008cc092407c754fe4153e2c4aa34f834a43e