diff --git a/README.md b/README.md index 7636624664..cd1d6795a5 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,9 @@ ledger rather than a feature list — where something has not been run on hardwa | Foldable, opened and closed mid-session | ✅ proven | | Background / foreground, wake locks | ✅ proven | | The session log folder | ✅ proven — all of it written, including this app's own log | +| Session folder finished after a crash or a kill | ⚠️ built: crash handler + next-start sweep; not yet forced on a device | +| ROMs folder and Storage in the session's home | ⚠️ built; not yet opened from an emulator on a device | +| The in-app file picker | ⚠️ built; not yet used on a device | | Stopping a competing Steam client | ⚠️ it is asked to stop and says so, but one that restarts itself from boot wins the race — uninstall it | | DirectAudio for games, and the microphone | ⚠️ wired and the modules load; voice not yet confirmed in Steam's tester | | Client and game core masks | ⚠️ applied and logged; no measured difference yet | @@ -163,6 +166,23 @@ themselves through Vulkan and Turnip — it is the desktop's own compositing tha Programs whose child processes sandbox themselves with seccomp and namespaces cannot set those up under proot; Firefox's are turned off in the session's environment, without which its tabs crash. +### The device's files, and the ROMs folder + +Inside a session the phone's storage is at `/storage/emulated/0`, as it is outside - but no +program's file dialog will show it: they list "Computer" from `/proc/mounts`, where a proot bind +never appears, and open in the home folder, where nothing pointed at the phone. So the home +folder now carries two entries every session: + +- **`Storage`** - all of internal storage. +- **`ROMs`** - the folder chosen with **ROMs folder** on the main screen, wherever it is on the + device, an SD card included (it is a bind, not a link). Point any emulator's game directory at + `/root/ROMs` once and it is the same folder in every session after. + +Both are the live folders, not copies: a save an emulator writes next to its ROM lands on the +phone. Choosing is done in the app's own file picker, the one Bannerlator's File Manager offers +in pick mode - every mounted card in a drive menu, folders first, an up-arrow that stops at the +card's root - and the same picker is what imports a graphics driver. + ## Pointer The app draws the arrow. On the desktop, touch is a **touchpad** (Bannerlator's desktop-container @@ -294,6 +314,10 @@ Contents screen makes: imported AdrenoTools zip can be chosen instead. The compositor loads its driver once per app process, so this one applies after the app is fully closed and started again. +Both imports open the app's own file picker rather than Android's document picker: an SD card is a +card in its drive menu, the folder last picked from is where it opens next time, and it hands back +a plain path. + ## Frame generation Extra frames are generated between the real ones on the way to the screen — inside the app's @@ -341,6 +365,7 @@ Download/SteamDeck/session-20260921-161256/ wayland.log the app's compositor - what it presented, at what size, and how fast app.log what the app itself decided and reported crash.log Android's crash buffer, as it stood when the session ended + crash-app.txt the stack trace, if the app itself crashed audio.log the PulseAudio daemon and the DirectAudio relay helper network.txt the link, the DNS the runtime was given, and what it means steam.log the Steam client's log, scrubbed (Steam mode) @@ -357,6 +382,20 @@ so a module that refuses to load is visible instead of being a silent absence of `network.txt` records the transport, whether the link validated, the address families and the DNS servers the runtime was actually given - **never the network's name**. +A folder is finished **however the session ends**, not only at a clean stop. Everything written +*during* a session is on disk as it happens; only the ending - the compositor's log, Steam's +scrubbed logs, the crash buffer - is gathered afterwards, and three things gather it: the ordinary +stop; the app's own crash handler, which writes `crash-app.txt` with the stack trace and finishes +the folder before the process dies; and a sweep at the next app start, for a folder whose process +was killed outright (Android's phantom-process killer, a native crash in the compositor, a dead +battery) - that folder gets `ended-without-teardown.txt` saying so, and `crash.log` as the buffer +stands then, which still holds the entry unless the device rebooted. A finished folder carries a +`.complete` marker; one without it is what the sweep looks for. + +**Session logs** on the main screen turns the folder off. The session still writes its logs - the +scripts and the compositor need somewhere to - but into the app's cache, and they are deleted +when the session ends, so nothing accumulates in Downloads. + `device.txt` is written before the session starts, so a session that dies in its first second still says what it ran on: model, SoC, Android and kernel, cores and their ceilings, RAM, the GPU as KGSL names it, the panel, **which driver each half of the session chose**, the runtime version, diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 895c35c55c..a571023575 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -26,6 +26,7 @@ + + >(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(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") } } diff --git a/app/src/main/java/com/steamdeck/launcher/files/FilePickerActivity.kt b/app/src/main/java/com/steamdeck/launcher/files/FilePickerActivity.kt new file mode 100644 index 0000000000..28ac499416 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/FilePickerActivity.kt @@ -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, 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" + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/FilePickerScreen.kt b/app/src/main/java/com/steamdeck/launcher/files/FilePickerScreen.kt new file mode 100644 index 0000000000..f09c2ddc1c --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/FilePickerScreen.kt @@ -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, + 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?>(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 { !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) diff --git a/app/src/main/java/com/steamdeck/launcher/files/InAppFilePicker.kt b/app/src/main/java/com/steamdeck/launcher/files/InAppFilePicker.kt new file mode 100644 index 0000000000..89dd548339 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/InAppFilePicker.kt @@ -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 = 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) } +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/StorageRoots.kt b/app/src/main/java/com/steamdeck/launcher/files/StorageRoots.kt new file mode 100644 index 0000000000..8708bf5004 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/StorageRoots.kt @@ -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/`, as + * `/mnt/media_rw/`, 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() + /** App-specific directories, used to find a readable path inside an unreadable root. */ + val seeds = LinkedHashSet() + } + + fun list(context: Context): List { + val volumes = LinkedHashMap() + + 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/ 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): List { + 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//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 = + 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('/') +} diff --git a/app/src/main/java/com/steamdeck/launcher/session/CrashHandler.kt b/app/src/main/java/com/steamdeck/launcher/session/CrashHandler.kt new file mode 100644 index 0000000000..bd85ad345d --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/session/CrashHandler.kt @@ -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) + } + } + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/session/SessionArtifacts.kt b/app/src/main/java/com/steamdeck/launcher/session/SessionArtifacts.kt new file mode 100644 index 0000000000..a96ae0798e --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/session/SessionArtifacts.kt @@ -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()) +} diff --git a/app/src/main/java/com/steamdeck/launcher/session/SessionPaths.kt b/app/src/main/java/com/steamdeck/launcher/session/SessionPaths.kt index e5d2490edb..7e8673ff17 100644 --- a/app/src/main/java/com/steamdeck/launcher/session/SessionPaths.kt +++ b/app/src/main/java/com/steamdeck/launcher/session/SessionPaths.kt @@ -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) + } } } diff --git a/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt index 305bafd115..0d7f205a9d 100644 --- a/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt @@ -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() + } } diff --git a/app/src/main/java/com/steamdeck/launcher/session/SessionService.kt b/app/src/main/java/com/steamdeck/launcher/session/SessionService.kt index 79f3c2846e..ad4efb8589 100644 --- a/app/src/main/java/com/steamdeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/steamdeck/launcher/session/SessionService.kt @@ -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() 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, diff --git a/app/src/main/java/com/steamdeck/launcher/ui/MainScreen.kt b/app/src/main/java/com/steamdeck/launcher/ui/MainScreen.kt index 4ace9f59cb..dadf0ec49e 100644 --- a/app/src/main/java/com/steamdeck/launcher/ui/MainScreen.kt +++ b/app/src/main/java/com/steamdeck/launcher/ui/MainScreen.kt @@ -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( diff --git a/app/src/main/java/com/steamdeck/launcher/ui/RomsDialog.kt b/app/src/main/java/com/steamdeck/launcher/ui/RomsDialog.kt new file mode 100644 index 0000000000..fb8fda0d66 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/ui/RomsDialog.kt @@ -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") } + }, + ) +}