mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
feat: Better boot movies system; Added steamdeckrepo support (#1036)
This commit is contained in:
1 parent
b868863133
commit
e53232b301
52 files changed
+4040
-170
No files matched your search
@@ -1716,12 +1716,12 @@ class MainActivity : ComponentActivity() {
|
||||
SessionPrefs.setRunSteamAtStartup(this, on)
|
||||
runSteamAtStartup = on
|
||||
},
|
||||
onBootMovie = { id -> SessionPrefs.setBootMovie(this, id); loadBootMovie() },
|
||||
onBootMovie = { id -> com.droiddeck.launcher.session.BootMovie.select(this, id); loadBootMovie() },
|
||||
onBootMovieSound = { on -> SessionPrefs.setBootMovieSound(this, on); bootMovieSound = on },
|
||||
onImportBootMovie = {
|
||||
pickBootMovie.launch(InAppFilePicker.buildIntent(this, com.droiddeck.launcher.session.BootMovie.PICKER_EXTENSIONS, getString(R.string.boot_movie_pick)))
|
||||
},
|
||||
onRemoveBootMovie = { com.droiddeck.launcher.session.BootMovie.removeCustom(this); loadBootMovie() },
|
||||
onBootMovieChanged = { loadBootMovie() },
|
||||
onDeckyInstall = { release -> decky.installDecky(release) },
|
||||
onDeckyCheck = { decky.refreshDecky() },
|
||||
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled },
|
||||
|
||||
@@ -30,7 +30,7 @@ object BootMovie {
|
||||
internal val AUDIO_CODECS = setOf(MediaFormat.MIMETYPE_AUDIO_OPUS, MediaFormat.MIMETYPE_AUDIO_VORBIS)
|
||||
|
||||
sealed class Import {
|
||||
data class Done(val name: String, val audioDropped: Boolean) : Import()
|
||||
data class Done(val name: String, val audioDropped: Boolean, val id: String = "") : Import()
|
||||
object TooLong : Import()
|
||||
data class Unsupported(val codec: String?) : Import()
|
||||
object Failed : Import()
|
||||
@@ -39,6 +39,21 @@ object BootMovie {
|
||||
private fun dir(context: Context) = File(context.filesDir, "boot-movie")
|
||||
private fun customFile(context: Context) = File(dir(context), "custom.webm")
|
||||
|
||||
/** A movie imported before movies were kept in Steam's own folder. */
|
||||
internal fun legacyCustomFile(context: Context) = customFile(context)
|
||||
|
||||
/** Unpacks one of DroidDeck's own movies on demand; null for anything else. */
|
||||
internal fun assetFile(context: Context, id: String): File? = ASSETS[id]?.let { extractAsset(context, it) }
|
||||
|
||||
/** Picking a movie here makes it Steam's startup movie at the next session, over whatever Steam had picked. */
|
||||
fun select(context: Context, id: String) {
|
||||
SessionPrefs.setBootMovie(context, id)
|
||||
SessionPrefs.setBootMovieApplyNext(context, true)
|
||||
BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}")
|
||||
// Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later.
|
||||
SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
|
||||
}
|
||||
|
||||
fun customName(context: Context): String? =
|
||||
if (customFile(context).isFile) SessionPrefs.bootMovieCustomName(context) ?: "custom.webm" else null
|
||||
|
||||
@@ -46,21 +61,127 @@ object BootMovie {
|
||||
val chosen = SessionPrefs.bootMovie(context)
|
||||
return when {
|
||||
chosen == CUSTOM && customFile(context).isFile -> CUSTOM
|
||||
isLibraryId(chosen) && BootMovieLibrary.file(context, chosen) != null -> chosen
|
||||
chosen in ASSETS -> chosen
|
||||
else -> DROIDDECK_30
|
||||
}
|
||||
}
|
||||
|
||||
/** The file the current choice plays from, before any volume or length change. */
|
||||
fun currentFile(context: Context): File? = sourceOf(context, choice(context))
|
||||
|
||||
private fun sourceOf(context: Context, choice: String): File? = when {
|
||||
choice == CUSTOM -> customFile(context)
|
||||
isLibraryId(choice) -> BootMovieLibrary.file(context, choice)
|
||||
else -> ASSETS[choice]?.let { extractAsset(context, it) }
|
||||
}
|
||||
|
||||
private fun isLibraryId(id: String) = id.startsWith(BootMovieLibrary.PREFIX) || id.startsWith(BootMovieLibrary.STEAM_PREFIX)
|
||||
|
||||
fun prepare(context: Context): File? {
|
||||
val choice = choice(context)
|
||||
val source = if (choice == CUSTOM) customFile(context) else extractAsset(context, ASSETS.getValue(choice)) ?: return null
|
||||
if (SessionPrefs.bootMovieSound(context)) return source
|
||||
val muted = File(source.parentFile, source.nameWithoutExtension + "-muted.webm")
|
||||
if (muted.isFile && muted.lastModified() >= source.lastModified()) return muted
|
||||
if (remux(source, muted, audio = false)) return muted
|
||||
if (BootMovieTranscoder.transcode(source, muted, keepAudio = false) {} != null) return muted
|
||||
Log.e(TAG, "could not strip audio from ${source.name}; not staging it")
|
||||
return null
|
||||
BootMovieLibrary.restore(context)
|
||||
val source = sourceOf(context, choice(context)) ?: return null
|
||||
return variant(context, source)
|
||||
}
|
||||
|
||||
/** The movie as Steam should get it: with the chosen volume and cut off after the chosen number of seconds. */
|
||||
private fun variant(context: Context, source: File): File? {
|
||||
val volume = if (SessionPrefs.bootMovieSound(context)) SessionPrefs.bootMovieVolume(context) else 0
|
||||
val seconds = SessionPrefs.bootMovieSeconds(context)
|
||||
val folder = File(dir(context), "variants")
|
||||
val plan = if (isOversized(source)) oversizedPlan(volume) else plan(volume, seconds)
|
||||
if (plan.passthrough) {
|
||||
prune(folder, null)
|
||||
return source
|
||||
}
|
||||
folder.mkdirs()
|
||||
val limitUs = if (seconds > 0) seconds * 1_000_000L else Long.MAX_VALUE
|
||||
val out = File(folder, BootMovieLibrary.variantPrefix(source) + "v$volume-s$seconds.webm")
|
||||
if (out.isFile && out.length() > 0L && out.lastModified() >= source.lastModified()) {
|
||||
prune(folder, out.name)
|
||||
return out
|
||||
}
|
||||
val staged = File(folder, out.name + ".staged")
|
||||
val ok = runCatching {
|
||||
plan.steps.any { step ->
|
||||
when (step) {
|
||||
Step.REMUX_SILENT -> remux(source, staged, audio = false, limitUs)
|
||||
Step.REMUX_AUDIO -> remux(source, staged, audio = true, limitUs)
|
||||
Step.TRANSCODE_SILENT -> transcodeSilent(source, staged, limitUs)
|
||||
Step.TRANSCODE_AUDIO -> BootMovieTranscoder.transcode(source, staged, limitUs = limitUs, gain = volume / 100f) {} != null
|
||||
Step.REGAIN -> BootMovieTranscoder.regain(source, staged, volume / 100f, limitUs)
|
||||
}
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
if (ok && staged.renameTo(out)) {
|
||||
prune(folder, out.name)
|
||||
return out
|
||||
}
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not prepare ${source.name} (volume $volume, $seconds s)")
|
||||
return if (plan.sourceOnFailure) source else null
|
||||
}
|
||||
|
||||
internal enum class Step { REMUX_SILENT, REMUX_AUDIO, TRANSCODE_SILENT, TRANSCODE_AUDIO, REGAIN }
|
||||
|
||||
/**
|
||||
* How a movie is processed: the steps tried in order until one works, whether the source goes out untouched, and
|
||||
* whether it still plays as it is when every step fails.
|
||||
*/
|
||||
internal class Plan(val passthrough: Boolean, val steps: List<Step>, val sourceOnFailure: Boolean)
|
||||
|
||||
internal fun plan(volume: Int, seconds: Int): Plan = when {
|
||||
volume == 100 && seconds == 0 -> Plan(true, emptyList(), true)
|
||||
volume == 0 -> Plan(false, listOf(Step.REMUX_SILENT, Step.TRANSCODE_SILENT), false)
|
||||
// Only a length that could not be applied plays as it is; a volume that could not be applied plays no louder.
|
||||
volume == 100 -> Plan(false, listOf(Step.REMUX_AUDIO, Step.TRANSCODE_AUDIO), true)
|
||||
else -> Plan(false, listOf(Step.REGAIN, Step.REMUX_SILENT, Step.TRANSCODE_AUDIO), false)
|
||||
}
|
||||
|
||||
/** Frames beyond 1920x1080 (4K and the like) have made Steam crash while it starts, so such a movie is always scaled down. */
|
||||
internal const val MAX_LONG_SIDE = 1920
|
||||
internal const val MAX_SHORT_SIDE = 1080
|
||||
|
||||
internal fun oversized(width: Int, height: Int) = maxOf(width, height) > MAX_LONG_SIDE || minOf(width, height) > MAX_SHORT_SIDE
|
||||
|
||||
private fun oversized(format: MediaFormat) =
|
||||
format.containsKey(MediaFormat.KEY_WIDTH) && format.containsKey(MediaFormat.KEY_HEIGHT) &&
|
||||
oversized(format.getInteger(MediaFormat.KEY_WIDTH), format.getInteger(MediaFormat.KEY_HEIGHT))
|
||||
|
||||
private fun isOversized(source: File): Boolean = probe(source)?.first?.let { oversized(it) } == true
|
||||
|
||||
/** A movie that is too large never goes out as it is: it is converted at the chosen volume, and plays nothing if that fails. */
|
||||
internal fun oversizedPlan(volume: Int): Plan =
|
||||
Plan(false, listOf(if (volume == 0) Step.TRANSCODE_SILENT else Step.TRANSCODE_AUDIO), false)
|
||||
|
||||
private fun transcodeSilent(source: File, target: File, limitUs: Long) =
|
||||
BootMovieTranscoder.transcode(source, target, keepAudio = false, limitUs = limitUs) {} != null
|
||||
|
||||
/** Keeps at most the one processed copy in use, so trying settings never leaves movies piling up. */
|
||||
private fun prune(folder: File, keep: String?) {
|
||||
folder.listFiles()?.forEach { if (it.name != keep) it.delete() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes over a startup movie chosen in Steam's own settings: when Steam's config names a movie it did not name before,
|
||||
* that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed.
|
||||
*/
|
||||
fun syncFromSteam(context: Context): Boolean {
|
||||
val path = SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context)) ?: return false
|
||||
if (path == SessionPrefs.bootMovieSteamSeen(context)) return false
|
||||
SessionPrefs.setBootMovieSteamSeen(context, path)
|
||||
if (path == SessionFiles.BOOT_MOVIE_PATH) return false
|
||||
val prefix = "/uioverrides/movies/"
|
||||
// The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder.
|
||||
val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else {
|
||||
val listed = BootMovieLibrary.list(context).firstOrNull { it.id.startsWith(BootMovieLibrary.STEAM_PREFIX) && it.id.endsWith(path) }
|
||||
listed?.id ?: BootMovieLibrary.STEAM_PREFIX + path
|
||||
}
|
||||
if (BootMovieLibrary.file(context, id) == null) return false
|
||||
val changed = SessionPrefs.bootMovie(context) != id
|
||||
BootMovieReport.note(context, "Steam names $path, taken over as $id")
|
||||
SessionPrefs.setBootMovie(context, id)
|
||||
return changed
|
||||
}
|
||||
|
||||
private fun extractAsset(context: Context, name: String): File? {
|
||||
@@ -82,11 +203,15 @@ object BootMovie {
|
||||
}
|
||||
}
|
||||
|
||||
fun import(context: Context, file: File, onStart: () -> Unit = {}, onProgress: (Int) -> Unit = {}): Import {
|
||||
fun import(
|
||||
context: Context, file: File, onStart: () -> Unit = {}, onProgress: (Int) -> Unit = {},
|
||||
title: String? = null, source: String = BootMovieLibrary.SOURCE_IMPORT, repoId: String? = null,
|
||||
cover: ByteArray? = null, use: Boolean = true,
|
||||
): Import {
|
||||
val (format, audio) = probe(file) ?: return Import.Unsupported(null)
|
||||
val video = format.getString(MediaFormat.KEY_MIME)
|
||||
val audioPlayable = audio == null || audio in AUDIO_CODECS
|
||||
val playable = video in VIDEO_CODECS && file.length() <= MAX_BYTES
|
||||
val playable = video in VIDEO_CODECS && file.length() <= MAX_BYTES && !oversized(format)
|
||||
val copy = playable && audioPlayable && isWebm(file)
|
||||
val remux = !copy && playable && video in REMUX_CODECS
|
||||
if (!copy && !remux) {
|
||||
@@ -95,11 +220,12 @@ object BootMovie {
|
||||
if (durationUs > MAX_CONVERT_SECONDS * 1_000_000L) return Import.TooLong
|
||||
onStart()
|
||||
}
|
||||
val target = customFile(context)
|
||||
val staged = File(dir(context), "custom.webm.staged")
|
||||
val shown = title?.takeIf { it.isNotBlank() } ?: file.nameWithoutExtension
|
||||
val library = BootMovieLibrary.libraryDir(context)
|
||||
val staged = File(library, ".import-${System.nanoTime()}.staged")
|
||||
var audioDropped = remux && !audioPlayable
|
||||
return try {
|
||||
target.parentFile?.mkdirs()
|
||||
library.mkdirs()
|
||||
val ok = when {
|
||||
copy -> {
|
||||
file.inputStream().use { input -> staged.outputStream().use { output -> FileUtils.copy(input, output) } }
|
||||
@@ -108,11 +234,10 @@ object BootMovie {
|
||||
remux -> remux(file, staged, audio = true)
|
||||
else -> BootMovieTranscoder.transcode(file, staged, onProgress = onProgress)?.also { audioDropped = it.audioDropped } != null
|
||||
}
|
||||
if (!ok || !staged.renameTo(target)) return Import.Failed
|
||||
File(target.parentFile, "custom-muted.webm").delete()
|
||||
SessionPrefs.setBootMovieCustomName(context, file.name)
|
||||
SessionPrefs.setBootMovie(context, CUSTOM)
|
||||
Import.Done(file.name, audioDropped)
|
||||
if (!ok || !staged.setReadable(true, false)) return Import.Failed
|
||||
val name = BootMovieLibrary.commit(context, staged, shown, source, repoId, cover) ?: return Import.Failed
|
||||
if (use) select(context, BootMovieLibrary.idOf(name))
|
||||
Import.Done(shown, audioDropped, BootMovieLibrary.idOf(name))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not import ${file.name}", e)
|
||||
Import.Failed
|
||||
@@ -124,8 +249,9 @@ object BootMovie {
|
||||
fun removeCustom(context: Context) {
|
||||
customFile(context).delete()
|
||||
File(dir(context), "custom-muted.webm").delete()
|
||||
File(dir(context), "variants").listFiles { f -> f.name.startsWith(BootMovieLibrary.variantPrefix(customFile(context))) }?.forEach { it.delete() }
|
||||
SessionPrefs.setBootMovieCustomName(context, null)
|
||||
if (SessionPrefs.bootMovie(context) == CUSTOM) SessionPrefs.setBootMovie(context, DROIDDECK_30)
|
||||
if (SessionPrefs.bootMovie(context) == CUSTOM) select(context, DROIDDECK_30)
|
||||
}
|
||||
|
||||
private fun isWebm(file: File): Boolean {
|
||||
@@ -156,7 +282,7 @@ object BootMovie {
|
||||
}
|
||||
}
|
||||
|
||||
private fun remux(source: File, target: File, audio: Boolean): Boolean {
|
||||
private fun remux(source: File, target: File, audio: Boolean, limitUs: Long = Long.MAX_VALUE): Boolean {
|
||||
val staged = File(target.parentFile, target.name + ".remux")
|
||||
val extractor = MediaExtractor()
|
||||
var muxer: MediaMuxer? = null
|
||||
@@ -183,7 +309,7 @@ object BootMovie {
|
||||
val info = MediaCodec.BufferInfo()
|
||||
while (true) {
|
||||
val size = extractor.readSampleData(buffer, 0)
|
||||
if (size < 0) break
|
||||
if (size < 0 || extractor.sampleTime > limitUs) break
|
||||
val track = tracks[extractor.sampleTrackIndex]
|
||||
if (track != null) {
|
||||
val key = extractor.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Bitmap.CompressFormat
|
||||
import android.media.MediaMetadataRetriever
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The boot movies a person can pick from: DroidDeck's own two, a movie imported before this list existed, every `.webm` in
|
||||
* Steam's custom movies folder (imports, SteamDeckRepo and movies put there by hand; all of them can be removed), Steam's own
|
||||
* three startup movies and the movies bought in Steam's points shop (neither can be removed).
|
||||
*/
|
||||
object BootMovieLibrary {
|
||||
private const val TAG = "BootMovieLibrary"
|
||||
const val PREFIX = "file:"
|
||||
|
||||
/** A movie Steam itself keeps outside its custom movies folder, such as one bought in its points shop: `steam:<path Steam names>`. */
|
||||
const val STEAM_PREFIX = "steam:"
|
||||
|
||||
/** Held while the movie list is read and changed, so two imports at once cannot overwrite each other's entries. */
|
||||
private val lock = Any()
|
||||
|
||||
/** Names DroidDeck stages the chosen movie under; they are copies, not movies of their own. */
|
||||
internal val STAGED = setOf("bigpicture_startup.webm", "steam_os_startup.webm", "droiddeck-startup.webm")
|
||||
|
||||
const val SOURCE_DROIDDECK = "droiddeck"
|
||||
const val SOURCE_IMPORT = "import"
|
||||
const val SOURCE_REPO = "repo"
|
||||
const val SOURCE_STEAM = "steam"
|
||||
const val SOURCE_POINTSHOP = "pointshop"
|
||||
|
||||
class Entry(val id: String, val title: String, val source: String, val file: File?, val removable: Boolean)
|
||||
|
||||
internal fun moviesDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/config/uioverrides/movies")
|
||||
|
||||
/**
|
||||
* The folders whose custom movies are listed, found and removed: [moviesDir], where imports are put and managed, then the
|
||||
* x86-64 client's. The order never depends on which client is running, so a saved choice keeps meaning the same file.
|
||||
*/
|
||||
internal fun customMovieDirs(context: Context): List<File> =
|
||||
listOf(moviesDir(context), File(SessionPrefs.steamRoot(context, "x86_64"), "config/uioverrides/movies")).distinctBy { it.path }
|
||||
|
||||
/** Where imported and installed movies are kept for good; Steam's folder holds a copy, which is put back if it goes missing. */
|
||||
internal fun libraryDir(context: Context) = File(context.filesDir, "boot-movie/library")
|
||||
|
||||
private fun metaFile(context: Context) = File(context.filesDir, "boot-movie/movies.json")
|
||||
|
||||
internal fun steamRoot(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||
|
||||
/** The running (else selected) Steam client's config, the one whose startup movie choice is read and recorded. */
|
||||
internal fun steamConfig(context: Context) = File(SessionPrefs.activeSteamRoot(context), "config/config.vdf")
|
||||
|
||||
private fun thumbsDir(context: Context) = File(context.filesDir, "boot-movie/thumbs")
|
||||
|
||||
fun idOf(name: String) = PREFIX + name
|
||||
|
||||
/** Every Steam client folder: the usual one and the x86-64 client's. */
|
||||
internal fun steamRoots(context: Context): List<File> = listOf(
|
||||
steamRoot(context), File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/.local/share/Steam"),
|
||||
).filter { it.isDirectory }
|
||||
|
||||
private fun steamFile(context: Context, id: String): File? {
|
||||
val path = id.removePrefix(STEAM_PREFIX)
|
||||
if (!path.startsWith("/") || path.contains("..") || path.contains('\\') || !path.endsWith(".webm", ignoreCase = true)) return null
|
||||
return steamRoots(context).firstNotNullOfOrNull { root ->
|
||||
listOf("config", "steamui", "").map { File(root, it + path) }.firstOrNull { it.isFile && it.length() > 0L }
|
||||
}
|
||||
}
|
||||
|
||||
fun file(context: Context, id: String): File? {
|
||||
if (id.startsWith(STEAM_PREFIX)) return steamFile(context, id)
|
||||
if (!id.startsWith(PREFIX)) return null
|
||||
val name = id.removePrefix(PREFIX)
|
||||
if (name.isEmpty() || name.contains('/') || name.contains('\\') || name in STAGED) return null
|
||||
return customMovieDirs(context).map { File(it, name) }.firstOrNull { it.isFile && it.length() > 0L }
|
||||
}
|
||||
|
||||
private fun isMovie(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) &&
|
||||
file.name !in STAGED && !file.name.startsWith(".")
|
||||
|
||||
private fun readMeta(context: Context): JSONObject =
|
||||
runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject())
|
||||
|
||||
/** Changes the movie list one writer at a time; [change] gets the list and returns whether to save it. */
|
||||
private fun editMeta(context: Context, change: (JSONObject) -> Boolean) = synchronized(lock) {
|
||||
val meta = readMeta(context)
|
||||
if (change(meta)) {
|
||||
val file = metaFile(context)
|
||||
file.parentFile?.mkdirs()
|
||||
val staged = File(file.parentFile, file.name + ".staged")
|
||||
runCatching {
|
||||
staged.writeText(meta.toString())
|
||||
if (!staged.renameTo(file)) staged.delete()
|
||||
}.onFailure { staged.delete(); Log.w(TAG, "could not write the movie list", it) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The post a movie was installed from, if it came from SteamDeckRepo. */
|
||||
fun repoId(context: Context, name: String): String? =
|
||||
readMeta(context).optJSONObject(name)?.optString("repo")?.takeIf { it.isNotEmpty() }
|
||||
|
||||
fun installedRepoIds(context: Context): Set<String> {
|
||||
val meta = readMeta(context)
|
||||
return meta.keys().asSequence().filter { file(context, idOf(it)) != null }
|
||||
.mapNotNull { meta.optJSONObject(it)?.optString("repo")?.takeIf { id -> id.isNotEmpty() } }.toSet()
|
||||
}
|
||||
|
||||
fun nameForRepo(context: Context, repoId: String): String? {
|
||||
val meta = readMeta(context)
|
||||
return meta.keys().asSequence().firstOrNull { file(context, idOf(it)) != null && meta.optJSONObject(it)?.optString("repo") == repoId }
|
||||
}
|
||||
|
||||
fun list(context: Context): List<Entry> {
|
||||
val out = ArrayList<Entry>()
|
||||
out.add(Entry(BootMovie.DROIDDECK_30, "DroidDeck · 30 fps", SOURCE_DROIDDECK, null, removable = false))
|
||||
out.add(Entry(BootMovie.DROIDDECK_60, "DroidDeck · 60 fps", SOURCE_DROIDDECK, null, removable = false))
|
||||
BootMovie.customName(context)?.let { out.add(Entry(BootMovie.CUSTOM, it, SOURCE_IMPORT, BootMovie.legacyCustomFile(context), removable = true)) }
|
||||
restore(context)
|
||||
val meta = readMeta(context)
|
||||
val names = HashSet<String>()
|
||||
customMovieDirs(context).flatMap { dir -> dir.listFiles { f -> isMovie(f) }.orEmpty().toList() }
|
||||
.filter { names.add(it.name) }.sortedBy { it.name.lowercase() }.forEach { f ->
|
||||
val info = meta.optJSONObject(f.name)
|
||||
val source = info?.optString("source")?.takeIf { it.isNotEmpty() } ?: SOURCE_STEAM
|
||||
val title = info?.optString("title")?.takeIf { it.isNotEmpty() } ?: f.nameWithoutExtension
|
||||
// Everything in Steam's custom movies folder is the person's own (imported, from SteamDeckRepo or put there by hand).
|
||||
out.add(Entry(idOf(f.name), title, if (source == SOURCE_STEAM) SOURCE_IMPORT else source, f, removable = true))
|
||||
}
|
||||
val steam = LinkedHashMap<String, File>()
|
||||
SessionFiles.startupMoviePath(steamConfig(context))?.takeIf { !it.startsWith(OVERRIDES) }?.let { path ->
|
||||
steamFile(context, STEAM_PREFIX + path)?.let { steam[STEAM_PREFIX + path] = it }
|
||||
}
|
||||
val bought = HashMap<String, String>()
|
||||
for (root in steamRoots(context)) {
|
||||
File(root, "steamui/movies").listFiles { f -> isMovie(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
|
||||
.sortedBy { it.name.lowercase() }.forEach { steam.putIfAbsent(STEAM_PREFIX + "/movies/" + it.name, it) }
|
||||
val scan = pointShopMovies(root)
|
||||
bought.putAll(scan.titles)
|
||||
for (found in scan.files) steam.putIfAbsent(STEAM_PREFIX + "/" + found.relativeTo(root).invariantSeparatorsPath, found)
|
||||
}
|
||||
val seen = HashSet<String>()
|
||||
for ((id, file) in steam) {
|
||||
if (file.name in STAGED || !seen.add(file.canonicalPath)) continue
|
||||
val native = file.nameWithoutExtension.lowercase() in NATIVE
|
||||
// Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it.
|
||||
val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension
|
||||
out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The three startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
|
||||
private val NATIVE = mapOf("deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup")
|
||||
|
||||
private val skippedFolders = setOf("uioverrides", "steamapps", "librarycache", "httpcache", "logs", "compatdata", "shadercache")
|
||||
|
||||
private val scanLock = Any()
|
||||
private class Scan(val at: Long, val files: List<File>, val titles: Map<String, String>)
|
||||
|
||||
private val scans = HashMap<String, Scan>()
|
||||
|
||||
/** Forgets the last search for Steam's own movies. */
|
||||
internal fun forgetScan() = synchronized(scanLock) { scans.clear() }
|
||||
|
||||
/**
|
||||
* Movies Steam keeps outside its custom movies folder, such as ones bought in its points shop: every `.webm` below the
|
||||
* client's config, cache and user folders. The search is repeated at most every 15 seconds for each client folder.
|
||||
*/
|
||||
private fun pointShopMovies(root: File): Scan = synchronized(scanLock) {
|
||||
val now = System.currentTimeMillis()
|
||||
scans[root.path]?.let { if (now - it.at < 15_000L) return it }
|
||||
val found = listOf("config", "userdata", "appcache", "steamui").flatMap { top ->
|
||||
val base = File(root, top)
|
||||
if (!base.isDirectory) return@flatMap emptyList()
|
||||
base.walkTopDown().maxDepth(5)
|
||||
.onEnter { dir -> dir.name !in skippedFolders && !(top == "steamui" && dir.parentFile == base && dir.name == "movies") }
|
||||
.take(20_000).filter { isMovie(it) }.toList()
|
||||
}.sortedBy { it.path.lowercase() }
|
||||
val titles = HashMap<String, String>()
|
||||
for (file in found) boughtId(file)?.let { id -> boughtTitle(root, id)?.let { titles[file.path] = it } }
|
||||
val scan = Scan(now, found, titles)
|
||||
scans[root.path] = scan
|
||||
scan
|
||||
}
|
||||
|
||||
/** The item number in the name Steam gives a bought movie, `<item number>_<hash>.webm`; null for any other name. */
|
||||
private fun boughtId(file: File) = Regex("^(\\d+)_").find(file.nameWithoutExtension)?.groupValues?.get(1)
|
||||
|
||||
/** What the points shop calls a bought movie, from the list of startup movies Steam keeps in each user's local config. */
|
||||
private fun boughtTitle(root: File, id: String): String? {
|
||||
val key = "communityitemid\\\":\\\"$id\\\""
|
||||
val title = Regex("item_title\\\\\":\\\\\"([^\\\\\"]*)")
|
||||
for (user in File(root, "userdata").listFiles { f -> f.isDirectory }.orEmpty()) {
|
||||
val text = runCatching { File(user, "config/localconfig.vdf").readText() }.getOrNull() ?: continue
|
||||
val at = text.indexOf(key)
|
||||
if (at < 0) continue
|
||||
title.find(text.substring(at, (at + 3000).coerceAtMost(text.length)))?.groupValues?.get(1)?.takeIf { it.isNotBlank() }?.let { return it }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private const val OVERRIDES = "/uioverrides/movies/"
|
||||
|
||||
/** Puts back, in Steam's folder, any movie of DroidDeck's that went missing there, such as after the runtime was reset. */
|
||||
internal fun restore(context: Context) = synchronized(lock) {
|
||||
migrateLegacyMeta(context)
|
||||
val meta = readMeta(context)
|
||||
val library = libraryDir(context)
|
||||
meta.keys().asSequence().toList().forEach { name ->
|
||||
val kept = File(library, name)
|
||||
if (name.contains('/') || !kept.isFile || kept.length() == 0L) return@forEach
|
||||
val copy = File(moviesDir(context), name)
|
||||
if (!copy.isFile || copy.length() != kept.length()) mirror(kept, copy)
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes in the movie notes an earlier version kept inside Steam's movies folder, so those movies keep their title and source. */
|
||||
private fun migrateLegacyMeta(context: Context) {
|
||||
val legacy = File(moviesDir(context), ".droiddeck-movies.json")
|
||||
if (!legacy.isFile) return
|
||||
val old = runCatching { JSONObject(legacy.readText()) }.getOrNull() ?: return
|
||||
editMeta(context) { meta ->
|
||||
var changed = false
|
||||
old.keys().asSequence().toList().forEach { name ->
|
||||
val info = old.optJSONObject(name) ?: return@forEach
|
||||
if (meta.optJSONObject(name) == null && File(moviesDir(context), name).isFile) { meta.put(name, info); changed = true }
|
||||
}
|
||||
changed
|
||||
}
|
||||
legacy.delete()
|
||||
}
|
||||
|
||||
/** Copies [kept] to [copy] through a staging name, so Steam never sees half a movie. */
|
||||
private fun mirror(kept: File, copy: File): Boolean {
|
||||
val staged = File(copy.parentFile, copy.name + ".${System.nanoTime()}.staged")
|
||||
return try {
|
||||
copy.parentFile?.mkdirs()
|
||||
kept.inputStream().use { input -> staged.outputStream().use { output -> input.copyTo(output) } }
|
||||
staged.setReadable(true, false) && staged.renameTo(copy)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not copy ${kept.name} into Steam's movies", e)
|
||||
false
|
||||
} finally {
|
||||
staged.delete()
|
||||
}
|
||||
}
|
||||
|
||||
fun title(context: Context, id: String): String = list(context).firstOrNull { it.id == id }?.title ?: id
|
||||
|
||||
/** The file a movie id plays from; DroidDeck's own movies live in the app and are unpacked on demand. */
|
||||
fun fileOf(context: Context, entry: Entry): File? = entry.file ?: BootMovie.assetFile(context, entry.id)
|
||||
|
||||
/** A free `.webm` name for a movie called [title]; the same title twice gets " (2)", " (3)"… */
|
||||
fun freeName(context: Context, title: String): String {
|
||||
val base = title.replace(Regex("[^\\p{L}\\p{N} ._()\\-]"), "").replace(Regex("\\s+"), " ").trim().trim('.').take(60).ifEmpty { "movie" }
|
||||
val dirs = customMovieDirs(context)
|
||||
val library = libraryDir(context)
|
||||
var name = "$base.webm"
|
||||
var n = 2
|
||||
while (dirs.any { File(it, name).exists() } || File(library, name).exists() || name in STAGED) name = "$base ($n).webm".also { n++ }
|
||||
return name
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the finished movie [staged] (a file in [libraryDir]) under a free name, copies it into Steam's folder and notes its
|
||||
* title, source and cover. Returns the name, or null when it could not be kept. Runs one movie at a time.
|
||||
*/
|
||||
internal fun commit(context: Context, staged: File, title: String, source: String, repoId: String? = null, cover: ByteArray? = null): String? =
|
||||
synchronized(lock) {
|
||||
val name = freeName(context, title)
|
||||
val kept = File(libraryDir(context), name)
|
||||
if (!staged.renameTo(kept)) return null
|
||||
if (!mirror(kept, File(moviesDir(context), name))) { kept.delete(); return null }
|
||||
register(context, name, title, source, repoId, cover)
|
||||
name
|
||||
}
|
||||
|
||||
/** Notes a movie that was just put into Steam's folder: what to call it, where it came from and its cover. */
|
||||
fun register(context: Context, name: String, title: String, source: String, repoId: String? = null, cover: ByteArray? = null) {
|
||||
editMeta(context) { meta ->
|
||||
val info = JSONObject().put("title", title).put("source", source)
|
||||
if (repoId != null) info.put("repo", repoId)
|
||||
meta.put(name, info)
|
||||
true
|
||||
}
|
||||
if (cover != null) runCatching {
|
||||
thumbsDir(context).mkdirs()
|
||||
File(thumbsDir(context), coverName(name)).writeBytes(cover)
|
||||
}
|
||||
}
|
||||
|
||||
fun remove(context: Context, id: String): Boolean {
|
||||
val removed = when {
|
||||
id == BootMovie.CUSTOM -> { BootMovie.removeCustom(context); true }
|
||||
else -> {
|
||||
// Only movies in Steam's custom movies folder are ever deleted; Steam's own and points shop movies are left alone.
|
||||
if (!id.startsWith(PREFIX)) return false
|
||||
val name = id.removePrefix(PREFIX)
|
||||
if (name.isEmpty() || name.contains('/') || name.contains('\\') || name in STAGED) return false
|
||||
val copies = customMovieDirs(context).map { File(it, name) }
|
||||
// A name can exist in more than one client's folder; the entry is the first one found (see customMovieDirs), and only that file is deleted.
|
||||
val target = copies.firstOrNull { it.exists() }
|
||||
val managed = File(libraryDir(context), name)
|
||||
if (readMeta(context).optJSONObject(name) == null && target == null && !managed.isFile) return false
|
||||
synchronized(lock) {
|
||||
val main = File(moviesDir(context), name)
|
||||
val another = copies.any { it != target && it.exists() }
|
||||
val ownsRecord = target == null || target.path == main.path || (!another && !managed.isFile)
|
||||
var gone = target == null || target.delete()
|
||||
if (gone && ownsRecord) {
|
||||
gone = !managed.exists() || managed.delete()
|
||||
if (gone) {
|
||||
editMeta(context) { it.remove(name) != null }
|
||||
File(thumbsDir(context), coverName(name)).delete()
|
||||
thumbsDir(context).listFiles { f -> f.name.startsWith("frame-" + safe(name) + "-") }?.forEach { it.delete() }
|
||||
}
|
||||
}
|
||||
if (gone) {
|
||||
val prefixes = listOfNotNull(target, main.takeIf { ownsRecord }).map { variantPrefix(it) }
|
||||
File(context.filesDir, "boot-movie/variants").listFiles { f -> prefixes.any { f.name.startsWith(it) } }?.forEach { it.delete() }
|
||||
}
|
||||
gone
|
||||
}
|
||||
}
|
||||
}
|
||||
if (removed && SessionPrefs.bootMovie(context) == id) BootMovie.select(context, BootMovie.DROIDDECK_30)
|
||||
return removed
|
||||
}
|
||||
|
||||
/** What every processed copy of [source] starts with; the hash of its full path keeps same-named files in different places apart. */
|
||||
internal fun variantPrefix(source: File) = safe(source.name) + "." + Integer.toHexString(source.absolutePath.hashCode()) + "-"
|
||||
|
||||
private fun safe(name: String) = name.replace(Regex("[^A-Za-z0-9._-]"), "_")
|
||||
|
||||
private fun coverName(name: String) = "cover-" + safe(name)
|
||||
|
||||
/** How long a movie runs, in whole seconds; 0 when it cannot be read. */
|
||||
fun durationSeconds(file: File?): Int {
|
||||
if (file == null || !file.isFile) return 0
|
||||
val retriever = MediaMetadataRetriever()
|
||||
return try {
|
||||
retriever.setDataSource(file.path)
|
||||
val ms = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
|
||||
((ms + 500) / 1000).toInt()
|
||||
} catch (e: Exception) {
|
||||
0
|
||||
} finally {
|
||||
runCatching { retriever.release() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The first frame that is not nearly black out of several taken through the movie, else the brightest; a movie may open dark. */
|
||||
private fun brightestFrame(retriever: MediaMetadataRetriever, durationMs: Long): Bitmap? {
|
||||
var best: Bitmap? = null
|
||||
var bestLuma = -1
|
||||
for (fraction in doubleArrayOf(0.33, 0.5, 0.66, 0.2, 0.8, 0.1, 0.9)) {
|
||||
val frame = runCatching { retriever.getFrameAtTime((durationMs * 1000L * fraction).toLong(), MediaMetadataRetriever.OPTION_CLOSEST) }.getOrNull() ?: continue
|
||||
val luma = averageLuma(frame)
|
||||
if (luma >= MIN_COVER_LUMA) return frame
|
||||
if (luma > bestLuma) { best = frame; bestLuma = luma }
|
||||
}
|
||||
return best ?: runCatching { retriever.frameAtTime }.getOrNull()
|
||||
}
|
||||
|
||||
private fun averageLuma(bitmap: Bitmap): Int {
|
||||
val small = Bitmap.createScaledBitmap(bitmap, 16, 9, true)
|
||||
var sum = 0L
|
||||
for (y in 0 until small.height) for (x in 0 until small.width) {
|
||||
val c = small.getPixel(x, y)
|
||||
sum += (((c shr 16) and 0xFF) * 3 + ((c shr 8) and 0xFF) * 6 + (c and 0xFF)) / 10
|
||||
}
|
||||
return (sum / (small.width * small.height)).toInt()
|
||||
}
|
||||
|
||||
private const val MIN_COVER_LUMA = 24
|
||||
|
||||
/** A cover for a movie: the picture SteamDeckRepo gave it, or one frame taken from the video and remembered. */
|
||||
fun cover(context: Context, entry: Entry): File? {
|
||||
val file = fileOf(context, entry) ?: return null
|
||||
val name = if (entry.id.startsWith(PREFIX)) file.name else entry.id
|
||||
// Points Shop covers once kept a picture that was not always the movie's own; those files are not used.
|
||||
val given = File(thumbsDir(context), if (entry.source == SOURCE_POINTSHOP) "v2-" + coverName(name) else coverName(name))
|
||||
if (given.isFile && given.length() > 0L) return given
|
||||
val key = "frame-" + safe(name) + "-v2-" + file.length() + "-" + file.lastModified() + ".jpg"
|
||||
val frame = File(thumbsDir(context), key)
|
||||
if (frame.isFile && frame.length() > 0L) return frame
|
||||
val retriever = MediaMetadataRetriever()
|
||||
return try {
|
||||
retriever.setDataSource(file.path)
|
||||
val ms = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
|
||||
val bitmap = brightestFrame(retriever, ms) ?: return null
|
||||
val width = 480
|
||||
val scaled = if (bitmap.width > width) Bitmap.createScaledBitmap(bitmap, width, (bitmap.height * width / bitmap.width).coerceAtLeast(1), true) else bitmap
|
||||
thumbsDir(context).mkdirs()
|
||||
thumbsDir(context).listFiles { f -> f.name.startsWith("frame-" + safe(name) + "-") }?.forEach { it.delete() }
|
||||
val staged = File(thumbsDir(context), "$key.staged")
|
||||
staged.outputStream().use { scaled.compress(CompressFormat.JPEG, 82, it) }
|
||||
if (staged.renameTo(frame)) frame else null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "no cover for ${file.name}", e)
|
||||
null
|
||||
} finally {
|
||||
runCatching { retriever.release() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* What DroidDeck and Steam know about boot movies, in one text file: Steam's startup movie setting, every movie file and
|
||||
* where it lives, DroidDeck's own state, and a short trace of what each session start did to Steam's config.
|
||||
*/
|
||||
object BootMovieReport {
|
||||
private const val TAG = "BootMovieReport"
|
||||
private const val MAX_TRACE_LINES = 200
|
||||
private const val MAX_HITS = 60
|
||||
private val KNOWN_TITLES = listOf("Turret Factory")
|
||||
private val SKIPPED = setOf("steamapps", "compatdata", "shadercache", "logs")
|
||||
private val BINARY = setOf("webm", "jpg", "jpeg", "png", "ico", "mp4", "ogg", "mp3", "wav", "ttf", "woff", "woff2", "gif", "webp", "bin", "so", "dll", "exe", "zip", "pak")
|
||||
private val lock = Any()
|
||||
|
||||
private fun traceFile(context: Context) = File(context.filesDir, "boot-movie/apply.log")
|
||||
|
||||
/** Adds a line to the short trace kept for the report; only the latest lines are kept. */
|
||||
fun note(context: Context, line: String) {
|
||||
synchronized(lock) {
|
||||
runCatching {
|
||||
val file = traceFile(context)
|
||||
file.parentFile?.mkdirs()
|
||||
val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
val lines = (if (file.isFile) file.readLines() else emptyList()) + "$stamp $line"
|
||||
file.writeText(lines.takeLast(MAX_TRACE_LINES).joinToString("\n") + "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the report to Downloads/DroidDeck, or to the app's own folder when that is not possible; null when the report cannot be built or neither folder works. */
|
||||
fun write(context: Context): File? {
|
||||
val text = runCatching { build(context) }.getOrElse {
|
||||
Log.w(TAG, "could not build the report", it)
|
||||
return null
|
||||
}
|
||||
val folders = listOfNotNull(
|
||||
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck"),
|
||||
context.getExternalFilesDir(null),
|
||||
)
|
||||
for (folder in folders) {
|
||||
val file = File(folder, "boot-movie-report.txt")
|
||||
val saved = runCatching { folder.mkdirs(); file.writeText(text); true }.getOrDefault(false)
|
||||
if (saved) return file
|
||||
Log.w(TAG, "could not write the report to ${file.path}")
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun describe(file: File) =
|
||||
"${file.path} ${file.length()} bytes ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date(file.lastModified()))}"
|
||||
|
||||
internal fun build(context: Context): String {
|
||||
val out = StringBuilder()
|
||||
fun line(text: String = "") { out.append(text).append('\n') }
|
||||
fun listing(title: String, folder: File) {
|
||||
line("-- $title: ${folder.path}")
|
||||
val files = folder.listFiles()?.sortedBy { it.name.lowercase() }
|
||||
if (files == null) line(" (missing)") else if (files.isEmpty()) line(" (empty)")
|
||||
else files.forEach { line(" " + describe(it)) }
|
||||
}
|
||||
|
||||
line("DroidDeck boot movie report, ${Date()}")
|
||||
line()
|
||||
line("== DroidDeck state")
|
||||
line("choice=${BootMovie.choice(context)} saved choice=${SessionPrefs.bootMovie(context)} pending pick=${SessionPrefs.bootMovieApplyNext(context)}")
|
||||
line("last Steam path seen=${SessionPrefs.bootMovieSteamSeen(context)}")
|
||||
line("sound=${SessionPrefs.bootMovieSound(context)} volume=${SessionPrefs.bootMovieVolume(context)} seconds=${SessionPrefs.bootMovieSeconds(context)}")
|
||||
line("session running=${SessionState.running}")
|
||||
line()
|
||||
line("== The movie list as shown")
|
||||
BootMovieLibrary.list(context).forEach { line("${it.id} title=${it.title} source=${it.source} removable=${it.removable} file=${it.file?.path}") }
|
||||
line()
|
||||
line("== DroidDeck folders")
|
||||
listing("library", BootMovieLibrary.libraryDir(context))
|
||||
listing("processed copies", File(context.filesDir, "boot-movie/variants"))
|
||||
val meta = File(context.filesDir, "boot-movie/movies.json")
|
||||
line("-- movie list file: ${if (meta.isFile) meta.readText().take(8000) else "(missing)"}")
|
||||
|
||||
val roots = BootMovieLibrary.steamRoots(context)
|
||||
val movieIds = HashSet<String>()
|
||||
for (root in roots) {
|
||||
line()
|
||||
line("== Steam folder ${root.path}")
|
||||
val config = File(root, "config/config.vdf")
|
||||
line("config.vdf: ${if (config.isFile) describe(config) else "(missing)"}")
|
||||
val text = runCatching { config.readText() }.getOrNull()
|
||||
if (text != null) {
|
||||
line("-- StartupMovie block:")
|
||||
(SessionFiles.startupMovieBlock(config) ?: " (none)").lines().forEach { line(" $it") }
|
||||
line("-- Customization section with the lines before it:")
|
||||
(SessionFiles.customizationBlock(config) ?: " (none)").lines().forEach { line(" $it") }
|
||||
line("-- every line of config.vdf that mentions a movie:")
|
||||
text.lines().filter { it.contains("movie", ignoreCase = true) }.take(40).forEach { line(" ${it.trim()}") }
|
||||
Regex("\"MovieID\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)?.takeIf { it.isNotEmpty() && it != "0" }?.let { movieIds.add(it) }
|
||||
}
|
||||
listing("custom movies", File(root, "config/uioverrides/movies"))
|
||||
listing("Steam's own movies", File(root, "steamui/movies"))
|
||||
listing("config/movies", File(root, "config/movies"))
|
||||
line("-- every .webm below config, userdata, appcache and steamui:")
|
||||
var shown = 0
|
||||
for (top in listOf("config", "userdata", "appcache", "steamui")) {
|
||||
val base = File(root, top)
|
||||
if (!base.isDirectory) continue
|
||||
for (file in base.walkTopDown().maxDepth(8).onEnter { it.name !in SKIPPED }) {
|
||||
if (!file.isFile || !file.name.endsWith(".webm", ignoreCase = true)) continue
|
||||
if (shown++ >= 300) break
|
||||
line(" " + describe(file))
|
||||
Regex("^(\\d+)_[0-9a-fA-F]+").find(file.name)?.groupValues?.get(1)?.let { movieIds.add(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
line()
|
||||
line("== Where Steam keeps movie names (text found in Steam's files)")
|
||||
val needles = (KNOWN_TITLES + movieIds).distinct()
|
||||
line("looking for: ${needles.joinToString(", ")}")
|
||||
search(roots, needles) { line(" $it") }
|
||||
|
||||
line()
|
||||
line("== What each session start did to Steam's config (latest last)")
|
||||
val trace = traceFile(context)
|
||||
if (trace.isFile) trace.readLines().forEach { line(" $it") } else line(" (nothing yet: start a session after picking a movie)")
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
private fun search(roots: List<File>, needles: List<String>, report: (String) -> Unit) {
|
||||
if (needles.isEmpty()) return
|
||||
val deadline = System.currentTimeMillis() + 25_000L
|
||||
var scanned = 0
|
||||
var hits = 0
|
||||
outer@ for (root in roots) {
|
||||
for (top in listOf("config", "userdata", "appcache", "steamui")) {
|
||||
val base = File(root, top)
|
||||
if (!base.isDirectory) continue
|
||||
for (file in base.walkTopDown().maxDepth(8).onEnter { it.name !in SKIPPED }) {
|
||||
if (!file.isFile || file.length() > (2L shl 20) || file.extension.lowercase() in BINARY) continue
|
||||
if (++scanned > 20_000 || System.currentTimeMillis() > deadline || hits >= MAX_HITS) break@outer
|
||||
val text = runCatching { String(file.readBytes(), Charsets.ISO_8859_1) }.getOrNull() ?: continue
|
||||
for (needle in needles) {
|
||||
val at = text.indexOf(needle)
|
||||
if (at < 0) continue
|
||||
hits++
|
||||
val around = text.substring((at - 60).coerceAtLeast(0), (at + needle.length + 100).coerceAtMost(text.length))
|
||||
report("$needle in ${file.path}: " + around.map { if (it in ' '..'~') it else '.' }.joinToString(""))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
report("(searched $scanned files, $hits matches)")
|
||||
}
|
||||
}
|
||||
@@ -37,15 +37,77 @@ internal object BootMovieTranscoder {
|
||||
MediaCodecList(MediaCodecList.REGULAR_CODECS).findDecoderForFormat(format) != null
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun transcode(source: File, target: File, keepAudio: Boolean = true, onProgress: (Int) -> Unit): Result? {
|
||||
fun transcode(source: File, target: File, keepAudio: Boolean = true, limitUs: Long = Long.MAX_VALUE, gain: Float = 1f, onProgress: (Int) -> Unit): Result? {
|
||||
val hadAudio = keepAudio && trackFormat(source, "audio/") != null
|
||||
val audio = if (hadAudio) runCatching { encodeAudio(source) }
|
||||
val audio = if (hadAudio) runCatching { encodeAudio(source, gain, limitUs) }
|
||||
.onFailure { Log.w(TAG, "could not convert the audio of ${source.name}", it) }.getOrNull() else null
|
||||
val muxedAudio = runCatching { encodeVideo(source, target, audio, onProgress) }
|
||||
val muxedAudio = runCatching { encodeVideo(source, target, audio, limitUs, onProgress) }
|
||||
.onFailure { Log.w(TAG, "could not convert ${source.name}", it) }.getOrNull() ?: return null
|
||||
return Result(audioDropped = hadAudio && !muxedAudio)
|
||||
}
|
||||
|
||||
/** Copies the video of [source] untouched and gives it its sound again at [gain] of its level, cut to [limitUs]. */
|
||||
fun regain(source: File, target: File, gain: Float, limitUs: Long): Boolean {
|
||||
val audio = runCatching { encodeAudio(source, gain, limitUs) }
|
||||
.onFailure { Log.w(TAG, "could not change the volume of ${source.name}", it) }.getOrNull() ?: return false
|
||||
val extractor = MediaExtractor()
|
||||
var muxer: MediaMuxer? = null
|
||||
val staged = File(target.parentFile, target.name + ".regain")
|
||||
return try {
|
||||
extractor.setDataSource(source.path)
|
||||
var videoTrack = -1
|
||||
var videoFormat: MediaFormat? = null
|
||||
for (i in 0 until extractor.trackCount) {
|
||||
val format = extractor.getTrackFormat(i)
|
||||
val mime = format.getString(MediaFormat.KEY_MIME) ?: continue
|
||||
if (videoTrack < 0 && (mime == MediaFormat.MIMETYPE_VIDEO_VP8 || mime == MediaFormat.MIMETYPE_VIDEO_VP9)) {
|
||||
videoTrack = i
|
||||
videoFormat = format
|
||||
}
|
||||
}
|
||||
if (videoTrack < 0 || videoFormat == null) return false
|
||||
extractor.selectTrack(videoTrack)
|
||||
val mux = MediaMuxer(staged.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_WEBM).also { muxer = it }
|
||||
val outVideo = mux.addTrack(videoFormat)
|
||||
val outAudio = mux.addTrack(audio.format)
|
||||
mux.start()
|
||||
val info = MediaCodec.BufferInfo()
|
||||
var audioIndex = 0
|
||||
fun writeAudioUpTo(timeUs: Long) {
|
||||
while (audioIndex < audio.samples.size && audio.samples[audioIndex].timeUs <= timeUs) {
|
||||
val sample = audio.samples[audioIndex++]
|
||||
info.set(0, sample.data.size, sample.timeUs, 0)
|
||||
mux.writeSampleData(outAudio, ByteBuffer.wrap(sample.data), info)
|
||||
}
|
||||
}
|
||||
var bufferSize = 8 shl 20
|
||||
if (videoFormat.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) bufferSize = maxOf(bufferSize, videoFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE))
|
||||
val buffer = ByteBuffer.allocate(bufferSize)
|
||||
while (true) {
|
||||
val size = extractor.readSampleData(buffer, 0)
|
||||
if (size < 0 || extractor.sampleTime > limitUs) break
|
||||
val time = extractor.sampleTime
|
||||
writeAudioUpTo(time)
|
||||
val key = extractor.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0
|
||||
info.set(0, size, time, if (key) MediaCodec.BUFFER_FLAG_KEY_FRAME else 0)
|
||||
mux.writeSampleData(outVideo, buffer, info)
|
||||
extractor.advance()
|
||||
}
|
||||
writeAudioUpTo(Long.MAX_VALUE)
|
||||
mux.stop()
|
||||
mux.release()
|
||||
muxer = null
|
||||
staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not change the volume of ${source.name}", e)
|
||||
false
|
||||
} finally {
|
||||
runCatching { muxer?.release() }
|
||||
extractor.release()
|
||||
staged.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun trackFormat(source: File, prefix: String): Pair<Int, MediaFormat>? {
|
||||
val extractor = MediaExtractor()
|
||||
return try {
|
||||
@@ -75,6 +137,14 @@ internal object BootMovieTranscoder {
|
||||
return Layout(canvas, ch, (canvas - cw) / 2, 0, cw, ch)
|
||||
}
|
||||
|
||||
/** [pcm] made quieter by [gain] and cut to its first [limitUs] microseconds. */
|
||||
internal fun scale(pcm: ShortArray, channels: Int, gain: Float, limitUs: Long): ShortArray {
|
||||
val frames = pcm.size / channels
|
||||
val kept = if (limitUs == Long.MAX_VALUE) frames else minOf(frames.toLong(), limitUs * OPUS_RATE / 1_000_000L).toInt()
|
||||
if (gain == 1f && kept == frames) return pcm
|
||||
return ShortArray(kept * channels) { (pcm[it] * gain).toInt().coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt()).toShort() }
|
||||
}
|
||||
|
||||
internal fun resample(pcm: ShortArray, channels: Int, rate: Int): ShortArray {
|
||||
if (rate == OPUS_RATE) return pcm
|
||||
val frames = pcm.size / channels
|
||||
@@ -94,7 +164,10 @@ internal object BootMovieTranscoder {
|
||||
return out
|
||||
}
|
||||
|
||||
private fun encodeAudio(source: File): Audio? {
|
||||
/** Most decoded audio held in memory at once: about six minutes of 48 kHz stereo. */
|
||||
private const val MAX_PCM_BYTES = 64 shl 20
|
||||
|
||||
private fun encodeAudio(source: File, gain: Float = 1f, limitUs: Long = Long.MAX_VALUE): Audio? {
|
||||
val (track, inFormat) = trackFormat(source, "audio/") ?: return null
|
||||
val extractor = MediaExtractor()
|
||||
var decoder: MediaCodec? = null
|
||||
@@ -139,13 +212,16 @@ internal object BootMovieTranscoder {
|
||||
}
|
||||
dec.releaseOutputBuffer(index, false)
|
||||
if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) break
|
||||
// Past the length that will be kept there is nothing more to decode; without a length, a track too big to hold is dropped.
|
||||
if (limitUs != Long.MAX_VALUE && info.presentationTimeUs > limitUs) break
|
||||
if (pcm.size() > MAX_PCM_BYTES) { if (limitUs == Long.MAX_VALUE) return null else break }
|
||||
}
|
||||
}
|
||||
if (channels !in 1..2) return null
|
||||
val raw = pcm.toByteArray()
|
||||
val shorts = ShortArray(raw.size / 2)
|
||||
ByteBuffer.wrap(raw).order(ByteOrder.nativeOrder()).asShortBuffer().get(shorts)
|
||||
val samples = resample(shorts, channels, rate)
|
||||
val samples = scale(resample(shorts, channels, rate), channels, gain, limitUs)
|
||||
|
||||
val format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_OPUS, OPUS_RATE, channels)
|
||||
format.setInteger(MediaFormat.KEY_BIT_RATE, 128_000)
|
||||
@@ -201,7 +277,7 @@ internal object BootMovieTranscoder {
|
||||
private fun MediaFormat.intOrNull(key: String): Int? = if (!containsKey(key)) null else
|
||||
runCatching { getInteger(key) }.getOrElse { runCatching { getFloat(key).toInt() }.getOrNull() }
|
||||
|
||||
private fun encodeVideo(source: File, target: File, audio: Audio?, onProgress: (Int) -> Unit): Boolean {
|
||||
private fun encodeVideo(source: File, target: File, audio: Audio?, limitUs: Long, onProgress: (Int) -> Unit): Boolean {
|
||||
val (track, inFormat) = trackFormat(source, "video/") ?: throw IllegalStateException("no video track")
|
||||
val rotation = (inFormat.intOrNull(MediaFormat.KEY_ROTATION) ?: 0).mod(360)
|
||||
val layout = layout(inFormat.getInteger(MediaFormat.KEY_WIDTH), inFormat.getInteger(MediaFormat.KEY_HEIGHT), rotation)
|
||||
@@ -278,7 +354,8 @@ internal object BootMovieTranscoder {
|
||||
val index = dec.dequeueOutputBuffer(decInfo, TIMEOUT_US)
|
||||
if (index >= 0) {
|
||||
val timeUs = decInfo.presentationTimeUs
|
||||
val keep = decInfo.size > 0 && (lastKept == Long.MIN_VALUE || timeUs - lastKept >= minIntervalUs)
|
||||
val pastLimit = timeUs > limitUs
|
||||
val keep = decInfo.size > 0 && !pastLimit && (lastKept == Long.MIN_VALUE || timeUs - lastKept >= minIntervalUs)
|
||||
dec.releaseOutputBuffer(index, keep)
|
||||
if (keep) {
|
||||
if (!frames.awaitFrame()) throw IllegalStateException("decoder frame timed out")
|
||||
@@ -290,9 +367,10 @@ internal object BootMovieTranscoder {
|
||||
if (percent != lastProgress) { lastProgress = percent; onProgress(percent) }
|
||||
}
|
||||
}
|
||||
if (decInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
|
||||
if (pastLimit || decInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
|
||||
enc.signalEndOfInputStream()
|
||||
decoderDone = true
|
||||
inputDone = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,8 @@ object SessionFiles {
|
||||
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
|
||||
)
|
||||
|
||||
fun stage(context: Context, root: File) {
|
||||
/** Puts the session's files in place; [startsSession] is true only for the call that starts the Steam session. */
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) {
|
||||
if (DesktopCatalog.desktopInstalled(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||
GameEnvironmentStore.publish(context)
|
||||
@@ -208,18 +209,72 @@ object SessionFiles {
|
||||
Log.e(TAG, "could not write steam-compatibility-label")
|
||||
}
|
||||
|
||||
BootMovie.syncFromSteam(context)
|
||||
val startupMovie = BootMovie.prepare(context)
|
||||
// The x86-64 client's config is left alone until its first start creates it.
|
||||
val steamRoots = listOf(File(root, "root/.local/share/Steam"), File(root, "root/.droiddeck-x64/.local/share/Steam"))
|
||||
.filterIndexed { i, steam -> i == 0 || File(steam, "config").isDirectory }
|
||||
for (steam in steamRoots) {
|
||||
val startupMovieDir = File(steam, "config/uioverrides/movies")
|
||||
val bigPictureMovieInstalled = startupMovie != null &&
|
||||
stageStartupMovie(startupMovie, startupMovieDir, "bigpicture_startup.webm")
|
||||
if (startupMovie != null) stageStartupMovie(startupMovie, startupMovieDir, "steam_os_startup.webm")
|
||||
if (bigPictureMovieInstalled) {
|
||||
ensureStartupMovieDefault(File(steam, "config/config.vdf"))
|
||||
val force = SessionPrefs.bootMovieApplyNext(context)
|
||||
val steamHomes = listOf(File(root, "root/.local/share/Steam")) +
|
||||
listOf(File(root, "root/.droiddeck-x64/.local/share/Steam")).filter { File(it, "config").isDirectory }
|
||||
var allDone = true
|
||||
var allInstalled = true
|
||||
var seen: String? = null
|
||||
val activeIsX64 = SessionPrefs.activeSteamClientArch(context) == "x86_64"
|
||||
for (home in steamHomes) {
|
||||
val movieDir = File(home, "config/uioverrides/movies")
|
||||
val config = File(home, "config/config.vdf")
|
||||
if (startupMovie == null) {
|
||||
// Nothing to play (a movie whose volume could not be set is never played at another volume), so no earlier copy plays either.
|
||||
for (name in listOf("bigpicture_startup.webm", "steam_os_startup.webm")) {
|
||||
File(movieDir, name).delete()
|
||||
File(movieDir, ".$name.source").delete()
|
||||
}
|
||||
}
|
||||
val bigPictureMovieInstalled = startupMovie != null && stageStartupMovie(startupMovie, movieDir, "bigpicture_startup.webm")
|
||||
if (startupMovie != null) stageStartupMovie(startupMovie, movieDir, "steam_os_startup.webm")
|
||||
val before = startupMoviePath(config)
|
||||
val done = if (bigPictureMovieInstalled) ensureStartupMovieDefault(config, force) else resetMissingStartupMovie(config, force)
|
||||
BootMovieReport.note(
|
||||
context,
|
||||
"stage session=$startsSession pending=$force choice=${SessionPrefs.bootMovie(context)} movie=${startupMovie?.path} " +
|
||||
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
|
||||
)
|
||||
if (!done) allDone = false
|
||||
if (!bigPictureMovieInstalled) allInstalled = false
|
||||
if (done && home.path.contains(".droiddeck-x64") == activeIsX64) seen = if (bigPictureMovieInstalled) BOOT_MOVIE_PATH else ""
|
||||
}
|
||||
// A pick made in the app is done once a session started with every Steam client's config having it; guest commands run
|
||||
// before that, and a Steam that is already running writes its own choice back when it exits.
|
||||
if (force && allDone && allInstalled && startsSession) SessionPrefs.setBootMovieApplyNext(context, false)
|
||||
seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Points Steam's startup movie back at its own default when it names a movie that is gone: DroidDeck's staged copy that
|
||||
* could not be prepared, or (when a pick here is waiting) a movie removed from Steam's folder. True when Steam's config
|
||||
* no longer names a missing movie.
|
||||
*/
|
||||
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
|
||||
if (!config.isFile) return true
|
||||
val text = runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config to reset the startup movie", it)
|
||||
return false
|
||||
}
|
||||
val movie = activeStartupMovie(text) ?: return true
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
val path = scalar(block, "LocalPath").orEmpty()
|
||||
if (path.isEmpty()) return true
|
||||
val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR))
|
||||
val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH)
|
||||
if (!gone) return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline)
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated))
|
||||
(staged.renameTo(config)).also { if (!it) staged.delete() }
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not reset Steam startup movie selection", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +328,11 @@ object SessionFiles {
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setReadable(true, false) && staged.renameTo(movie)
|
||||
if (installed) FileUtils.writeString(stamp, identity)
|
||||
if (installed) {
|
||||
FileUtils.writeString(stamp, identity)
|
||||
// Steam's picker draws its preview from this picture and does not redraw it when the movie changes.
|
||||
File(directory, name.removeSuffix(".webm") + ".jpg").delete()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage Steam startup movie $name", e)
|
||||
} finally {
|
||||
@@ -285,43 +344,108 @@ object SessionFiles {
|
||||
|
||||
private data class VdfBlock(val keyStart: Int, val open: Int, val close: Int)
|
||||
|
||||
private fun ensureStartupMovieDefault(config: File) {
|
||||
val path = "/uioverrides/movies/bigpicture_startup.webm"
|
||||
internal const val BOOT_MOVIES_DIR = "/uioverrides/movies/"
|
||||
internal const val BOOT_MOVIE_PATH = "/uioverrides/movies/bigpicture_startup.webm"
|
||||
|
||||
/**
|
||||
* Steam's startup movie setting is the `StartupMovie` section inside its `Customization` section; the one under the Steam
|
||||
* settings is where older clients kept it, and DroidDeck still keeps it in step.
|
||||
*/
|
||||
private fun customizationMovie(text: String): VdfBlock? {
|
||||
var from = 0
|
||||
while (true) {
|
||||
val customization = findObject(text, "Customization", from, text.length) ?: return null
|
||||
findObject(text, "StartupMovie", customization.open + 1, customization.close)?.let { return it }
|
||||
from = customization.close + 1
|
||||
}
|
||||
}
|
||||
|
||||
/** The older `StartupMovie` section: the first one that is not inside `Customization`. */
|
||||
private fun olderMovie(text: String): VdfBlock? {
|
||||
val inside = customizationMovie(text)
|
||||
var from = 0
|
||||
while (true) {
|
||||
val movie = findObject(text, "StartupMovie", from, text.length) ?: return null
|
||||
if (inside == null || movie.keyStart != inside.keyStart) return movie
|
||||
from = movie.close + 1
|
||||
}
|
||||
}
|
||||
|
||||
/** The section Steam reads: the one under `Customization` when there is one. */
|
||||
private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text)
|
||||
|
||||
/** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */
|
||||
internal fun startupMoviePath(config: File): String? {
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return null
|
||||
val movie = activeStartupMovie(text) ?: return null
|
||||
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
/** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */
|
||||
internal fun startupMovieBlock(config: File): String? {
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return null
|
||||
val parts = listOfNotNull(
|
||||
customizationMovie(text)?.let { "under Customization:\n" + text.substring(it.keyStart, it.close + 1) },
|
||||
olderMovie(text)?.let { "older place:\n" + text.substring(it.keyStart, it.close + 1) },
|
||||
)
|
||||
return parts.takeIf { it.isNotEmpty() }?.joinToString("\n")
|
||||
}
|
||||
|
||||
/** The `Customization` section of Steam's config with the lines before it, for the report; null when there is none. */
|
||||
internal fun customizationBlock(config: File): String? {
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return null
|
||||
val customization = findObject(text, "Customization", 0, text.length) ?: return null
|
||||
val before = text.substring(0, customization.keyStart).lines().takeLast(4).joinToString("\n")
|
||||
return (before + "\n" + text.substring(customization.keyStart, customization.close + 1)).take(4000)
|
||||
}
|
||||
|
||||
private fun pointAt(text: String, movie: VdfBlock, path: String, newline: String): String {
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
return text.replaceRange(movie.keyStart, movie.close + 1, setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", path, newline))
|
||||
}
|
||||
|
||||
/** True when Steam's config selects DroidDeck's staged movie once this returns. */
|
||||
internal fun ensureStartupMovieDefault(config: File, force: Boolean = false): Boolean {
|
||||
val path = BOOT_MOVIE_PATH
|
||||
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
|
||||
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config for startup movie", it)
|
||||
return
|
||||
return false
|
||||
} else ""
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val movie = findObject(text, "StartupMovie", 0, text.length)
|
||||
if (movie != null) {
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
val custom = customizationMovie(text)
|
||||
val active = custom ?: olderMovie(text)
|
||||
if (active != null) {
|
||||
val block = text.substring(active.keyStart, active.close + 1)
|
||||
val selectedId = scalar(block, "MovieID")
|
||||
val selectedPath = scalar(block, "LocalPath")
|
||||
if (selectedPath == path) {
|
||||
if (selectedPath == path && custom != null) {
|
||||
Log.i(TAG, "Steam startup movie is set to DroidDeck")
|
||||
return
|
||||
return true
|
||||
}
|
||||
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
|
||||
val hasExplicitSelection =
|
||||
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
|
||||
if (!legacyDefault && hasExplicitSelection) {
|
||||
if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) {
|
||||
Log.i(TAG, "Steam startup movie selection preserved")
|
||||
return
|
||||
return false
|
||||
}
|
||||
val updated = setScalar(block, "MovieID", "0", newline)
|
||||
.let { setScalar(it, "LocalPath", path, newline) }
|
||||
text = text.replaceRange(movie.keyStart, movie.close + 1, updated)
|
||||
} else {
|
||||
}
|
||||
// Later sections first, so the positions of earlier ones stay valid.
|
||||
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
|
||||
for (target in targets) text = pointAt(text, target, path, newline)
|
||||
if (olderMovie(text) == null) {
|
||||
val steam = findSteamBlock(text)
|
||||
if (steam == null) {
|
||||
if (text.isNotBlank()) {
|
||||
if (text.isNotBlank() && customizationMovie(text) == null) {
|
||||
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
|
||||
return
|
||||
return false
|
||||
}
|
||||
if (text.isBlank()) {
|
||||
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
|
||||
val section = startupMovieSection("\t\t\t\t", path, newline)
|
||||
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
|
||||
}
|
||||
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
|
||||
val section = startupMovieSection("\t\t\t\t", path, newline)
|
||||
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
|
||||
@@ -329,22 +453,35 @@ object SessionFiles {
|
||||
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
|
||||
}
|
||||
}
|
||||
if (customizationMovie(text) == null) text = withCustomization(text, path, newline)
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
try {
|
||||
return try {
|
||||
config.parentFile?.mkdirs()
|
||||
staged.writeText(text)
|
||||
if (!staged.renameTo(config)) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write Steam startup movie selection")
|
||||
false
|
||||
} else {
|
||||
Log.i(TAG, "Steam startup movie default selected")
|
||||
true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not write Steam startup movie selection", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the `Customization` section Steam reads, next to the `Software` section, when the config has none. */
|
||||
private fun withCustomization(text: String, path: String, newline: String): String {
|
||||
val root = findObject(text, "InstallConfigStore", 0, text.length) ?: return text
|
||||
val lineStart = text.lastIndexOf('\n', root.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, root.close).takeWhile { it == '\t' || it == ' ' }
|
||||
val section = listOf(indent + "\t\"Customization\"", indent + "\t{", startupMovieSection(indent + "\t\t", path, newline), indent + "\t}").joinToString(newline)
|
||||
return text.substring(0, lineStart) + section + newline + text.substring(lineStart)
|
||||
}
|
||||
|
||||
private fun findSteamBlock(text: String): VdfBlock? {
|
||||
val install = findObject(text, "InstallConfigStore", 0, text.length) ?: return null
|
||||
val software = findObject(text, "Software", install.open + 1, install.close) ?: return null
|
||||
|
||||
@@ -528,6 +528,17 @@ object SessionPrefs {
|
||||
fun setBootMovie(context: Context, id: String) { prefs(context).edit().putString("bootMovie", id).apply() }
|
||||
fun bootMovieSound(context: Context): Boolean = prefs(context).getBoolean("bootMovieSound", true)
|
||||
fun setBootMovieSound(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieSound", on).apply() }
|
||||
fun bootMovieVolume(context: Context): Int = prefs(context).getInt("bootMovieVolume", 100).coerceIn(0, 100)
|
||||
fun setBootMovieVolume(context: Context, percent: Int) { prefs(context).edit().putInt("bootMovieVolume", percent.coerceIn(0, 100)).apply() }
|
||||
/** How long the boot movie plays, in seconds; 0 plays all of it. */
|
||||
fun bootMovieSeconds(context: Context): Int = prefs(context).getInt("bootMovieSeconds", 0).coerceAtLeast(0)
|
||||
fun setBootMovieSeconds(context: Context, seconds: Int) { prefs(context).edit().putInt("bootMovieSeconds", seconds.coerceAtLeast(0)).apply() }
|
||||
/** Set when a movie was picked here, so the next session makes it Steam's startup movie even if Steam had another one. */
|
||||
fun bootMovieApplyNext(context: Context): Boolean = prefs(context).getBoolean("bootMovieApplyNext", false)
|
||||
fun setBootMovieApplyNext(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieApplyNext", on).apply() }
|
||||
/** The startup movie path Steam's config held when it was last looked at, so only a change made in Steam is taken over. */
|
||||
fun bootMovieSteamSeen(context: Context): String? = prefs(context).getString("bootMovieSteamSeen", null)
|
||||
fun setBootMovieSteamSeen(context: Context, path: String) { prefs(context).edit().putString("bootMovieSteamSeen", path).apply() }
|
||||
fun bootMovieCustomName(context: Context): String? = prefs(context).getString("bootMovieCustomName", null)
|
||||
fun setBootMovieCustomName(context: Context, name: String?) {
|
||||
prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply()
|
||||
|
||||
@@ -319,7 +319,7 @@ class SessionService : Service() {
|
||||
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
SessionFiles.stage(this, root)
|
||||
SessionFiles.stage(this, root, startsSession = true)
|
||||
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
|
||||
SessionArtifacts.awaitCollections()
|
||||
SessionArtifacts.finishAbandoned(this)
|
||||
|
||||
@@ -21,7 +21,8 @@ object SettingsReset {
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
"questDefaultsV1",
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
/** steamdeckrepo.com's public boot video list, the same one its website and its own manager app read. */
|
||||
object SteamDeckRepo {
|
||||
private const val TAG = "SteamDeckRepo"
|
||||
const val BASE = "https://steamdeckrepo.com"
|
||||
|
||||
/** The site shows twelve movies a page. */
|
||||
const val PAGE_SIZE = 12
|
||||
const val MAX_DOWNLOAD_BYTES = 120L shl 20
|
||||
private const val MAX_JSON_BYTES = 1 shl 20
|
||||
private const val USER_AGENT = "DroidDeck (+https://github.com/Droid-Deck/DroidDeck)"
|
||||
private const val CACHE_MS = 10 * 60 * 1000L
|
||||
|
||||
enum class Sort(val key: String) {
|
||||
TRENDING("trending"), DOWNLOADS("downloads-desc"), LIKES("likes-desc"), NEWEST("created_at-desc"),
|
||||
}
|
||||
|
||||
/** `null` is every device. */
|
||||
val DEVICES = listOf("steam_deck", "steam_machine")
|
||||
|
||||
class Post(
|
||||
val id: String, val title: String, val content: String, val author: String, val thumbnail: String, val video: String,
|
||||
val seconds: Int, val likes: Int, val downloads: Int, val devices: List<String>, val url: String,
|
||||
)
|
||||
|
||||
sealed class Page {
|
||||
class Ok(val posts: List<Post>) : Page()
|
||||
object Failed : Page()
|
||||
}
|
||||
|
||||
/** The text of [key], empty when it is missing or JSON null, which `optString` would turn into the word "null". */
|
||||
private fun JSONObject.text(key: String): String = if (isNull(key)) "" else optString(key)
|
||||
|
||||
fun parse(json: String): List<Post>? {
|
||||
val array = runCatching { JSONObject(json).optJSONArray("posts") }.getOrNull() ?: return null
|
||||
val out = ArrayList<Post>()
|
||||
for (i in 0 until array.length()) {
|
||||
val o = array.optJSONObject(i) ?: continue
|
||||
val id = o.text("id")
|
||||
val video = o.text("video")
|
||||
if (id.isEmpty() || !video.startsWith("https://")) continue
|
||||
val devices = o.optJSONArray("devices")?.let { d -> (0 until d.length()).map { d.optString(it) } }.orEmpty()
|
||||
out.add(
|
||||
Post(
|
||||
id = id, title = o.text("title").ifBlank { id }, content = o.text("content"),
|
||||
author = o.optJSONObject("user")?.text("steam_name").orEmpty(),
|
||||
thumbnail = o.text("thumbnail").takeIf { it.startsWith("https://") }.orEmpty(), video = video,
|
||||
seconds = o.optInt("video_duration"), likes = o.optInt("likes"), downloads = o.optInt("downloads"),
|
||||
devices = devices, url = o.text("url"),
|
||||
),
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun url(sort: Sort, device: String?, search: String, page: Int = 1): String {
|
||||
val query = StringBuilder("sort=").append(sort.key)
|
||||
if (device != null) query.append("&device=").append(URLEncoder.encode(device, "UTF-8"))
|
||||
val term = search.trim()
|
||||
if (term.isNotEmpty()) query.append("&search=").append(URLEncoder.encode(term, "UTF-8").replace("+", "%20"))
|
||||
if (page > 1) query.append("&page=").append(page)
|
||||
return "$BASE/api/posts?$query"
|
||||
}
|
||||
|
||||
private class Cached(val at: Long, val page: Page.Ok)
|
||||
private val cache = HashMap<String, Cached>()
|
||||
|
||||
fun fetch(sort: Sort, device: String?, search: String, page: Int = 1, now: Long = System.currentTimeMillis()): Page {
|
||||
val url = url(sort, device, search, page)
|
||||
synchronized(cache) { cache[url]?.takeIf { now - it.at < CACHE_MS }?.let { return it.page } }
|
||||
val body = get(url) ?: return Page.Failed
|
||||
val posts = parse(body) ?: return Page.Failed
|
||||
val result = Page.Ok(posts.take(PAGE_SIZE))
|
||||
synchronized(cache) { cache[url] = Cached(now, result) }
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of the last page for a search, found by asking for pages: the site does not say how many there are, but a
|
||||
* page past the end is empty and the last one is short. Null when the site cannot be reached.
|
||||
*/
|
||||
fun lastPage(sort: Sort, device: String?, search: String, cap: Int = 512, count: (Int) -> Int? = { p ->
|
||||
(fetch(sort, device, search, p) as? Page.Ok)?.posts?.size
|
||||
}): Int? {
|
||||
val first = count(1) ?: return null
|
||||
if (first < PAGE_SIZE) return 1
|
||||
var good = 1
|
||||
var bad = -1
|
||||
var probe = 2
|
||||
while (probe <= cap) {
|
||||
val n = count(probe) ?: return null
|
||||
if (n == 0) { bad = probe; break }
|
||||
if (n < PAGE_SIZE) return probe
|
||||
good = probe
|
||||
probe *= 2
|
||||
}
|
||||
if (bad < 0) return good
|
||||
while (bad - good > 1) {
|
||||
val mid = (good + bad) / 2
|
||||
val n = count(mid) ?: return null
|
||||
if (n == 0) bad = mid else if (n < PAGE_SIZE) return mid else good = mid
|
||||
}
|
||||
return good
|
||||
}
|
||||
|
||||
/** Reads [input] to its end, or null as soon as it holds more than [limit] bytes, so a huge answer is never kept whole. */
|
||||
internal fun readLimited(input: java.io.InputStream, limit: Int): ByteArray? {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
if (out.size() + n > limit) return null
|
||||
out.write(buffer, 0, n)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
private fun get(url: String): String? {
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
connection = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 20_000
|
||||
setRequestProperty("User-Agent", USER_AGENT)
|
||||
setRequestProperty("Accept", "application/json")
|
||||
}
|
||||
if (connection.responseCode !in 200..299) null else connection.inputStream.use { readLimited(it, MAX_JSON_BYTES)?.toString(Charsets.UTF_8) }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "request failed: ${e.javaClass.simpleName}")
|
||||
null
|
||||
} finally {
|
||||
runCatching { connection?.disconnect() }
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetches a small picture such as a cover; null when it cannot be had. */
|
||||
fun bytes(url: String, limit: Int = 4 shl 20): ByteArray? {
|
||||
if (!url.startsWith("https://")) return null
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
connection = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 20_000
|
||||
setRequestProperty("User-Agent", USER_AGENT)
|
||||
}
|
||||
if (connection.responseCode !in 200..299 || connection.contentLengthLong > limit) null
|
||||
else connection.inputStream.use { input -> readLimited(input, limit)?.takeIf { it.isNotEmpty() } }
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
} finally {
|
||||
runCatching { connection?.disconnect() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads a movie to [target] through the site's own download address, so the site counts it like a download from
|
||||
* its website, and falls back to the video's address. True when a file was saved.
|
||||
*/
|
||||
fun download(post: Post, target: File, onProgress: (Int) -> Unit = {}): Boolean {
|
||||
for (url in listOf("$BASE/post/download/${post.id}", post.video)) {
|
||||
if (save(url, target, onProgress)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun save(url: String, target: File, onProgress: (Int) -> Unit): Boolean {
|
||||
var connection: HttpURLConnection? = null
|
||||
val staged = File(target.parentFile, target.name + ".part")
|
||||
return try {
|
||||
target.parentFile?.mkdirs()
|
||||
connection = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 30_000
|
||||
instanceFollowRedirects = true
|
||||
setRequestProperty("User-Agent", USER_AGENT)
|
||||
}
|
||||
if (connection.responseCode !in 200..299) return false
|
||||
val type = connection.contentType.orEmpty().lowercase()
|
||||
if (type.startsWith("text/") || type.contains("json")) return false
|
||||
val total = connection.contentLengthLong
|
||||
if (total > MAX_DOWNLOAD_BYTES) return false
|
||||
var done = 0L
|
||||
var lastPercent = -1
|
||||
connection.inputStream.use { input ->
|
||||
staged.outputStream().use { output ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) break
|
||||
done += n
|
||||
if (done > MAX_DOWNLOAD_BYTES) return false
|
||||
output.write(buffer, 0, n)
|
||||
if (total > 0) {
|
||||
val percent = (done * 100 / total).toInt()
|
||||
if (percent != lastPercent) { lastPercent = percent; onProgress(percent) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
done > 0 && (total <= 0 || done == total) && staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "download failed: ${e.javaClass.simpleName}")
|
||||
false
|
||||
} finally {
|
||||
runCatching { connection?.disconnect() }
|
||||
staged.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -305,6 +305,7 @@ internal fun AppDialog(
|
||||
modifier: Modifier = Modifier, maxWidth: Dp? = null,
|
||||
width: Dp? = null, fitContent: Boolean = false,
|
||||
back: (() -> Unit)? = null,
|
||||
scrollable: Boolean = true,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
@@ -342,7 +343,7 @@ internal fun AppDialog(
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
|
||||
.controllerBack(back ?: close)
|
||||
.then(modifier)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.then(if (scrollable) Modifier.verticalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 18.dp, vertical = 16.dp),
|
||||
content = content,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.widget.Toast
|
||||
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.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
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.RoundedCornerShape
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
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.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.selected
|
||||
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 android.graphics.SurfaceTexture
|
||||
import android.media.MediaPlayer
|
||||
import android.net.Uri
|
||||
import android.view.Surface
|
||||
import android.view.TextureView
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.BootMovie
|
||||
import com.droiddeck.launcher.session.BootMovieLibrary
|
||||
import com.droiddeck.launcher.session.BootMovieReport
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SteamDeckRepo
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
private enum class MovieTab { INSTALLED, IMPORT, REPO, SOUND }
|
||||
|
||||
/** Downloads run here rather than in a tab, so switching tabs or closing the settings does not cancel one halfway. */
|
||||
private val installScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
/** The downloads under way, by post id and percent; kept here so they are still known when the tab or the settings come back. */
|
||||
private val installProgress = mutableStateMapOf<String, Int>()
|
||||
|
||||
/** What the movie list looks like right now: every movie and the one Steam will play. */
|
||||
private class MovieSnapshot(val entries: List<BootMovieLibrary.Entry>, val selected: String)
|
||||
|
||||
/** The movie list, read again every couple of seconds so a movie picked, added or removed inside Steam shows up here too. */
|
||||
@Composable
|
||||
private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieSnapshot? {
|
||||
val app = LocalContext.current.applicationContext
|
||||
var snapshot by remember { mutableStateOf<MovieSnapshot?>(null) }
|
||||
val changed by androidx.compose.runtime.rememberUpdatedState(onSelectionChanged)
|
||||
LaunchedEffect(refresh) {
|
||||
while (true) {
|
||||
val before = snapshot?.selected
|
||||
snapshot = withContext(Dispatchers.IO) {
|
||||
BootMovie.syncFromSteam(app)
|
||||
MovieSnapshot(BootMovieLibrary.list(app), BootMovie.choice(app))
|
||||
}
|
||||
if (before != null && before != snapshot?.selected) changed()
|
||||
delay(2_000)
|
||||
}
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.clip(shape)
|
||||
.background(if (selected) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f))
|
||||
.border(if (selected) 2.dp else 1.dp, if (selected) pal.signal else pal.line, shape)
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.hoverable(src)
|
||||
.clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Tab, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.semantics { contentDescription = label; this.selected = selected }
|
||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(label, fontSize = 12.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
|
||||
color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
/** The "Boot movie" settings group: Installed movies, Import your own movies, SteamDeckRepo and Sound. */
|
||||
@Composable
|
||||
internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
|
||||
var tab by rememberSaveable { mutableStateOf(MovieTab.INSTALLED) }
|
||||
SettingsGroup(stringResource(R.string.boot_movie)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) {
|
||||
TabChip(stringResource(R.string.boot_movie_tab_installed), tab == MovieTab.INSTALLED, Modifier.weight(1f)) { tab = MovieTab.INSTALLED }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_import), tab == MovieTab.IMPORT, Modifier.weight(1f)) { tab = MovieTab.IMPORT }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_repo), tab == MovieTab.REPO, Modifier.weight(1f)) { tab = MovieTab.REPO }
|
||||
TabChip(stringResource(R.string.boot_movie_tab_sound), tab == MovieTab.SOUND, Modifier.weight(1f)) { tab = MovieTab.SOUND }
|
||||
}
|
||||
when (tab) {
|
||||
MovieTab.INSTALLED -> InstalledTab(a)
|
||||
MovieTab.IMPORT -> ImportTab(s, a)
|
||||
MovieTab.REPO -> RepoTab(a)
|
||||
MovieTab.SOUND -> SoundTab(s, a, host)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InstalledTab(a: ModeSettingsActions) {
|
||||
var browsing by remember { mutableStateOf(false) }
|
||||
val snapshot = rememberMovies(0, a.onBootMovieChanged)
|
||||
val current = snapshot?.let { snap -> snap.entries.firstOrNull { it.id == snap.selected }?.title }
|
||||
val hint = current ?: stringResource(R.string.common_working)
|
||||
SettingsRow(stringResource(R.string.boot_movie_installed), hint) {
|
||||
SecondaryButton(stringResource(R.string.boot_movie_browse), onClick = { browsing = true })
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.boot_movie_note), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp).padding(bottom = 12.dp),
|
||||
)
|
||||
val app = LocalContext.current.applicationContext
|
||||
val scope = rememberCoroutineScope()
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
// The report is for bug reports, so it shows only while Debugging tools is on (read each time this tab opens).
|
||||
val debugging = remember { com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(app) }
|
||||
if (debugging) {
|
||||
SettingsRow(stringResource(R.string.boot_movie_report), stringResource(R.string.boot_movie_report_hint)) {
|
||||
SecondaryButton(stringResource(R.string.boot_movie_report_save), enabled = !saving, onClick = {
|
||||
saving = true
|
||||
scope.launch {
|
||||
val file = withContext(Dispatchers.IO) { BootMovieReport.write(app) }
|
||||
saving = false
|
||||
Toast.makeText(
|
||||
app,
|
||||
file?.let { app.getString(R.string.boot_movie_report_saved, it.path) } ?: app.getString(R.string.boot_movie_report_failed),
|
||||
Toast.LENGTH_LONG,
|
||||
).show()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
if (browsing) InstalledMoviesDialog(a) { browsing = false }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MovieCover(entry: BootMovieLibrary.Entry, modifier: Modifier = Modifier) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
val cover by androidx.compose.runtime.produceState<File?>(null, entry.id, entry.title) {
|
||||
value = withContext(Dispatchers.IO) { BootMovieLibrary.cover(app, entry) }
|
||||
}
|
||||
Box(modifier.aspectRatio(16f / 9f).clip(RoundedCornerShape(8.dp)).background(Color(0xFF0E1218))) {
|
||||
cover?.let { AsyncImage(model = it, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun movieSourceLabel(source: String): String = stringResource(
|
||||
when (source) {
|
||||
BootMovieLibrary.SOURCE_DROIDDECK -> R.string.boot_movie_source_droiddeck
|
||||
BootMovieLibrary.SOURCE_REPO -> R.string.boot_movie_source_repo
|
||||
BootMovieLibrary.SOURCE_IMPORT -> R.string.boot_movie_source_import
|
||||
BootMovieLibrary.SOURCE_POINTSHOP -> R.string.boot_movie_source_pointshop
|
||||
else -> R.string.boot_movie_source_steam
|
||||
},
|
||||
)
|
||||
|
||||
/** The installed movies as a list with covers; the one Steam plays is highlighted, and the list follows changes made in Steam. */
|
||||
@Composable
|
||||
private fun InstalledMoviesDialog(a: ModeSettingsActions, onDismiss: () -> Unit) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
val scope = rememberCoroutineScope()
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
var refresh by remember { mutableIntStateOf(0) }
|
||||
val snapshot = rememberMovies(refresh, a.onBootMovieChanged)
|
||||
var picked by remember { mutableStateOf<String?>(null) }
|
||||
var removing by remember { mutableStateOf<BootMovieLibrary.Entry?>(null) }
|
||||
var filter by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
val selected = picked ?: snapshot?.selected
|
||||
LaunchedEffect(snapshot?.selected) { picked = null }
|
||||
removing?.let { entry ->
|
||||
RemoveMovieDialog(
|
||||
entry,
|
||||
onConfirm = {
|
||||
removing = null
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) { BootMovieLibrary.remove(app, entry.id) }
|
||||
a.onBootMovieChanged()
|
||||
refresh++
|
||||
}
|
||||
},
|
||||
onDismiss = { removing = null },
|
||||
)
|
||||
}
|
||||
val firstRow = remember { FocusRequester() }
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(snapshot != null, filter) {
|
||||
if (snapshot != null && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstRow }
|
||||
}
|
||||
AppDialog(shown, close, "boot-movies", wide = false, scrollable = false) {
|
||||
val filters = listOf(
|
||||
null to stringResource(R.string.store_all),
|
||||
BootMovieLibrary.SOURCE_DROIDDECK to movieSourceLabel(BootMovieLibrary.SOURCE_DROIDDECK),
|
||||
BootMovieLibrary.SOURCE_STEAM to movieSourceLabel(BootMovieLibrary.SOURCE_STEAM),
|
||||
BootMovieLibrary.SOURCE_POINTSHOP to movieSourceLabel(BootMovieLibrary.SOURCE_POINTSHOP),
|
||||
BootMovieLibrary.SOURCE_REPO to movieSourceLabel(BootMovieLibrary.SOURCE_REPO),
|
||||
BootMovieLibrary.SOURCE_IMPORT to movieSourceLabel(BootMovieLibrary.SOURCE_IMPORT),
|
||||
)
|
||||
var filterOpen by remember { mutableStateOf(false) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.boot_movie_installed), fontSize = 15.sp, color = MaterialTheme.colorScheme.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
|
||||
)
|
||||
Box {
|
||||
androidx.compose.runtime.CompositionLocalProvider(LocalChipMinWidth provides 100.dp) {
|
||||
ValueChip(filters.first { it.first == filter }.second, filterOpen) { filterOpen = !filterOpen }
|
||||
}
|
||||
AnchoredMenu(filterOpen, onDismiss = { filterOpen = false }, compact = true) { firstItemFocus ->
|
||||
filters.forEachIndexed { index, (source, label) ->
|
||||
MenuItem(label, checked = filter == source, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
filter = source
|
||||
filterOpen = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = close)
|
||||
}
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().weight(1f, fill = false)) {
|
||||
itemsIndexed(snapshot?.entries.orEmpty().filter { filter == null || it.source == filter }, key = { _, entry -> entry.id }) { index, entry ->
|
||||
ListRow(accent = entry.id == selected, tall = true, focus = if (index == 0) firstRow else null, onClick = { picked = entry.id; a.onBootMovie(entry.id) }) {
|
||||
MovieCover(entry, Modifier.size(width = 96.dp, height = 54.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(entry.title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
|
||||
maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(movieSourceLabel(entry.source), fontSize = 12.sp, color = if (entry.id == selected) LocalPalette.current.signal else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
if (entry.removable) SmallIconButton(Icons.Filled.Close, stringResource(R.string.boot_movie_remove), MaterialTheme.colorScheme.error) {
|
||||
removing = entry
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RemoveMovieDialog(entry: BootMovieLibrary.Entry, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.boot_movie_remove_confirm, entry.title)) },
|
||||
text = { Text(stringResource(R.string.boot_movie_remove_confirm_body)) },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm) { Text(stringResource(R.string.boot_movie_remove)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ImportTab(s: ModeSettings, a: ModeSettingsActions) {
|
||||
SettingsRow(
|
||||
stringResource(R.string.boot_movie_custom),
|
||||
stringResource(R.string.boot_movie_custom_hint, (BootMovie.MAX_BYTES shr 20).toInt(), BootMovie.MAX_CONVERT_SECONDS),
|
||||
) {
|
||||
SecondaryButton(
|
||||
when {
|
||||
s.bootMovieProgress >= 0 -> stringResource(R.string.boot_movie_converting, s.bootMovieProgress)
|
||||
s.bootMovieImporting -> stringResource(R.string.common_working)
|
||||
else -> stringResource(R.string.boot_movie_import)
|
||||
},
|
||||
enabled = !s.bootMovieImporting,
|
||||
progress = s.bootMovieProgress.takeIf { it >= 0 }?.let { it / 100f },
|
||||
onClick = a.onImportBootMovie,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SoundTab(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
var volume by remember { mutableIntStateOf(SessionPrefs.bootMovieVolume(app)) }
|
||||
var seconds by remember { mutableIntStateOf(SessionPrefs.bootMovieSeconds(app)) }
|
||||
val duration by androidx.compose.runtime.produceState(0, s.bootMovie) {
|
||||
value = withContext(Dispatchers.IO) { BootMovieLibrary.durationSeconds(BootMovie.currentFile(app)) }
|
||||
}
|
||||
ToggleRow(
|
||||
host, "boot-movie-sound", stringResource(R.string.boot_movie_sound),
|
||||
stringResource(R.string.common_applies_next_session), s.bootMovieSound, onChange = a.onBootMovieSound,
|
||||
)
|
||||
Box(Modifier.padding(horizontal = 6.dp)) {
|
||||
ValueSlider(
|
||||
volume, 0..100, 5, s.bootMovieSound, stringResource(R.string.boot_movie_volume), { "$it%" },
|
||||
) { volume = it; SessionPrefs.setBootMovieVolume(app, it) }
|
||||
}
|
||||
Box(Modifier.padding(horizontal = 6.dp)) {
|
||||
val shownSeconds = if (seconds in 1 until duration) seconds else duration
|
||||
ValueSlider(
|
||||
shownSeconds, 1..duration.coerceAtLeast(2), 1, duration > 1, stringResource(R.string.boot_movie_length),
|
||||
{ value -> app.getString(R.string.boot_movie_seconds, value) },
|
||||
) { next ->
|
||||
val stored = if (next >= duration) 0 else next
|
||||
seconds = stored
|
||||
SessionPrefs.setBootMovieSeconds(app, stored)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.boot_movie_length_hint), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp).padding(bottom = 12.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RepoTab(a: ModeSettingsActions) {
|
||||
val progress = installProgress
|
||||
val app = LocalContext.current.applicationContext
|
||||
val scope = rememberCoroutineScope()
|
||||
var sort by rememberSaveable { mutableStateOf(SteamDeckRepo.Sort.TRENDING) }
|
||||
var device by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var page by rememberSaveable { mutableIntStateOf(1) }
|
||||
var retry by remember { mutableIntStateOf(0) }
|
||||
var searching by remember { mutableStateOf(false) }
|
||||
var jumping by remember { mutableStateOf(false) }
|
||||
var previewing by remember { mutableStateOf<SteamDeckRepo.Post?>(null) }
|
||||
var installed by remember { mutableStateOf(setOf<String>()) }
|
||||
val chosen = rememberMovies(0, a.onBootMovieChanged)?.selected
|
||||
val inUse by androidx.compose.runtime.produceState<String?>(null, chosen) {
|
||||
value = withContext(Dispatchers.IO) {
|
||||
chosen?.takeIf { it.startsWith(BootMovieLibrary.PREFIX) }?.let { BootMovieLibrary.repoId(app, it.removePrefix(BootMovieLibrary.PREFIX)) }
|
||||
}
|
||||
}
|
||||
LaunchedEffect(progress.size) { installed = withContext(Dispatchers.IO) { BootMovieLibrary.installedRepoIds(app) } }
|
||||
val result by androidx.compose.runtime.produceState<SteamDeckRepo.Page?>(null, sort, device, query, page, retry) {
|
||||
value = null
|
||||
value = withContext(Dispatchers.IO) { SteamDeckRepo.fetch(sort, device, query, page) }
|
||||
}
|
||||
val last by androidx.compose.runtime.produceState<Int?>(null, sort, device, query, retry) {
|
||||
value = null
|
||||
value = withContext(Dispatchers.IO) { SteamDeckRepo.lastPage(sort, device, query) }
|
||||
}
|
||||
LaunchedEffect(last) { last?.let { if (page > it) page = it } }
|
||||
val installPost: (SteamDeckRepo.Post) -> Unit = { post ->
|
||||
if (progress.isEmpty()) {
|
||||
progress[post.id] = 0
|
||||
installScope.launch {
|
||||
val outcome = try {
|
||||
withContext(Dispatchers.IO) { install(app, post) { progress[post.id] = it } }
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
app.getString(R.string.boot_movie_repo_download_failed)
|
||||
} finally {
|
||||
progress.remove(post.id)
|
||||
}
|
||||
Toast.makeText(app, outcome ?: app.getString(R.string.boot_movie_repo_installed, post.title), Toast.LENGTH_LONG).show()
|
||||
a.onBootMovieChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
val usePost: (SteamDeckRepo.Post) -> Unit = { post ->
|
||||
scope.launch {
|
||||
val name = withContext(Dispatchers.IO) { BootMovieLibrary.nameForRepo(app, post.id) }
|
||||
if (name != null) a.onBootMovie(BootMovieLibrary.idOf(name))
|
||||
}
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).padding(bottom = 12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Box(Modifier.weight(1f)) {
|
||||
ListRow(tall = true, onClick = { searching = true }) {
|
||||
Icon(Icons.Filled.Search, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp))
|
||||
Text(
|
||||
query.ifEmpty { stringResource(R.string.boot_movie_repo_search) }, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (query.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (query.isNotEmpty()) SecondaryButton(stringResource(R.string.boot_movie_repo_clear), compact = true) { query = ""; page = 1 }
|
||||
}
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
TabChip(stringResource(R.string.boot_movie_repo_all), device == null) { device = null; page = 1 }
|
||||
TabChip(stringResource(R.string.boot_movie_repo_deck), device == "steam_deck") { device = "steam_deck"; page = 1 }
|
||||
TabChip(stringResource(R.string.boot_movie_repo_machine), device == "steam_machine") { device = "steam_machine"; page = 1 }
|
||||
}
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
SteamDeckRepo.Sort.values().forEach { option ->
|
||||
TabChip(
|
||||
stringResource(
|
||||
when (option) {
|
||||
SteamDeckRepo.Sort.TRENDING -> R.string.boot_movie_repo_trending
|
||||
SteamDeckRepo.Sort.DOWNLOADS -> R.string.boot_movie_repo_downloads
|
||||
SteamDeckRepo.Sort.LIKES -> R.string.boot_movie_repo_likes
|
||||
SteamDeckRepo.Sort.NEWEST -> R.string.boot_movie_repo_newest
|
||||
},
|
||||
),
|
||||
sort == option,
|
||||
) { sort = option; page = 1 }
|
||||
}
|
||||
}
|
||||
when (val r = result) {
|
||||
null -> Text(stringResource(R.string.common_working), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
|
||||
is SteamDeckRepo.Page.Failed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(stringResource(R.string.boot_movie_repo_failed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f))
|
||||
SecondaryButton(stringResource(R.string.boot_movie_repo_retry), compact = true) { retry++ }
|
||||
}
|
||||
is SteamDeckRepo.Page.Ok -> {
|
||||
if (r.posts.isEmpty()) Text(stringResource(R.string.boot_movie_repo_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
|
||||
r.posts.chunked(2).forEach { row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
row.forEach { post ->
|
||||
RepoCard(
|
||||
post, installed = post.id in installed, inUse = post.id == inUse, percent = progress[post.id], busy = progress.isNotEmpty(),
|
||||
modifier = Modifier.weight(1f), onPreview = { previewing = post }, onInstall = { installPost(post) }, onUse = { usePost(post) },
|
||||
)
|
||||
}
|
||||
if (row.size == 1) Box(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
RepoPager(page, last, hasMore = r.posts.size >= SteamDeckRepo.PAGE_SIZE, onPage = { page = it }, onJump = { jumping = true })
|
||||
}
|
||||
}
|
||||
}
|
||||
if (searching) TextEntryDialog(
|
||||
stringResource(R.string.boot_movie_repo_search), query, number = false, confirm = stringResource(R.string.stores_search_open),
|
||||
onSubmit = { value -> if (value != query) { query = value; page = 1 } }, onDismiss = { searching = false },
|
||||
)
|
||||
if (jumping) TextEntryDialog(
|
||||
stringResource(R.string.boot_movie_repo_go_to_page), page.toString(), number = true, confirm = stringResource(R.string.common_ok),
|
||||
onSubmit = { value -> value.toIntOrNull()?.let { n -> page = n.coerceIn(1, maxOf(1, last ?: n)) } }, onDismiss = { jumping = false },
|
||||
)
|
||||
previewing?.let { post ->
|
||||
PreviewDialog(
|
||||
post, installed = post.id in installed, inUse = post.id == inUse, percent = progress[post.id], busy = progress.isNotEmpty(),
|
||||
onInstall = { installPost(post) }, onUse = { usePost(post) }, onDismiss = { previewing = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Downloads [post] and puts it among the installed movies; returns a message when it failed, null when it worked. */
|
||||
private fun install(app: android.content.Context, post: SteamDeckRepo.Post, onProgress: (Int) -> Unit): String? {
|
||||
val folder = File(app.cacheDir, "boot-movie-download").apply { mkdirs() }
|
||||
// Leftovers of a download that was cut short are cleared, and every download has a file of its own.
|
||||
folder.listFiles()?.forEach { if (System.currentTimeMillis() - it.lastModified() > 60 * 60 * 1000L) it.delete() }
|
||||
val file = File.createTempFile("movie-", ".webm", folder)
|
||||
return try {
|
||||
if (!SteamDeckRepo.download(post, file, onProgress)) return app.getString(R.string.boot_movie_repo_download_failed)
|
||||
val cover = if (post.thumbnail.isNotEmpty()) SteamDeckRepo.bytes(post.thumbnail) else null
|
||||
when (BootMovie.import(app, file, onProgress = onProgress, title = post.title, source = BootMovieLibrary.SOURCE_REPO, repoId = post.id, cover = cover, use = false)) {
|
||||
is BootMovie.Import.Done -> null
|
||||
BootMovie.Import.TooLong -> app.getString(R.string.boot_movie_too_long, BootMovie.MAX_CONVERT_SECONDS)
|
||||
is BootMovie.Import.Unsupported -> app.getString(R.string.boot_movie_unsupported)
|
||||
BootMovie.Import.Failed -> app.getString(R.string.boot_movie_import_failed)
|
||||
}
|
||||
} finally {
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RepoCard(
|
||||
post: SteamDeckRepo.Post, installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean, modifier: Modifier,
|
||||
onPreview: () -> Unit, onInstall: () -> Unit, onUse: () -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
val thumbShape = RoundedCornerShape(7.dp)
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val previewLabel = stringResource(R.string.boot_movie_repo_preview)
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(5.dp),
|
||||
modifier = modifier.clip(shape)
|
||||
.background(if (inUse) pal.signal.copy(alpha = 0.14f) else colors.surface.copy(alpha = 0.6f))
|
||||
.border(if (inUse) 2.dp else 1.dp, if (inUse) pal.signal else pal.line, shape).padding(6.dp),
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).clip(thumbShape).background(Color(0xFF0E1218))
|
||||
.glideBorder(hot, thumbShape, pal.signal)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onPreview)
|
||||
.controllerConfirm(onClick = onPreview)
|
||||
.semantics { contentDescription = previewLabel },
|
||||
) {
|
||||
if (post.thumbnail.isNotEmpty()) AsyncImage(model = post.thumbnail, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
Box(Modifier.size(40.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.55f)), contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.Filled.PlayArrow, contentDescription = null, tint = Color.White, modifier = Modifier.size(26.dp))
|
||||
}
|
||||
}
|
||||
Text(post.title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(repoInfo(post), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
RepoAction(installed, inUse, percent, busy, Modifier.fillMaxWidth(), onInstall, onUse)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun repoInfo(post: SteamDeckRepo.Post): String =
|
||||
listOf(post.author, "♥ ${post.likes}", "⇩ ${post.downloads}", if (post.seconds > 0) stringResource(R.string.boot_movie_seconds, post.seconds) else "")
|
||||
.filter { it.isNotEmpty() }.joinToString(" · ")
|
||||
|
||||
@Composable
|
||||
private fun RepoAction(installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean, modifier: Modifier, onInstall: () -> Unit, onUse: () -> Unit) {
|
||||
if (inUse) SecondaryButton(stringResource(R.string.boot_movie_in_use), compact = true, modifier = modifier, onClick = {})
|
||||
else if (installed) SecondaryButton(stringResource(R.string.boot_movie_repo_use), compact = true, modifier = modifier, onClick = onUse)
|
||||
else SecondaryButton(
|
||||
if (percent != null) stringResource(R.string.boot_movie_converting, percent) else stringResource(R.string.boot_movie_repo_install),
|
||||
enabled = !busy, compact = true, modifier = modifier, onClick = onInstall,
|
||||
)
|
||||
}
|
||||
|
||||
/** A movie from SteamDeckRepo played straight from the site, so it can be checked before it is installed. */
|
||||
@Composable
|
||||
private fun PreviewDialog(
|
||||
post: SteamDeckRepo.Post, installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean,
|
||||
onInstall: () -> Unit, onUse: () -> Unit, onDismiss: () -> Unit,
|
||||
) {
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
val action = remember { FocusRequester() }
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(Unit) { if (inputMode.inputMode == InputMode.Keyboard) focusSoon { action } }
|
||||
val maxVideoHeight = (LocalConfiguration.current.screenHeightDp - 200).coerceAtLeast(120).dp
|
||||
AppDialog(shown, close, "boot-movie-preview", wide = false, maxWidth = 620.dp) {
|
||||
DialogTitleRow(post.title, close)
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
MoviePreview(post.video, Modifier.heightIn(max = maxVideoHeight).aspectRatio(16f / 9f))
|
||||
}
|
||||
Text(repoInfo(post), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
RepoAction(installed, inUse, percent, busy, Modifier.fillMaxWidth().focusRequester(action), onInstall, onUse)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MoviePreview(url: String, modifier: Modifier = Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
var state by remember(url) { mutableIntStateOf(0) }
|
||||
var ratio by remember(url) { mutableFloatStateOf(16f / 9f) }
|
||||
val player = remember(url) { arrayOfNulls<MediaPlayer>(1) }
|
||||
DisposableEffect(url) {
|
||||
onDispose {
|
||||
runCatching { player[0]?.release() }
|
||||
player[0] = null
|
||||
}
|
||||
}
|
||||
val toggle = { runCatching { player[0]?.let { if (it.isPlaying) it.pause() else it.start() } }; Unit }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.clip(shape).background(Color.Black)
|
||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle)
|
||||
.controllerConfirm(onClick = toggle),
|
||||
) {
|
||||
AndroidView(
|
||||
modifier = Modifier.aspectRatio(ratio),
|
||||
factory = { viewContext ->
|
||||
TextureView(viewContext).apply {
|
||||
surfaceTextureListener = object : TextureView.SurfaceTextureListener {
|
||||
override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) {
|
||||
val mp = MediaPlayer()
|
||||
player[0] = mp
|
||||
try {
|
||||
mp.setDataSource(viewContext, Uri.parse(url), mapOf("User-Agent" to "DroidDeck"))
|
||||
mp.setSurface(Surface(texture))
|
||||
mp.isLooping = true
|
||||
mp.setOnVideoSizeChangedListener { _, w, h -> if (w > 0 && h > 0) ratio = w.toFloat() / h }
|
||||
mp.setOnPreparedListener { it.start(); state = 1 }
|
||||
mp.setOnErrorListener { _, _, _ -> state = 2; true }
|
||||
mp.prepareAsync()
|
||||
} catch (e: Exception) {
|
||||
state = 2
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) = Unit
|
||||
|
||||
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean {
|
||||
runCatching { player[0]?.release() }
|
||||
player[0] = null
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
if (state == 0) Text(stringResource(R.string.common_working), fontSize = 13.sp, color = Color.White.copy(alpha = 0.8f))
|
||||
if (state == 2) Text(stringResource(R.string.boot_movie_repo_preview_failed), fontSize = 13.sp, color = Color.White.copy(alpha = 0.8f), modifier = Modifier.padding(12.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** A dialog with one text box, for a search term or a page number; the Android keyboard comes up with it. */
|
||||
@Composable
|
||||
private fun TextEntryDialog(
|
||||
title: String, initial: String, number: Boolean, confirm: String, onSubmit: (String) -> Unit, onDismiss: () -> Unit,
|
||||
) {
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
var text by remember { mutableStateOf(initial) }
|
||||
val submit = { onSubmit(text.trim()); close() }
|
||||
AppDialog(shown, close, "boot-movie-entry", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(title, close)
|
||||
AdbTextField(
|
||||
value = text, onValueChange = { text = it }, label = "", keyboardType = if (number) KeyboardType.Number else KeyboardType.Text,
|
||||
imeAction = ImeAction.Done, placeholder = title, focusOnShow = true, onDone = { submit() },
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close)
|
||||
SecondaryButton(confirm, modifier = Modifier.weight(1f)) { submit() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Page buttons around the current page, which opens a box to type another page into; first and last page show their numbers. */
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun RepoPager(page: Int, last: Int?, hasMore: Boolean, onPage: (Int) -> Unit, onJump: () -> Unit) {
|
||||
val reach = last ?: if (hasMore) Int.MAX_VALUE else page
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
SecondaryButton(stringResource(R.string.boot_movie_repo_previous), enabled = page > 1, compact = true) { onPage(page - 1) }
|
||||
if (page - 3 > 1) SecondaryButton("1", compact = true) { onPage(1) }
|
||||
for (n in maxOf(1, page - 3) until page) SecondaryButton("$n", compact = true) { onPage(n) }
|
||||
TabChip("$page", true, Modifier.widthIn(min = 52.dp).heightIn(min = 44.dp), onJump)
|
||||
for (n in page + 1..minOf(page + 3, reach)) SecondaryButton("$n", compact = true) { onPage(n) }
|
||||
if (last != null && page + 3 < last) SecondaryButton("$last", compact = true) { onPage(last) }
|
||||
SecondaryButton(stringResource(R.string.boot_movie_repo_next), enabled = page < reach, compact = true) { onPage(page + 1) }
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ class ModeSettingsActions(
|
||||
val onBootMovie: (String) -> Unit = {},
|
||||
val onBootMovieSound: (Boolean) -> Unit = {},
|
||||
val onImportBootMovie: () -> Unit = {},
|
||||
val onRemoveBootMovie: () -> Unit = {},
|
||||
val onBootMovieChanged: () -> Unit = {},
|
||||
val onWifiDiscovery: (Boolean) -> Unit = {},
|
||||
val onWifiDiscoverySettings: () -> Unit = {},
|
||||
val onDeckyInstall: (DeckyManager.Release) -> Unit = {},
|
||||
@@ -467,41 +467,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
onPick = a.onSteamClientArch,
|
||||
)
|
||||
}
|
||||
if (s.bootMovie != null) SettingsGroup(stringResource(R.string.boot_movie)) {
|
||||
ChoiceRow(
|
||||
host, "boot-movie", stringResource(R.string.boot_movie_video), stringResource(R.string.common_applies_next_session),
|
||||
buildList {
|
||||
add(BootMovie.DROIDDECK_30 to stringResource(R.string.boot_movie_droiddeck, 30))
|
||||
add(BootMovie.DROIDDECK_60 to stringResource(R.string.boot_movie_droiddeck, 60))
|
||||
s.bootMovieCustomName?.let { add(BootMovie.CUSTOM to it) }
|
||||
}, s.bootMovie,
|
||||
note = stringResource(R.string.boot_movie_note), onPick = a.onBootMovie,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "boot-movie-sound", stringResource(R.string.boot_movie_sound),
|
||||
stringResource(R.string.common_applies_next_session), s.bootMovieSound, onChange = a.onBootMovieSound,
|
||||
)
|
||||
SettingsRow(
|
||||
stringResource(R.string.boot_movie_custom),
|
||||
stringResource(R.string.boot_movie_custom_hint, (BootMovie.MAX_BYTES shr 20).toInt(), BootMovie.MAX_CONVERT_SECONDS),
|
||||
) {
|
||||
Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton(
|
||||
when {
|
||||
s.bootMovieProgress >= 0 -> stringResource(R.string.boot_movie_converting, s.bootMovieProgress)
|
||||
s.bootMovieImporting -> stringResource(R.string.common_working)
|
||||
else -> stringResource(R.string.boot_movie_import)
|
||||
},
|
||||
enabled = !s.bootMovieImporting,
|
||||
progress = s.bootMovieProgress.takeIf { it >= 0 }?.let { it / 100f },
|
||||
onClick = a.onImportBootMovie,
|
||||
)
|
||||
if (s.bootMovieCustomName != null) SecondaryButton(
|
||||
stringResource(R.string.boot_movie_remove), enabled = !s.bootMovieImporting, onClick = a.onRemoveBootMovie,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.bootMovie != null) BootMovieGroup(s, a, host)
|
||||
if (s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
|
||||
val hint = when {
|
||||
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
|
||||
|
||||
Reference in new issue
Block a user