feat: Add Soundtracks tab and music player (#2389)

This commit is contained in:
FX1922 authored and GitHub committed 2026-11-13 08:49:48 -05:00
1 parent 33dbd8755f
commit d33f4b4896
78 files changed
+5618 -64

No files matched your search

@@ -70,6 +70,7 @@ import com.droiddeck.launcher.frontend.AddedGameArt
import com.droiddeck.launcher.frontend.AddedGameEdits
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.LogoPosition
import com.droiddeck.launcher.frontend.SoundtrackCollectionArt
import com.droiddeck.launcher.frontend.SteamGameArt
import com.droiddeck.launcher.frontend.SteamGridDb
import com.droiddeck.launcher.frontend.SteamLaunchOptions
@@ -179,6 +180,16 @@ internal class ArtTarget(
{ c, value -> AddedGameEdits.setLogoPosition(c, game.folder.path, value) },
)
fun ofCollection(id: Int, name: String, root: java.io.File? = null) = ArtTarget(
name,
{ c, _ -> SoundtrackCollectionArt.source(c, id) },
{ c, _ -> AddedGameArt.Choices(SoundtrackCollectionArt.options(c, id, root), SteamGridDb.Status.OK) },
{ c, _, option -> SoundtrackCollectionArt.choose(c, id, option) },
{ c, _ -> SoundtrackCollectionArt.reset(c, id) },
{ _ -> null },
{ _, _ -> false },
)
fun of(game: com.droiddeck.launcher.frontend.Library.SteamGame) = ArtTarget(
game.name,
{ c, slot -> SteamGameArt.chosenSource(c, game.appId, slot).second },
@@ -199,6 +210,12 @@ internal fun SteamGameArtEditor(
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged)
}
@Composable
internal fun CollectionArtEditor(id: Int, name: String, root: java.io.File? = null, onClose: () -> Unit, onChanged: () -> Unit) {
val target = remember(id, root) { ArtTarget.ofCollection(id, name, root) }
ArtOnlyEditor(name, target, id, { SoundtrackCollectionArt.describe(it, id, root) }, onClose, onChanged, listOf(AddedGameArt.Slot.COVER))
}
@Composable
internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Unit, onChanged: () -> Unit) {
val app = LocalContext.current.applicationContext
@@ -212,7 +229,7 @@ internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Uni
@Composable
private fun ArtOnlyEditor(
name: String, target: ArtTarget?, refresh: Any?, describe: (Context) -> List<AddedGameArt.SlotState>,
onClose: () -> Unit, onChanged: () -> Unit,
onClose: () -> Unit, onChanged: () -> Unit, slots: List<AddedGameArt.Slot> = AddedGameArt.Slot.values().toList(),
) {
val app = LocalContext.current.applicationContext
val shown = rememberShown(onClose)
@@ -233,7 +250,7 @@ private fun ArtOnlyEditor(
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
) {
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp))
for (slot in AddedGameArt.Slot.values()) key(slot) {
for (slot in slots) key(slot) {
val state = arts.firstOrNull { it.slot == slot }
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER) first else null, onClick = { if (target != null) artSlot = slot }) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
@@ -242,7 +259,7 @@ private fun ArtOnlyEditor(
}
}
}
PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
if (AddedGameArt.Slot.LOGO in slots) PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
}
}
val chosen = target ?: return
@@ -115,6 +115,7 @@ internal fun Pane(
s.pageKey != null && page != null -> null
selected.startsWith("app:") -> s.steamGames.firstOrNull { "app:${it.appId}" == selected }?.art
selected == "games" -> s.steamGames.maxByOrNull { it.lastPlayed }?.art
selected.startsWith("sound:") -> s.soundtracks.firstOrNull { "sound:${it.appId}" == selected }?.let { it.hero ?: it.art }
selected.startsWith("rom:") -> romFor(s, selected)?.second?.art
else -> null
}
@@ -124,10 +125,12 @@ internal fun Pane(
val origins = remember { HashMap<String, Origin>() }
val paneAt = remember { arrayOf(Offset.Zero) }
val livePage by rememberUpdatedState(s.pageKey)
val railContent = if (selected.startsWith("app:")) "games" else selected
val railContent = if (selected.startsWith("app:")) "games" else if (selected.startsWith("sound:")) "soundtracks" else selected
val target = if (page != null && s.pageKey != null) s.pageKey else railContent
val gameShown = remember { arrayOf("games") }
if (selected == "games" || selected.startsWith("app:")) gameShown[0] = selected
val soundShown = remember { arrayOf("soundtracks") }
if (selected == "soundtracks" || selected.startsWith("sound:")) soundShown[0] = selected
val before = remember { arrayOf(target) }
if (page != null && s.pageKey != null) {
pages[s.pageKey] = page
@@ -171,7 +174,7 @@ internal fun Pane(
label = "pane",
) { key ->
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
?: { Content(s, if (key == "games") gameShown[0] else if (key == "soundtracks") soundShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
val hopSink by androidx.compose.animation.core.animateFloatAsState(
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
)
@@ -262,7 +265,7 @@ private fun Content(
StoresPage(s, a, modifier)
return
}
if (selected == "games" || selected.startsWith("app:")) {
if (selected == "games" || selected.startsWith("app:") || selected == "soundtracks" || selected.startsWith("sound:")) {
LibraryPage(s, a, selected, onSelect, modifier)
return
}
@@ -126,6 +126,7 @@ internal fun BottomBar(
internal fun navigationKeys(s: FrontEndState) = buildList {
add("steam"); add("games")
if (s.soundtracksEnabled) add("soundtracks")
if (s.gameStoresEnabled) add("stores")
add("desktop")
if (com.droiddeck.launcher.agent.AgentTab.visible) add("agent")
@@ -200,6 +201,7 @@ internal fun SideRail(
internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
"steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports
"games" -> R.string.rail_games to Icons.Outlined.VideoLibrary
"soundtracks" -> R.string.rail_music to SoundtrackIcon
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
"components" -> R.string.rail_components to Icons.Outlined.Layers
@@ -181,6 +181,10 @@ class FrontEndState(
val lowStorageWarning: Boolean = true,
val launcherIcon: String = com.droiddeck.launcher.LauncherIcon.DARK,
val gameStoresEnabled: Boolean = true,
val soundtracksEnabled: Boolean = true,
val soundtracksIngame: Boolean = false,
val soundtracks: List<Library.SteamGame> = emptyList(),
val soundtracksLoaded: Boolean = true,
val gameStoresSpeedTier: String = "fast",
val navigate: String? = null,
val addedGamesArt: Boolean = true,
@@ -285,6 +289,11 @@ class FrontEndActions(
val onDownloadPrefix: (String) -> Unit = {},
val onDownloadProxy: (String) -> Unit = {},
val onGameStoresEnabled: (Boolean) -> Unit = {},
val onSoundtracksEnabled: (Boolean) -> Unit = {},
val onSoundtracksIngame: (Boolean) -> Unit = {},
val onSoundtrackAdded: (java.io.File) -> Unit = {},
val onSoundtracksChanged: () -> Unit = {},
val onSoundtrackRemoved: (Library.SteamGame) -> Unit = {},
val onGameStoresSpeedTier: (String) -> Unit = {},
val onNavigated: () -> Unit = {},
val onStoresShowMature: (Boolean) -> Unit = {},
@@ -567,8 +576,14 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop"
}
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
LaunchedEffect(s.steamGames.isEmpty()) {
if (s.steamGames.isEmpty() && selected.startsWith("app:") && GameRef.parse(selected).appId != null) selected = "games"
LaunchedEffect(s.soundtracksEnabled) {
if (!s.soundtracksEnabled && (selected == "soundtracks" || selected.startsWith("sound:"))) selected = "games"
}
LaunchedEffect(s.steamGames.isEmpty(), s.soundtracks, s.soundtracksLoaded) {
if (s.steamGames.isEmpty() && selected.startsWith("app:")) {
val id = GameRef.parse(selected).appId
if (id != null && s.soundtracks.none { it.appId == id } && s.soundtracksLoaded) selected = "games"
}
}
remember { Motion.refresh(ctx); true }
@@ -577,6 +592,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
s.pageKey == "performance" -> "steam"
s.pageKey == "controller-mapping" -> "setup"
selected.startsWith("app:") -> "games"
selected.startsWith("sound:") -> "soundtracks"
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop"
else -> s.pageKey ?: selected
}
@@ -688,7 +704,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val r = Hops.restore ?: return@LaunchedEffect
if (r.surface == HOP_SURFACE_SHEET) return@LaunchedEffect
Hops.restore = null
if (r.rail != selected && !(r.rail == "games" && selected.startsWith("app:"))) selected = r.rail
if (r.rail != selected && !(r.rail == "games" && selected.startsWith("app:")) && !(r.rail == "soundtracks" && selected.startsWith("sound:"))) selected = r.rail
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
frontFocus.last = r.control
@@ -457,6 +457,8 @@ internal fun SetupPanel(
ToggleRow(host, "rail-labels", stringResource(R.string.setup_rail_labels), stringResource(R.string.setup_rail_labels_hint), RailLabels.shown) { RailLabels.set(railContext, it) }
LanguageRow(host, s.language, a.onLanguage)
ToggleRow(host, "show-stores", stringResource(R.string.setup_stores), null, s.gameStoresEnabled, onChange = a.onGameStoresEnabled)
ToggleRow(host, "show-soundtracks", stringResource(R.string.setup_soundtracks), null, s.soundtracksEnabled, onChange = a.onSoundtracksEnabled)
if (s.soundtracksEnabled) ToggleRow(host, "soundtracks-ingame", stringResource(R.string.setup_soundtracks_ingame), stringResource(R.string.setup_soundtracks_ingame_hint), s.soundtracksIngame, onChange = a.onSoundtracksIngame)
}
}
val device: @Composable () -> Unit = {
@@ -148,7 +148,7 @@ internal fun GameDetail(
val narrow = LocalNarrowPane.current
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
val ref = remember(key) { GameRef.parse(key) }
val games = s.steamGames + rememberXboxCloudRows(s)
val games = s.steamGames + rememberXboxCloudRows(s) + if (s.soundtracksEnabled) emptyList() else s.soundtracks
val found = ref.game(games)
val known = remember(key) { arrayOfNulls<Pair<Store, String>>(1) }
val store = ref.store ?: Store.byId(found?.source) ?: known[0]?.first
@@ -280,7 +280,7 @@ internal fun GameDetail(
}
@Composable
private fun SourceBadge(source: String) {
internal fun SourceBadge(source: String) {
val c = sourceColours(source)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp),
@@ -574,13 +574,13 @@ private fun buyLabel(item: CatalogItem): String = when {
}
@Composable
private fun FileButtons(game: Library.SteamGame, a: FrontEndActions) {
internal fun FileButtons(game: Library.SteamGame, a: FrontEndActions) {
game.gameFiles?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_files), compact = true) { a.onBrowseFiles(dir) } }
game.protonPrefix?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_prefix), compact = true) { a.onBrowseFiles(dir) } }
}
@Composable
private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
internal fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
var open by remember(g.gameId) { mutableStateOf(false) }
Box {
SecondaryButton(stringResource(R.string.game_shortcut), compact = true) { open = !open }
@@ -593,7 +593,7 @@ private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
}
@Composable
private fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
internal fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
val ctx = LocalContext.current
val folder = g.gameFiles
return when {
@@ -607,7 +607,7 @@ private fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
}
@Composable
private fun EditArtButton(g: Library.SteamGame) {
internal fun EditArtButton(g: Library.SteamGame) {
val open = rememberEditArt(g) ?: return
IconAction(Icons.Outlined.Edit, stringResource(R.string.game_edit_art), "game:edit", onClick = open)
}
@@ -664,7 +664,7 @@ internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, l
}
@Composable
private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
internal fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id && installed?.sidecar?.id?.let(BattleNetInstall::product) == null) return
@@ -38,6 +38,7 @@ import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.draw.blur
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.painter.Painter
@@ -147,6 +148,7 @@ internal fun GameBackdrop(
fadeTop: Boolean,
modifier: Modifier = Modifier,
onArtPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit = {},
artBlur: androidx.compose.ui.unit.Dp = 0.dp,
content: @Composable () -> Unit,
) {
val ctx = LocalContext.current
@@ -178,13 +180,13 @@ internal fun GameBackdrop(
glass.fadeBottom(this, size)
},
)
if (art != null) ArtLayer(art, ambient ?: art, fadeTop, onArtPlaced)
if (art != null) ArtLayer(art, ambient ?: art, fadeTop, artBlur, onArtPlaced)
CompositionLocalProvider(LocalGlass provides glass) { content() }
}
}
@Composable
private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, onPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit) {
private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, blur: androidx.compose.ui.unit.Dp, onPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit) {
val colors = MaterialTheme.colorScheme
val light = colors.background.luminance() > 0.5f
val pale = ((rememberArtBrightness(sample) - 0.28f) / 0.5f).coerceIn(0f, 1f)
@@ -208,7 +210,7 @@ private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, onPlaced: (and
model = model, contentDescription = null, contentScale = ContentScale.Crop,
alignment = BiasAlignment(0.45f, -0.35f),
colorFilter = artFilter,
modifier = Modifier.matchParentSize(),
modifier = Modifier.matchParentSize().then(if (blur > 0.dp) Modifier.blur(blur) else Modifier),
)
Box(
Modifier.matchParentSize().drawBehind {
@@ -42,6 +42,7 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.FilterAlt
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.PlayArrow
@@ -61,6 +62,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.produceState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -92,6 +94,11 @@ import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.frontend.Soundtrack
import com.droiddeck.launcher.frontend.SoundtrackCollections
import com.droiddeck.launcher.frontend.SoundtrackIndex
import com.droiddeck.launcher.frontend.SoundtrackTracks
import com.droiddeck.launcher.playback.SoundtrackController
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
@@ -156,7 +163,7 @@ internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = e
internal const val LIBRARY_ALL = "all"
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet()): List<String> =
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED)
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED + Library.SOURCE_COLLECTION)
.filter { source -> source in always || entries.any { it.source == source } }
internal object LibraryDisplay {
@@ -215,14 +222,24 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
LaunchedEffect(Unit) { StoresState.refresh(ctx) }
remember { LibraryDisplay.load(ctx) }
val stores = s.gameStoresEnabled && !s.shortcutPicker
val soundMode = selected == "soundtracks" || selected.startsWith("sound:")
val stores = s.gameStoresEnabled && !s.shortcutPicker && !soundMode
val signedIn = Store.entries.filter { StoresState.isSignedIn(it) }
LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } }
val owned = if (stores) signedIn.associateWith { StoresState.library[it].orEmpty() } else emptyMap()
val installedStore = StoresState.installed.map { it.key }.toSet()
val syncing = if (stores) signedIn.mapNotNull { st -> StoresState.status[st]?.let { st to it } } else emptyList()
val cloudRows = rememberXboxCloudRows(s)
val all = remember(s.steamGames, cloudRows, owned, installedStore) { libraryEntries(s.steamGames + cloudRows, owned, installedStore) }
remember { SoundtrackCollections.load(ctx) }
val savedSnapshot = SoundtrackCollections.snapshot
val favoritesLabel = stringResource(R.string.soundtracks_favorites)
val all = remember(soundMode, s.steamGames, s.soundtracks, s.soundtracksEnabled, cloudRows, owned, installedStore, savedSnapshot, favoritesLabel) {
if (soundMode) s.soundtracks.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } +
(if (s.soundtracks.isEmpty() && savedSnapshot.favorites.isEmpty() && savedSnapshot.collections.isEmpty()) emptyList() else SoundtrackCollections.games(ctx, favoritesLabel))
.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) }
else libraryEntries(s.steamGames + cloudRows + if (s.soundtracksEnabled) emptyList() else s.soundtracks.filter { it.library != Library.ADDED }, owned, installedStore)
}
var addingSoundtrack by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) }
var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) }
var collectionShows by remember { mutableStateOf<Pair<String, Boolean>?>(null) }
@@ -240,7 +257,10 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
}
val itchSignedIn = owned.containsKey(Store.ITCH)
val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT)
val sources = librarySources(all, SessionPrefs.storesTabOrder(ctx), listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn }).toSet())
val sources = librarySources(
all, SessionPrefs.storesTabOrder(ctx),
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.SOURCE_COLLECTION.takeIf { soundMode }).toSet(),
)
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
val q = LibraryView.query.trim().lowercase()
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
@@ -265,6 +285,30 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
}
val listUninstalled = if (collectionId == null) showUninstalled else collectionShows?.takeIf { it.first == collectionId }?.second ?: true
val trackHits by produceState<List<SoundtrackIndex.Hit>>(emptyList(), soundMode, q, source, s.soundtracks) {
if (!soundMode || q.isEmpty()) {
value = emptyList()
return@produceState
}
kotlinx.coroutines.delay(150)
value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
SoundtrackIndex.build(ctx, s.soundtracks)
.filter { (source == LIBRARY_ALL || it.game.source == source) && SoundtrackTracks.matches(q, it.ref.title, it.ref.artist, it.ref.album) }
.distinctBy { it.ref.path }
.sortedWith(compareBy({ SoundtrackTracks.rank(q, it.ref.title) }, { it.ref.title.lowercase() }))
.take(100)
}
}
val shownHits = trackHits.filter { source == LIBRARY_ALL || it.game.source == source }
val hitScope = rememberCoroutineScope()
val playHit: (SoundtrackIndex.Hit) -> Unit = { hit ->
val dir = hit.game.gameFiles
if (dir != null) hitScope.launch {
val album = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { Soundtrack.load(ctx, dir, hit.game.art) }
SoundtrackController.play(ctx, album, hit.game.name, hit.ref.path, root = dir)
}
}
var savedDialog by remember { mutableStateOf(false) }
val candidates = if (listUninstalled) matching else matching.filter { it.installed }
val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed }
val sort = s.storesSort
@@ -304,18 +348,20 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
var stable by remember { mutableStateOf(emptyList<LibraryEntry>()) }
val ordered = if (sizesPending) retainOrder(candidates, stable) { it.key } else sorted
SideEffect { if (!sizesPending) stable = sorted }
val visible = installedFirst(ordered)
val visible = installedFirst(ordered).let { list ->
if (soundMode && source == Library.SOURCE_COLLECTION) list.sortedBy { if (it.game?.appId == SoundtrackCollections.FAVORITES_ID) 0 else 1 } else list
}
val split = visible.count { it.installed }.takeIf { it in 1 until visible.size } ?: 0
val open = selected.takeIf { it.startsWith("app:") }
val back = { onSelect("games") }
val open = selected.takeIf { it.startsWith(if (soundMode) "sound:" else "app:") }
val back = { onSelect(if (soundMode) "soundtracks" else "games") }
BackHandler(enabled = open == null && LibraryView.query.isNotEmpty()) { LibraryView.query = "" }
BackHandler(enabled = open != null) { back() }
val lead = remember { FocusRequester() }
var detailFocused by remember { mutableStateOf(false) }
var lastOpened by remember { mutableStateOf<String?>(null) }
val wasOpen = remember { booleanArrayOf(false) }
val backLabel = stringResource(R.string.rail_games)
val backLabel = stringResource(if (soundMode) R.string.rail_soundtracks else R.string.rail_games)
LaunchedEffect(open) {
val closing = open == null && wasOpen[0]
wasOpen[0] = open != null
@@ -349,7 +395,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
kotlinx.coroutines.delay(Motion.ms(240).toLong())
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
}
if (all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
if (!soundMode && all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
LibraryEmpty(s, a, modifier)
return
}
@@ -385,9 +431,26 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
onOpen = { focusManager.clearFocus(force = true); onSelect(it) },
searchCleared = open != null,
onFocus = { gridFocused = it },
soundMode = soundMode,
emptyText = when {
soundMode && all.isEmpty() -> R.string.soundtracks_empty
soundMode && source == Library.SOURCE_COLLECTION && q.isEmpty() -> R.string.soundtracks_collections_empty
else -> R.string.stores_nothing_matches
},
onAddSoundtrack = { addingSoundtrack = true },
onCollections = { savedDialog = true },
trackHits = shownHits, onPlayHit = playHit,
)
},
) { key -> GameDetail(key, s, a, lead, backLabel, hopRail = "games", onBack = back) }
) { key ->
if (soundMode || (!s.soundtracksEnabled && s.soundtracks.any { GameRef.key(it) == key })) SoundtrackDetail(key, s, a, lead, backLabel, onBack = back)
else GameDetail(key, s, a, lead, backLabel, hopRail = "games", onBack = back)
}
if (savedDialog) SavedDialog(emptyList(), onOpen = { id -> onSelect("sound:$id") }) { savedDialog = false }
if (addingSoundtrack) SyncFolderPicker(stringResource(R.string.soundtracks_add_title), null, onDismiss = { addingSoundtrack = false }) { dir ->
addingSoundtrack = false
a.onSoundtrackAdded(dir)
}
}
@Composable
@@ -416,6 +479,8 @@ private fun LibraryGrid(
sources: List<String>, source: String, sizesPending: Boolean, syncing: List<Pair<Store, String>>,
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, hiddenUninstalled: Int,
onSource: (String) -> Unit, onCycle: (Int) -> Unit, onOpen: (String) -> Unit, onFocus: (Boolean) -> Unit, searchCleared: Boolean,
soundMode: Boolean = false, emptyText: Int = R.string.stores_nothing_matches, onAddSoundtrack: () -> Unit = {},
onCollections: () -> Unit = {}, trackHits: List<SoundtrackIndex.Hit> = emptyList(), onPlayHit: (SoundtrackIndex.Hit) -> Unit = {},
) {
val listMode = s.storesView == "list"
val capsules = s.storesView == "capsules"
@@ -438,7 +503,7 @@ private fun LibraryGrid(
val next = storeGridNeighbor(index, visible.size, if (listMode) 1 else columns, direction, split)
when {
direction == 0 || index < 0 -> false
next == null -> direction > 0
next == null -> direction > 0 && trackHits.isEmpty()
else -> {
if (key.action == KeyEvent.ACTION_DOWN) {
val target = "card:${visible[next].key}"
@@ -470,7 +535,7 @@ private fun LibraryGrid(
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }) }
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections) }
}
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
Rise(1) { LibraryFilters(sources, source, onSource) }
@@ -488,7 +553,7 @@ private fun LibraryGrid(
Text(stringResource(R.string.store_section_loading), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
val empty = R.string.stores_nothing_matches
val empty = emptyText
if (visible.isEmpty() && hiddenUninstalled > 0) item(key = "browse-owned", span = { GridItemSpan(maxLineSpan) }) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp)) {
Text(stringResource(R.string.library_no_installed_matches), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -502,6 +567,40 @@ private fun LibraryGrid(
item(key = "not-installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_not_installed)) }
libraryGrid(visible.drop(split), empty, tile)
}
if (trackHits.isNotEmpty()) {
item(key = "tracks-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.soundtracks_tracks_heading)) }
items(trackHits, key = { "track:${it.ref.path}" }, span = { GridItemSpan(maxLineSpan) }, contentType = { "track" }) { hit -> TrackHitRow(hit, onPlayHit) }
}
}
}
@Composable
private fun TrackHitRow(hit: SoundtrackIndex.Hit, onPlay: (SoundtrackIndex.Hit) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(10.dp)
val cover = hit.ref.cover.takeIf { it.isNotEmpty() }?.let { java.io.File(it) }?.takeIf { it.isFile }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp).paneItem("trackhit:${hit.ref.path}").testTag("track-hit")
.clip(shape).glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current) { onPlay(hit) }
.controllerConfirm { onPlay(hit) }
.padding(horizontal = 10.dp, vertical = 6.dp),
) {
Box(Modifier.size(44.dp).clip(RoundedCornerShape(8.dp)).background(artBrush(hueOf(hit.ref.album)))) {
if (cover != null) AsyncImage(model = cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(hit.ref.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
listOf(hit.ref.album, hit.ref.artist).filter { it.isNotBlank() }.joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
if (hit.ref.durationMs > 0) Text(Soundtrack.formatLength(hit.ref.durationMs), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
@@ -532,28 +631,31 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
private fun LibraryHeader(
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Store?,
soundMode: Boolean = false, onAddSoundtrack: () -> Unit = {}, onCollections: () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
val heading = stringResource(if (soundMode) R.string.rail_soundtracks else R.string.rail_games)
ModeHeader(
stringResource(R.string.rail_games), LibraryView.query, { LibraryView.query = it },
placeholder = stringResource(R.string.stores_search_library),
heading, LibraryView.query, { LibraryView.query = it },
placeholder = stringResource(if (soundMode) R.string.soundtracks_search else R.string.stores_search_library),
clearSearchFocus = searchCleared, inlineWhenStacked = true,
lead = {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
Text(stringResource(R.string.rail_games), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(pluralStringResource(R.plurals.mode_added_count, total, total), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
Text(heading, fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(if (soundMode) total.toString() else pluralStringResource(R.plurals.mode_added_count, total, total), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
if (s.steamGamesX64 && !narrow) ClientTag()
}
},
) {
if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onCollections)
DisplayButton()
if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
if (!soundMode && (showUninstalled != null || xbox)) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
if (collections != null) CollectionsButton(collections)
SortButton(s, a)
ViewButton(s, a)
GameFileFolderActions(s, a)
if (!s.shortcutPicker) AddGameButton { GamesDialogState.adding = true }
if (!soundMode) GameFileFolderActions(s, a)
if (!s.shortcutPicker) AddGameButton { if (soundMode) onAddSoundtrack() else GamesDialogState.adding = true }
}
if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
}
@@ -570,7 +672,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
val store = Store.byId(src)
val dot = when {
store != null -> sourceColours(src).dot.copy(alpha = if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f)
src == Library.SOURCE_STEAM -> sourceColours(src).dot
src == Library.SOURCE_STEAM || src == Library.ADDED || src == Library.SOURCE_COLLECTION -> sourceColours(src).dot
else -> null
}
SourceFilterChip(src, if (src == Library.ADDED) stringResource(R.string.library_filter_added) else store?.shortLabel ?: sourceLabel(src), source == src, dot) { onSource(src) }
@@ -649,7 +751,7 @@ private fun LibraryArt(e: LibraryEntry, wide: Any?, tall: Any?, download: Downlo
}
ArtCard(
e.title, wide, tall, download, hot, capsule, chip,
badge = if (showSource) ({ SourceChip(e.source, small = true, modifier = Modifier.align(Alignment.TopStart).padding(6.dp)) }) else null,
badge = if (showSource) ({ SourceChip(e.source, small = true, modifier = Modifier.align(Alignment.TopStart).padding(6.dp), label = favoritesBadge(e), colours = favoritesColours(e)) }) else null,
) { LibrarySize(e) }
}
@@ -786,7 +888,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(e.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SourceChip(e.source, small = true)
SourceChip(e.source, small = true, label = favoritesBadge(e), colours = favoritesColours(e))
Text(meta.joinToString(" · "), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@@ -1004,3 +1106,10 @@ private fun ViewButton(s: FrontEndState, a: FrontEndActions) {
"view",
) { a.onStoresView(next) }
}
@Composable
private fun favoritesBadge(e: LibraryEntry): String? =
if (e.game?.appId == SoundtrackCollections.FAVORITES_ID && e.source == Library.SOURCE_COLLECTION) stringResource(R.string.soundtracks_favorites) else null
private fun favoritesColours(e: LibraryEntry): SourceColours? =
if (e.game?.appId == SoundtrackCollections.FAVORITES_ID && e.source == Library.SOURCE_COLLECTION) FavoritesColours else null
@@ -0,0 +1,295 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.CheckBoxOutlineBlank
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.frontend.Soundtrack
import com.droiddeck.launcher.frontend.SoundtrackCollections
import com.droiddeck.launcher.frontend.SoundtrackIndex
import com.droiddeck.launcher.frontend.SoundtrackTracks
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable
internal fun SavedDialog(pending: List<SoundtrackCollections.TrackRef>, onOpen: ((Int) -> Unit)?, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
remember { SoundtrackCollections.load(ctx) }
val snapshot = SoundtrackCollections.snapshot
val favoritesLabel = stringResource(R.string.soundtracks_favorites)
var naming by remember { mutableStateOf(false) }
val rows = listOf(Triple(SoundtrackCollections.FAVORITES_ID, favoritesLabel, snapshot.favorites)) +
snapshot.collections.map { Triple(it.id, it.name, it.tracks) }
AlertDialog(
onDismissRequest = onDismiss,
title = {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.soundtracks_saved), modifier = Modifier.weight(1f))
Icon(Icons.Filled.Bookmark, contentDescription = null, tint = colors.onSurfaceVariant)
}
},
text = {
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
SavedRow(stringResource(R.string.soundtracks_create_collection), stringResource(R.string.soundtracks_organise), null, "saved-create", null) {
TextButton(onClick = { naming = true }, modifier = Modifier.focusGlide(CircleShape).testTag("saved-new")) {
Icon(Icons.Filled.Add, contentDescription = null, modifier = Modifier.size(18.dp))
Text(stringResource(R.string.soundtracks_new))
}
}
for ((id, name, tracks) in rows) {
val cover = tracks.firstNotNullOfOrNull { t -> t.cover.takeIf { it.isNotEmpty() }?.let { java.io.File(it) }?.takeIf { it.isFile } }
val subtitle = stringResource(R.string.soundtracks_length_value, tracks.size, Soundtrack.formatLength(tracks.sumOf { it.durationMs }))
val added = pending.isNotEmpty() && pending.all { p -> tracks.any { it.path == p.path } }
SavedRow(name, subtitle, cover, "saved-$id", if (pending.isEmpty() && onOpen != null) ({ onDismiss(); onOpen(id) }) else null) {
if (pending.isNotEmpty()) CircleAction(if (added) Icons.Filled.Check else Icons.Filled.Add, name, "saved-add-$id") {
if (added) SoundtrackCollections.remove(ctx, id, pending.map { it.path }.toSet())
else SoundtrackCollections.add(ctx, id, pending)
}
}
}
}
},
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_close)) } },
)
if (naming) NameDialog(
stringResource(R.string.soundtracks_create_collection), "", stringResource(R.string.soundtracks_create),
onConfirm = { name ->
val id = SoundtrackCollections.create(ctx, name, pending)
if (id != null && pending.isEmpty() && onOpen != null) { onDismiss(); onOpen(id) }
id != null
},
onDismiss = { naming = false },
)
}
@Composable
private fun SavedRow(title: String, subtitle: String, cover: Any?, tag: String, onClick: (() -> Unit)?, trailing: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && onClick != null
val shape = RoundedCornerShape(10.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().testTag(tag).clip(shape).background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, Color.Transparent)
.then(
if (onClick != null) Modifier.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
else Modifier,
)
.padding(vertical = 4.dp),
) {
Box(Modifier.size(52.dp).clip(RoundedCornerShape(8.dp)).background(Color.White.copy(alpha = 0.08f))) {
if (cover != null) AsyncImage(cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(subtitle, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
trailing()
}
}
@Composable
private fun CircleAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, tag: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.testTag(tag).size(40.dp).clip(CircleShape).background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.border(1.dp, if (hot) pal.signal else colors.onSurface.copy(alpha = 0.7f), CircleShape)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = label },
) { Icon(icon, contentDescription = null, tint = colors.onSurface, modifier = Modifier.size(20.dp)) }
}
@Composable
internal fun NameDialog(title: String, initial: String, confirm: String, onConfirm: (String) -> Boolean, onDismiss: () -> Unit) {
var text by remember { mutableStateOf(initial) }
var invalid by remember { mutableStateOf(false) }
val submit: () -> Unit = {
val ok = onConfirm(text)
if (ok) onDismiss()
invalid = !ok
}
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
AdbTextField(
value = text, onValueChange = { text = it; invalid = false }, label = stringResource(R.string.soundtracks_collection_name),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, focusOnShow = true, onDone = submit,
)
if (invalid) Text(stringResource(R.string.soundtracks_name_invalid), fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
}
},
confirmButton = { TextButton(onClick = submit, modifier = Modifier.focusGlide(CircleShape).testTag("name-confirm")) { Text(confirm) } },
dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@Composable
internal fun ManageDialog(id: Int, games: List<Library.SteamGame>, onRemoveMode: () -> Unit, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val name = SoundtrackCollections.snapshot.collections.firstOrNull { it.id == id }?.name.orEmpty()
val favorites = id == SoundtrackCollections.FAVORITES_ID
var renaming by remember { mutableStateOf(false) }
var adding by remember { mutableStateOf(false) }
var deleting by remember { mutableStateOf(false) }
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
AppDialog(shown, close, "soundtrackManage", wide = false, maxWidth = 420.dp) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
DialogTitleRow(stringResource(R.string.soundtracks_manage), onClose = close)
if (!favorites) PickerRow(Icons.Filled.Edit, stringResource(R.string.soundtracks_rename), null) { renaming = true }
PickerRow(Icons.Filled.Add, stringResource(R.string.soundtracks_add_tracks), null) { adding = true }
PickerRow(Icons.Filled.Remove, stringResource(R.string.soundtracks_remove_tracks), null) { onDismiss(); onRemoveMode() }
if (!favorites) PickerRow(Icons.Filled.Delete, stringResource(R.string.soundtracks_delete_collection), null) { deleting = true }
}
}
if (renaming) NameDialog(
stringResource(R.string.soundtracks_rename), name, stringResource(R.string.soundtracks_rename),
onConfirm = { SoundtrackCollections.rename(ctx, id, it) }, onDismiss = { renaming = false },
)
if (adding) TrackPickerDialog(id, games) { adding = false }
if (deleting) ConfirmDialog(
title = stringResource(R.string.soundtracks_delete_title, name), text = stringResource(R.string.soundtracks_delete_body),
confirm = stringResource(R.string.common_delete),
onConfirm = { SoundtrackCollections.delete(ctx, id); onDismiss() },
onDismiss = { deleting = false },
)
}
@Composable
internal fun TrackPickerDialog(id: Int, games: List<Library.SteamGame>, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val hits by produceState<List<SoundtrackIndex.Hit>?>(null, games) { value = withContext(Dispatchers.IO) { SoundtrackIndex.build(ctx, games) } }
var query by remember { mutableStateOf("") }
var picked by remember { mutableStateOf(setOf<String>()) }
val have = SoundtrackCollections.tracksOf(id).mapTo(HashSet()) { it.path }
val list = hits?.distinctBy { it.ref.path }?.filter { it.ref.path !in have && SoundtrackTracks.matches(query, it.ref.title, it.ref.artist, it.ref.album) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.soundtracks_add_tracks)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
AdbTextField(
value = query, onValueChange = { query = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = stringResource(R.string.soundtracks_search_tracks), compact = true,
)
Row(horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically) {
TextButton(onClick = { picked = picked + list.orEmpty().map { it.ref.path } }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.soundtracks_select_all))
}
TextButton(onClick = { picked = emptySet() }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.soundtracks_deselect_all))
}
}
if (list == null) Text(stringResource(R.string.store_section_loading), fontSize = 13.sp, color = colors.onSurfaceVariant)
else LazyColumn(Modifier.fillMaxWidth().heightIn(max = 340.dp).testTag("track-picker")) {
items(list, key = { it.ref.path }) { hit ->
val on = hit.ref.path in picked
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val toggle = { picked = if (on) picked - hit.ref.path else picked + hit.ref.path }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(if (on) pal.signal.copy(alpha = 0.16f) else if (hot) Color.White.copy(alpha = 0.08f) else Color.Transparent)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Checkbox, onClick = toggle)
.controllerConfirm(onClick = toggle).padding(horizontal = 8.dp, vertical = 8.dp),
) {
Icon(
if (on) Icons.Filled.CheckBox else Icons.Filled.CheckBoxOutlineBlank, contentDescription = null,
tint = if (on) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp),
)
Column(Modifier.weight(1f)) {
Text(hit.ref.title, fontSize = 14.sp, color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
listOf(hit.ref.album, hit.ref.artist).filter { it.isNotBlank() }.joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
if (hit.ref.durationMs > 0) Text(Soundtrack.formatLength(hit.ref.durationMs), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
}
}
},
confirmButton = {
TextButton(
enabled = picked.isNotEmpty(),
onClick = {
SoundtrackCollections.add(ctx, id, hits.orEmpty().filter { it.ref.path in picked }.map { it.ref })
onDismiss()
},
modifier = Modifier.focusGlide(CircleShape).testTag("picker-add"),
) { Text(stringResource(R.string.soundtracks_add_count, picked.size)) }
},
dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -0,0 +1,391 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Repeat
import androidx.compose.material.icons.filled.RepeatOne
import androidx.compose.material.icons.filled.Shuffle
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.filled.VolumeOff
import androidx.compose.material.icons.filled.VolumeUp
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.media3.common.Player
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.frontend.Soundtrack
import com.droiddeck.launcher.frontend.SoundtrackCollections
import com.droiddeck.launcher.frontend.SoundtrackOrder
import com.droiddeck.launcher.playback.SoundtrackController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
@Composable
internal fun SoundtrackDetail(key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, onBack: () -> Unit) {
val appId = remember(key) { key.removePrefix("sound:").removePrefix("app:").toIntOrNull() }
val ctx = LocalContext.current
remember { SoundtrackCollections.load(ctx) }
val favoritesLabel = stringResource(R.string.soundtracks_favorites)
val snapshot = SoundtrackCollections.snapshot
val saved = remember(snapshot, favoritesLabel) { SoundtrackCollections.games(ctx, favoritesLabel) }
val game = s.soundtracks.firstOrNull { it.appId == appId } ?: saved.firstOrNull { it.appId == appId }
LaunchedEffect(game == null, s.soundtracksLoaded) { if (game == null && s.soundtracksLoaded) onBack() }
if (game == null) return
val narrow = LocalNarrowPane.current
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
val root = game.gameFiles
val collectionId = if (game.source == Library.SOURCE_COLLECTION) game.appId else null
val target = remember(root, collectionId) { PlayTarget(root, collectionId) }
val loadedAlbum by produceState<Soundtrack.Album?>(null, root, game.art, SoundtrackOrder.version) {
value = root?.let { dir -> withContext(Dispatchers.IO) { Soundtrack.load(ctx, dir, game.art) } }
}
val collectionAlbum = remember(snapshot, collectionId) { collectionId?.let { SoundtrackCollections.album(ctx, it) } }
val album = collectionAlbum ?: loadedAlbum
LaunchedEffect(Unit) { SoundtrackController.connect(ctx) }
val inset = LocalDetailInset.current
val currentTrack = if (target.belongs) SoundtrackController.currentId else null
val trackArt by produceState<java.io.File?>(null, currentTrack) {
value = currentTrack?.let { id -> withContext(Dispatchers.IO) { Soundtrack.trackCover(ctx, java.io.File(id)) } }
}
val pinned = game.art?.path.orEmpty().let { it.contains("/steam-art/") || it.contains("/soundtrack-art/") }
val art: Any? = if (pinned) game.art else trackArt ?: game.art ?: album?.cover
val refs = remember(snapshot, collectionId) { collectionId?.let { id -> SoundtrackCollections.tracksOf(id).associateBy { it.path } }.orEmpty() }
val coverPath = (game.art ?: album?.cover)?.path.orEmpty()
val refOf: (Soundtrack.Track) -> SoundtrackCollections.TrackRef = { t ->
refs[t.id] ?: SoundtrackCollections.TrackRef(t.id, t.title, t.artist.ifBlank { album?.artist.orEmpty() }, game.name, t.durationMs, coverPath)
}
var selectRequest by remember { mutableIntStateOf(0) }
val onReorder: ((List<String>) -> Unit)? = when {
collectionId != null -> ({ paths: List<String> -> SoundtrackCollections.reorder(ctx, collectionId, paths) })
game.library == Library.ADDED && root != null -> ({ paths: List<String> -> SoundtrackOrder.set(ctx, root, paths) })
else -> null
}
GameBackdrop(art, art, hueOf(game.name), fadeTop = inset.top < 8.dp, artBlur = 24.dp) {
Column(Modifier.fillMaxWidth().padding(horizontal = inset.horizontal).padding(top = inset.top)) {
Rise(0) {
Row(Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.glass(CircleShape)) { BackLink(backLabel, compact = true, onClick = onBack) }
Spacer(Modifier.weight(1f))
SourceBadge(game.source)
}
}
val loaded = album
if (stacked) Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
Rise(1) { SoundtrackPlayer(game, loaded, art, lead, s, a, target, refOf, collectionId) { selectRequest++ } }
if (loaded != null) Rise(2) {
TrackPanel(loaded, game.name, target, refOf, collectionId, selectRequest, onReorder, Modifier.fillMaxWidth().height((LocalConfiguration.current.screenHeightDp * 0.55f).dp))
}
} else Row(horizontalArrangement = Arrangement.spacedBy(28.dp), modifier = Modifier.fillMaxWidth()) {
Rise(1, Modifier.weight(0.42f)) { SoundtrackPlayer(game, loaded, art, lead, s, a, target, refOf, collectionId) { selectRequest++ } }
if (loaded != null) Rise(2, Modifier.weight(0.58f)) {
TrackPanel(loaded, game.name, target, refOf, collectionId, selectRequest, onReorder, Modifier.fillMaxWidth().height((LocalConfiguration.current.screenHeightDp * 0.72f).dp))
}
}
}
}
}
@Composable
private fun SoundtrackPlayer(
game: Library.SteamGame, album: Soundtrack.Album?, art: Any?, lead: FocusRequester, s: FrontEndState, a: FrontEndActions,
target: PlayTarget, refOf: (Soundtrack.Track) -> SoundtrackCollections.TrackRef, collectionId: Int?, onRemoveMode: () -> Unit,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val belongs = target.belongs
val playing = belongs && SoundtrackController.playing
val shownArt: Any? = art
var saving by remember { mutableStateOf(false) }
Column(verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) {
Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top) {
Box(Modifier.size(120.dp).clip(RoundedCornerShape(10.dp)).background(Color.Black.copy(alpha = 0.35f))) {
if (shownArt != null) AsyncImage(shownArt, contentDescription = game.name, contentScale = ContentScale.Fit, modifier = Modifier.matchParentSize().testTag("soundtrack-cover"))
}
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.weight(1f)) {
Text(
game.name, fontSize = 22.sp, lineHeight = 26.sp, fontWeight = FontWeight.Black, color = colors.onBackground,
maxLines = 2, overflow = TextOverflow.Ellipsis,
)
val artist = album?.artist.orEmpty()
if (artist.isNotBlank()) Text(artist, fontSize = 14.sp, color = colors.onBackground.copy(alpha = 0.8f), maxLines = 1, overflow = TextOverflow.Ellipsis)
if (album != null && album.tracks.isNotEmpty()) {
Text(
stringResource(R.string.soundtracks_total_length).uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.8.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp),
)
Text(
stringResource(R.string.soundtracks_length_value, album.tracks.size, Soundtrack.formatLength(album.totalMs)),
fontSize = 13.sp, color = colors.onBackground,
)
}
}
}
Seek(target, album)
val shuffleLabel = stringResource(R.string.soundtracks_shuffle)
val previousLabel = stringResource(R.string.soundtracks_previous)
val playLabel = stringResource(if (playing) R.string.soundtracks_pause else R.string.soundtracks_play)
val nextLabel = stringResource(R.string.soundtracks_next)
val repeatLabel = stringResource(
when (SoundtrackController.repeat) {
Player.REPEAT_MODE_ALL -> R.string.soundtracks_repeat_all
Player.REPEAT_MODE_ONE -> R.string.soundtracks_repeat_one
else -> R.string.soundtracks_repeat_off
},
)
val loaded = album?.takeIf { it.tracks.isNotEmpty() }
Row(horizontalArrangement = Arrangement.spacedBy(14.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
TransportButton(Icons.Filled.Shuffle, shuffleLabel, "sound:shuffle", on = belongs && SoundtrackController.shuffle, enabled = loaded != null) {
if (loaded == null) return@TransportButton
if (belongs) SoundtrackController.setShuffle(ctx, !SoundtrackController.shuffle)
else SoundtrackController.play(ctx, loaded, game.name, null, shuffled = true, root = target.root, collection = target.collection)
}
TransportButton(Icons.Filled.SkipPrevious, previousLabel, "sound:previous", enabled = loaded != null) {
if (loaded == null) return@TransportButton
if (belongs) SoundtrackController.previous(ctx) else SoundtrackController.play(ctx, loaded, game.name, null, root = target.root, collection = target.collection)
}
TransportButton(
if (playing) Icons.Filled.Pause else Icons.Filled.PlayArrow, playLabel, "sound:play", big = true, enabled = loaded != null,
modifier = Modifier.focusRequester(lead),
) {
if (loaded != null) SoundtrackController.toggle(ctx, loaded, game.name, target.root, target.collection)
}
TransportButton(Icons.Filled.SkipNext, nextLabel, "sound:next", enabled = loaded != null) {
if (loaded == null) return@TransportButton
if (belongs) SoundtrackController.next(ctx) else SoundtrackController.play(ctx, loaded, game.name, null, root = target.root, collection = target.collection)
}
TransportButton(
if (SoundtrackController.repeat == Player.REPEAT_MODE_ONE) Icons.Filled.RepeatOne else Icons.Filled.Repeat, repeatLabel, "sound:repeat",
on = SoundtrackController.repeat != Player.REPEAT_MODE_OFF, enabled = loaded != null && belongs,
) { SoundtrackController.cycleRepeat(ctx) }
}
val heartTrack = if (belongs) loaded?.tracks?.firstOrNull { it.id == SoundtrackController.currentId } else null
val liked = heartTrack != null && SoundtrackCollections.snapshot.favorites.any { it.path == heartTrack.id }
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
TransportButton(
if (liked) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder, stringResource(R.string.soundtracks_add_favorites), "sound:favorite",
on = liked, enabled = heartTrack != null,
) { heartTrack?.let { SoundtrackCollections.toggleFavorite(ctx, refOf(it)) } }
TransportButton(Icons.Filled.BookmarkBorder, stringResource(R.string.soundtracks_saved), "sound:saved", enabled = heartTrack != null) { saving = true }
}
if (saving && heartTrack != null) SavedDialog(listOf(refOf(heartTrack)), null) { saving = false }
Volume()
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) {
SoundtrackActions(game, s, a, collectionId, onRemoveMode)
}
}
}
@Composable
private fun Seek(target: PlayTarget, album: Soundtrack.Album?) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val belongs = target.belongs
var position by remember { mutableFloatStateOf(0f) }
var dragging by remember { mutableStateOf(false) }
val duration = if (belongs) SoundtrackController.durationMs else 0L
LaunchedEffect(belongs, SoundtrackController.currentId) {
if (!belongs) {
if (!dragging) position = 0f
return@LaunchedEffect
}
while (true) {
if (!dragging) position = SoundtrackController.position().toFloat()
delay(400)
}
}
Column(verticalArrangement = Arrangement.spacedBy(0.dp), modifier = Modifier.fillMaxWidth()) {
Slider(
value = if (duration > 0) (position / duration).coerceIn(0f, 1f) else 0f,
onValueChange = { dragging = true; position = it * duration },
onValueChangeFinished = { dragging = false; SoundtrackController.seekTo(ctx, position.toLong()) },
enabled = belongs && duration > 0 && album != null,
colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onBackground.copy(alpha = 0.18f)),
modifier = Modifier.fillMaxWidth().testTag("soundtrack-seek"),
)
Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) {
Text(Soundtrack.formatLength(position.toLong()), fontSize = 11.sp, color = colors.onSurfaceVariant)
Spacer(Modifier.weight(1f))
Text(Soundtrack.formatLength(duration), fontSize = 11.sp, color = colors.onSurfaceVariant)
}
}
}
@Composable
private fun Volume() {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var level by remember { mutableFloatStateOf(SoundtrackController.volume) }
LaunchedEffect(SoundtrackController.volume) { level = SoundtrackController.volume }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
Icon(if (level <= 0.001f) Icons.Filled.VolumeOff else Icons.Filled.VolumeUp, contentDescription = stringResource(R.string.soundtracks_volume), tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
Slider(
value = level, onValueChange = { level = it; SoundtrackController.setVolume(ctx, it) },
colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onBackground.copy(alpha = 0.18f)),
modifier = Modifier.weight(1f).testTag("soundtrack-volume"),
)
}
}
@Composable
private fun TransportButton(
icon: ImageVector, label: String, id: String, big: Boolean = false, on: Boolean = false, enabled: Boolean = true,
modifier: Modifier = Modifier, onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && enabled
val size = if (big) 60.dp else 44.dp
val fill = when {
big -> pal.signal.copy(alpha = if (hot) 1f else 0.9f)
hot -> pal.signal.copy(alpha = 0.16f)
else -> Color.Transparent
}
Box(
contentAlignment = Alignment.Center,
modifier = modifier.paneItem(id).testTag(id).size(size).clip(CircleShape).background(fill)
.glideBorder(hot, CircleShape, pal.signal, if (big) Color.Transparent else Color.Transparent)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.semantics { contentDescription = label },
) {
Icon(
icon, contentDescription = null,
tint = when {
big -> colors.background
!enabled -> colors.onSurfaceVariant.copy(alpha = 0.4f)
on -> pal.signal
else -> colors.onBackground
},
modifier = Modifier.size(if (big) 34.dp else 26.dp),
)
}
}
@Composable
private fun SeeMoreButton(label: String, id: String, danger: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(10.dp)
val accent = if (danger) colors.error else pal.signal
Box(
contentAlignment = Alignment.Center,
modifier = modifier.fillMaxWidth().paneItem(id).testTag(id).heightIn(min = 44.dp).clip(shape)
.background(if (hot) accent.copy(alpha = 0.16f) else Color.White.copy(alpha = 0.09f))
.glideBorder(hot, shape, accent, Color.White.copy(alpha = 0.10f))
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 10.dp),
) {
Text(
label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center,
color = if (danger && hot) colors.error else colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
}
@Composable
private fun SoundtrackActions(game: Library.SteamGame, s: FrontEndState, a: FrontEndActions, collectionId: Int?, onRemoveMode: () -> Unit) {
var options by remember { mutableStateOf(false) }
var managing by remember { mutableStateOf(false) }
if (collectionId != null) SeeMoreButton(stringResource(R.string.soundtracks_manage), "sound:manage") { managing = true }
if (managing && collectionId != null) ManageDialog(collectionId, s.soundtracks, onRemoveMode) { managing = false }
SeeMoreButton(stringResource(R.string.soundtracks_options), "sound:options") { options = true }
if (options) SoundtrackOptionsDialog { options = false }
game.gameFiles?.takeIf { it.isDirectory }?.let { dir ->
SeeMoreButton(stringResource(R.string.games_files), "sound:files") { a.onBrowseFiles(dir) }
}
var menu by remember(game.appId) { mutableStateOf(false) }
Box {
SeeMoreButton(stringResource(R.string.game_shortcut), "sound:shortcut") { menu = !menu }
AnchoredMenu(menu, onDismiss = { menu = false }, title = stringResource(R.string.game_shortcut)) { first ->
MenuItem(stringResource(R.string.game_shortcut_add), checked = false, focusRequester = first) { menu = false; a.onGameShortcut(game) }
MenuItem(stringResource(R.string.game_link_copy), checked = false) { menu = false; a.onCopyGameLink(game) }
}
}
var collectionArt by remember(game.appId) { mutableStateOf(false) }
val ownArt = game.library == Library.ADDED
if (ownArt) SeeMoreButton(stringResource(R.string.game_edit_art), "sound:art") { collectionArt = true }
else SeeMoreButton(stringResource(R.string.game_edit_art), "sound:art") { GamesDialogState.steamArt = game }
if (collectionArt && ownArt) CollectionArtEditor(
game.appId, game.name, game.gameFiles,
onClose = { collectionArt = false },
onChanged = { if (collectionId != null) SoundtrackCollections.refresh() else a.onSoundtracksChanged() },
)
if (collectionId != null) return
var asking by remember(game.appId) { mutableStateOf(false) }
val added = game.library == Library.ADDED
val label = stringResource(if (added) R.string.edit_remove else R.string.common_uninstall)
SeeMoreButton(label, "sound:remove", danger = true) { asking = true }
if (asking) ConfirmDialog(
title = if (added) stringResource(R.string.games_remove_title, game.name) else stringResource(R.string.stores_uninstall_title, game.name),
text = if (added) stringResource(R.string.games_remove_body) else stringResource(R.string.games_uninstall_body),
confirm = label,
onConfirm = { a.onSoundtrackRemoved(game) },
onDismiss = { asking = false },
)
}
@@ -0,0 +1,15 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.addPathNodes
import androidx.compose.ui.unit.dp
private const val NOTES = "M8.4,4.5 L20,2 V6 L8.4,8.5 Z M8.4,4.5 H10.6 V17.5 H8.4 Z M17.9,2 H20 V15.5 H17.9 Z M7.2,14.7 A3.4,2.8 0 1,0 7.2,20.3 A3.4,2.8 0 1,0 7.2,14.7 Z M16.6,12.7 A3.4,2.8 0 1,0 16.6,18.3 A3.4,2.8 0 1,0 16.6,12.7 Z"
internal val SoundtrackIcon: ImageVector by lazy {
ImageVector.Builder("Soundtrack", 24.dp, 24.dp, 24f, 24f)
.addPath(addPathNodes(NOTES), fill = SolidColor(Color.Black))
.build()
}
@@ -0,0 +1,217 @@
package com.droiddeck.launcher.ui
import android.media.AudioManager
import android.media.audiofx.BassBoost
import android.media.audiofx.Equalizer
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Soundtrack
import com.droiddeck.launcher.playback.SoundtrackController
import com.droiddeck.launcher.playback.SoundtrackSettings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlin.math.roundToInt
private class EqInfo(
val bands: Int, val min: Int, val max: Int, val freqs: List<Int>, val presets: List<Pair<String, List<Int>>>, val bassSupported: Boolean,
)
private fun readEqInfo(audio: AudioManager): EqInfo? = runCatching {
val id = audio.generateAudioSessionId()
val eq = Equalizer(0, id)
try {
val count = eq.numberOfBands.toInt()
val presets = (0 until eq.numberOfPresets.toInt()).map { preset ->
eq.usePreset(preset.toShort())
eq.getPresetName(preset.toShort()) to (0 until count).map { eq.getBandLevel(it.toShort()).toInt() }
}
val bass = runCatching { BassBoost(0, id).let { b -> try { b.strengthSupported } finally { b.release() } } }.getOrDefault(false)
EqInfo(
count, eq.bandLevelRange[0].toInt(), eq.bandLevelRange[1].toInt(),
(0 until count).map { eq.getCenterFreq(it.toShort()) / 1000 }, presets, bass,
)
} finally {
eq.release()
}
}.getOrNull()
@Composable
internal fun SoundtrackOptionsDialog(onDismiss: () -> Unit) {
val ctx = LocalContext.current
LaunchedEffect(Unit) { SoundtrackSettings.load(ctx) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.soundtracks_options)) },
text = {
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(16.dp)) {
RateRow(stringResource(R.string.theme_rgb_speed), SoundtrackSettings.speed, "soundtrack-speed") { SoundtrackController.setSpeed(ctx, it) }
RateRow(stringResource(R.string.soundtracks_pitch), SoundtrackSettings.pitch, "soundtrack-pitch") { SoundtrackController.setPitch(ctx, it) }
SwitchRow(stringResource(R.string.soundtracks_skip_silence), SoundtrackSettings.skipSilence, "soundtrack-skip-silence") {
SoundtrackController.setSkipSilence(ctx, it)
}
SleepSection()
EqualizerSection()
}
},
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_close)) } },
)
}
@Composable
private fun RateRow(label: String, value: Float, tag: String, onChange: (Float) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurface, modifier = Modifier.weight(1f))
Text("%.2f×".format(value), fontSize = 14.sp, color = colors.onSurfaceVariant)
TextButton(onClick = { onChange(1f) }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.soundtracks_reset)) }
}
Slider(
value = value, onValueChange = { v -> (v * 20f).roundToInt().div(20f).let { if (it != value) onChange(it) } },
valueRange = SoundtrackSettings.MIN_RATE..SoundtrackSettings.MAX_RATE, steps = 29,
colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onSurface.copy(alpha = 0.18f)),
modifier = Modifier.fillMaxWidth().testTag(tag),
)
}
}
@Composable
private fun SwitchRow(label: String, checked: Boolean, tag: String, onChange: (Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().focusGlide(RoundedCornerShape(12.dp)).toggleable(checked, role = Role.Switch, onValueChange = onChange).padding(vertical = 4.dp).testTag(tag),
) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurface, modifier = Modifier.weight(1f))
Switch(checked = checked, onCheckedChange = null)
}
}
@Composable
private fun OptionChip(label: String, selected: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(99.dp)
Text(
label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
color = if (selected) pal.signal else colors.onSurface,
modifier = Modifier.focusGlide(shape).clip(shape)
.background(if (selected) pal.signal.copy(alpha = 0.18f) else colors.onSurface.copy(alpha = 0.08f))
.selectable(selected = selected, role = Role.RadioButton, onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
)
}
@Composable
private fun SleepSection() {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
var left by remember { mutableLongStateOf(0L) }
LaunchedEffect(Unit) {
while (true) {
left = SoundtrackController.sleepRemainingMs()
delay(1000)
}
}
val trackEnd = SoundtrackController.sleepTrackEnd
val timed = left > 0L
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.soundtracks_sleep), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurface, modifier = Modifier.weight(1f))
if (timed) Text(stringResource(R.string.soundtracks_sleep_left, Soundtrack.formatLength(left)), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OptionChip(stringResource(R.string.perf_cap_off), !timed && !trackEnd) { SoundtrackController.setSleep(ctx, 0) }
for (minutes in listOf(15, 30, 60)) OptionChip(stringResource(R.string.soundtracks_sleep_minutes, minutes), false) { SoundtrackController.setSleep(ctx, minutes) }
OptionChip(stringResource(R.string.soundtracks_sleep_track_end), trackEnd) { SoundtrackController.setSleep(ctx, -1) }
}
}
}
@Composable
private fun EqualizerSection() {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val info by produceState<EqInfo?>(null) {
value = withContext(Dispatchers.IO) { readEqInfo(ctx.getSystemService(AudioManager::class.java)) }
}
val ready = info
val on = SoundtrackSettings.eqOn
val levels = ready?.let { i -> SoundtrackSettings.bands.takeIf { it.size == i.bands } ?: List(i.bands) { 0 } }.orEmpty()
val bass = SoundtrackSettings.bass
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
SwitchRow(stringResource(R.string.soundtracks_equalizer), on && ready != null, "soundtrack-eq") {
if (ready != null) SoundtrackController.setEqualizer(ctx, it, levels, bass)
}
if (ready == null || ready.bands == 0) {
if (ready != null) Text(stringResource(R.string.soundtracks_eq_unavailable), fontSize = 13.sp, color = colors.onSurfaceVariant)
return@Column
}
if (ready.presets.isNotEmpty()) Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
for ((name, preset) in ready.presets) OptionChip(name, on && preset == levels) { SoundtrackController.setEqualizer(ctx, true, preset, bass) }
}
for (band in 0 until ready.bands) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
val hz = ready.freqs[band]
Text(if (hz >= 1000) "%.1f kHz".format(hz / 1000f) else "$hz Hz", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(end = 2.dp))
Slider(
value = levels[band].toFloat(), valueRange = ready.min.toFloat()..ready.max.toFloat(),
onValueChange = { v -> SoundtrackController.setEqualizer(ctx, true, levels.toMutableList().also { it[band] = v.roundToInt() }, bass) },
colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onSurface.copy(alpha = 0.18f)),
modifier = Modifier.weight(1f).testTag("soundtrack-eq-$band"),
)
}
}
if (ready.bassSupported) Column {
Text(stringResource(R.string.soundtracks_bass), fontSize = 13.sp, color = colors.onSurfaceVariant)
Slider(
value = bass.toFloat(), valueRange = 0f..1000f,
onValueChange = { v -> SoundtrackController.setEqualizer(ctx, true, levels, v.roundToInt()) },
colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onSurface.copy(alpha = 0.18f)),
modifier = Modifier.fillMaxWidth().testTag("soundtrack-bass"),
)
}
TextButton(onClick = { SoundtrackController.setEqualizer(ctx, on, List(ready.bands) { 0 }, 0) }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.soundtracks_reset))
}
}
}
@@ -0,0 +1,391 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.CheckBoxOutlineBlank
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.launch
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.zIndex
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Soundtrack
import com.droiddeck.launcher.frontend.SoundtrackCollections
import com.droiddeck.launcher.frontend.SoundtrackTracks
import com.droiddeck.launcher.playback.SoundtrackController
internal class PlayTarget(val root: java.io.File?, val collection: Int?) {
val belongs: Boolean get() = if (collection != null) SoundtrackController.belongsCollection(collection) else SoundtrackController.belongs(root)
}
private sealed interface SoundRow {
class Disc(val number: Int, val label: String) : SoundRow
class Item(val track: Soundtrack.Track) : SoundRow
}
private fun rowsOf(album: Soundtrack.Album): List<SoundRow> = buildList {
for ((disc, tracks) in album.disc) {
if (album.multiDisc) add(SoundRow.Disc(disc, tracks.firstOrNull()?.discLabel ?: disc.toString()))
tracks.forEach { add(SoundRow.Item(it)) }
}
}
@Composable
private fun sortLabel(sort: SoundtrackTracks.Sort): String = stringResource(
when (sort) {
SoundtrackTracks.Sort.DEFAULT -> R.string.soundtracks_sort_default
SoundtrackTracks.Sort.TITLE_ASC -> R.string.stores_sort_title_asc
SoundtrackTracks.Sort.TITLE_DESC -> R.string.stores_sort_title_desc
SoundtrackTracks.Sort.LONGEST -> R.string.soundtracks_sort_longest
SoundtrackTracks.Sort.SHORTEST -> R.string.soundtracks_sort_shortest
},
)
@Composable
internal fun TrackPanel(
album: Soundtrack.Album, title: String, target: PlayTarget, refOf: (Soundtrack.Track) -> SoundtrackCollections.TrackRef,
collectionId: Int?, selectRequest: Int, onReorder: ((List<String>) -> Unit)?, modifier: Modifier,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
var query by remember { mutableStateOf("") }
var sort by remember { mutableStateOf(SoundtrackTracks.Sort.DEFAULT) }
var sortMenu by remember { mutableStateOf(false) }
var selecting by remember { mutableStateOf(false) }
var picked by remember { mutableStateOf(setOf<String>()) }
var saving by remember { mutableStateOf(false) }
val leave: () -> Unit = {
selecting = false
picked = emptySet()
}
LaunchedEffect(selectRequest) { if (selectRequest > 0) selecting = true }
BackHandler(enabled = selecting) { leave() }
val rows: List<SoundRow> = remember(album, query, sort) {
if (sort == SoundtrackTracks.Sort.DEFAULT && query.isBlank()) rowsOf(album)
else SoundtrackTracks.sort(
album.tracks.filter { SoundtrackTracks.matches(query, it.title, it.artist) }, sort, { it.title }, { it.durationMs },
).map { SoundRow.Item(it) }
}
val rowIds = rows.filterIsInstance<SoundRow.Item>().map { it.track.id }
var working by remember(rowIds) { mutableStateOf<List<SoundRow>?>(null) }
val display = working ?: rows
val canReorder = onReorder != null && sort == SoundtrackTracks.Sort.DEFAULT && query.isBlank() && selecting
var dragId by remember { mutableStateOf<String?>(null) }
var dragTotal by remember { mutableFloatStateOf(0f) }
var dragTo by remember { mutableIntStateOf(0) }
val numbers = remember(display) {
val out = HashMap<String, Int>()
var n = 0
for (row in display) {
if (row is SoundRow.Disc) n = 0
else if (row is SoundRow.Item) out[row.track.id] = ++n
}
out
}
val state = rememberLazyListState()
val scope = rememberCoroutineScope()
val drag = remember { DragState() }
fun applyDrag() {
drag.total = drag.total.coerceIn((drag.lo - drag.from) * drag.size, (drag.hi - drag.from) * drag.size)
dragTotal = drag.total
dragTo = dragTarget(drag.total, drag.size, drag.from, drag.lo, drag.hi)
}
val finishDrag: () -> Unit = {
if (dragId != null) {
val from = drag.from
val to = dragTo
if (to != from && from in drag.base.indices) {
val moved = drag.base.toMutableList().apply { add(to, removeAt(from)) }
val index = state.firstVisibleItemIndex
val offset = state.firstVisibleItemScrollOffset
working = moved
scope.launch { state.scrollToItem(index, offset) }
onReorder?.invoke(moved.filterIsInstance<SoundRow.Item>().map { it.track.id })
}
dragId = null
dragTotal = 0f
dragTo = from
}
}
val rowsNow by rememberUpdatedState(rows)
val finishNow by rememberUpdatedState(finishDrag)
val current = if (target.belongs) SoundtrackController.currentId else null
var scrolledTo by remember { mutableStateOf<String?>(null) }
LaunchedEffect(album, current) {
if (current == null) {
scrolledTo = null
return@LaunchedEffect
}
if (dragId != null || current == scrolledTo) return@LaunchedEffect
val at = rows.indexOfFirst { it is SoundRow.Item && it.track.id == current }
if (at >= 0) {
scrolledTo = current
state.animateScrollToItem(at)
}
}
val chosen = album.tracks.filter { it.id in picked }.map(refOf)
Column(modifier) {
Row(Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Box(Modifier.weight(1f)) {
AdbTextField(
value = query, onValueChange = { query = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = stringResource(R.string.soundtracks_search_tracks), compact = true,
)
}
Box {
HeaderIconButton(stringResource(R.string.stores_sort), Icons.Filled.Sort, "tracks-sort") { sortMenu = !sortMenu }
AnchoredMenu(sortMenu, onDismiss = { sortMenu = false }, title = stringResource(R.string.stores_sort)) { first ->
SoundtrackTracks.Sort.values().forEachIndexed { i, option ->
MenuItem(sortLabel(option), checked = option == sort, focusRequester = if (i == 0) first else null) {
sort = option
sortMenu = false
}
}
}
}
HeaderIconButton(stringResource(R.string.soundtracks_select), Icons.Filled.CheckBox, "tracks-select") {
if (selecting) leave() else selecting = true
}
}
if (selecting) Row(
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(bottom = 6.dp),
horizontalArrangement = Arrangement.spacedBy(2.dp), verticalAlignment = Alignment.CenterVertically,
) {
Text(stringResource(R.string.soundtracks_selected, picked.size), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 6.dp))
TextButton(onClick = { picked = rowIds.toSet() }, modifier = Modifier.focusGlide(CircleShape).testTag("tracks-select-all")) {
Text(stringResource(R.string.soundtracks_select_all))
}
TextButton(onClick = { picked = emptySet() }, modifier = Modifier.focusGlide(CircleShape).testTag("tracks-deselect-all")) {
Text(stringResource(R.string.soundtracks_deselect_all))
}
TextButton(enabled = picked.isNotEmpty(), onClick = { saving = true }, modifier = Modifier.focusGlide(CircleShape).testTag("tracks-add-collection")) {
Text(stringResource(R.string.soundtracks_add_to_collection))
}
TextButton(
enabled = picked.isNotEmpty(),
onClick = {
SoundtrackCollections.add(ctx, SoundtrackCollections.FAVORITES_ID, chosen)
leave()
},
modifier = Modifier.focusGlide(CircleShape).testTag("tracks-add-favorites"),
) { Text(stringResource(R.string.soundtracks_add_favorites)) }
if (collectionId != null) TextButton(
enabled = picked.isNotEmpty(),
onClick = {
SoundtrackCollections.remove(ctx, collectionId, picked)
leave()
},
modifier = Modifier.focusGlide(CircleShape).testTag("tracks-remove"),
) { Text(stringResource(R.string.soundtracks_remove_from_collection)) }
TextButton(onClick = leave, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
}
if (display.isEmpty()) Text(
stringResource(if (album.tracks.isEmpty()) R.string.soundtracks_no_tracks else R.string.stores_nothing_matches),
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 12.dp),
)
else LazyColumn(
state = state,
modifier = Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(Color.Black.copy(alpha = 0.28f)).testTag("soundtrack-tracks"),
) {
items(display, key = { if (it is SoundRow.Item) it.track.id else "disc-${(it as SoundRow.Disc).number}" }) { row ->
when (row) {
is SoundRow.Disc -> Text(
stringResource(R.string.soundtracks_disc, row.label), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
modifier = Modifier.fillMaxWidth().background(Color.White.copy(alpha = 0.12f)).padding(horizontal = 12.dp, vertical = 8.dp),
)
is SoundRow.Item -> {
val id = row.track.id
val flip = { picked = if (id in picked) picked - id else picked + id }
val dragging = dragId == id
val draggable = canReorder && id in picked
val shift = if (!canReorder) Modifier else Modifier
.zIndex(if (dragging) 1f else 0f)
.graphicsLayer {
translationY = when {
dragId == null -> 0f
dragId == id -> dragTotal
else -> {
val at = drag.index[id] ?: -1
val f = drag.from
val t = dragTo
if (at < 0) 0f
else if (f < t && at in (f + 1)..t) -drag.size
else if (t < f && at in t until f) drag.size
else 0f
}
}
}
val dragModifier = if (!draggable) shift else shift
.pointerInput(id) {
detectDragGesturesAfterLongPress(
onDragStart = {
val base = working ?: rowsNow
val from = base.indexOfFirst { it is SoundRow.Item && it.track.id == id }
if (from >= 0) {
val disc = (base[from] as SoundRow.Item).track.disc
var lo = from
while (lo > 0 && (base[lo - 1] as? SoundRow.Item)?.track?.disc == disc) lo--
var hi = from
while (hi < base.lastIndex && (base[hi + 1] as? SoundRow.Item)?.track?.disc == disc) hi++
val visible = state.layoutInfo.visibleItemsInfo
val me = visible.firstOrNull { it.key == id }
val next = visible.firstOrNull { it.index == (me?.index ?: -2) + 1 && it.key != "disc-0" && base.getOrNull(from + 1) is SoundRow.Item }
val prev = visible.firstOrNull { it.index == (me?.index ?: -2) - 1 && base.getOrNull(from - 1) is SoundRow.Item }
val pitch = when {
me != null && next != null -> (next.offset - me.offset).toFloat()
me != null && prev != null -> (me.offset - prev.offset).toFloat()
else -> me?.size?.toFloat() ?: 0f
}
drag.base = base
drag.index = HashMap<String, Int>().also { m -> base.forEachIndexed { i, r -> if (r is SoundRow.Item) m[r.track.id] = i } }
drag.from = from
drag.lo = lo
drag.hi = hi
drag.size = if (pitch > 0f) pitch else 1f
drag.total = 0f
dragTotal = 0f
dragTo = from
dragId = id
}
},
onDrag = { change, amount ->
change.consume()
if (dragId == id) {
drag.total += amount.y
applyDrag()
}
},
onDragEnd = { finishNow() },
onDragCancel = { finishNow() },
)
}
TrackRow(
row.track, numbers[id] ?: row.track.number, dragging, dragModifier, id == current, selecting, id in picked,
onClick = {
if (selecting) flip()
else if (id == current) SoundtrackController.toggle(ctx, album, title, target.root, target.collection)
else SoundtrackController.play(ctx, album, title, id, root = target.root, collection = target.collection)
},
onLongClick = if (draggable) null else ({
if (selecting) flip()
else {
selecting = true
picked = setOf(id)
}
}),
)
}
}
}
}
}
if (saving) SavedDialog(chosen, null) {
saving = false
leave()
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TrackRow(
track: Soundtrack.Track, number: Int, dragging: Boolean, extra: Modifier, current: Boolean, selecting: Boolean, selected: Boolean,
onClick: () -> Unit, onLongClick: (() -> Unit)?,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(8.dp)
val tint = if (current) pal.signal else colors.onBackground
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = extra.fillMaxWidth().padding(horizontal = 4.dp, vertical = 1.dp).clip(shape)
.background(if (dragging) pal.signal.copy(alpha = 0.32f) else if (selected) pal.signal.copy(alpha = 0.24f) else if (current) pal.signal.copy(alpha = 0.14f) else if (hot) Color.White.copy(alpha = 0.08f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, Color.Transparent)
.hoverable(src)
.combinedClickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onLongClick = onLongClick, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 10.dp, vertical = 9.dp),
) {
Box(Modifier.width(28.dp), contentAlignment = Alignment.CenterEnd) {
when {
selecting -> Icon(
if (selected) Icons.Filled.CheckBox else Icons.Filled.CheckBoxOutlineBlank, contentDescription = null,
tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp),
)
current && SoundtrackController.playing -> Icon(Icons.Filled.PlayArrow, contentDescription = null, tint = tint, modifier = Modifier.size(16.dp))
else -> Text("$number.", fontSize = 13.sp, color = if (current) pal.signal else colors.onSurfaceVariant, maxLines = 1)
}
}
Text(
track.title, fontSize = 14.sp, color = tint, fontWeight = if (current) FontWeight.SemiBold else FontWeight.Normal,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
if (track.durationMs > 0) Text(Soundtrack.formatLength(track.durationMs), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
private class DragState {
var base: List<SoundRow> = emptyList()
var index: Map<String, Int> = emptyMap()
var from = 0
var lo = 0
var hi = 0
var size = 1f
var total = 0f
}
internal fun dragTarget(total: Float, size: Float, from: Int, lo: Int, hi: Int): Int =
(from + Math.round(total / size)).coerceIn(lo, hi)
@@ -25,6 +25,8 @@ internal const val FLATHUB = "flathub"
internal class SourceColours(val fill: Color, val ink: Color, val dot: Color)
internal val FavoritesColours = SourceColours(Color(0xFF3D1A26), Color(0xFFFFB3C8), Color(0xFFFF5C8A))
internal fun sourceColours(source: String): SourceColours = when (source) {
Store.GOG.id -> SourceColours(Color(0xFF3A1A3C), Color(0xFFE6A3EA), Color(0xFFC25BC8))
Store.EPIC.id -> SourceColours(Color(0xFF2A2A2A), Color(0xFFDDDDDD), Color(0xFFBDBDBD))
@@ -37,6 +39,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747))
Store.ROCKSTAR.id -> SourceColours(Color(0xFF3A2A06), Color(0xFFFFD780), Color(0xFFFCAF17))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
Library.SOURCE_COLLECTION -> SourceColours(Color(0xFF2B1A3D), Color(0xFFD2A8FF), Color(0xFFA25BFF))
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
}
@@ -44,6 +47,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
@Composable
internal fun sourceLabel(source: String): String = when (source) {
Library.SOURCE_STEAM -> stringResource(R.string.source_steam)
Library.SOURCE_COLLECTION -> stringResource(R.string.soundtracks_collections)
Store.GOG.id -> Store.GOG.label
Store.EPIC.id -> Store.EPIC.label
Store.AMAZON.id -> Store.AMAZON.label
@@ -58,10 +62,10 @@ internal fun sourceLabel(source: String): String = when (source) {
}
@Composable
internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifier = Modifier) {
val c = sourceColours(source)
internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifier = Modifier, label: String? = null, colours: SourceColours? = null) {
val c = colours ?: sourceColours(source)
Text(
sourceLabel(source), fontSize = if (small) 10.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.4.sp,
label ?: sourceLabel(source), fontSize = if (small) 10.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.4.sp,
color = c.ink, maxLines = 1,
modifier = modifier.clip(RoundedCornerShape(6.dp)).background(c.fill)
.padding(horizontal = if (small) 6.dp else 8.dp, vertical = if (small) 1.dp else 2.dp),