ROMs folder and Storage in the session's home, the app's own file picker, logs finished on a crash, a two-column menu

A program's file dialog inside the session never showed the phone: internal storage was bound
at its own path, but proot binds do not appear in /proc/mounts and nothing under home pointed at
it. Every session now binds internal storage at /root/Storage and the folder chosen with the new
ROMs folder tile at /root/ROMs - a bind, so a folder on an SD card works the same.

Folder and file choosing is the app's own picker (files/), Bannerlator's File Manager pick mode
carried over: StorageRoots verbatim for the drive menu, the same intent API (InAppFilePicker),
folders first, an up-arrow floored at the volume root, the last folder remembered. Both driver
imports use it instead of the system document picker.

A session folder is finished whichever way the session ends: SessionArtifacts is shared by the
ordinary stop, an uncaught-exception handler (App/CrashHandler, writes crash-app.txt and finishes
the folder before the process dies) and a sweep at the next app start for a folder without its
.complete marker (a kill or a native crash), which gets ended-without-teardown.txt and the crash
buffer. A Session logs tile turns the folder off: it then lives in the cache and is deleted at
the end.

The main menu is two columns of tiles, each with its setting's value under its title.
This commit is contained in:
The412Banner committed 2026-09-21 22:43:56 -04:00
1 parent 3aa0162055
commit cb5a1b5a31
15 files changed
+1066 -91

No files matched your search

@@ -0,0 +1,12 @@
package com.steamdeck.launcher
import android.app.Application
import com.steamdeck.launcher.session.CrashHandler
/** Process-wide setup: the crash handler, so a session's folder is finished even when we die. */
class App : Application() {
override fun onCreate() {
super.onCreate()
CrashHandler.install(this)
}
}
@@ -45,6 +45,10 @@ import com.steamdeck.launcher.ui.FrameGenDialog
import com.steamdeck.launcher.ui.MainScreen
import com.steamdeck.launcher.ui.MainUiState
import com.steamdeck.launcher.ui.SteamDeckTheme
import com.steamdeck.launcher.ui.RomsDialog
import com.steamdeck.launcher.files.InAppFilePicker
import com.steamdeck.launcher.session.SessionArtifacts
import com.steamdeck.launcher.session.SessionState
/**
* The whole app outside a session: is the runtime installed, is there a newer one, frame
@@ -95,14 +99,23 @@ class MainActivity : ComponentActivity() {
private var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
private var androidSelected by mutableStateOf("")
// The system file picker, once per driver list: the two lists validate differently, and the
// reason a zip is refused names the list it belongs in.
private val pickLinuxDriver = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) importDriver(uri, linux = true)
// The app's own picker (files/), once per kind of pick: the two driver lists validate
// differently, and the reason a zip is refused names the list it belongs in.
private val pickLinuxDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = true) }
}
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) importDriver(uri, linux = false)
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = false) }
}
private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
SessionPrefs.setRomsDir(this, path)
romsDir = path
}
}
private var romsDir by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true)
private var showRoms by mutableStateOf(false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -117,6 +130,7 @@ class MainActivity : ComponentActivity() {
frameGenLabel = frameGenLabel,
desktopInstalled = desktopInstalled,
offlineAccount = offlineAccount, offline = offline,
romsDir = romsDir, logsEnabled = logsEnabled,
),
onPlay = { startActivity(Intent(this, SessionActivity::class.java)) },
onDesktop = {
@@ -134,8 +148,22 @@ class MainActivity : ComponentActivity() {
onDrivers = { refreshDrivers(); showDrivers = true },
onAudio = { directAudio = SessionPrefs.directAudio(this); mic = SessionPrefs.micEnabled(this); showAudio = true },
onPerformance = { refreshCores(); showPerformance = true },
onRoms = { showRoms = true },
onLogs = {
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
logsEnabled = SessionPrefs.logsEnabled(this)
},
onCredits = { showCredits = true },
)
if (showRoms) RomsDialog(
path = romsDir,
onChoose = {
showRoms = false
pickRomsDir.launch(InAppFilePicker.buildDirIntent(this, "Choose the ROMs folder", romsDir))
},
onClear = { SessionPrefs.setRomsDir(this, ""); romsDir = null; showRoms = false },
onDismiss = { showRoms = false },
)
if (showApps) DesktopAppsDialog(
rows = packageRows, busyStage = pkgStage, busyPercent = pkgPercent,
onInstall = { id -> installPackage(id) },
@@ -153,10 +181,10 @@ class MainActivity : ComponentActivity() {
linuxRows = linuxRows, linuxSteam = linuxSteam, linuxDesktop = linuxDesktop,
androidRows = androidRows, androidSelected = androidSelected,
onSelectLinux = { mode, id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() },
onImportLinux = { pickLinuxDriver.launch(ZIP_TYPES) },
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
onRemoveLinux = { id -> LinuxVulkanDriverManager(this).removeDriver(id); refreshDrivers() },
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() },
onImportAndroid = { pickAndroidDriver.launch(ZIP_TYPES) },
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
onRemoveAndroid = { id -> TurnipDriver(this).remove(id); refreshDrivers() },
onDismiss = { showDrivers = false },
)
@@ -221,6 +249,8 @@ class MainActivity : ComponentActivity() {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
}
// A session folder left without its ending - the process was killed - gets it now.
if (!SessionState.running) Thread({ SessionArtifacts.finishAbandoned(this) }, "finish-abandoned").start()
}
override fun onResume() {
@@ -319,7 +349,7 @@ class MainActivity : ComponentActivity() {
}, "import-driver").start()
}
private fun displayNameOf(uri: Uri): String? = try {
private fun displayNameOf(uri: Uri): String? = if (uri.scheme == "file") uri.lastPathSegment else try {
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
} catch (e: Exception) {
@@ -359,6 +389,8 @@ class MainActivity : ComponentActivity() {
installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this)
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
}
private fun onRuntimeButton() {
@@ -402,6 +434,6 @@ class MainActivity : ComponentActivity() {
companion object {
private const val TAG = "MainActivity"
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
private val ZIP_TYPES = arrayOf("application/zip", "application/octet-stream")
private val ZIP_EXT = listOf("zip")
}
}
@@ -0,0 +1,77 @@
package com.steamdeck.launcher.files
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.steamdeck.launcher.ui.SteamDeckTheme
import java.io.File
/**
* Themed host for [FilePickerScreen]. Launched through [InAppFilePicker] and answers with the
* picked path in [EXTRA_SELECTED_FILE] on RESULT_OK.
*
* Extras:
* - [EXTRA_EXTENSIONS] allowed lowercase extensions, no dot; absent or empty = all files
* - [EXTRA_PICK_DIRECTORY] true to pick a folder instead of a file
* - [EXTRA_INITIAL_DIRECTORY] where to open; absent = the last folder picked from, then internal storage
* - [EXTRA_PICKER_TITLE] the header
*/
class FilePickerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// targetSdk 28: the old storage permission is exactly what lets us list the card.
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
val extensions = intent.getStringArrayExtra(EXTRA_EXTENSIONS)?.toList() ?: emptyList()
val pickDir = intent.getBooleanExtra(EXTRA_PICK_DIRECTORY, false)
val title = intent.getStringExtra(EXTRA_PICKER_TITLE)
val prefs = getSharedPreferences("picker", MODE_PRIVATE)
val initialDir = (intent.getStringExtra(EXTRA_INITIAL_DIRECTORY) ?: prefs.getString("lastDir", null))
?.let { File(it) }?.takeIf { it.isDirectory }
setContent {
SteamDeckTheme {
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
FilePickerScreen(
pickDirMode = pickDir,
pickExtensions = extensions,
initialDir = initialDir,
title = title ?: if (pickDir) "Choose a folder" else "Choose a file",
onPick = { file ->
val remembered = if (file.isDirectory) file else file.parentFile
remembered?.let { prefs.edit().putString("lastDir", it.absolutePath).apply() }
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
finish()
},
onCancel = { setResult(Activity.RESULT_CANCELED); finish() },
)
}
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// The screen re-lists on its own when the grant lands; nothing to relay.
if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate()
}
companion object {
const val EXTRA_EXTENSIONS = "extensions"
const val EXTRA_PICK_DIRECTORY = "pickDirectory"
const val EXTRA_INITIAL_DIRECTORY = "initialDirectory"
const val EXTRA_PICKER_TITLE = "pickerTitle"
const val EXTRA_SELECTED_FILE = "selectedFile"
}
}
@@ -0,0 +1,283 @@
package com.steamdeck.launcher.files
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.steamdeck.launcher.core.FileUtils
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* The file picker, as Bannerlator's File Manager behaves in pick mode: a drive menu with every
* mounted volume ([StorageRoots]), the path with an up-arrow that stops at the drive's root so
* nobody is trapped in a subfolder, folders first, and either a tap on a matching file or "Use
* this folder". Nothing here edits, runs or copies anything; that is a file manager's job and
* this app does not have one.
*/
@Composable
fun FilePickerScreen(
pickDirMode: Boolean,
pickExtensions: List<String>,
initialDir: File?,
title: String,
onPick: (File) -> Unit,
onCancel: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val lowerExts = remember(pickExtensions) { pickExtensions.map { it.lowercase() } }
val start = remember { initialDir?.takeIf { it.isDirectory } ?: File(INTERNAL) }
var currentDir by remember { mutableStateOf(start) }
// The floor for up/back: the volume the folder is on, never the folder itself.
var currentRoot by remember { mutableStateOf(volumeRootOf(start)) }
var entries by remember { mutableStateOf<List<File>?>(null) }
var storageTick by remember { mutableStateOf(0) }
val drives = remember(storageTick) { StorageRoots.list(context) }
var showDrives by remember { mutableStateOf(false) }
fun matches(file: File): Boolean {
if (file.isDirectory) return true
if (pickDirMode) return false
if (lowerExts.isEmpty()) return true
val name = file.name.lowercase()
return lowerExts.any { name.endsWith(".$it") }
}
fun reload() {
entries = currentDir.listFiles()
?.filter { !it.name.startsWith(".") && matches(it) }
?.sortedWith(compareBy<File> { !it.isDirectory }.thenBy { it.name.lowercase() })
}
fun open(dir: File) {
currentDir = dir
reload()
}
fun openDrive(root: File) {
currentRoot = root
open(root)
}
fun goUp() {
val parent = currentDir.parentFile ?: return
if (currentDir.absolutePath == currentRoot.absolutePath) return
open(parent)
}
val atRoot = currentDir.absolutePath == currentRoot.absolutePath
LaunchedEffect(Unit) { reload() }
BackHandler { if (atRoot) onCancel() else goUp() }
Column(modifier = Modifier.fillMaxSize().systemBarsPadding()) {
// Header: back, title, drive menu, refresh.
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 4.dp, end = 4.dp, top = 4.dp),
) {
IconButton(onClick = onCancel) { Icon(Icons.Filled.ArrowBack, contentDescription = "Cancel") }
Text(
title, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
Box {
val driveLabel = drives.firstOrNull { currentRoot.absolutePath == it.dir.absolutePath }?.label
?: currentRoot.name.ifEmpty { "/" }
OutlinedButton(onClick = { showDrives = true }) {
Text(driveLabel, fontSize = 12.sp, maxLines = 1)
Icon(Icons.Filled.ArrowDropDown, contentDescription = null, modifier = Modifier.size(18.dp))
}
DropdownMenu(expanded = showDrives, onDismissRequest = { showDrives = false }) {
drives.forEach { drive ->
DropdownMenuItem(
text = {
Column {
Text(drive.label + if (drive.removable) " · SD" else "")
Text(
if (drive.readable) drive.dir.absolutePath else "mounted, not readable right now",
fontSize = 11.sp, color = colors.onSurfaceVariant,
)
}
},
enabled = drive.readable,
onClick = { showDrives = false; openDrive(drive.dir) },
)
}
}
}
IconButton(onClick = { storageTick++; reload() }) {
Icon(Icons.Filled.Refresh, contentDescription = "Refresh")
}
}
// The path, with up.
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),
) {
IconButton(onClick = { goUp() }, enabled = !atRoot) {
Icon(Icons.Filled.KeyboardArrowUp, contentDescription = "Up")
}
Text(
elideStart(currentDir.absolutePath, 60), fontSize = 12.sp, color = colors.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
HorizontalDivider(color = colors.surfaceVariant)
val list = entries
when {
list == null -> Message(
if (currentDir.canRead()) "Nothing to list here" else "Not readable — allow storage access for SteamDeck and try again",
Modifier.weight(1f),
)
list.isEmpty() -> Message(
when {
pickDirMode -> "No folders here — use this one, or go up"
lowerExts.isNotEmpty() -> "No ${lowerExts.joinToString(" / ") { ".$it" }} files here"
else -> "Empty folder"
},
Modifier.weight(1f),
)
else -> LazyColumn(modifier = Modifier.weight(1f).fillMaxWidth()) {
items(list, key = { it.absolutePath }) { file ->
EntryRow(file) { if (file.isDirectory) open(file) else onPick(file) }
}
}
}
if (pickDirMode) {
HorizontalDivider(color = colors.surfaceVariant)
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().padding(12.dp),
) {
OutlinedButton(onClick = onCancel, modifier = Modifier.weight(1f)) { Text("Cancel") }
Button(onClick = { onPick(currentDir) }, modifier = Modifier.weight(2f)) {
Text("Use this folder", maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
}
@Composable
private fun Message(text: String, modifier: Modifier) {
Box(modifier = modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
Text(text, color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 13.sp)
}
}
@Composable
private fun EntryRow(file: File, onTap: () -> Unit) {
val colors = MaterialTheme.colorScheme
val isDir = file.isDirectory
val detail = remember(file.absolutePath) {
val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(file.lastModified()))
if (isDir) stamp else "${FileUtils.sizeToString(file.length())} · $stamp"
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().clickable(onClick = onTap).padding(horizontal = 16.dp, vertical = 9.dp),
) {
Glyph(isDir, if (isDir) colors.primary else colors.onSurfaceVariant)
Spacer(Modifier.width(14.dp))
Column(modifier = Modifier.weight(1f)) {
Text(file.name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
HorizontalDivider(color = colors.surfaceVariant, modifier = Modifier.padding(start = 56.dp))
}
/** A folder or a page, drawn: the app ships no icon set beyond the few in Material's core. */
@Composable
private fun Glyph(folder: Boolean, tint: Color) {
Canvas(modifier = Modifier.size(26.dp)) {
val w = size.width
val h = size.height
if (folder) {
// Tab, then body.
drawRoundRect(tint, Offset(0f, h * 0.18f), Size(w * 0.42f, h * 0.2f), CornerRadius(w * 0.06f))
drawRoundRect(tint, Offset(0f, h * 0.28f), Size(w, h * 0.58f), CornerRadius(w * 0.08f))
} else {
val left = w * 0.15f
val top = h * 0.06f
drawRoundRect(
tint, Offset(left, top), Size(w * 0.7f, h * 0.88f), CornerRadius(w * 0.06f),
style = Stroke(width = w * 0.07f),
)
// Three lines of "text".
for (i in 0..2) {
val y = h * (0.38f + 0.17f * i)
drawLine(tint, Offset(w * 0.3f, y), Offset(w * 0.7f, y), strokeWidth = w * 0.06f)
}
}
}
}
private const val INTERNAL = "/storage/emulated/0"
/** `/storage/emulated/0/Download/x` -> `/storage/emulated/0`; `/storage/ABCD-1234/y` -> the card. */
private fun volumeRootOf(dir: File): File {
val abs = dir.absolutePath
return when {
abs == INTERNAL || abs.startsWith("$INTERNAL/") -> File(INTERNAL)
abs.startsWith("/storage/") -> {
val name = abs.removePrefix("/storage/").substringBefore('/')
if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else dir
}
else -> dir
}
}
private fun elideStart(path: String, max: Int): String =
if (path.length <= max) path else "…" + path.takeLast(max - 1)
@@ -0,0 +1,44 @@
package com.steamdeck.launcher.files
import android.content.Context
import android.content.Intent
import android.net.Uri
import java.io.File
/**
* The app's own file picker, the way Bannerlator's File Manager offers its pick mode: one intent
* builder per kind of pick, and the picked path read back from the result. Every import on the
* main screen goes through here rather than Android's document picker, which cannot show an SD
* card as a card, remembers nothing, and hands back a content URI the runtime cannot bind.
*/
object InAppFilePicker {
/** Pick one file. [extensions] are lowercase, without the dot; empty = any file. */
fun buildIntent(
context: Context,
extensions: List<String> = emptyList(),
title: String? = null,
initialDir: String? = null,
): Intent = Intent(context, FilePickerActivity::class.java).apply {
putExtra(FilePickerActivity.EXTRA_EXTENSIONS, extensions.toTypedArray())
title?.let { putExtra(FilePickerActivity.EXTRA_PICKER_TITLE, it) }
initialDir?.let { putExtra(FilePickerActivity.EXTRA_INITIAL_DIRECTORY, it) }
}
/** Pick a folder: only folders are listed, and "Use this folder" returns the one open. */
fun buildDirIntent(
context: Context,
title: String? = null,
initialDir: String? = null,
): Intent = Intent(context, FilePickerActivity::class.java).apply {
putExtra(FilePickerActivity.EXTRA_PICK_DIRECTORY, true)
title?.let { putExtra(FilePickerActivity.EXTRA_PICKER_TITLE, it) }
initialDir?.let { putExtra(FilePickerActivity.EXTRA_INITIAL_DIRECTORY, it) }
}
fun pickedPath(data: Intent?): String? = data?.getStringExtra(FilePickerActivity.EXTRA_SELECTED_FILE)
fun pickedFile(data: Intent?): File? = pickedPath(data)?.let { File(it) }
/** The picked file as the `file:` URI the import code already accepts. */
fun pickedUri(data: Intent?): Uri? = pickedFile(data)?.let { Uri.fromFile(it) }
}
@@ -0,0 +1,214 @@
package com.steamdeck.launcher.files
import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.storage.StorageManager
import android.os.storage.StorageVolume
import java.io.File
/**
* A storage volume offered in the file manager's drive menu.
*
* [dir] is the best path we found for the volume: its root when that is listable, otherwise the
* deepest directory we can actually read on the way down to the app-specific directory. A volume
* always gets exactly one entry, even if several paths lead to it.
*/
data class StorageRoot(
val label: String,
val dir: File,
val removable: Boolean,
/** False when no path on the volume could be listed; the entry is still shown. */
val readable: Boolean,
)
/**
* Enumerates mounted storage volumes.
*
* Listing `/storage` is not enough on its own: a volume can be absent from this process's mount
* view (notably after a container exits and the app process is restarted onto a stale storage
* sandbox) even though it is mounted and healthy. The framework knows about it regardless, so the
* volume set is built from several independent sources:
*
* 1. [StorageManager.getStorageVolumes] — the authoritative list, read over Binder.
* 2. [Context.getExternalFilesDirs] — per-app directories, granted separately from shared storage.
* 3. `/storage` and `/mnt/media_rw` directory listings — the filesystem view, as a backstop.
*
* Those sources overlap heavily: one SD card is reachable as `/storage/<uuid>`, as
* `/mnt/media_rw/<uuid>`, and via its app-specific directory, and typically only some of them are
* readable. So paths are grouped by the *volume* they belong to rather than by path, and each
* volume contributes a single entry pointing at the best path available for it.
*/
object StorageRoots {
private const val EMULATED_PREFIX = "/storage/emulated"
private const val INTERNAL_PATH = "/storage/emulated/0"
/** Identifies the physical volume a path belongs to; paths sharing a key are the same card. */
private const val PRIMARY_KEY = "primary"
private class Volume(val key: String) {
var label: String? = null
var removable: Boolean = key != PRIMARY_KEY
/** Candidate directories, best-guess first. */
val candidates = LinkedHashSet<File>()
/** App-specific directories, used to find a readable path inside an unreadable root. */
val seeds = LinkedHashSet<File>()
}
fun list(context: Context): List<StorageRoot> {
val volumes = LinkedHashMap<String, Volume>()
fun volumeOf(key: String) = volumes.getOrPut(key) { Volume(key) }
// Internal storage is never removable and never absent; seed it first so it heads the menu.
volumeOf(PRIMARY_KEY).apply {
label = "Internal"
removable = false
candidates += File(INTERNAL_PATH)
}
val appDirs = appSpecificDirs(context)
val storageManager = context.getSystemService(StorageManager::class.java)
// 1 + 2 — framework-reported volumes. Authoritative, and unaffected by our mount view.
storageManager?.storageVolumes.orEmpty()
.filter { isMounted(it.state) }
.forEach { volume ->
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: return@forEach)
entry.removable = !volume.isPrimary && volume.isRemovable
if (entry.label == null) entry.label = labelFor(context, volume, uuid)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
volume.directory?.let { entry.candidates += it }
}
if (uuid != null) {
entry.candidates += File("/storage/$uuid")
// Last resort only: the raw mount is normally unreadable to an app, so it must
// never outrank /storage/<uuid> and must never become an entry of its own.
entry.candidates += File("/mnt/media_rw/$uuid")
}
appDirs.filter { belongsTo(storageManager!!, it, volume) }.forEach { entry.seeds += it }
}
// 3 — filesystem backstop, for any volume the framework did not report.
File("/storage").listFiles().orEmpty().forEach { child ->
if (!child.isDirectory || child.name == "self" || child.name == "emulated") return@forEach
volumeOf(child.name).candidates += child
}
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
if (child.isDirectory) volumeOf(child.name).candidates += child
}
// App-specific directories, which stay reachable when shared storage is not.
appDirs.forEach { dir ->
val root = volumeRootOf(dir) ?: return@forEach
val entry = volumeOf(if (isEmulated(root)) PRIMARY_KEY else root.name)
entry.candidates += root
entry.seeds += dir
}
val roots = volumes.values.map { it.toRoot() }
val internal = roots.filter { !it.removable }
val removable = roots.filter { it.removable }.sortedBy { it.label }
return disambiguate(internal + removable)
}
private fun Volume.toRoot(): StorageRoot {
// Prefer a path we can actually list; a readable child beats an unreadable root.
val dir = candidates.firstOrNull(::canBrowse)
?: candidates.firstNotNullOfOrNull { root -> seeds.firstNotNullOfOrNull { deepestReadable(root, it) } }
?: seeds.firstOrNull(::canBrowse)
// Report the volume anyway; an entry that lists empty beats one that silently vanished.
?: candidates.firstOrNull()
?: File("/storage/$key")
return StorageRoot(
label = label ?: defaultLabel(),
dir = dir,
removable = removable,
readable = canBrowse(dir),
)
}
private fun Volume.defaultLabel(): String = if (removable) "SD card" else key
/** Appends the volume id to any label used by more than one volume, so entries stay tellable apart. */
private fun disambiguate(roots: List<StorageRoot>): List<StorageRoot> {
val counts = roots.groupingBy { it.label }.eachCount()
return roots.map { root ->
if (counts.getValue(root.label) == 1) root else root.copy(label = "${root.label} (${root.dir.name})")
}
}
/** Walks up from [seed] towards [root] and returns the highest directory we can list. */
private fun deepestReadable(root: File, seed: File): File? {
var current: File? = seed.absoluteFile
var best: File? = null
while (current != null && isWithin(current, root)) {
if (canBrowse(current)) best = current
current = current.parentFile
}
return best
}
/** `/storage/ABCD-1234/Android/data/<pkg>/files` -> `/storage/ABCD-1234`. */
private fun volumeRootOf(appDir: File): File? =
generateSequence(appDir.absoluteFile) { it.parentFile }
.firstOrNull { it.name.equals("Android", ignoreCase = true) }
?.parentFile
private fun appSpecificDirs(context: Context): List<File> =
context.getExternalFilesDirs(null)
.orEmpty()
.filterNotNull()
.filter { isMounted(Environment.getExternalStorageState(it)) }
private fun belongsTo(storageManager: StorageManager, dir: File, volume: StorageVolume): Boolean {
val owner = storageManager.getStorageVolume(dir) ?: return false
if (owner.isPrimary != volume.isPrimary) return false
val ownerUuid = owner.uuid
val volumeUuid = volume.uuid
return if (!ownerUuid.isNullOrBlank() || !volumeUuid.isNullOrBlank()) {
ownerUuid == volumeUuid
} else {
true
}
}
/**
* Names a volume the way the rest of the file manager does. The framework description is only
* used when it says something more useful than "SD card" — on some devices it is a bare disk
* name like "android", which tells the user nothing about which card they are looking at.
*/
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
if (volume.isPrimary) return "Internal"
if (volume.isRemovable) return "SD card"
val description = volume.getDescription(context)?.trim()
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
?: uuid
?: "Storage"
}
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
private fun isMounted(state: String?): Boolean =
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY
private fun canBrowse(dir: File?): Boolean =
dir != null && dir.isDirectory && dir.canRead() && dir.listFiles() != null
private fun isWithin(child: File, ancestor: File): Boolean {
val c = canonicalPath(child)
val a = canonicalPath(ancestor)
return c == a || c.startsWith("$a/")
}
private fun canonicalPath(file: File): String =
try {
file.canonicalPath
} catch (e: Exception) {
file.absolutePath
}.trimEnd('/')
}
@@ -0,0 +1,44 @@
package com.steamdeck.launcher.session
import android.content.Context
import android.util.Log
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
/**
* The last thing that runs when our own code throws on any thread: the stack trace into the
* session's folder, then the folder's ending ([SessionArtifacts.collect]), then Android's own
* handler so the crash is still reported and still lands in the crash buffer. Bounded, because
* a handler that hangs turns a crash into a frozen app: the collect gets a few seconds and the
* process dies regardless.
*
* A native crash (the compositor, a JNI call) never reaches here - the process is gone before
* Java sees anything. [SessionArtifacts.finishAbandoned] at the next start covers that case.
*/
object CrashHandler {
private const val TAG = "CrashHandler"
fun install(context: Context) {
val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
try {
Log.e(TAG, "uncaught on ${thread.name}", error)
val dir = SessionPaths.current()
if (dir != null && dir.isDirectory) {
val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
File(dir, "crash-app.txt").writeText(
"The app itself crashed on thread \"${thread.name}\":\n\n$trace"
)
val worker = Thread({ SessionArtifacts.collect(context, dir, "app crash") }, "crash-collect")
worker.start()
worker.join(8000)
}
} catch (e: Throwable) {
// Nothing more to do for a crash inside the crash handler.
} finally {
previous?.uncaughtException(thread, error) ?: Runtime.getRuntime().halt(2)
}
}
}
}
@@ -0,0 +1,109 @@
package com.steamdeck.launcher.session
import android.content.Context
import android.util.Log
import com.steamdeck.launcher.core.LogRedactor
import com.steamdeck.launcher.core.SessionLogCapture
import com.steamdeck.launcher.runtime.LinuxRuntime
import com.steamdeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Finishes a session's folder: the compositor's log, the Steam client's logs scrubbed line by
* line, Android's crash buffer, and a marker that says the folder is complete.
*
* Three callers, because a session ends three ways. [collect] runs at an ordinary stop. The
* app's uncaught-exception handler ([CrashHandler]) runs it as the process dies, so a crash in
* our own code leaves a full folder and not a half one. And [finishAbandoned] runs at the next
* app start for a folder that has no marker: the process was killed outright (Android's phantom
* process killer, a native crash in the compositor, the battery) and nothing of ours got to run.
* Everything written *during* the session - session.log, app.log, wayland.log, audio.log, the
* device report - is already on disk at that point; only the pieces gathered at the end were
* missing, and the crash buffer keeps its entries after the process is gone, which is the whole
* reason it is worth coming back for.
*/
object SessionArtifacts {
private const val TAG = "SessionArtifacts"
/** Written last; a folder without it did not get its ending. */
const val COMPLETE_MARKER = ".complete"
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
fun collect(context: Context, dir: File, reason: String) {
try {
val wayland = File(dir, "wayland.log")
if (!wayland.exists()) {
WaylandCompositor.currentLogFile()?.takeIf { it.isFile }?.let { src ->
src.copyTo(wayland, overwrite = true)
}
}
copySteamLogs(context, dir)
// A session the system killed leaves its trace here and nowhere else.
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
} catch (e: Exception) {
Log.w(TAG, "collecting session artifacts", e)
}
}
/** Steam's logs: redacted into steam/, never copied verbatim. */
private fun copySteamLogs(context: Context, dir: File) {
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() }
logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
try {
File(out, src.name).bufferedWriter().use { w ->
src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
}
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${src.name}", e)
}
}
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
/**
* Every session folder without a marker gets its ending now. Only the newest of them gets the
* Steam logs - the runtime holds one set, and it belongs to the last session that ran; an
* older folder would be handed logs that are not its own. Runs on a worker thread at app
* start; nothing here touches the session that is about to begin.
*/
fun finishAbandoned(context: Context) {
val parent = LinuxRuntime.debugLogDir()
val abandoned = parent.listFiles { f ->
f.isDirectory && f.name.startsWith("session-") && !File(f, COMPLETE_MARKER).exists()
}?.sortedBy { it.name } ?: return
if (abandoned.isEmpty()) return
val current = SessionPaths.current()
abandoned.forEachIndexed { i, dir ->
if (dir == current) return@forEachIndexed
val newest = i == abandoned.lastIndex
try {
File(dir, "ended-without-teardown.txt").writeText(
"This session's process ended without running its own teardown - killed by\n" +
"Android, a native crash, or the device going down - so the files below were\n" +
"gathered when the app next started, at ${now()}.\n" +
"The logs written during the session (session.log, app.log, wayland.log,\n" +
"audio.log, device.txt) were on disk already and are as they were left.\n" +
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
)
if (newest) {
copySteamLogs(context, dir)
}
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
Log.i(TAG, "finished the abandoned session folder $dir")
} catch (e: Exception) {
Log.w(TAG, "could not finish $dir", e)
}
}
}
private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
}
@@ -30,15 +30,21 @@ object SessionPaths {
@Volatile
private var dir: File? = null
/** The folder for the session now starting, or the one already in progress. */
/**
* The folder for the session now starting, or the one already in progress. With logs turned
* off on the main screen the folder lives in the app's cache instead of Downloads - the
* scripts and the compositor still need somewhere to write - and [release] deletes it.
*/
@Synchronized
fun beginOrCurrent(context: Context): File {
dir?.let { if (it.isDirectory) return it }
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val made = File(SessionFiles.logDirectory(context), "session-$stamp")
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
else File(context.cacheDir, "session-logs")
val made = File(parent, "session-$stamp")
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
dir = made
Log.i(TAG, "session logs: $made")
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
return made
}
@@ -50,7 +56,12 @@ object SessionPaths {
/** Let the next session claim a new folder. Called when a session ends. */
@Synchronized
fun release() {
fun release(context: Context) {
val ended = dir
dir = null
// A folder kept in the cache was never meant to outlive its session.
if (ended != null && ended.path.startsWith(context.cacheDir.path)) {
com.steamdeck.launcher.core.FileUtils.delete(ended)
}
}
}
@@ -156,4 +156,29 @@ object SessionPrefs {
fun setAndroidDriver(context: Context, id: String) {
prefs(context).edit().putString("androidDriver", id).apply()
}
// ── Storage the session can see ─────────────────────────────────────────────────────────────
/**
* The folder on this device that every session shows at `/root/ROMs`, for the emulators on the
* desktop. "" = none chosen. All of internal storage is at `/root/Storage` regardless.
*/
fun romsDir(context: Context): String =
prefs(context).getString("romsDir", "") ?: ""
fun setRomsDir(context: Context, path: String) {
prefs(context).edit().putString("romsDir", path).apply()
}
/**
* Whether a session writes its folder under Download/SteamDeck. Off, the same logs are kept in
* the app's cache for the session's lifetime (the scripts need somewhere to write) and thrown
* away at the end, so nothing accumulates in Downloads.
*/
fun logsEnabled(context: Context): Boolean =
prefs(context).getBoolean("logs", true)
fun setLogsEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("logs", on).apply()
}
}
@@ -24,7 +24,6 @@ import com.steamdeck.launcher.audio.PulseAudioComponent
import com.steamdeck.launcher.core.CpuCores
import com.steamdeck.launcher.core.DeviceReport
import com.steamdeck.launcher.core.EnvVars
import com.steamdeck.launcher.core.LogRedactor
import com.steamdeck.launcher.core.SessionLogCapture
import com.steamdeck.launcher.core.NetworkReport
import com.steamdeck.launcher.core.EnvironmentComponent
@@ -33,7 +32,6 @@ import com.steamdeck.launcher.core.ProcessHelper
import com.steamdeck.launcher.input.FakeInputWriter
import com.steamdeck.launcher.runtime.LinuxNetworkLinkComponent
import com.steamdeck.launcher.runtime.LinuxRuntime
import com.steamdeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
@@ -81,44 +79,19 @@ class SessionService : Service() {
}
/**
* Pull everything a report needs into the session's folder, after the session has stopped: the
* compositor's log (it writes for as long as the compositor lives, which outlasts one session)
* and the Steam client's own logs, scrubbed line by line. The guest script copies Steam's logs
* too, at a clean exit; this one runs whatever killed the session, which is when they matter.
* Finish the session's folder after the session has stopped, then let go of it. The guest
* script copies Steam's logs too, at a clean exit; this runs whatever killed the session,
* which is when they matter. The collecting itself is [SessionArtifacts], shared with the
* crash handler and the next-start sweep so a folder is finished whichever way it ends.
*/
private fun collectSessionArtifacts() {
val dir = SessionPaths.current() ?: return
try {
// The compositor's own file, wherever it opened it.
val wayland = File(dir, "wayland.log")
if (!wayland.exists()) {
WaylandCompositor.currentLogFile()?.takeIf { it.isFile }?.let { src ->
src.copyTo(wayland, overwrite = true)
}
}
// Steam's logs: redacted into steam/, never copied verbatim.
val logs = File(LinuxRuntime.rootDir(this), "root/.local/share/Steam/logs")
if (logs.isDirectory) {
val out = File(dir, "steam").apply { mkdirs() }
logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
try {
File(out, src.name).bufferedWriter().use { w ->
src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
}
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${src.name}", e)
}
}
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
// A session the system killed leaves its trace here and nowhere else.
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
} catch (e: Exception) {
Log.w(TAG, "collecting session artifacts", e)
SessionArtifacts.collect(this, dir, "session stopped")
} finally {
// Last, so everything above is in the file it is about.
SessionLogCapture.stop()
SessionPaths.release()
SessionPaths.release(this)
}
}
@@ -310,6 +283,23 @@ class SessionService : Service() {
val binds = ArrayList<String>()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
// Where the device's files appear inside the session. Internal storage is bound at its own
// path already, and every program's file dialog opens at home and lists "Computer" from
// /proc/mounts, where a proot bind never shows - so a user saw only the runtime's own
// tree and could not find the phone at all. The same storage is placed under home as
// well, and the ROMs folder chosen on the main screen beside it; a bind rather than a
// link, so a folder on an SD card works the same.
val home = File(LinuxRuntime.rootDir(this), "root")
File(home, "Storage").mkdirs()
binds.add(Environment.getExternalStorageDirectory().path + ":/root/Storage")
val roms = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }?.let { File(it) }
if (roms != null && roms.isDirectory && roms.canRead()) {
File(home, "ROMs").mkdirs()
binds.add(roms.path + ":/root/ROMs")
Log.i(TAG, "roms: $roms -> /root/ROMs")
} else if (roms != null) {
Log.w(TAG, "roms: $roms is not a readable folder; /root/ROMs not offered this session")
}
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
@@ -3,7 +3,10 @@ package com.steamdeck.launcher.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
@@ -27,6 +30,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.steamdeck.launcher.R
@@ -46,6 +50,9 @@ class MainUiState(
/** The account the client would sign in as offline, or null if it has never signed in. */
val offlineAccount: String?,
val offline: Boolean,
/** The folder every session shows at /root/ROMs, or null if none is chosen. */
val romsDir: String?,
val logsEnabled: Boolean,
)
/**
@@ -56,6 +63,10 @@ class MainUiState(
* scaled by the height available — everything on it, text included, shrinks together until it
* fits — with scrolling left as the last resort, and a width cap so the buttons never span a
* wide panel. The system bars are kept clear of.
*
* Play and Desktop span the column; everything else is a tile in two columns, a title with the
* setting's current value under it, so the menu is read at a glance and fits without scrolling
* on a handheld.
*/
@Composable
fun MainScreen(
@@ -70,6 +81,8 @@ fun MainScreen(
onAudio: () -> Unit,
onPerformance: () -> Unit,
onOffline: () -> Unit,
onRoms: () -> Unit,
onLogs: () -> Unit,
onCredits: () -> Unit,
) {
BoxWithConstraints(
@@ -141,57 +154,58 @@ fun MainScreen(
) { Text("Play", fontSize = 14.sp * k) }
OutlinedButton(
onClick = onDesktop, enabled = state.ready && !state.busy && state.desktopInstalled,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight),
) { Text(if (state.desktopInstalled) "Desktop" else "Desktop — install it under Desktop & apps", fontSize = 13.sp * k) }
// Offline is read while the client starts, so it is decided here rather than in the
// session's drawer, and it needs credentials from an earlier sign-in to be possible.
OutlinedButton(
onClick = onOffline, enabled = state.offlineAccount != null,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
) {
Text(
when {
state.offlineAccount == null -> "Start offline — sign in once first"
state.offline -> "Start offline: on · ${state.offlineAccount}"
else -> "Start offline: off"
},
fontSize = 13.sp * k,
)
}
Spacer(Modifier.height(8.dp * k))
val runtimeLabel = when {
state.busy -> "Working…"
!state.ready -> "Install Linux runtime"
state.available != null && state.available != state.installed -> "Update Linux runtime"
else -> "Remove Linux runtime"
}
OutlinedButton(
onClick = onRuntime, enabled = !state.busy,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
) { Text(runtimeLabel, fontSize = 13.sp * k) }
OutlinedButton(
onClick = onFrameGen,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
) { Text("Frame generation: ${state.frameGenLabel}", fontSize = 13.sp * k) }
OutlinedButton(
onClick = onApps, enabled = state.ready && !state.busy,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
) { Text("Desktop & apps", fontSize = 13.sp * k) }
OutlinedButton(
onClick = onProtons,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
) { Text("Compatibility tools", fontSize = 13.sp * k) }
OutlinedButton(
onClick = onDrivers,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
) { Text("Graphics drivers", fontSize = 13.sp * k) }
OutlinedButton(
onClick = onAudio,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
) { Text("Audio", fontSize = 13.sp * k) }
OutlinedButton(
onClick = onPerformance,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight + 5.dp * k),
) { Text("Performance", fontSize = 13.sp * k) }
val tileGap = Arrangement.spacedBy(6.dp * k)
Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) {
MenuTile(runtimeLabel, null, k, Modifier.weight(1f), enabled = !state.busy, onClick = onRuntime)
MenuTile("Desktop & apps", null, k, Modifier.weight(1f), enabled = state.ready && !state.busy, onClick = onApps)
}
Spacer(Modifier.height(6.dp * k))
Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) {
MenuTile("Frame generation", state.frameGenLabel, k, Modifier.weight(1f), onClick = onFrameGen)
MenuTile("Compatibility tools", null, k, Modifier.weight(1f), onClick = onProtons)
}
Spacer(Modifier.height(6.dp * k))
Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) {
MenuTile("Graphics drivers", null, k, Modifier.weight(1f), onClick = onDrivers)
MenuTile("Audio", null, k, Modifier.weight(1f), onClick = onAudio)
}
Spacer(Modifier.height(6.dp * k))
Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) {
MenuTile("Performance", null, k, Modifier.weight(1f), onClick = onPerformance)
// The folder's own name is the value; the whole path is in the dialog.
MenuTile(
"ROMs folder", state.romsDir?.substringAfterLast('/')?.ifEmpty { state.romsDir } ?: "not chosen",
k, Modifier.weight(1f), onClick = onRoms,
)
}
Spacer(Modifier.height(6.dp * k))
Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) {
// Offline is read while the client starts, so it is decided here rather than in the
// session's drawer, and it needs credentials from an earlier sign-in to be possible.
MenuTile(
"Start offline",
when {
state.offlineAccount == null -> "sign in once first"
state.offline -> "on · ${state.offlineAccount}"
else -> "off"
},
k, Modifier.weight(1f), enabled = state.offlineAccount != null, onClick = onOffline,
)
MenuTile(
"Session logs", if (state.logsEnabled) "on · Download/SteamDeck" else "off",
k, Modifier.weight(1f), onClick = onLogs,
)
}
Spacer(Modifier.height(10.dp * k))
Text(
"by The412Banner and maxjivi05 · credits",
@@ -202,6 +216,33 @@ fun MainScreen(
}
}
/** One tile of the two-column menu: what it is, and under it what it is set to. */
@Composable
private fun MenuTile(
title: String,
value: String?,
k: Float,
modifier: Modifier,
enabled: Boolean = true,
onClick: () -> Unit,
) {
OutlinedButton(
onClick = onClick, enabled = enabled,
modifier = modifier.height(if (value != null) 52.dp * k else 44.dp * k),
contentPadding = PaddingValues(horizontal = 8.dp * k, vertical = 4.dp * k),
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(title, fontSize = 12.sp * k, maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center)
if (value != null) {
Text(
value, fontSize = 10.sp * k, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center,
)
}
}
}
}
@Composable
fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
AlertDialog(
@@ -0,0 +1,48 @@
package com.steamdeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.ui.Modifier
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
/** The ROMs folder: where it is, and where the emulators will find it. */
@Composable
fun RomsDialog(path: String?, onChoose: () -> Unit, onClear: () -> Unit, onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("ROMs folder") },
text = {
Column {
Text(
"A folder on this device that every session shows as ROMs in the home folder " +
"(/root/ROMs) — open it from any emulator's file dialog. All of internal " +
"storage is there too, as Storage.",
style = MaterialTheme.typography.bodyMedium,
)
Spacer(Modifier.height(10.dp))
Text(
path ?: "No folder chosen yet.",
style = MaterialTheme.typography.bodySmall,
color = if (path != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(6.dp))
Text(
"Takes effect at the next session. A folder on an SD card works too.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
confirmButton = { TextButton(onClick = onChoose) { Text(if (path == null) "Choose folder" else "Change folder") } },
dismissButton = {
if (path != null) TextButton(onClick = onClear) { Text("Forget") }
else TextButton(onClick = onDismiss) { Text("Cancel") }
},
)
}