mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
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:
1 parent
3aa0162055
commit
cb5a1b5a31
15 files changed
+1066
-91
No files matched your search
@@ -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('/')
|
||||
}
|
||||
Reference in new issue
Block a user