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

@@ -206,6 +206,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var lowStorageWarning by mutableStateOf(true)
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true)
private var soundtracksEnabled by mutableStateOf(true)
private var soundtracksIngame by mutableStateOf(false)
private var soundtracks by mutableStateOf<List<Library.SteamGame>>(emptyList())
private var soundtracksLoaded by mutableStateOf(false)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf<String?>(null)
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
@@ -785,6 +789,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var shortcutPicker by mutableStateOf(false)
private var shortcutLibraryScanning by mutableStateOf(false)
@Volatile private var libraryScanGeneration = 0
private class SoundtrackRemoval(val op: Int, var scan: Int, var settled: Boolean)
private val soundtrackRemovals = HashMap<String, SoundtrackRemoval>()
private var soundtrackOp = 0
private var soundtrackAddScan = -1
private val soundtrackWork = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-work").apply { isDaemon = true } }
@Volatile private var lastComponentRestore = 0L
@Volatile private var componentRestoreRetry = false
private val componentRestoreLock = Any()
@@ -847,6 +856,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
pendingGameLink = null
gameLinkReading = false
gameLinkTried = false
soundtrackLaunch = false
val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request)
if (soundtrackId != null) {
soundtrackLaunch = true
navRequest = if (SessionPrefs.soundtracksEnabled(this)) "sound:$soundtrackId" else "app:$soundtrackId"
request.data = null
request.action = Intent.ACTION_MAIN
return
}
if (GameLaunchIntent.accepts(request.action)) {
gameLinkReading = true
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
@@ -871,6 +889,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
if (pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
@@ -1144,6 +1163,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
LauncherIcon.repair(this, intent?.component)
launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
soundtracksEnabled = SessionPrefs.soundtracksEnabled(this)
soundtracksIngame = SessionPrefs.soundtracksIngame(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
storesShowMature = SessionPrefs.storesShowMature(this)
storesSort = SessionPrefs.storesSort(this)
@@ -1239,6 +1260,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
lowStorageWarning = lowStorageWarning,
launcherIcon = launcherIcon,
gameStoresEnabled = gameStoresEnabled,
soundtracksEnabled = soundtracksEnabled,
soundtracksIngame = soundtracksIngame,
soundtracks = soundtracks,
soundtracksLoaded = soundtracksLoaded,
gameStoresSpeedTier = gameStoresSpeedTier,
navigate = navRequest,
addedGamesArt = addedGamesArt,
@@ -1287,7 +1312,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
},
onEpicLauncher = { openEpicLauncher() },
onUninstallEpicLauncher = { uninstallEpicLauncher() },
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
onGameShortcut = { g ->
if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.pin(this, g)
else com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g)
},
onExportGameFile = { g -> pickGameExport(g) },
onSyncGameFiles = { pickGameExport(null) },
onAddGameExe = { path -> addGameExe(path) },
@@ -1312,8 +1340,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}, "game-file-stop-sync").start()
},
onCopyGameLink = { g ->
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
ClipData.newPlainText(g.name, com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)))
val link = if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.uri(g.appId)
else com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText(g.name, link))
android.widget.Toast.makeText(this, R.string.game_link_copied, android.widget.Toast.LENGTH_SHORT).show()
},
onDesktop = {
@@ -1338,6 +1367,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
},
onRom = { g ->
val e = emulatorList.first { it.id == g.emulatorId }
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, e.program)
@@ -1506,6 +1536,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
},
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
onSoundtracksEnabled = { on -> SessionPrefs.setSoundtracksEnabled(this, on); soundtracksEnabled = on },
onSoundtracksIngame = { on ->
SessionPrefs.setSoundtracksIngame(this, on)
soundtracksIngame = on
com.droiddeck.launcher.playback.SoundtrackController.setIngame(this, on)
},
onSoundtrackAdded = { folder -> addSoundtrack(folder) },
onSoundtracksChanged = { refreshAddedSoundtracks() },
onSoundtrackRemoved = { g -> removeSoundtrack(g) },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
onLauncherIcon = { style -> switchLauncherIcon(style) },
onLanguage = { tag ->
@@ -1799,7 +1838,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
startSteamAtStartupIfEnabled()
}
private var soundtrackLaunch = false
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
if (soundtrackLaunch) return
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
if (isFinishing || isDestroyed) return
when (SessionPrefs.startupSession(this)) {
@@ -2644,15 +2686,89 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
val version = (steamArtRefreshes[appId] ?: 0) + 1
steamArtRefreshes[appId] = version
Thread({
val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this).firstOrNull { it.appId == appId } ?: return@Thread
val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this, soundtracks = true).firstOrNull { it.appId == appId } ?: return@Thread
ui.post {
if (steamArtRefreshes[appId] != version) return@post
steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
if (fresh.soundtrack) soundtracks = soundtracks.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
else steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
}
}, "steam-art-update").start()
}
private fun addSoundtrack(folder: java.io.File) {
val op = ++soundtrackOp
soundtrackAddScan = libraryScanGeneration
soundtrackWork.execute {
val added = com.droiddeck.launcher.frontend.AddedSoundtracks.add(this, folder)
val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
ui.post {
if (added) {
soundtrackRemovals[folder.path]?.takeIf { it.op < op }?.let {
soundtrackRemovals.remove(folder.path)
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(folder.path))
}
val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] }?.let { it.op > op } == true }
soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible
} else android.widget.Toast.makeText(this, R.string.soundtracks_add_empty, android.widget.Toast.LENGTH_SHORT).show()
}
}
}
private fun refreshAddedSoundtracks() {
val op = soundtrackOp
soundtrackWork.execute {
val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
ui.post {
if (op != soundtrackOp) return@post
val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null }
soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible
}
}
}
private fun removeSoundtrack(g: Library.SteamGame) {
val path = g.gameFiles?.path
val added = g.library == Library.ADDED
val target = if (added) null else com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
com.droiddeck.launcher.playback.SoundtrackController.stopIf(this, g.gameFiles)
val marker = SoundtrackRemoval(++soundtrackOp, libraryScanGeneration, added)
path?.let { soundtrackRemovals[it] = marker }
if (target == null) {
soundtracks = soundtracks.filterNot { it.appId == g.appId && it.library == Library.ADDED }
soundtrackWork.execute {
val removed = com.droiddeck.launcher.frontend.AddedSoundtracks.remove(this, path.orEmpty())
val list = if (removed) emptyList() else com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
if (!removed) ui.post {
if (path != null && soundtrackRemovals[path] === marker) {
soundtrackRemovals.remove(path)
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path))
}
soundtracks = soundtracks.filter { it.library != Library.ADDED } + list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null }
android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show()
}
}
return
}
soundtrackWork.execute {
val deleted = com.droiddeck.launcher.frontend.GameRemoval.delete(target)
ui.post {
if (deleted) {
marker.scan = libraryScanGeneration
marker.settled = true
} else {
if (path != null && soundtrackRemovals[path] === marker) {
soundtrackRemovals.remove(path)
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path))
}
android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show()
}
refresh()
}
}
}
private fun removeGame(g: Library.SteamGame) {
if (g.soundtrack) { removeSoundtrack(g); return }
val folder = g.gameFiles ?: return
when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) {
com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit
@@ -2936,6 +3052,19 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
val scannedArch = SessionPrefs.activeSteamClientArch(this)
val scannedX64 = scannedArch == "x86_64"
val scannedSoundtracks = runCatching {
(if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.soundtracks(this, scannedArch) else emptyList()) +
com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
}.getOrDefault(emptyList())
ui.post {
if (scanGeneration == libraryScanGeneration) {
val scanned = if (scanGeneration <= soundtrackAddScan) scannedSoundtracks + soundtracks.filter { cur -> cur.library == Library.ADDED && scannedSoundtracks.none { it.library == Library.ADDED && it.appId == cur.appId } } else scannedSoundtracks
val kept = scanned.filterNot { s -> s.gameFiles?.path?.let { p -> soundtrackRemovals[p]?.let { m -> !m.settled || s.library == Library.ADDED || scanGeneration <= m.scan } } == true }
com.droiddeck.launcher.playback.SoundtrackController.allow(kept.mapNotNull { it.gameFiles?.path })
soundtracks = kept
soundtracksLoaded = true
}
}
val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
val all = games.distinctBy { it.gameId }
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
@@ -0,0 +1,69 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object AddedSoundtracks {
private fun file(context: Context) = File(context.filesDir, "added-soundtracks.json")
class Entry(val path: String, val name: String, val id: Int = 0)
internal fun assignIds(list: List<Entry>): List<Entry> {
val used = list.filter { it.id != 0 }.map { it.id }.toMutableSet()
return list.map { e ->
if (e.id != 0) e else {
var id = idOf(e.path)
while (id == 0 || !used.add(id)) id = (id + 1) or Int.MIN_VALUE
Entry(e.path, e.name, id)
}
}
}
@Synchronized
fun entries(context: Context): List<Entry> = runCatching {
val f = file(context).takeIf { it.isFile } ?: return emptyList()
val array = JSONArray(f.readText())
val raw = List(array.length()) { i -> array.getJSONObject(i).let { Entry(it.getString("path"), it.getString("name"), it.optInt("id", 0)) } }
val ready = assignIds(raw)
if (raw.any { it.id == 0 }) save(context, ready)
ready
}.getOrDefault(emptyList())
@Synchronized
private fun save(context: Context, list: List<Entry>): Boolean =
runCatching {
val array = JSONArray()
list.forEach { array.put(JSONObject().put("path", it.path).put("name", it.name).put("id", it.id)) }
val f = file(context)
val tmp = File(f.path + ".tmp")
tmp.writeText(array.toString())
if (tmp.renameTo(f)) true else { tmp.delete(); false }
}.getOrDefault(false)
fun add(context: Context, folder: File): Boolean {
if (!folder.isDirectory || Soundtrack.audioFiles(folder).isEmpty()) return false
return synchronized(this) {
val list = entries(context)
list.any { it.path == folder.path } || save(context, assignIds(list + Entry(folder.path, folder.name)))
}
}
fun remove(context: Context, path: String): Boolean =
synchronized(this) { save(context, entries(context).filterNot { it.path == path }) }
internal fun idOf(path: String): Int = path.hashCode() or Int.MIN_VALUE
fun games(context: Context): List<Library.SteamGame> = entries(context).mapNotNull { e ->
val dir = File(e.path).takeIf { it.isDirectory } ?: return@mapNotNull null
game(context, e, dir, e.id)
}
private fun game(context: Context, e: Entry, dir: File, id: Int): Library.SteamGame {
return Library.SteamGame(
appId = id, name = e.name, art = SoundtrackCollectionArt.chosen(context, id) ?: Soundtrack.firstCover(context, dir), library = Library.ADDED, gameId = id.toLong() and 0xFFFFFFFFL,
gameFiles = dir, source = Library.ADDED, soundtrack = true,
)
}
}
@@ -21,7 +21,7 @@ object GameRemoval {
fun steamFiles(game: Library.SteamGame): SteamFiles? {
val dir = game.gameFiles ?: return null
val common = dir.parentFile ?: return null
if (common.name != "common") return null
if (common.name != (if (game.soundtrack) "music" else "common")) return null
val steamapps = common.parentFile ?: return null
if (steamapps.name != "steamapps") return null
val manifest = File(steamapps, "appmanifest_${game.appId}.acf")
@@ -19,9 +19,10 @@ object Library {
val storeId: String? = null,
val logo: File? = null,
val installedAt: Long = 0L,
val soundtrack: Boolean = false,
) {
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt)
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt, soundtrack)
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
val launchKey: String get() = if (storeId != null) "$source:$storeId" else gameIdString
@@ -38,6 +39,7 @@ object Library {
const val BATTLENET_LAUNCHER = "battlenet-launcher"
const val XBOX_CLOUD = "xbox-cloud"
const val SOURCE_STEAM = "steam"
const val SOURCE_COLLECTION = "collection"
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
@@ -123,9 +125,12 @@ object Library {
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
}
fun soundtracks(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> =
steamGames(context, arch = arch, withShared = false, soundtracks = true, soundtracksOnly = true)
fun steamGames(
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
withShared: Boolean = true,
withShared: Boolean = true, soundtracks: Boolean = false, soundtracksOnly: Boolean = false,
onlyAppIds: Set<Int>? = null,
): List<SteamGame> {
val root = SessionPrefs.steamRoot(context, arch)
@@ -146,16 +151,19 @@ object Library {
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
if (name.isEmpty() || flags and 4 == 0) return@forEach
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
val musicFiles = if (gameFiles == null) installDir?.let { File(steamapps, "music/$it").takeIf(File::isDirectory) } else null
if (musicFiles != null && !soundtracks) return@forEach
if (soundtracksOnly && musicFiles == null) return@forEach
val images = SteamCacheImages(File(cache, appId.toString()))
val art = images.find(STEAM_CAPSULES)
val hero = images.find(STEAM_HEROES)
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
out[appId] = SteamGameArt.withOverrides(context, SteamGame(
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles,
appId, name, art ?: musicFiles?.let { Soundtrack.firstCover(context, it) }, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles ?: musicFiles, soundtrack = musicFiles != null,
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
icon = images.icon(),
logo = images.find(STEAM_LOGOS),
@@ -177,6 +185,7 @@ object Library {
strictRead = strictRead,
arch = other,
withShared = false,
soundtracks = soundtracks,
onlyAppIds = shared,
)
} catch (e: Exception) {
@@ -0,0 +1,308 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.media.MediaMetadataRetriever
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object Soundtrack {
class Track(
val file: File, val title: String, val disc: Int, val number: Int, val durationMs: Long, val artist: String = "",
val discLabel: String = disc.toString(),
) {
val id: String get() = file.path
}
class Album(val disc: Map<Int, List<Track>>, val artist: String, val cover: File?) {
val tracks: List<Track> get() = disc.values.flatten()
val discs: List<Int> get() = disc.keys.toList()
val multiDisc: Boolean get() = disc.size > 1
val totalMs: Long get() = tracks.sumOf { it.durationMs }
}
class Raw(
val file: File, val folder: String, val tagDisc: Int?, val tagTrack: Int?, val tagTitle: String?, val tagArtist: String?,
val durationMs: Long, val size: Long = file.length(),
)
val EXTENSIONS = setOf("mp3", "flac", "ogg", "oga", "opus", "wav", "m4a", "aac")
private val LOSSLESS = setOf("flac", "wav")
private val COVERS = listOf("AlbumArtwork", "albumartwork", "cover", "Cover", "folder", "Folder", "front", "Front", "artwork", "Artwork")
internal val COVER_EXT = listOf("png", "jpg", "jpeg", "webp")
private val LEADING = Regex("^\\s*\\d+\\s*[.\\-_)]*\\s+")
private val DIGITS = Regex("^\\s*(\\d+)")
fun isAudio(file: File): Boolean = file.isFile && file.extension.lowercase() in EXTENSIONS
fun cleanTitle(fileName: String): String {
val base = fileName.substringBeforeLast('.', fileName).trim()
val tail = if (" - " in base) base.substringAfterLast(" - ") else base
val stripped = tail.replace(LEADING, "").trim()
return stripped.ifEmpty { tail.ifEmpty { base } }
}
internal fun leadingNumber(fileName: String): Int? = DIGITS.find(fileName.substringAfterLast(" - "))?.groupValues?.get(1)?.toIntOrNull()
private fun identity(r: Raw): String {
val d = r.tagDisc
val t = r.tagTrack
if (d != null && t != null) return "n:$d:$t"
val title = (r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name)).lowercase().filter { it.isLetterOrDigit() }
return "t:$title:${leadingNumber(r.file.name)}"
}
private fun better(a: Raw, b: Raw): Raw {
val la = a.file.extension.lowercase() in LOSSLESS
val lb = b.file.extension.lowercase() in LOSSLESS
return when {
la != lb -> if (la) a else b
a.size != b.size -> if (a.size > b.size) a else b
else -> if (a.file.path <= b.file.path) a else b
}
}
fun group(raws: List<Raw>): Map<Int, List<Track>> {
if (raws.isEmpty()) return emptyMap()
val unique = LinkedHashMap<String, Raw>()
val home = HashMap<String, String>()
val disc = HashMap<String, Int>()
val track = HashMap<String, Int>()
val title = HashMap<String, String>()
for (r in raws) {
val id = identity(r)
unique[id] = unique[id]?.let { better(it, r) } ?: r
if (r.folder.isNotEmpty() && home[id].isNullOrEmpty()) home[id] = r.folder
r.tagDisc?.let { disc.putIfAbsent(id, it) }
r.tagTrack?.let { track.putIfAbsent(id, it) }
r.tagTitle?.takeIf { it.isNotBlank() }?.let { title.putIfAbsent(id, it) }
}
val kept = unique.map { (id, r) ->
Raw(
r.file, home[id] ?: r.folder, disc[id] ?: r.tagDisc, track[id] ?: r.tagTrack, title[id] ?: r.tagTitle, r.tagArtist,
r.durationMs, r.size,
)
}
val folders = kept.filter { it.tagDisc == null }.map { it.folder }.distinct().sortedWith(naturalOrder)
val discs = kept.groupBy { r ->
r.tagDisc ?: if (folders.size <= 1 && kept.none { it.tagDisc != null }) 0 else folders.indexOf(r.folder) + 1
}
return discs.toSortedMap().mapValues { (disc, list) ->
list.sortedWith(
compareBy<Raw>({ leadingNumber(it.file.name) ?: it.tagTrack ?: Int.MAX_VALUE }, { it.tagTrack ?: Int.MAX_VALUE }, { it.file.name.lowercase() }),
).mapIndexed { i, r ->
Track(
r.file, r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name), disc, i + 1,
r.durationMs, r.tagArtist.orEmpty(), labelOf(r, disc),
)
}
}
}
private val FOLDER_LABEL = Regex("[0-9][0-9 +&,.\\-]*")
private fun labelOf(r: Raw, disc: Int): String {
if (r.tagDisc != null) return disc.toString()
val name = r.folder.substringAfterLast('/')
return if (FOLDER_LABEL.matches(name)) name else disc.toString()
}
private val naturalOrder = Comparator<String> { a, b ->
val x = Regex("\\d+|\\D+").findAll(a.lowercase()).map { it.value }.toList()
val y = Regex("\\d+|\\D+").findAll(b.lowercase()).map { it.value }.toList()
var i = 0
var out = 0
while (out == 0 && i < minOf(x.size, y.size)) {
val nx = x[i].toBigIntegerOrNull()
val ny = y[i].toBigIntegerOrNull()
out = if (nx != null && ny != null) nx.compareTo(ny) else x[i].compareTo(y[i])
i++
}
if (out != 0) out else x.size.compareTo(y.size)
}
fun cover(dir: File): File? {
for (name in COVERS) for (ext in COVER_EXT) File(dir, "$name.$ext").takeIf { it.isFile }?.let { return it }
return dir.listFiles()?.filter { it.isFile && it.extension.lowercase() in COVER_EXT }?.minByOrNull { it.name.lowercase() }
}
private fun parseNumber(value: String?): Int? = value?.substringBefore('/')?.trim()?.toIntOrNull()
private fun read(file: File, root: File): Raw {
val folder = file.parentFile?.let { parent ->
if (parent.path == root.path) "" else parent.path.removePrefix(root.path).trimStart('/')
}.orEmpty()
val retriever = MediaMetadataRetriever()
return try {
retriever.setDataSource(file.path)
Raw(
file, folder,
parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER)),
parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER)),
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE),
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
?: retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST),
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L,
)
} catch (e: Exception) {
Raw(file, folder, null, null, null, null, 0L)
} finally {
runCatching { retriever.release() }
}
}
private fun cacheFile(context: Context, root: File) = File(context.filesDir, "soundtrack-index/${root.path.hashCode().toUInt()}.json")
private fun fromCache(context: Context, root: File, files: List<File>): List<Raw>? = runCatching {
val f = cacheFile(context, root).takeIf { it.isFile } ?: return null
val json = JSONObject(f.readText())
if (json.optString("root") != root.path) return null
val rows = json.getJSONArray("rows")
val byPath = HashMap<String, JSONObject>()
for (i in 0 until rows.length()) rows.getJSONObject(i).let { byPath[it.getString("p")] = it }
if (byPath.size != files.size) return null
files.map { file ->
val row = byPath[file.path] ?: return null
if (row.getLong("s") != file.length() || row.getLong("m") != file.lastModified()) return null
Raw(
file, row.getString("f"), row.optInt("d", -1).takeIf { it >= 0 }, row.optInt("n", -1).takeIf { it >= 0 },
row.optString("t").takeIf { it.isNotEmpty() }, row.optString("a").takeIf { it.isNotEmpty() }, row.optLong("l"),
)
}
}.getOrNull()
private fun toCache(context: Context, root: File, raws: List<Raw>) {
runCatching {
val rows = JSONArray()
for (r in raws) rows.put(
JSONObject().put("p", r.file.path).put("s", r.file.length()).put("m", r.file.lastModified()).put("f", r.folder)
.put("d", r.tagDisc ?: -1).put("n", r.tagTrack ?: -1).put("t", r.tagTitle.orEmpty()).put("a", r.tagArtist.orEmpty())
.put("l", r.durationMs),
)
val f = cacheFile(context, root)
f.parentFile?.mkdirs()
val tmp = File(f.path + ".tmp")
tmp.writeText(JSONObject().put("root", root.path).put("rows", rows).toString())
if (!tmp.renameTo(f)) tmp.delete()
}
}
fun audioFiles(root: File): List<File> {
val out = ArrayList<File>()
fun walk(dir: File, depth: Int) {
val children = dir.listFiles() ?: return
for (c in children.sortedBy { it.name.lowercase() }) {
if (c.isDirectory) { if (depth < 4) walk(c, depth + 1) } else if (isAudio(c)) out += c
}
}
walk(root, 0)
return out
}
private fun coverCache(context: Context, root: File): File {
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(root.path.toByteArray(Charsets.UTF_8))
val key = digest.take(16).joinToString("") { "%02x".format(it) }
return File(context.filesDir, "soundtrack-index/cover-$key.jpg")
}
fun cachedCover(context: Context, root: File): File? = coverCache(context, root).takeIf { it.isFile && it.length() > 0L }
private fun embeddedBytes(file: File): ByteArray? = runCatching {
val retriever = MediaMetadataRetriever()
try {
retriever.setDataSource(file.path)
retriever.embeddedPicture
} finally {
runCatching { retriever.release() }
}
}.getOrNull()?.takeIf { it.isNotEmpty() }
private fun hashOf(bytes: ByteArray): String =
java.security.MessageDigest.getInstance("SHA-256").digest(bytes).take(16).joinToString("") { "%02x".format(it) }
private fun embeddedCover(context: Context, root: File, files: List<File>): File? {
cachedCover(context, root)?.let { return it }
val miss = File(coverCache(context, root).path + ".none")
val probed = files.take(8)
val signature = hashOf(probed.joinToString("\n") { "${it.path}|${it.length()}|${it.lastModified()}" }.toByteArray(Charsets.UTF_8))
if (runCatching { miss.isFile && miss.readText().trim() == signature }.getOrDefault(false)) return null
for (file in probed) {
val bytes = embeddedBytes(file) ?: continue
val out = coverCache(context, root)
runCatching {
out.parentFile?.mkdirs()
out.writeBytes(bytes)
}.onSuccess { return out }
}
runCatching {
miss.parentFile?.mkdirs()
miss.writeText(signature)
}
return null
}
fun firstCover(context: Context, root: File): File? = cover(root) ?: embeddedCover(context, root, audioFiles(root))
@Synchronized
fun trackCover(context: Context, file: File): File? {
val dir = File(context.filesDir, "soundtrack-index/track-covers")
val marker = File(dir, "t-" + hashOf("${file.path}|${file.length()}|${file.lastModified()}".toByteArray(Charsets.UTF_8)))
if (marker.isFile) {
val name = runCatching { marker.readText().trim() }.getOrDefault("")
if (name.isEmpty()) return null
File(dir, name).takeIf { it.isFile && it.length() > 0L }?.let {
val now = System.currentTimeMillis()
marker.setLastModified(now)
it.setLastModified(now)
return it
}
}
val bytes = embeddedBytes(file)
return runCatching {
dir.mkdirs()
if (bytes == null) {
marker.writeText("")
prune(dir, setOf(marker.name))
null
} else {
val out = File(dir, "c-" + hashOf(bytes) + ".jpg")
if (!out.isFile || out.length() == 0L) out.writeBytes(bytes)
marker.writeText(out.name)
prune(dir, setOf(marker.name, out.name))
out
}
}.getOrNull()
}
private const val TRACK_COVER_BYTES = 64L * 1024 * 1024
private const val TRACK_COVER_FILES = 2000
private fun prune(dir: File, keep: Set<String>) {
val all = dir.listFiles()?.filter { it.isFile } ?: return
var bytes = all.sumOf { it.length() }
var count = all.size
for (f in all.sortedBy { it.lastModified() }) {
if (bytes <= TRACK_COVER_BYTES && count <= TRACK_COVER_FILES) break
if (f.name in keep) continue
bytes -= f.length()
count--
f.delete()
}
}
fun load(context: Context, root: File, coverHint: File? = null): Album {
val files = audioFiles(root)
val raws = fromCache(context, root, files) ?: files.map { read(it, root) }.also { toCache(context, root, it) }
val disc = SoundtrackOrder.apply(context, root, group(raws))
val artist = disc.values.flatten().map { it.artist }.filter { it.isNotBlank() }.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key.orEmpty()
return Album(disc, artist, coverHint ?: cover(root) ?: embeddedCover(context, root, files))
}
fun formatLength(ms: Long): String {
val total = ms / 1000
val h = total / 3600
val m = (total % 3600) / 60
val s = total % 60
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s)
}
}
@@ -0,0 +1,50 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import java.io.File
object SoundtrackCollectionArt {
internal fun dir(context: Context, id: Int) = File(context.filesDir, "soundtrack-art/$id")
private fun sourceFile(context: Context, id: Int) = File(dir(context, id), "source")
fun chosen(context: Context, id: Int): File? = dir(context, id).takeIf { it.isDirectory }?.let { AddedGameArt.chosen(it, AddedGameArt.Slot.COVER) }
fun source(context: Context, id: Int): String =
sourceFile(context, id).takeIf { it.isFile }?.readText()?.trim().orEmpty().substringAfter('|', "")
fun options(context: Context, id: Int, root: File?): List<AddedGameArt.Option> {
val paths = if (root != null) {
val images = root.listFiles()?.filter { it.isFile && it.extension.lowercase() in Soundtrack.COVER_EXT }?.sortedBy { it.name.lowercase() }.orEmpty()
(images + listOfNotNull(Soundtrack.firstCover(context, root))).map { it.path }
} else SoundtrackCollections.tracksOf(id).map { it.cover }
return paths.filter { it.isNotEmpty() && File(it).isFile }.distinct().map { AddedGameArt.Option(AddedGameArt.FOLDER, it, it) }
}
fun choose(context: Context, id: Int, option: AddedGameArt.Option): Boolean {
val folder = dir(context, id)
val fresh = AddedGameArt.storeNew(folder, AddedGameArt.Slot.COVER, option) ?: return false
AddedGameArt.dropOlder(folder, AddedGameArt.Slot.COVER, fresh)
sourceFile(context, id).writeText(option.group + "|" + option.full)
return true
}
fun reset(context: Context, id: Int) {
chosen(context, id)?.delete()
sourceFile(context, id).delete()
}
fun describe(context: Context, id: Int, root: File? = null): List<AddedGameArt.SlotState> {
val own = chosen(context, id)
val state = if (own != null) AddedGameArt.SlotState(AddedGameArt.Slot.COVER, own, AddedGameArt.FILE, true)
else {
val auto = if (root != null) Soundtrack.firstCover(context, root) else SoundtrackCollections.autoCover(id)
AddedGameArt.SlotState(AddedGameArt.Slot.COVER, auto, if (auto != null) AddedGameArt.FOLDER else AddedGameArt.AUTO, false)
}
return listOf(state)
}
fun clear(context: Context, id: Int) {
dir(context, id).deleteRecursively()
}
}
@@ -0,0 +1,191 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import androidx.compose.runtime.mutableStateOf
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.Executors
object SoundtrackCollections {
const val FAVORITES_ID = 2_000_000_000
class TrackRef(val path: String, val title: String, val artist: String, val album: String, val durationMs: Long, val cover: String = "")
class Collection(val id: Int, val name: String, val tracks: List<TrackRef>)
class Snapshot(val favorites: List<TrackRef>, val collections: List<Collection>)
private val state = mutableStateOf(Snapshot(emptyList(), emptyList()))
private var loaded = false
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-collections").apply { isDaemon = true } }
val snapshot: Snapshot get() = state.value
private fun file(context: Context) = File(context.filesDir, "soundtrack-collections.json")
internal fun toggled(list: List<TrackRef>, ref: TrackRef): List<TrackRef> =
if (list.any { it.path == ref.path }) list.filterNot { it.path == ref.path } else list + ref
internal fun merged(list: List<TrackRef>, add: List<TrackRef>): List<TrackRef> {
val have = list.mapTo(HashSet()) { it.path }
return list + add.filter { have.add(it.path) }
}
internal fun cleanName(raw: String): String = raw.trim().replace(Regex("\\s+"), " ")
internal fun nameTaken(collections: List<Collection>, name: String, except: Int? = null): Boolean =
collections.any { it.id != except && it.name.equals(name, ignoreCase = true) }
internal fun nextId(collections: List<Collection>): Int =
(collections.maxOfOrNull { it.id } ?: FAVORITES_ID).coerceAtLeast(FAVORITES_ID) + 1
private fun encode(s: Snapshot): String {
fun refs(list: List<TrackRef>) = JSONArray().also { array ->
list.forEach {
array.put(
JSONObject().put("path", it.path).put("title", it.title).put("artist", it.artist).put("album", it.album)
.put("duration", it.durationMs).put("cover", it.cover),
)
}
}
val collections = JSONArray()
s.collections.forEach { collections.put(JSONObject().put("id", it.id).put("name", it.name).put("tracks", refs(it.tracks))) }
return JSONObject().put("favorites", refs(s.favorites)).put("collections", collections).toString()
}
private fun decode(text: String): Snapshot {
fun refs(array: JSONArray?): List<TrackRef> = if (array == null) emptyList() else List(array.length()) { i ->
array.getJSONObject(i).let {
TrackRef(it.getString("path"), it.optString("title"), it.optString("artist"), it.optString("album"), it.optLong("duration"), it.optString("cover"))
}
}
val root = JSONObject(text)
val collections = root.optJSONArray("collections")
return Snapshot(
refs(root.optJSONArray("favorites")),
if (collections == null) emptyList() else List(collections.length()) { i ->
collections.getJSONObject(i).let { Collection(it.getInt("id"), it.getString("name"), refs(it.optJSONArray("tracks"))) }
},
)
}
@Synchronized
fun load(context: Context) {
if (loaded) return
loaded = true
val f = file(context)
if (f.isFile) runCatching { state.value = decode(f.readText()) }
}
private fun commit(context: Context, next: Snapshot) {
state.value = next
val f = file(context)
val json = encode(next)
writer.execute {
runCatching {
val tmp = File(f.path + ".tmp")
tmp.writeText(json)
if (!tmp.renameTo(f)) tmp.delete()
}
}
}
fun tracksOf(id: Int): List<TrackRef> =
if (id == FAVORITES_ID) snapshot.favorites else snapshot.collections.firstOrNull { it.id == id }?.tracks.orEmpty()
fun isFavorite(path: String): Boolean = snapshot.favorites.any { it.path == path }
@Synchronized
fun toggleFavorite(context: Context, ref: TrackRef) {
load(context)
val s = snapshot
commit(context, Snapshot(toggled(s.favorites, ref), s.collections))
}
@Synchronized
fun create(context: Context, rawName: String, tracks: List<TrackRef>): Int? {
load(context)
val s = snapshot
val name = cleanName(rawName)
if (name.isEmpty() || nameTaken(s.collections, name)) return null
val id = nextId(s.collections)
commit(context, Snapshot(s.favorites, s.collections + Collection(id, name, merged(emptyList(), tracks))))
return id
}
@Synchronized
fun rename(context: Context, id: Int, rawName: String): Boolean {
load(context)
val s = snapshot
val name = cleanName(rawName)
if (id == FAVORITES_ID || name.isEmpty() || nameTaken(s.collections, name, id)) return false
commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, name, it.tracks) else it }))
return true
}
@Synchronized
fun delete(context: Context, id: Int) {
load(context)
val s = snapshot
if (id == FAVORITES_ID) return
commit(context, Snapshot(s.favorites, s.collections.filterNot { it.id == id }))
SoundtrackCollectionArt.clear(context, id)
}
@Synchronized
fun add(context: Context, id: Int, tracks: List<TrackRef>) {
load(context)
val s = snapshot
if (id == FAVORITES_ID) commit(context, Snapshot(merged(s.favorites, tracks), s.collections))
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, merged(it.tracks, tracks)) else it }))
}
@Synchronized
fun remove(context: Context, id: Int, paths: Set<String>) {
load(context)
val s = snapshot
if (id == FAVORITES_ID) commit(context, Snapshot(s.favorites.filterNot { it.path in paths }, s.collections))
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, it.tracks.filterNot { t -> t.path in paths }) else it }))
}
@Synchronized
fun reorder(context: Context, id: Int, ordered: List<String>) {
load(context)
val s = snapshot
fun arrange(list: List<TrackRef>): List<TrackRef> {
val byPath = list.associateBy { it.path }
val placed = ordered.mapNotNull { byPath[it] }
val named = ordered.toSet()
val rest = list.filter { it.path !in named }
return placed + rest
}
if (id == FAVORITES_ID) commit(context, Snapshot(arrange(s.favorites), s.collections))
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, arrange(it.tracks)) else it }))
}
@Synchronized
fun refresh() {
state.value = Snapshot(state.value.favorites, state.value.collections)
}
internal fun autoCover(id: Int): File? = coverOf(tracksOf(id))
private fun coverOf(tracks: List<TrackRef>): File? =
tracks.firstNotNullOfOrNull { t -> t.cover.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } }
private fun game(context: Context, id: Int, name: String, tracks: List<TrackRef>): Library.SteamGame = Library.SteamGame(
appId = id, name = name, art = SoundtrackCollectionArt.chosen(context, id) ?: coverOf(tracks), library = Library.ADDED, gameId = id.toLong(),
source = Library.SOURCE_COLLECTION, soundtrack = true,
)
fun games(context: Context, favoritesLabel: String): List<Library.SteamGame> {
val s = snapshot
return listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + s.collections.map { game(context, it.id, it.name, it.tracks) }
}
fun album(context: Context, id: Int): Soundtrack.Album {
val tracks = tracksOf(id).filter { File(it.path).isFile }.mapIndexed { i, t ->
Soundtrack.Track(File(t.path), t.title, 1, i + 1, t.durationMs, t.artist)
}
return Soundtrack.Album(mapOf(1 to tracks), "", SoundtrackCollectionArt.chosen(context, id))
}
}
@@ -0,0 +1,32 @@
package com.droiddeck.launcher.frontend
import android.content.Context
object SoundtrackIndex {
class Hit(val ref: SoundtrackCollections.TrackRef, val game: Library.SteamGame)
private var cacheKey = ""
private var cache: List<Hit> = emptyList()
private fun fingerprint(dir: java.io.File?): Long =
if (dir == null) 0L else Soundtrack.audioFiles(dir).fold(17L) { h, f -> 31 * (31 * (31 * h + f.path.hashCode()) + f.length()) + f.lastModified() }
fun build(context: Context, games: List<Library.SteamGame>): List<Hit> {
val roots = games.filter { it.gameFiles != null }
val key = roots.joinToString("|") { "${it.appId}:${it.gameFiles?.path}:${it.art?.path}:${fingerprint(it.gameFiles)}" }
synchronized(this) { if (key == cacheKey) return cache }
val hits = roots.flatMap { g ->
val dir = g.gameFiles ?: return@flatMap emptyList()
val album = Soundtrack.load(context, dir, g.art)
val cover = (g.art ?: album.cover)?.path.orEmpty()
album.tracks.map { t ->
Hit(SoundtrackCollections.TrackRef(t.file.path, t.title, t.artist.ifBlank { album.artist }, g.name, t.durationMs, cover), g)
}
}
synchronized(this) {
cacheKey = key
cache = hits
}
return hits
}
}
@@ -0,0 +1,67 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import androidx.compose.runtime.mutableIntStateOf
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.Executors
object SoundtrackOrder {
private val changes = mutableIntStateOf(0)
private var cache: Map<String, List<String>>? = null
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-order").apply { isDaemon = true } }
val version: Int get() = changes.intValue
private fun file(context: Context) = File(context.filesDir, "soundtrack-order.json")
@Synchronized
private fun read(context: Context): Map<String, List<String>> {
cache?.let { return it }
val out = HashMap<String, List<String>>()
val f = file(context)
if (f.isFile) runCatching {
val json = JSONObject(f.readText())
for (key in json.keys()) {
val array = json.getJSONArray(key)
out[key] = List(array.length()) { array.getString(it) }
}
}
cache = out
return out
}
@Synchronized
fun set(context: Context, root: File, paths: List<String>) {
val next = HashMap(read(context))
next[root.path] = paths
cache = next
val body = JSONObject().also { json -> next.forEach { (k, v) -> json.put(k, JSONArray(v)) } }.toString()
val target = file(context)
writer.execute {
val tmp = File(target.path + ".tmp")
runCatching {
tmp.writeText(body)
if (!tmp.renameTo(target)) tmp.delete()
}
}
changes.intValue++
}
internal fun ordered(disc: Map<Int, List<Soundtrack.Track>>, order: List<String>): Map<Int, List<Soundtrack.Track>> {
if (order.isEmpty()) return disc
val index = HashMap<String, Int>()
order.forEachIndexed { i, p -> index.putIfAbsent(p, i) }
return disc.mapValues { (_, list) ->
list.sortedBy { index[it.file.path] ?: Int.MAX_VALUE }.mapIndexed { i, t ->
Soundtrack.Track(t.file, t.title, t.disc, i + 1, t.durationMs, t.artist, t.discLabel)
}
}
}
fun apply(context: Context, root: File, disc: Map<Int, List<Soundtrack.Track>>): Map<Int, List<Soundtrack.Track>> {
val order = read(context)[root.path] ?: return disc
return ordered(disc, order)
}
}
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.frontend
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Icon
import android.net.Uri
import android.widget.Toast
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.LauncherIcon
import com.droiddeck.launcher.R
object SoundtrackShortcuts {
private val linkPattern = Regex("droiddeck://soundtrack/(-?[0-9]{1,11})")
fun uri(appId: Int): String = "droiddeck://soundtrack/$appId"
fun parse(link: String?): Int? = link?.let { linkPattern.matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }
fun read(intent: Intent): Int? = if (intent.action == Intent.ACTION_VIEW) parse(intent.dataString) else null
private fun info(context: Context, game: Library.SteamGame): ShortcutInfo {
val name = game.name.ifBlank { context.getString(R.string.app_name) }
val icon = GameShortcuts.iconBitmap(game)?.let(Icon::createWithBitmap) ?: Icon.createWithResource(context, R.mipmap.ic_launcher)
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri(game.appId)), context, FrontEndActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
return ShortcutInfo.Builder(context, "soundtrack:${game.appId}")
.setActivity(LauncherIcon.activity(context))
.setShortLabel(name.take(40)).setLongLabel(name).setIcon(icon).setIntent(intent).build()
}
fun pin(activity: Activity, game: Library.SteamGame) {
val manager = activity.getSystemService(ShortcutManager::class.java)
val requested = runCatching {
manager.isRequestPinShortcutSupported && manager.requestPinShortcut(info(activity, game), null)
}.getOrDefault(false)
if (!requested) Toast.makeText(activity, R.string.game_shortcut_unsupported, Toast.LENGTH_LONG).show()
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.frontend
object SoundtrackTracks {
enum class Sort { DEFAULT, TITLE_ASC, TITLE_DESC, LONGEST, SHORTEST }
fun <T> sort(items: List<T>, sort: Sort, title: (T) -> String, duration: (T) -> Long): List<T> = when (sort) {
Sort.DEFAULT -> items
Sort.TITLE_ASC -> items.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, title))
Sort.TITLE_DESC -> items.sortedWith(compareByDescending(String.CASE_INSENSITIVE_ORDER, title))
Sort.LONGEST -> items.sortedByDescending(duration)
Sort.SHORTEST -> items.sortedBy(duration)
}
fun matches(query: String, vararg fields: String): Boolean {
val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() }
if (words.isEmpty()) return true
val haystack = fields.map { it.lowercase() }
return words.all { word -> haystack.any { it.contains(word) } }
}
fun rank(query: String, title: String): Int {
val q = query.trim().lowercase()
val t = title.lowercase()
return when {
t == q -> 0
t.startsWith(q) -> 1
else -> 2
}
}
}
@@ -24,11 +24,7 @@ object SteamGameArt {
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO)
if (cover == null && hero == null && icon == null && logo == null) return game
return Library.SteamGame(
game.appId, game.name, cover ?: game.art, game.library, game.gameId,
hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId,
logo ?: game.logo,
)
return game.withArt(cover ?: game.art, hero ?: game.hero, icon ?: game.icon, logo ?: game.logo)
}
fun chosenSource(context: Context, appId: Int, slot: AddedGameArt.Slot): Pair<String, String> {
@@ -0,0 +1,288 @@
package com.droiddeck.launcher.playback
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.PlaybackParameters
import androidx.media3.common.Player
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import com.droiddeck.launcher.frontend.Soundtrack
import com.google.common.util.concurrent.ListenableFuture
import java.io.File
object SoundtrackController {
var playing by mutableStateOf(false)
private set
var currentId by mutableStateOf<String?>(null)
private set
var title by mutableStateOf("")
private set
var shuffle by mutableStateOf(false)
private set
var repeat by mutableStateOf(Player.REPEAT_MODE_OFF)
private set
var durationMs by mutableStateOf(0L)
private set
var buffering by mutableStateOf(false)
private set
var volume by mutableStateOf(1f)
private set
var activeCollection by mutableStateOf<Int?>(null)
private set
var sleepEndsAt by mutableLongStateOf(0L)
private set
var sleepTrackEnd by mutableStateOf(false)
private set
private var app: Context? = null
private val removed: MutableSet<String> = java.util.Collections.synchronizedSet(HashSet())
private var activeRoot: String? = null
private var savedId: String? = null
private var future: ListenableFuture<MediaController>? = null
private var controller: MediaController? = null
private val pending = ArrayList<(MediaController) -> Unit>()
private val listener = object : Player.Listener {
override fun onEvents(player: Player, events: Player.Events) = sync(player)
}
private val disconnect = object : MediaController.Listener {
override fun onDisconnected(controller: MediaController) {
if (this@SoundtrackController.controller === controller) {
this@SoundtrackController.controller = null
future = null
reset()
}
}
}
private fun reset() {
playing = false
currentId = null
title = ""
durationMs = 0L
buffering = false
volume = 1f
activeCollection = null
}
private fun sync(player: Player) {
playing = player.isPlaying
buffering = player.playbackState == Player.STATE_BUFFERING
currentId = player.currentMediaItem?.mediaId?.takeIf { player.mediaItemCount > 0 }
title = player.mediaMetadata.title?.toString().orEmpty()
shuffle = player.shuffleModeEnabled
repeat = player.repeatMode
durationMs = player.duration.takeIf { it > 0 } ?: 0L
volume = player.volume
if (!player.playWhenReady) sleepTrackEnd = false
persistResume(player)
}
private fun persistResume(player: Player) {
val context = app ?: return
val id = currentId ?: return
if (activeCollection != null) return
val root = activeRoot ?: SoundtrackSettings.resume(context)?.root?.takeIf { id.startsWith("$it/") }?.also { activeRoot = it } ?: return
if (id != savedId || !player.isPlaying) {
savedId = id
SoundtrackSettings.saveResume(context, root, id, if (player.playbackState == Player.STATE_ENDED) 0L else player.currentPosition)
}
}
private fun applySettings(c: MediaController) {
val context = app ?: return
SoundtrackSettings.load(context)
c.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch))
c.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.skipSilence) })
sendEqualizer(c)
c.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(context)) })
}
private fun sendEqualizer(c: MediaController) {
c.sendCustomCommand(
SoundtrackService.EQUALIZER,
Bundle().apply {
putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.eqOn)
putIntArray(SoundtrackService.ARG_BANDS, SoundtrackSettings.bands.toIntArray())
putInt(SoundtrackService.ARG_BASS, SoundtrackSettings.bass)
},
)
}
private fun run(context: Context, block: (MediaController) -> Unit) {
app = context.applicationContext
val live = controller
if (live != null) { block(live); return }
pending += block
if (future != null) return
val app = context.applicationContext
val token = SessionToken(app, ComponentName(app, SoundtrackService::class.java))
val built = MediaController.Builder(app, token).setListener(disconnect)
.setConnectionHints(Bundle().apply { putBoolean(SoundtrackService.HINT_OWNER, true) }).buildAsync()
future = built
built.addListener({
val ready = runCatching { built.get() }.getOrNull()
if (ready == null) {
future = null
pending.clear()
return@addListener
}
controller = ready
ready.addListener(listener)
applySettings(ready)
sync(ready)
val queued = pending.toList()
pending.clear()
queued.forEach { it(ready) }
}, ContextCompat.getMainExecutor(app))
}
fun connect(context: Context) = run(context) { }
fun position(): Long = controller?.currentPosition ?: 0L
fun belongsCollection(id: Int): Boolean = activeCollection == id && currentId != null
fun belongs(root: File?): Boolean {
if (activeCollection != null) return false
val id = currentId ?: return false
return root != null && id.startsWith(root.path + "/")
}
private fun items(album: Soundtrack.Album, albumTitle: String): List<MediaItem> {
val cover = album.cover?.let { Uri.fromFile(it) }
return album.tracks.map { t ->
MediaItem.Builder()
.setMediaId(t.file.path)
.setMediaMetadata(
MediaMetadata.Builder()
.setTitle(t.title)
.setArtist(t.artist.ifBlank { album.artist }.ifBlank { null })
.setAlbumTitle(albumTitle)
.setTrackNumber(t.number)
.setDiscNumber(t.disc.takeIf { it > 0 })
.setArtworkUri(cover)
.setIsPlayable(true)
.build(),
)
.build()
}
}
fun play(
context: Context, album: Soundtrack.Album, albumTitle: String, startId: String?, shuffled: Boolean? = null,
root: File? = null, startMs: Long = 0L, collection: Int? = null,
) {
val list = items(album, albumTitle)
if (list.isEmpty()) return
run(context) { c ->
if (root != null && root.path in removed) return@run
val start = list.indexOfFirst { it.mediaId == startId }.coerceAtLeast(0)
root?.let { activeRoot = it.path }
activeCollection = collection
c.setMediaItems(list, start, startMs)
shuffled?.let { c.shuffleModeEnabled = it }
c.prepare()
c.play()
}
}
fun allow(paths: Collection<String>) {
removed.removeAll(paths.toSet())
}
fun toggle(context: Context, album: Soundtrack.Album, albumTitle: String, root: File?, collection: Int? = null) {
run(context) { c ->
if (root != null && root.path in removed) return@run
val mine = if (collection != null) belongsCollection(collection) else belongs(root)
if (mine && c.mediaItemCount > 0) {
if (c.isPlaying) c.pause() else {
if (c.playbackState == Player.STATE_ENDED) c.seekToDefaultPosition(0)
c.play()
}
} else {
val saved = if (collection != null) null else root?.let { r -> SoundtrackSettings.resume(context)?.takeIf { it.root == r.path && album.tracks.any { t -> t.id == it.id } } }
play(context, album, albumTitle, saved?.id ?: album.tracks.firstOrNull()?.id, root = root, startMs = saved?.positionMs ?: 0L, collection = collection)
}
}
}
fun pause(context: Context) {
val live = controller
if (live != null) live.pause() else if (future != null) pending += { it.pause() }
}
fun next(context: Context) = run(context) { it.seekToNext() }
fun previous(context: Context) = run(context) { c -> if (c.currentPosition > 3000L) c.seekTo(0) else c.seekToPrevious() }
fun seekTo(context: Context, ms: Long) = run(context) { it.seekTo(ms) }
fun setShuffle(context: Context, on: Boolean) = run(context) { it.shuffleModeEnabled = on }
fun cycleRepeat(context: Context) = run(context) {
it.repeatMode = when (it.repeatMode) {
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
else -> Player.REPEAT_MODE_OFF
}
}
fun setVolume(context: Context, volume: Float) = run(context) { it.volume = volume.coerceIn(0f, 1f) }
fun setSpeed(context: Context, value: Float) {
SoundtrackSettings.load(context)
SoundtrackSettings.setSpeed(context, value)
run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) }
}
fun setPitch(context: Context, value: Float) {
SoundtrackSettings.load(context)
SoundtrackSettings.setPitch(context, value)
run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) }
}
fun setSkipSilence(context: Context, on: Boolean) {
SoundtrackSettings.load(context)
SoundtrackSettings.setSkipSilence(context, on)
run(context) { it.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) }
}
fun setEqualizer(context: Context, on: Boolean, bands: List<Int>, bass: Int) {
SoundtrackSettings.load(context)
SoundtrackSettings.setEqualizer(context, on, bands, bass)
run(context) { sendEqualizer(it) }
}
fun setIngame(context: Context, on: Boolean) {
run(context) { it.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) }
}
fun setSleep(context: Context, minutes: Int) {
sleepEndsAt = if (minutes > 0) System.currentTimeMillis() + minutes * 60_000L else 0L
sleepTrackEnd = minutes < 0
run(context) { it.sendCustomCommand(SoundtrackService.SLEEP, Bundle().apply { putInt(SoundtrackService.ARG_MINUTES, minutes) }) }
}
fun sleepRemainingMs(): Long {
val left = sleepEndsAt - System.currentTimeMillis()
if (sleepEndsAt > 0L && left <= 0L) sleepEndsAt = 0L
return left.coerceAtLeast(0L)
}
fun stopIf(context: Context, root: File?) {
root?.let { removed.add(it.path) }
if (root == null || currentId?.startsWith(root.path + "/") != true) return
run(context) { c ->
c.stop()
c.clearMediaItems()
}
}
}
@@ -0,0 +1,282 @@
package com.droiddeck.launcher.playback
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.audiofx.BassBoost
import android.media.audiofx.Equalizer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Process
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.CommandButton
import androidx.media3.session.DefaultMediaNotificationProvider
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import androidx.media3.session.SessionCommand
import androidx.media3.session.SessionResult
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Soundtrack
import com.google.common.collect.ImmutableList
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import java.io.File
private class EdgeButtonsProvider(context: Context) : DefaultMediaNotificationProvider(context) {
override fun getMediaButtons(
session: MediaSession, playerCommands: Player.Commands, customLayout: ImmutableList<CommandButton>, showPauseButton: Boolean,
): ImmutableList<CommandButton> {
val all = super.getMediaButtons(session, playerCommands, customLayout, showPauseButton)
val custom = all.filter { it.sessionCommand != null }
if (custom.size < 2) return all
return ImmutableList.builder<CommandButton>()
.add(custom.first())
.addAll(all.filter { it.sessionCommand == null })
.addAll(custom.drop(1))
.build()
}
}
class SoundtrackService : MediaSessionService() {
private var session: MediaSession? = null
private var exo: ExoPlayer? = null
private var equalizer: Equalizer? = null
private var bassBoost: BassBoost? = null
private var effectsSession = C.AUDIO_SESSION_ID_UNSET
private var eqOn = false
private var eqBands = IntArray(0)
private var eqBass = 0
private var sleepAtTrackEnd = false
private val handler = Handler(Looper.getMainLooper())
private val sleepRunnable = Runnable { session?.player?.pause() }
private val covers = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-cover").apply { isDaemon = true } }
override fun onCreate() {
super.onCreate()
val player = ExoPlayer.Builder(this)
.setAudioAttributes(mediaAttributes(), !com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(this))
.setHandleAudioBecomingNoisy(true)
.setWakeMode(androidx.media3.common.C.WAKE_MODE_LOCAL)
.build()
exo = player
val sessionIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
player.addListener(object : Player.Listener {
override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) = refreshButtons()
override fun onRepeatModeChanged(repeatMode: Int) = refreshButtons()
override fun onAudioSessionIdChanged(audioSessionId: Int) = applyEffects()
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
if (!playWhenReady) sleepAtTrackEnd = false
}
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
refreshTrackCover(mediaItem)
val ended = reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT
if (sleepAtTrackEnd && ended) {
sleepAtTrackEnd = false
player.pause()
}
}
})
session = MediaSession.Builder(this, player).setCallback(Resolver()).apply { sessionIntent?.let { setSessionActivity(it) } }.build()
setMediaNotificationProvider(EdgeButtonsProvider(this).apply { setSmallIcon(R.drawable.ic_soundtrack) })
}
private fun mediaAttributes(): AudioAttributes =
AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build()
private fun buttons(player: Player): ImmutableList<CommandButton> = ImmutableList.of(
CommandButton.Builder()
.setDisplayName(getString(R.string.soundtracks_shuffle))
.setIconResId(if (player.shuffleModeEnabled) R.drawable.ic_shuffle_on else R.drawable.ic_shuffle_off)
.setSessionCommand(SHUFFLE)
.build(),
CommandButton.Builder()
.setDisplayName(
getString(
when (player.repeatMode) {
Player.REPEAT_MODE_ALL -> R.string.soundtracks_repeat_all
Player.REPEAT_MODE_ONE -> R.string.soundtracks_repeat_one
else -> R.string.soundtracks_repeat_off
},
),
)
.setIconResId(
when (player.repeatMode) {
Player.REPEAT_MODE_ALL -> R.drawable.ic_repeat_all
Player.REPEAT_MODE_ONE -> R.drawable.ic_repeat_one
else -> R.drawable.ic_repeat_off
},
)
.setSessionCommand(REPEAT)
.build(),
)
private fun hasPinnedArt(item: MediaItem): Boolean =
item.mediaMetadata.artworkUri?.path.orEmpty().let { it.contains("/steam-art/") || it.contains("/soundtrack-art/") }
private fun refreshTrackCover(item: MediaItem?) {
val current = item ?: return
if (hasPinnedArt(current)) return
val file = File(current.mediaId)
covers.execute {
val art = Soundtrack.trackCover(this, file) ?: return@execute
handler.post {
val player = exo ?: return@post
val live = player.currentMediaItem ?: return@post
val uri = Uri.fromFile(art)
if (live.mediaId != current.mediaId || live.mediaMetadata.artworkUri == uri || hasPinnedArt(live)) return@post
player.replaceMediaItem(
player.currentMediaItemIndex,
live.buildUpon().setMediaMetadata(live.mediaMetadata.buildUpon().setArtworkUri(uri).build()).build(),
)
}
}
}
private fun releaseEffects() {
runCatching { equalizer?.release() }
runCatching { bassBoost?.release() }
equalizer = null
bassBoost = null
effectsSession = C.AUDIO_SESSION_ID_UNSET
}
private fun applyEffects() {
val id = exo?.audioSessionId ?: C.AUDIO_SESSION_ID_UNSET
if (!eqOn || id == C.AUDIO_SESSION_ID_UNSET) {
releaseEffects()
return
}
if (id != effectsSession) {
releaseEffects()
effectsSession = id
equalizer = runCatching { Equalizer(0, id) }.getOrNull()
bassBoost = runCatching { BassBoost(0, id) }.getOrNull()
}
runCatching {
equalizer?.let { eq ->
val range = eq.bandLevelRange
for (band in 0 until minOf(eq.numberOfBands.toInt(), eqBands.size)) {
eq.setBandLevel(band.toShort(), eqBands[band].coerceIn(range[0].toInt(), range[1].toInt()).toShort())
}
eq.enabled = true
}
}
runCatching {
bassBoost?.let { boost ->
if (boost.strengthSupported) boost.setStrength(eqBass.coerceIn(0, 1000).toShort())
boost.enabled = eqBass > 0
}
}
}
private fun setSleep(minutes: Int) {
handler.removeCallbacks(sleepRunnable)
sleepAtTrackEnd = false
if (minutes > 0) handler.postDelayed(sleepRunnable, minutes * 60_000L)
else if (minutes < 0) sleepAtTrackEnd = true
}
private fun refreshButtons() {
val live = session ?: return
live.setCustomLayout(buttons(live.player))
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = session
override fun onTaskRemoved(rootIntent: Intent?) {
val player = session?.player
if (player == null || !player.playWhenReady || player.mediaItemCount == 0 || player.playbackState == Player.STATE_ENDED) stopSelf()
}
override fun onDestroy() {
handler.removeCallbacks(sleepRunnable)
covers.shutdownNow()
releaseEffects()
session?.let {
it.player.release()
it.release()
}
session = null
super.onDestroy()
}
companion object {
const val HINT_OWNER = "droiddeck.owner"
private val SHUFFLE = SessionCommand("droiddeck.shuffle", Bundle.EMPTY)
private val REPEAT = SessionCommand("droiddeck.repeat", Bundle.EMPTY)
val SKIP_SILENCE = SessionCommand("droiddeck.skipsilence", Bundle.EMPTY)
val EQUALIZER = SessionCommand("droiddeck.equalizer", Bundle.EMPTY)
val SLEEP = SessionCommand("droiddeck.sleep", Bundle.EMPTY)
val INGAME = SessionCommand("droiddeck.ingame", Bundle.EMPTY)
const val ARG_ON = "on"
const val ARG_BANDS = "bands"
const val ARG_BASS = "bass"
const val ARG_MINUTES = "minutes"
}
private inner class Resolver : MediaSession.Callback {
private fun isOwner(controller: MediaSession.ControllerInfo) =
controller.uid == Process.myUid() && controller.connectionHints.getBoolean(HINT_OWNER, false)
override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult =
if (controller.uid == Process.myUid() || controller.isTrusted) {
MediaSession.ConnectionResult.AcceptedResultBuilder(session)
.setAvailableSessionCommands(
MediaSession.ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon().add(SHUFFLE).add(REPEAT).add(SKIP_SILENCE).add(EQUALIZER).add(SLEEP).add(INGAME).build(),
)
.setCustomLayout(buttons(session.player))
.build()
} else {
MediaSession.ConnectionResult.reject()
}
override fun onCustomCommand(
session: MediaSession, controller: MediaSession.ControllerInfo, customCommand: SessionCommand, args: Bundle,
): ListenableFuture<SessionResult> {
val player = session.player
when (customCommand.customAction) {
SHUFFLE.customAction -> player.shuffleModeEnabled = !player.shuffleModeEnabled
REPEAT.customAction -> player.repeatMode = when (player.repeatMode) {
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
else -> Player.REPEAT_MODE_OFF
}
SKIP_SILENCE.customAction, EQUALIZER.customAction, SLEEP.customAction, INGAME.customAction -> {
if (!isOwner(controller)) return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_PERMISSION_DENIED))
when (customCommand.customAction) {
SKIP_SILENCE.customAction -> exo?.skipSilenceEnabled = args.getBoolean(ARG_ON)
INGAME.customAction -> exo?.setAudioAttributes(mediaAttributes(), !args.getBoolean(ARG_ON))
EQUALIZER.customAction -> {
eqOn = args.getBoolean(ARG_ON)
eqBands = args.getIntArray(ARG_BANDS) ?: IntArray(0)
eqBass = args.getInt(ARG_BASS)
applyEffects()
}
else -> setSleep(args.getInt(ARG_MINUTES))
}
}
else -> return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_NOT_SUPPORTED))
}
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
}
override fun onAddMediaItems(
mediaSession: MediaSession, controller: MediaSession.ControllerInfo, mediaItems: MutableList<MediaItem>,
): ListenableFuture<MutableList<MediaItem>> {
if (!isOwner(controller)) return Futures.immediateFailedFuture(SecurityException("Only DroidDeck can queue soundtrack files"))
val resolved = mediaItems.mapNotNull { item ->
val file = File(item.mediaId)
if (Soundtrack.isAudio(file)) item.buildUpon().setUri(Uri.fromFile(file)).build() else null
}.toMutableList()
return Futures.immediateFuture(resolved)
}
}
}
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.playback
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
object SoundtrackSettings {
const val MIN_RATE = 0.5f
const val MAX_RATE = 2f
var speed by mutableFloatStateOf(1f)
private set
var pitch by mutableFloatStateOf(1f)
private set
var skipSilence by mutableStateOf(false)
private set
var eqOn by mutableStateOf(false)
private set
var bands by mutableStateOf<List<Int>>(emptyList())
private set
var bass by mutableIntStateOf(0)
private set
class Resume(val root: String, val id: String, val positionMs: Long)
private var loaded = false
private fun prefs(context: Context) = context.applicationContext.getSharedPreferences("soundtrack_settings", Context.MODE_PRIVATE)
@Synchronized
fun load(context: Context) {
if (loaded) return
loaded = true
val p = prefs(context)
speed = p.getFloat("speed", 1f).coerceIn(MIN_RATE, MAX_RATE)
pitch = p.getFloat("pitch", 1f).coerceIn(MIN_RATE, MAX_RATE)
skipSilence = p.getBoolean("skipSilence", false)
eqOn = p.getBoolean("eqOn", false)
bands = p.getString("bands", "").orEmpty().split(',').mapNotNull { it.trim().toIntOrNull() }
bass = p.getInt("bass", 0).coerceIn(0, 1000)
}
fun setSpeed(context: Context, value: Float) {
speed = value.coerceIn(MIN_RATE, MAX_RATE)
prefs(context).edit().putFloat("speed", speed).apply()
}
fun setPitch(context: Context, value: Float) {
pitch = value.coerceIn(MIN_RATE, MAX_RATE)
prefs(context).edit().putFloat("pitch", pitch).apply()
}
fun setSkipSilence(context: Context, on: Boolean) {
skipSilence = on
prefs(context).edit().putBoolean("skipSilence", on).apply()
}
fun setEqualizer(context: Context, on: Boolean, levels: List<Int>, bassStrength: Int) {
eqOn = on
bands = levels
bass = bassStrength.coerceIn(0, 1000)
prefs(context).edit().putBoolean("eqOn", on).putString("bands", levels.joinToString(",")).putInt("bass", bass).apply()
}
fun resume(context: Context): Resume? {
val p = prefs(context)
val root = p.getString("resumeRoot", null) ?: return null
val id = p.getString("resumeId", null) ?: return null
return Resume(root, id, p.getLong("resumePosition", 0L))
}
fun saveResume(context: Context, root: String, id: String, positionMs: Long) {
prefs(context).edit().putString("resumeRoot", root).putString("resumeId", id).putLong("resumePosition", positionMs.coerceAtLeast(0L)).apply()
}
}
@@ -201,6 +201,18 @@ object SessionPrefs {
prefs(context).edit().putBoolean("gameStoresEnabled", on).apply()
}
fun soundtracksEnabled(context: Context): Boolean = prefs(context).getBoolean("soundtracksEnabled", true)
fun setSoundtracksEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("soundtracksEnabled", on).apply()
}
fun soundtracksIngame(context: Context): Boolean = prefs(context).getBoolean("soundtracksIngame", false)
fun setSoundtracksIngame(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("soundtracksIngame", on).apply()
}
fun gameStoresSpeedTier(context: Context): String = prefs(context).getString("gameStoresSpeedTier", "fast") ?: "fast"
fun setGameStoresSpeedTier(context: Context, tier: String) {
@@ -14,7 +14,7 @@ object SettingsReset {
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"gameStoresEnabled", "soundtracksEnabled", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
@@ -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),