This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-13 21:27:42 -04:00
1 parent 4163b31b02
commit 83ec5708ed
852 files changed
+4844 -46144

No files matched your search

@@ -23,15 +23,6 @@ import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
/**
* The app's own data folder (the Linux runtime, settings, logs) in Android's file picker, under the
* app's name beside the phone's storage - what MT Manager's "documents provider" injection does, as
* part of the app. Only the system's documents UI can bind it (MANAGE_DOCUMENTS); another app sees
* a file only when the user picks it there.
*
* A document id is the file's absolute path, and nothing outside the data folder is ever handed out
* or accepted: every id is resolved and checked to lie inside it.
*/
class AppFilesProvider : DocumentsProvider() {
private lateinit var base: File
private lateinit var baseCanonical: String
@@ -65,8 +56,6 @@ class AppFilesProvider : DocumentsProvider() {
override fun queryChildDocuments(parentDocumentId: String, projection: Array<String>?, sortOrder: String?): Cursor {
val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS)
// A link in the runtime that leads out of the data folder (/etc/localtime and the like) is
// left out rather than listed as something that cannot be opened.
fileFor(parentDocumentId).listFiles()?.filter { inside(it) }?.forEach { addRow(result, it) }
return result
}
@@ -104,10 +93,6 @@ class AppFilesProvider : DocumentsProvider() {
}
}
/**
* Deletes a file or a folder and what is in it without ever following a link: the runtime holds
* links to places outside it, and deleting a folder must remove the link, not what it points at.
*/
private fun deleteTree(root: Path) {
if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
Files.delete(root)
@@ -158,7 +143,6 @@ class AppFilesProvider : DocumentsProvider() {
val needle = query.lowercase()
val pending = ArrayDeque(listOf(base))
var visited = 0
// The runtime is tens of thousands of files: a bounded walk, not the whole tree.
while (pending.isNotEmpty() && result.count < 50 && visited++ < 20000) {
val f = pending.removeFirst()
if (!inside(f)) continue
@@ -168,7 +152,6 @@ class AppFilesProvider : DocumentsProvider() {
return result
}
/** The file an id names, when it exists and lies inside the data folder (links followed). */
private fun fileFor(documentId: String): File {
val f = File(documentId)
if (!f.isAbsolute || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files")
@@ -177,7 +160,6 @@ class AppFilesProvider : DocumentsProvider() {
}
private fun inside(f: File): Boolean {
// The folder's own entries are listed as they are; a link is judged by where it leads.
val abs = f.absoluteFile.normalize().path
if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false
val real = runCatching { f.canonicalPath }.getOrNull() ?: return false
@@ -225,11 +207,6 @@ class AppFilesProvider : DocumentsProvider() {
Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
)
/**
* The name in the picker. The same app ships under other package names (for the performance
* modes some phones give only named apps); each says which it is, so four installs are not
* four identical "DroidDeck" entries.
*/
fun titleFor(context: Context): String {
val name = context.getString(R.string.app_name)
return when (context.packageName) {
@@ -49,38 +49,26 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/** One tappable entry in a [CollapsibleRail] (a container tab, a file-manager location, …). */
data class RailItem(
val label: String,
val icon: ImageVector,
val selected: Boolean,
/** >0 shows a small accent count badge on the item's icon (expanded and collapsed). */
val badge: Int = 0,
/** The under-icon label when the rail is collapsed, for names too long to fit; null derives one. */
val shortLabel: String? = null,
// onClick stays LAST so existing call sites can pass it as a trailing lambda; badge is an
// optional named param before it (default 0).
val onClick: () -> Unit,
)
/** A group of [RailItem]s under an optional small section header (STORAGE / QUICK / FAVORITES …). */
data class RailSection(val header: String?, val items: List<RailItem>)
/**
* The tiny under-icon label for a COLLAPSED rail item. The rail width never changes, so labels must
* fit the narrow (~58dp) column: multi-word names wrap to a second line; single words too long to
* fit are abbreviated; short ones pass through. (Explicit abbreviations first, then a length guard.)
*/
private fun collapsedLabel(label: String): String {
when (label) {
"ENVIROMENT" -> return "ENVIRON" // the app's existing (mis)spelling, kept uppercase
"ENVIROMENT" -> return "ENVIRON"
"WIN COMPONENTS" -> return "WIN COMP"
}
if (label.contains(' ')) return label // multi-word → wraps to 2 lines
if (label.contains(' ')) return label
return if (label.length > 9) label.take(8) + "…" else label
}
/** A rail item's 20dp icon, with a small accent count badge on its corner when [badge] > 0. */
@Composable
private fun RailItemIcon(item: RailItem, tint: androidx.compose.ui.graphics.Color) {
if (item.badge > 0) {
@@ -99,21 +87,10 @@ private fun RailItemIcon(item: RailItem, tint: androidx.compose.ui.graphics.Colo
}
}
/** A secondary link shown under the header (e.g. "What is all this?", "Reset to app defaults"). */
data class RailLink(val label: String, val icon: ImageVector, val onClick: () -> Unit)
/**
* State for a [CollapsibleRail], with the app-wide unified rule:
* - PORTRAIT → always collapsed (icon-only), the toggle is HIDDEN and it can never expand.
* - LANDSCAPE → expanded by default; the user's collapse choice is remembered PER-SCREEN
* ([screenKey]) and is NOT overridden by rotation. portrait→landscape restores that choice.
*
* Backed by rememberSaveable (survives process death) and by the fact the app UI activity keeps
* orientation in configChanges (no recreate) so the selected item / fields / scroll are preserved.
*/
class RailState internal constructor(
val collapsed: Boolean,
/** True in portrait: the rail is locked collapsed and must not show an expand toggle. */
val portraitLocked: Boolean,
val onToggle: () -> Unit,
)
@@ -121,15 +98,12 @@ class RailState internal constructor(
@Composable
fun rememberRailState(screenKey: String): RailState {
val context = LocalContext.current
// The same file the File Manager keeps its own browse settings in (no androidx.preference here).
val prefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
val isLandscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE
val choseKey = "rail_${screenKey}_userChose"
val collapsedKey = "rail_${screenKey}_collapsed"
// Keep the landscape choice in saveable state regardless of orientation so portrait→landscape
// restores it. In portrait we simply report collapsed+locked and ignore it.
var userChose by rememberSaveable(screenKey) { mutableStateOf(prefs.getBoolean(choseKey, false)) }
var landscapeCollapsed by rememberSaveable(screenKey) {
mutableStateOf(if (prefs.getBoolean(choseKey, false)) prefs.getBoolean(collapsedKey, false) else false)
@@ -152,16 +126,6 @@ fun rememberRailState(screenKey: String): RailState {
)
}
/**
* The shared collapsible left rail (mockup "Option 3"): app glyph + title, optional links, and the
* navigation items, replacing a top tab bar so content runs full height beside it. Width animates
* 190dp ↔ 58dp. When collapsed it is icon-only (the caller surfaces the active item's name over the
* content). Used by the container editors, File Manager and Save Manager.
*
* [footer] is an optional slot pinned to the bottom of the rail (a weighted spacer pushes it down),
* for a persistent per-screen summary (e.g. the Save Manager's "N games need syncing" line). The
* caller renders whatever it wants there and can key it off [RailState.collapsed] to go icon-only.
*/
@Composable
fun CollapsibleRail(
state: RailState,
@@ -170,12 +134,7 @@ fun CollapsibleRail(
modifier: Modifier = Modifier,
links: List<RailLink> = emptyList(),
footer: (@Composable ColumnScope.() -> Unit)? = null,
// Optional header glyph (a themed drawable). When null the rail shows its plain solid square.
// Used by the container editors to show the wine-glass container icon; other rails leave it null.
@DrawableRes headerIcon: Int? = null,
// When true each item gets a rounded outlined-button look (the selected one takes the accent
// border + accent-dim fill), matching the File Manager's "New Folder" button. Off by default so
// the container/save rails keep their lighter flat rows (5 stacked outlined tabs read too heavy).
outlinedItems: Boolean = false,
) {
val collapsed = state.collapsed
@@ -187,7 +146,6 @@ fun CollapsibleRail(
.fillMaxHeight()
.background(MaterialTheme.colorScheme.surfaceContainerHigh)
) {
// ── Header: app glyph + title + collapse handle (handle hidden when portrait-locked) ──
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = if (collapsed) Arrangement.Center else Arrangement.Start,
@@ -228,14 +186,12 @@ fun CollapsibleRail(
}
}
}
// Collapsed (landscape only) → an expand handle; portrait is locked with no handle.
if (collapsed && !state.portraitLocked) {
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) {
Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
}
}
// ── Links ──
if (links.isNotEmpty()) {
if (collapsed) {
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
@@ -258,8 +214,6 @@ fun CollapsibleRail(
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
// ── Sections + items (SCROLLABLE so a tall rail - e.g. many File Manager favourites - is
// fully reachable in both orientations; the header above and footer below stay pinned) ──
Column(
modifier = Modifier
.weight(1f)
@@ -283,8 +237,6 @@ fun CollapsibleRail(
}
section.items.forEach { item ->
val active = item.selected
// Outlined variant: each item is a rounded outlined button; selected = accent border +
// accent-dim fill. Flat variant (default): a simple accent-tinted highlight for selected.
val shape = RoundedCornerShape(9.dp)
val base = Modifier.fillMaxWidth()
val styled = if (outlinedItems) {
@@ -308,9 +260,6 @@ fun CollapsibleRail(
val iconTint = if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
val labelColor = if (active) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant
if (collapsed) {
// Icon-only width is unchanged - a TINY label goes UNDER the icon (2 lines max,
// centre-aligned, wrapping/abbreviated) so every button stays identifiable without
// widening the rail.
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = styled,
@@ -350,9 +299,8 @@ fun CollapsibleRail(
}
}
} // end scrollable section list (its weight fills the gap so the footer stays pinned)
}
// ── Optional pinned footer (e.g. the sync summary) ──
if (footer != null) {
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
footer()
@@ -360,16 +308,6 @@ fun CollapsibleRail(
}
}
/**
* Portrait counterpart to [CollapsibleRail]: the same navigation [items] laid out as a horizontal
* icon-over-label bar pinned across the top, with an accent underline under the selected one. Mirrors
* the container editor's top tab bar so every editor reads the same - pin this in portrait wherever a
* [CollapsibleRail] is used in landscape. Optional [links] (Help / Reset …) are appended after a
* faint separator, exactly like the rail's links.
*
* (The container editor still carries its own private copy of this bar; new screens should prefer
* this shared one, and the container editor can migrate to it later.)
*/
@Composable
fun RailTopTabs(
items: List<RailItem>,
@@ -391,7 +329,6 @@ fun RailTopTabs(
)
}
if (links.isNotEmpty()) {
// Faint separator: everything past here is an action button, not a tab.
Box(
modifier = Modifier
.padding(horizontal = 2.dp)
@@ -408,8 +345,6 @@ fun RailTopTabs(
}
}
/** One cell of [RailTopTabs] - icon over a small label, with an accent underline (zero-width when
* unselected, so every cell keeps the same height). Mirrors the container editor's TopCell. */
@Composable
private fun TopTabCell(
icon: ImageVector,
@@ -3,15 +3,6 @@ package com.droiddeck.launcher.files
import android.content.Context
import org.json.JSONArray
/**
* Persists the File Manager's favourite / bookmarked directories.
*
* Stores an ordered (insertion-order) list of absolute path strings as a JSON array
* under "file_manager_favorites" in SharedPreferences "file_manager_prefs". Only the
* absolute path is kept - everything shown on a favourite card (drive label, container
* name, display path) is derived live, so a renamed or deleted container resolves
* correctly for free.
*/
object FavoritesStore {
private const val PREFS_NAME = "file_manager_prefs"
@@ -20,7 +11,6 @@ object FavoritesStore {
private fun prefs(context: Context) =
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
/** Ordered list of favourited absolute paths (insertion order). */
fun list(context: Context): List<String> {
val raw = prefs(context).getString(KEY, null) ?: return emptyList()
return runCatching {
@@ -31,7 +21,6 @@ object FavoritesStore {
fun isFavorite(context: Context, path: String): Boolean = list(context).contains(path)
/** Add [path] if not already present (deduped); keeps insertion order. */
fun add(context: Context, path: String) {
val current = list(context)
if (current.contains(path)) return
@@ -44,7 +33,6 @@ object FavoritesStore {
save(context, current.filterNot { it == path })
}
/** Toggle [path]; returns true if it is now a favourite, false if it was removed. */
fun toggle(context: Context, path: String): Boolean =
if (isFavorite(context, path)) {
remove(context, path); false
@@ -4,30 +4,18 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import java.io.File
// Reading and setting a file's read-only and hidden attributes (the DOS attribute xattr).
// ── DOS file attributes (Read-only / Hidden) ──
// The in-container file manager (wfm.exe) exposes these in its Properties dialog; this mirrors the
// same two toggles for files browsed from the app side. No root - we only touch permission bits the
// app owns (container files) and the Wine DOS-attribute xattr.
// FILE_ATTRIBUTE_HIDDEN, as Wine encodes it in the user.DOSATTRIB extended attribute.
private const val FILE_ATTRIBUTE_HIDDEN = 0x2
private const val DOSATTRIB_XATTR = "user.DOSATTRIB"
// Snapshot of a file's two toggleable attributes. hiddenSupported is false when the underlying
// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) - the Hidden toggle is then
// disabled while Read-only keeps working.
internal data class FileAttrState(
val readOnly: Boolean,
val hidden: Boolean,
val hiddenSupported: Boolean,
)
// Wine (and Samba) store user.DOSATTRIB as an ASCII hex string ("0x22"), sometimes with trailing
// Samba fields after a separator. We only need the leading DOS-attribute hex, so read from the "0x"
// prefix and stop at the first non-hex character.
private fun parseDosAttrib(raw: ByteArray): Int {
val s = String(raw, Charsets.US_ASCII).trim()
val hex = if (s.startsWith("0x") || s.startsWith("0X")) s.substring(2) else s
@@ -35,11 +23,8 @@ private fun parseDosAttrib(raw: ByteArray): Int {
return digits.toIntOrNull(16) ?: 0
}
// Read the current read-only + Wine-hidden state. Never throws: an xattr-unsupported filesystem
// comes back hiddenSupported=false (Hidden toggle disabled), Read-only always resolves.
internal fun readFileAttrs(file: File): FileAttrState {
val path = file.absolutePath
// Read-only reflects the OWNER write bit - that's what Wine maps to FILE_ATTRIBUTE_READONLY.
val readOnly = runCatching {
(android.system.Os.stat(path).st_mode and android.system.OsConstants.S_IWUSR) == 0
}.getOrDefault(!file.canWrite())
@@ -49,8 +34,6 @@ internal fun readFileAttrs(file: File): FileAttrState {
try {
hidden = (parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR)) and FILE_ATTRIBUTE_HIDDEN) != 0
} catch (e: android.system.ErrnoException) {
// ENODATA: xattr namespace works, the attribute just isn't set yet -> still toggleable.
// ENOTSUP/EOPNOTSUPP/anything else: the fs can't store it -> disable the Hidden toggle.
supported = e.errno == android.system.OsConstants.ENODATA
} catch (e: Exception) {
supported = false
@@ -58,10 +41,6 @@ internal fun readFileAttrs(file: File): FileAttrState {
return FileAttrState(readOnly, hidden, supported)
}
// Toggle read-only by flipping the write bits, preserving every other permission bit. Setting
// read-only clears owner/group/other write (so Wine sees FILE_ATTRIBUTE_READONLY regardless of which
// write bit it checks); clearing it restores owner write. Falls back to File.setWritable if chmod is
// somehow refused. Returns true on success.
internal fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching {
val path = file.absolutePath
val mode = android.system.Os.stat(path).st_mode
@@ -73,10 +52,6 @@ internal fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching {
true
}.getOrElse { file.setWritable(!readOnly, true) }
// Flip Wine's DOS hidden bit in user.DOSATTRIB, preserving the other DOS-attribute bits
// (archive/system/read-only) already encoded there, and synthesizing a minimal value when absent.
// Writes Wine's own "0x%x" format, which Wine reads back natively. Returns false when the fs can't
// store the xattr, so the caller can disable just the Hidden toggle.
internal fun setHidden(file: File, hidden: Boolean): Boolean = try {
val path = file.absolutePath
var attr = try {
@@ -13,7 +13,6 @@ import androidx.compose.ui.Modifier
import com.droiddeck.launcher.ui.DroidDeckTheme
import java.io.File
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
class FileManagerActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
@@ -77,23 +77,16 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
// The File Manager's rows, tiles, favourites and context menu.
// Semantic identity colours for the favourite-card drive badge. Intentionally NOT theme
// accent colours - they identify the storage source at a glance. Returns (background, foreground).
private fun badgeColors(loc: FavLocation): Pair<Color, Color> {
val white = Color(0xFFFFFFFF)
return when {
loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white // blue
loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white // green
else -> Color(0xFF555555) to white // grey
loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white
loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white
else -> Color(0xFF555555) to white
}
}
// The context-menu item list shared by the list rows (FileItemRow) and the grid tiles
// (FileGridTile), so both open the identical menu. Gating (isDir/canRun/isInno/looksLikeArchive) is
// recomputed from [file] here - one source of truth for what each item shows. Every item dismisses
// the menu first, then runs its action.
@Composable
private fun FileContextMenuItems(
file: File,
@@ -114,15 +107,12 @@ private fun FileContextMenuItems(
onClick = { onDismissMenu(); onSelect() },
)
MenuItemDivider()
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_properties)) },
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onProperties() },
)
MenuItemDivider()
// Favorites are directories - only folders get the pin toggle.
if (isDir) {
DropdownMenuItem(
text = { Text(if (isFavorite) stringResource(R.string.fm_favorite_remove) else stringResource(R.string.fm_favorite_add)) },
@@ -189,11 +179,8 @@ internal fun FileItemRow(
val context = LocalContext.current
val isDir = file.isDirectory
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
// wallpaper/icon). Coil sizes the decode to the 36dp slot and caches it, so scrolling stays smooth.
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
// For real PE executables, try to pull out the embedded application icon (async, off the main thread).
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
if (!isDir && file.name.lowercase().endsWith(".exe")) {
LaunchedEffect(file.absolutePath) {
@@ -207,8 +194,6 @@ internal fun FileItemRow(
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.combinedClickable(
// In selection mode a tap toggles instead of opening, so you can rattle through a
// folder without long-pressing every single row.
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
@@ -231,7 +216,6 @@ internal fun FileItemRow(
Spacer(Modifier.width(4.dp))
}
when {
// Show the executable's own embedded icon when we managed to extract one.
exeIcon != null -> Image(
bitmap = exeIcon!!,
contentDescription = null,
@@ -249,7 +233,6 @@ internal fun FileItemRow(
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
// Real image preview. Falls back to the generic file icon while loading or on decode failure.
isImage -> AsyncImage(
model = file,
contentDescription = null,
@@ -313,8 +296,6 @@ internal fun FileItemRow(
}
}
// The ".." row at the top of a folder: one level up, styled like a folder row so it reads as part
// of the list and takes controller focus the same way.
@Composable
internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
Card(
@@ -354,8 +335,6 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
}
}
// Dedicated Favorites list that replaces the file list while the star toggle is on.
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
@Composable
internal fun FavoritesList(
currentDir: File,
@@ -431,9 +410,6 @@ internal fun FavoritesList(
}
}
// A single favourite - matches the FileItemRow card style (surfaceContainer + outline +
// RoundedCornerShape(10.dp)). Shows the folder name, a coloured drive badge + origin text,
// and the full display path; tapping jumps into it, the filled star unpins.
@Composable
private fun FavoriteCard(
file: File,
@@ -472,7 +448,6 @@ private fun FavoriteCard(
overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(2.dp))
// Origin line: coloured drive badge + source description.
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = stringResource(loc.driveLabel),
@@ -517,13 +492,6 @@ private fun FavoriteCard(
}
}
/**
* One entry in the File Manager's grid view: a big thumbnail with the name under it.
*
* Deliberately drops size and date - at this width they truncate to noise. The grid is for
* recognising things by sight (screenshots, covers, game folders); the list stays the view for
* reading details.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun FileGridTile(
@@ -554,7 +522,6 @@ internal fun FileGridTile(
if (bmp != null) exeIcon = bmp.asImageBitmap()
}
}
// The tile has no ⋮ button - long-press opens this menu, anchored to the Box around the Card.
Box {
Card(
modifier = Modifier
@@ -608,8 +575,6 @@ internal fun FileGridTile(
}
}
Spacer(Modifier.height(4.dp))
// Always reserve two lines (issue #475): a one-line name used to make its card shorter than
// its neighbours, so grid rows had ragged heights. Fixed min/max keeps every tile the same size.
Text(
file.name,
color = MaterialTheme.colorScheme.onSurface,
@@ -12,33 +12,8 @@ import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import java.io.File
// The File Manager's non-UI helpers: sorting, paths, conflict choices and favourite locations.
/*
* Bannerlator's File Manager (ui/screens/FileManagerScreen.kt), carried over whole: the same
* browsing, grid and list, sorting, search, multi-select, copy/cut/paste with conflicts and
* progress, rename, delete, new folder, properties, favourites and the locations rail, and the
* same pick modes. What this app has no use for is not here: running a file in a Wine container,
* adding it to a container's shortcuts, the Drive C: / Drive Z: locations and the archive
* unpacker that installs into a prefix. Everything else is line for line the same so a fix in
* either app carries to the other.
*/
/**
* What to do when a pasted item already exists at the destination.
*
* OVERWRITE and MERGE resolve to the same call - `copyWithProgress` recurses into an existing
* directory and truncates existing files - but they mean different things to the user, so both are
* offered and the wording is chosen per item type (files overwrite, folders merge).
*/
enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP }
/**
* Shortens a path from the LEFT, keeping whole segments.
*
* Compose's TextOverflow can only ellipsise the tail, which for a path throws away the part that
* matters - `/storage/emulated/0/Games/Racing/Dir…` tells you nothing about where you are.
*/
internal fun elidePathStart(path: String, max: Int): String {
if (path.length <= max) return path
val parts = path.split('/').filter { it.isNotEmpty() }
@@ -50,12 +25,9 @@ internal fun elidePathStart(path: String, max: Int): String {
return if (out.isEmpty()) "…" + path.takeLast(max - 1) else "…$out"
}
/** Folder-first ordering stays fixed across both sort directions. */
internal fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
val inner: Comparator<File> = when (sortBy) {
"date" -> compareBy { it.lastModified() }
// Directory length() is meaningless, so folders sort by name within the size ordering
// instead of pretending to have one.
"size" -> compareBy { if (it.isDirectory) -1L else it.length() }
else -> compareBy { it.name.lowercase() }
}
@@ -63,27 +35,23 @@ internal fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
return compareBy<File> { if (it.isDirectory) 0 else 1 }.then(directed)
}
// Image extensions that get a real thumbnail (via Coil) instead of the generic file icon.
internal val IMAGE_THUMB_EXTS = setOf("jpg", "jpeg", "png", "webp", "bmp", "gif")
// True when [child] is [ancestor] itself or lives anywhere inside it.
internal fun isWithin(child: File, ancestor: File): Boolean {
val c = runCatching { child.canonicalPath }.getOrDefault(child.absolutePath)
val a = runCatching { ancestor.canonicalPath }.getOrDefault(ancestor.absolutePath)
return c == a || c.startsWith(a + File.separator)
}
// ── Favorites: origin resolution ──
enum class FavStorage { INTERNAL, SD, OTHER }
data class FavLocation(
val storage: FavStorage,
@StringRes val driveLabel: Int, // Internal, SD card, or Storage
val displayPath: String // the unix absolute path
@StringRes val driveLabel: Int,
val displayPath: String
)
// Resolve where [file] lives (storage source + a friendly label) by prefix-matching its path.
fun describeLocation(file: File): FavLocation {
val abs = file.absolutePath
@@ -99,7 +67,6 @@ fun describeLocation(file: File): FavLocation {
}
}
// The Linux system's root (the app's files/linuxfs, the sessions' /) and anything under it.
if (Regex("/files/linuxfs(/|$)").containsMatchIn(abs)) {
return FavLocation(FavStorage.OTHER, R.string.fm_drive_linux, abs)
}
@@ -98,12 +98,7 @@ import java.util.Date
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FileManagerScreen(
// Pick mode (issue #73): reuse this File Manager as a themed file picker. When on, editing/run
// features are gated off and tapping a matching file returns it via [onPick]. Defaults keep the
// full-featured File Manager nav destination unchanged.
pickMode: Boolean = false,
// Directory-pick mode (issue #70): only folders are listed, files are hidden, and a
// "Select this folder" action returns the current directory via [onPick]. Implies pickMode.
pickDirMode: Boolean = false,
pickExtensions: List<String> = emptyList(),
initialDir: File? = null,
@@ -113,7 +108,6 @@ fun FileManagerScreen(
val context = LocalContext.current
val scope = rememberCoroutineScope()
// Only matching files are shown in pick mode (directories are always shown). Empty = all files.
val lowerExts = remember(pickExtensions) { pickExtensions.map { it.lowercase() } }
fun matchesPickExt(file: File): Boolean {
if (lowerExts.isEmpty()) return true
@@ -124,18 +118,10 @@ fun FileManagerScreen(
val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
val browsePrefs = pickPrefs
val rootDir = remember {
// Both modes: honour an explicit caller-supplied start dir (e.g. Log Manager's game-log
// folder), else open at the INTERNAL STORAGE ROOT. Selection screens (drive-folder pick,
// local component pick, imports) previously defaulted to Download which - combined with the
// currentRoot floor below - trapped users in Download with no way up (reported bug).
initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
}
var currentDir by remember { mutableStateOf(rootDir) }
// The up/back FLOOR - back + the up-arrow are disabled while currentDir == currentRoot. It MUST be
// the VOLUME ROOT of the start dir (internal /storage/emulated/0, or an SD card /storage/XXXX-XXXX),
// NOT the start dir itself: otherwise opening at any subfolder disables up/back and traps the user
// there. (Mirrors the volume-root logic in favLocationOf above.)
var currentRoot by remember {
val abs = rootDir.absolutePath
val internal = "/storage/emulated/0"
@@ -145,8 +131,6 @@ fun FileManagerScreen(
val name = abs.removePrefix("/storage/").substringBefore('/')
if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else rootDir
}
// A game's own folder or Proton prefix lives in the app's private storage, which has no
// volume above it: floor at the app's files dir so up/back still reach the library roots.
else -> {
val appFiles = runCatching { context.filesDir.canonicalPath }.getOrNull()
generateSequence(rootDir) { it.parentFile }
@@ -159,40 +143,26 @@ fun FileManagerScreen(
var entries by remember { mutableStateOf(listOf<File>()) }
var selectedEntry by remember { mutableStateOf<File?>(null) }
var showMenuFor by remember { mutableStateOf<File?>(null) }
// Clipboard holds a LIST so one paste can carry a whole selection. Cut/copy semantics are a
// flag on the batch rather than per item - mixing the two in one clipboard has no sane meaning.
var clipboardFiles by remember { mutableStateOf<List<File>>(emptyList()) }
var isCutOperation by remember { mutableStateOf(false) }
// Multi-select. Keyed by absolute path rather than File so a directory reload (which builds
// fresh File objects) doesn't silently drop the selection.
var selectionMode by remember { mutableStateOf(false) }
var selectedPaths by remember { mutableStateOf<Set<String>>(emptySet()) }
// Paste conflict resolution, surfaced from the IO coroutine and answered by the dialog.
var pendingConflict by remember { mutableStateOf<File?>(null) }
var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) }
var conflictApplyToAll by remember { mutableStateOf(false) }
// Set while a copy/move runs so the progress UI can offer a cancel.
var operationJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) }
// Browse controls. Persisted so the list doesn't reset its order every time you open a folder.
var searchQuery by remember { mutableStateOf("") }
var showSearch by remember { mutableStateOf(false) }
var sortBy by remember { mutableStateOf(browsePrefs.getString("fmSortBy", "name") ?: "name") }
var sortDesc by remember { mutableStateOf(browsePrefs.getBoolean("fmSortDesc", false)) }
var showHidden by remember { mutableStateOf(browsePrefs.getBoolean("fmShowHidden", true)) }
var showSortMenu by remember { mutableStateOf(false) }
// View mode: list of cards (default) or a thumbnail grid. Density applies to the list only -
// a grid tile has no second line to compact.
// The grid/list toggle is the SOURCE OF TRUTH in BOTH orientations (it drives the view and its
// choice persists across rotation). Grid is the default - most useful in landscape, and in
// portrait GridCells.Adaptive naturally renders fewer columns (~2). Do NOT force portrait to list:
// that broke the toggle on-device (tapping it did nothing in portrait).
var gridView by remember { mutableStateOf(browsePrefs.getBoolean("fmGridView", true)) }
val showGrid = gridView
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
var showNewFolderDialog by remember { mutableStateOf(false) }
var renameTarget by remember { mutableStateOf<File?>(null) }
// Properties sheet (basic info + Read-only / Hidden toggles) target; null when closed.
var propertiesTarget by remember { mutableStateOf<File?>(null) }
var isOperationRunning by remember { mutableStateOf(false) }
var operationLabel by remember { mutableStateOf("") }
@@ -201,24 +171,16 @@ fun FileManagerScreen(
val listState = rememberLazyListState()
val pullState = rememberPullToRefreshState()
// Favorites view: when on, a dedicated bookmarks list replaces the file list.
// favTick is bumped on any add/remove/toggle so the favorites view + per-row star recompute.
var showFavorites by remember { mutableStateOf(false) }
var favTick by remember { mutableIntStateOf(0) }
// resetScroll: jump to the top of the list (true for navigation; false for in-place reloads
// after delete/paste/rename/refresh so the user keeps their scroll position).
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
currentDir = dir
// Remember the browsed directory so the next pick resumes here.
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
scope.launch {
val list = withContext(Dispatchers.IO) {
dir.listFiles()?.toList()
// Dir-pick mode: folders only. File-pick: folders + matching files. Else: all.
?.filter { if (pickDirMode) it.isDirectory else !pickMode || it.isDirectory || matchesPickExt(it) }
// Dotfiles are noise in a storage root (.aya, .$recycle_bin$) but occasionally
// the thing you came for, so it's a toggle rather than a permanent filter.
?.filter { showHidden || !it.name.startsWith(".") }
?.sortedWith(comparatorFor(sortBy, sortDesc)) ?: emptyList()
}
@@ -227,7 +189,6 @@ fun FileManagerScreen(
}
}
// Pull-to-refresh: re-list the current directory, keeping scroll position.
if (pullState.isRefreshing) {
LaunchedEffect(true) {
loadDirectory(currentDir, resetScroll = false)
@@ -235,19 +196,13 @@ fun FileManagerScreen(
}
}
// Jump to a drive's root; pins the Back boundary so we don't climb above it.
fun openDrive(dir: File) {
currentRoot = dir
loadDirectory(dir)
}
// Open the start dir without openDrive(): that pins the floor to the start dir itself, which
// greyed out up/back whenever the manager was opened at a game's folder.
LaunchedEffect(Unit) { loadDirectory(rootDir) }
// System/gesture Back: while the Favorites view is open it closes that first; otherwise
// it goes up one directory. Only at the current drive's root with Favorites closed is it
// disabled, letting Back propagate to close the File Manager.
BackHandler(enabled = showFavorites || currentDir != currentRoot) {
if (showFavorites) {
showFavorites = false
@@ -257,15 +212,12 @@ fun FileManagerScreen(
if (parent != null && parent.exists()) loadDirectory(parent)
}
// One level up, never above the current drive's root: shared by the toolbar arrow and the
// ".." row at the top of the list.
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
fun goUp() {
val parent = currentDir.parentFile
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
}
// Resolve a non-colliding destination in [dir] for [name] (foo.txt -> "foo (1).txt").
fun uniqueDestination(dir: File, name: String): File {
var candidate = File(dir, name)
if (!candidate.exists()) return candidate
@@ -291,12 +243,9 @@ fun FileManagerScreen(
}
}
/** Waits for the user to answer the conflict dialog for [file]; null if they cancelled it. */
suspend fun askConflict(file: File): ConflictChoice? {
pendingConflict = file
conflictChoice = null
// Poll rather than plumb a CompletableDeferred through Compose state - the dialog answers
// by setting conflictChoice, and this coroutine is already off the critical path.
while (pendingConflict != null && conflictChoice == null) kotlinx.coroutines.delay(50)
return conflictChoice
}
@@ -319,12 +268,10 @@ fun FileManagerScreen(
var done = 0
for (src in sources) {
// Pasting a folder into itself or its own subtree would recurse forever.
if (src.isDirectory && isWithin(dstDir, src)) {
failed++
continue
}
// Moving into the folder it already sits in is a no-op.
if (cut && src.parentFile?.absolutePath == dstDir.absolutePath) {
skipped++
continue
@@ -336,16 +283,12 @@ fun FileManagerScreen(
if (conflictApplyToAll) applyToAll = it
} ?: run { skipped++; null } ?: continue
when (choice) {
// Overwrite and Merge both paste onto the real destination: copyWithProgress
// recurses into an existing directory and truncates existing files, so the
// two differ only in what the user expects, not in what we call.
ConflictChoice.OVERWRITE, ConflictChoice.MERGE -> Unit
ConflictChoice.KEEP_BOTH -> dst = uniqueDestination(dstDir, src.name)
ConflictChoice.SKIP -> { skipped++; continue }
}
}
// Progress is per item; with a batch the label carries the overall position.
operationLabel = if (sources.size > 1) {
context.getString(if (cut) R.string.fm_op_moving_batch else R.string.fm_op_copying_batch, done + 1, sources.size, src.name)
} else {
@@ -419,8 +362,6 @@ fun FileManagerScreen(
}
var showDriveMenu by remember { mutableStateOf(false) }
// Re-enumerated whenever we come back to the screen: returning from a container can leave this
// process on a stale storage view, and the volume set has to be re-read rather than cached.
var storageTick by remember { mutableIntStateOf(0) }
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
@@ -435,7 +376,6 @@ fun FileManagerScreen(
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
}
// ── Dialogs ──
if (showNewFolderDialog) {
var folderName by remember { mutableStateOf("") }
@@ -488,8 +428,6 @@ fun FileManagerScreen(
FilePropertiesDialog(
file = file,
onDismiss = { propertiesTarget = null },
// Attribute changes affect Hidden/read-only which the listing filters/sorts on, so refresh
// in place (keeping scroll) after any toggle applies.
onChanged = { loadDirectory(currentDir, resetScroll = false) },
)
}
@@ -519,7 +457,6 @@ fun FileManagerScreen(
Column {
Text(stringResource(R.string.fm_cannot_undo))
Spacer(Modifier.height(6.dp))
// Name a few so an accidental Select-All is obvious before it's too late.
victims.take(5).forEach {
Text("• ${it.name}", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
}
@@ -557,7 +494,6 @@ fun FileManagerScreen(
)
}
// Paste conflict - one per colliding item, with "apply to all" for a long batch.
pendingConflict?.let { conflict ->
val isDir = conflict.isDirectory
OutlinedAlertDialog(
@@ -605,7 +541,6 @@ fun FileManagerScreen(
}
Column(modifier = Modifier.fillMaxSize()) {
// ── Pick-mode title ──
if (pickMode && !pickerTitle.isNullOrEmpty()) {
Text(
text = pickerTitle,
@@ -618,7 +553,6 @@ fun FileManagerScreen(
.padding(horizontal = 16.dp, vertical = 10.dp),
)
}
// ── Dir-pick action bar: confirm the currently-browsed folder ──
if (pickDirMode) {
Button(
onClick = { onPick?.invoke(currentDir) },
@@ -631,7 +565,6 @@ fun FileManagerScreen(
Text(stringResource(R.string.fm_select_this_folder))
}
}
// ── Path bar ──
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
@@ -644,12 +577,8 @@ fun FileManagerScreen(
}
val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel)
// Dim the drive chip while the Favorites list is open (it's not the active context).
val driveChipAlpha = if (showFavorites) 0.45f else 1f
Box {
// The drive/location selector opens the drive dropdown, so give it the same outlined
// look as the "New Folder" button + the rail location items - it reads as a button, not
// plain text. Border uses the theme accent token; behaviour unchanged.
val driveChipShape = RoundedCornerShape(8.dp)
Text(
text = " $currentDriveLabel ▾",
@@ -720,13 +649,8 @@ fun FileManagerScreen(
modifier = Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
// PORTRAIT: hide the current-folder name - it's redundant with the path bar directly
// below (which shows the full path). The spacer keeps the action icons right-aligned.
Spacer(Modifier.weight(1f))
} else {
// LANDSCAPE: the CURRENT FOLDER, not the full path. A path ellipsised on the right
// hides its tail - the only part that says where you are ("…/Games/Racing/Dir…"). The
// full path moves to the line below, where it has room.
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
color = MaterialTheme.colorScheme.onSurface,
@@ -739,7 +663,6 @@ fun FileManagerScreen(
}
if (!showFavorites) {
// Keep New Folder in the toolbar so the file list uses the full height.
if (!pickMode) {
OutlinedButton(
onClick = { showNewFolderDialog = true },
@@ -777,8 +700,6 @@ fun FileManagerScreen(
Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label)
},
onClick = {
// Tapping the active field flips direction; a different
// field switches to it ascending.
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
browsePrefs.edit().putString("fmSortBy", sortBy)
.putBoolean("fmSortDesc", sortDesc).apply()
@@ -809,7 +730,6 @@ fun FileManagerScreen(
}
}
// Star toggle: open/close the dedicated Favorites list.
IconButton(onClick = { showFavorites = !showFavorites }) {
if (showFavorites) {
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
@@ -819,7 +739,6 @@ fun FileManagerScreen(
}
}
// ── Search field ── filters the current folder only; it is not a recursive search.
if (showSearch && !showFavorites) {
OutlinedTextField(
value = searchQuery,
@@ -830,7 +749,6 @@ fun FileManagerScreen(
)
}
// Free space on the volume being browsed - worth knowing before starting a 60 GB copy.
val freeSpace = remember(currentDir.absolutePath, entries) {
runCatching { currentDir.usableSpace }.getOrDefault(0L)
}
@@ -840,14 +758,10 @@ fun FileManagerScreen(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 2.dp),
) {
Text(
// Elided from the LEFT: the deepest part of a path is the informative part, so
// when it doesn't fit we drop the /storage/emulated/0 prefix, not the tail.
text = elidePathStart(currentDir.absolutePath, 52),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
// fill = true: the path takes all remaining width, so the free-space figure
// is pinned to the right edge instead of sliding around with the path length.
modifier = Modifier.weight(1f),
)
if (freeSpace > 0) {
@@ -863,7 +777,6 @@ fun FileManagerScreen(
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
// ── Selection bar ── replaces the paste banner while picking items.
if (selectionMode) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -878,7 +791,6 @@ fun FileManagerScreen(
fontSize = 13.sp,
modifier = Modifier.weight(1f),
)
// Compact outlined buttons so all five fit one row alongside the count.
val selBarPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp)
OutlinedButton(
onClick = {
@@ -924,7 +836,6 @@ fun FileManagerScreen(
}
}
// ── Paste banner ──
if (clipboardFiles.isNotEmpty()) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -948,7 +859,6 @@ fun FileManagerScreen(
}
}
// ── Progress overlay ──
if (isOperationRunning) {
Column(
modifier = Modifier
@@ -966,8 +876,6 @@ fun FileManagerScreen(
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
// A multi-gigabyte copy onto a slow card is exactly when you discover you
// picked the wrong folder; without this the only way out was killing the app.
if (operationJob != null) {
TextButton(onClick = {
operationJob?.cancel()
@@ -996,10 +904,6 @@ fun FileManagerScreen(
}
}
// ── Left locations rail (mockup Option 2) + content ──
// Shared collapsible rail: landscape expanded by default, portrait collapsed icon-only. Not
// shown in pick mode (the themed picker keeps its slim layout). Built each recompose (cheap)
// so it tracks the current drive/favourites without stale click lambdas.
val fmRailState = rememberRailState("filemanager")
fun locItem(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, dir: File, shortLabel: String? = null) =
RailItem(label, icon, !showFavorites && currentRoot.absolutePath == dir.absolutePath, shortLabel = shortLabel) {
@@ -1012,15 +916,12 @@ fun FileManagerScreen(
showFavorites = false; if (d.readable) openDrive(d.dir)
})
}
// The Linux system the sessions run in: its own / (the desktop's root), once installed.
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
}
val quickItems = buildList {
File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_downloads), Icons.Filled.Download, it, stringResource(R.string.fm_rail_downloads_short))) }
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
// The app's own logs folder: private, which this file manager (the app itself) can read.
com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
}
@@ -1033,12 +934,10 @@ fun FileManagerScreen(
}
Row(modifier = Modifier.weight(1f).fillMaxWidth()) {
// The slim picker keeps its layout: no rail.
if (!pickMode) {
CollapsibleRail(state = fmRailState, title = stringResource(R.string.fm_rail_title), sections = locationSections, outlinedItems = true)
}
Box(modifier = Modifier.weight(1f).fillMaxSize()) {
// ── Favorites list OR file list ──
if (showFavorites) {
FavoritesList(
currentDir = currentDir,
@@ -1060,7 +959,6 @@ fun FileManagerScreen(
modifier = Modifier.fillMaxSize(),
)
} else {
// ── File list (pull down to refresh) ──
Box(
modifier = Modifier
.fillMaxSize()
@@ -1088,8 +986,6 @@ fun FileManagerScreen(
selected = file.absolutePath in selectedPaths,
onLongPress = {
if (!pickMode) {
// In selection mode a long-press toggles; otherwise it opens the
// same context menu the list rows show (the tile has no ⋮ button).
if (selectionMode) {
selectedPaths = if (file.absolutePath in selectedPaths)
selectedPaths - file.absolutePath
@@ -1168,8 +1064,6 @@ fun FileManagerScreen(
selectionMode = selectionMode,
selected = file.absolutePath in selectedPaths,
onLongPress = {
// In selection mode a long-press toggles; otherwise it opens the
// per-item context menu (matching the grid tiles).
if (!pickMode) {
if (selectionMode) {
selectedPaths = if (file.absolutePath in selectedPaths)
@@ -1223,8 +1117,6 @@ fun FileManagerScreen(
}
}
}
// material3 1.2.0's PullToRefreshContainer draws its indicator even at rest;
// only show it while the user is actively pulling or a refresh is running.
if (pullState.verticalOffset > 0.5f || pullState.isRefreshing) {
PullToRefreshContainer(
state = pullState,
@@ -1233,7 +1125,7 @@ fun FileManagerScreen(
}
}
}
} // end content Box (beside the rail)
} // end rail + content Row
}
}
}
}
@@ -10,15 +10,9 @@ import java.io.IOException
import java.nio.file.Files
import java.util.Locale
/**
* The file operations the File Manager needs, as Bannerlator's FileUtils has them: a delete that
* says whether it worked, a copy and a move that report bytes as they go, and the size format
* the rows use. Kept apart from core/FileUtils, whose callers want a quiet delete.
*/
object FileOps {
private const val TAG = "FileOps"
/** Byte-accurate copy progress (copied/total bytes), reported as the copy proceeds. */
fun interface ProgressCallback { fun onProgress(copiedBytes: Long, totalBytes: Long) }
fun formatBytes(context: Context, bytes: Long): String {
@@ -30,7 +24,6 @@ object FileOps {
fun isSymlink(file: File): Boolean = try { Files.isSymbolicLink(file.toPath()) } catch (e: Exception) { false }
/** Recursive delete that never follows a symlink; true when everything went. */
fun delete(target: File?): Boolean {
if (target == null) return false
if (target.isDirectory && !isSymlink(target)) {
@@ -46,20 +39,12 @@ object FileOps {
return ok
}
/** Recursive total size in bytes of files under [f] (skips symlinks). Used to size a progress bar. */
fun totalSize(f: File?): Long {
if (f == null || !f.exists() || isSymlink(f)) return 0
if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it) } ?: 0
return f.length()
}
/**
* Moves [src] to [dst], relinking instead of copying whenever possible. A rename is instant
* regardless of size but only works within one filesystem; renameTo returning false is the
* signal that a boundary was crossed, so it doubles as the check, and the fallback is
* copy-then-delete. Only attempted when the destination does not exist: renaming onto an
* existing directory does not merge.
*/
fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean {
if (sameFile(src, dst)) return true
if (!dst.exists() && src.renameTo(dst)) {
@@ -70,7 +55,6 @@ object FileOps {
return delete(src)
}
/** A copy that reports byte progress, smooth even within one large file. */
fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean {
val total = maxOf(totalSize(src), 1L)
return copyWithProgress(src, dst, longArrayOf(0), total, progress)
@@ -96,7 +80,7 @@ object FileOps {
}
val parent = dst.parentFile
if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false
val chunk = 4L * 1024 * 1024 // report progress every 4 MiB
val chunk = 4L * 1024 * 1024
try {
FileInputStream(src).channel.use { input ->
FileOutputStream(dst).channel.use { output ->
@@ -123,7 +107,6 @@ object FileOps {
private fun sameFile(a: File, b: File): Boolean =
try { a.canonicalPath == b.canonicalPath } catch (e: IOException) { a.absolutePath == b.absolutePath }
/** True when [child] is [ancestor] itself or lives anywhere inside it. */
private fun isWithin(child: File, ancestor: File): Boolean {
val c = try { child.canonicalPath } catch (e: IOException) { child.absolutePath }
val a = try { ancestor.canonicalPath } catch (e: IOException) { ancestor.absolutePath }
@@ -16,16 +16,6 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.ui.DroidDeckTheme
import java.io.File
/**
* Themed host for [FileManagerScreen] in pick mode. 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 attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
@@ -36,7 +26,6 @@ class FilePickerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
// 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)
}
@@ -44,7 +33,6 @@ class FilePickerActivity : ComponentActivity() {
val extensions = intent.getStringArrayExtra(EXTRA_EXTENSIONS)?.toList() ?: emptyList()
val pickDir = intent.getBooleanExtra(EXTRA_PICK_DIRECTORY, false)
val title = intent.getStringExtra(EXTRA_PICKER_TITLE)
// The screen remembers the folder it last picked from; an explicit start wins over it.
val prefs = getSharedPreferences("file_manager", MODE_PRIVATE)
val initialDir = (intent.getStringExtra(EXTRA_INITIAL_DIRECTORY) ?: prefs.getString("lastFilePickerDir", null))
?.let { File(it) }?.takeIf { it.isDirectory }
@@ -70,7 +58,6 @@ class FilePickerActivity : ComponentActivity() {
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()
}
@@ -39,17 +39,7 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
// The File Manager's properties dialog.
/**
* Properties sheet for a single file or folder: basic info plus the two Windows/Wine file attributes
* the in-container file manager (wfm.exe) also exposes - Read-only and Hidden. Each toggle applies
* immediately (off the main thread) and refreshes the listing via [onChanged].
*
* State is keyed on the file so it always reflects the entry it was opened for. On a filesystem that
* can't store Wine's DOSATTRIB xattr (the FUSE /storage volumes) only the Hidden toggle is disabled;
* Read-only keeps working everywhere.
*/
@Composable
internal fun FilePropertiesDialog(
file: File,
@@ -60,7 +50,6 @@ internal fun FilePropertiesDialog(
val scope = rememberCoroutineScope()
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
var attrs by remember(file.absolutePath) { mutableStateOf<FileAttrState?>(null) }
// Guards against a second toggle landing while the first is still being applied off-thread.
var busy by remember(file.absolutePath) { mutableStateOf(false) }
LaunchedEffect(file.absolutePath) {
attrs = withContext(Dispatchers.IO) { readFileAttrs(file) }
@@ -71,7 +60,6 @@ internal fun FilePropertiesDialog(
title = { Text(stringResource(R.string.fm_properties)) },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
// ── Basic info ──
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
@@ -95,7 +83,6 @@ internal fun FilePropertiesDialog(
Spacer(Modifier.height(6.dp))
val state = attrs
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
AttributeToggleRow(
label = stringResource(R.string.fm_read_only),
description = stringResource(R.string.fm_read_only_hint),
@@ -116,7 +103,6 @@ internal fun FilePropertiesDialog(
},
)
Spacer(Modifier.height(2.dp))
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
val hiddenSupported = state?.hiddenSupported == true
AttributeToggleRow(
label = stringResource(R.string.fm_hidden),
@@ -134,7 +120,6 @@ internal fun FilePropertiesDialog(
attrs = attrs?.copy(hidden = want)
onChanged()
} else {
// The write failed after all - disable the toggle rather than lie.
attrs = attrs?.copy(hiddenSupported = false)
Toast.makeText(context, R.string.fm_hidden_failed, Toast.LENGTH_SHORT).show()
}
@@ -147,7 +132,6 @@ internal fun FilePropertiesDialog(
)
}
// One "label: value" line in the Properties info block.
@Composable
private fun PropertyLine(label: String, value: String) {
Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
@@ -168,7 +152,6 @@ private fun PropertyLine(label: String, value: String) {
}
}
// A labelled attribute switch with a one-line description, used by the Properties sheet.
@Composable
private fun AttributeToggleRow(
label: String,
@@ -5,14 +5,7 @@ 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(),
@@ -24,7 +17,6 @@ object InAppFilePicker {
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,
@@ -39,6 +31,5 @@ object InAppFilePicker {
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) }
}
@@ -10,9 +10,6 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
// Shared outlined-card look for the app's popup menus, matching the FileManager / CommunityCard
// idiom (surfaceContainer fill, 1dp outline, rounded 10dp). Applied to a DropdownMenu's modifier so
// the popup reads as an outlined card. Keep all three menu call-sites on this so they stay identical.
@Composable
internal fun Modifier.outlinedMenuCard(): Modifier {
val cs = MaterialTheme.colorScheme
@@ -23,7 +20,6 @@ internal fun Modifier.outlinedMenuCard(): Modifier {
.border(1.dp, cs.outline, shape)
}
// The thin low-alpha separator that sits between items inside an outlined menu card.
@Composable
internal fun MenuItemDivider() {
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f))
@@ -12,12 +12,6 @@ import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
// Single source of truth for the app's AlertDialogs: a drop-in wrapper around the Material3
// slot-based AlertDialog that adds a 1dp outline around the whole popup box - matching the
// outline that Modifier.outlinedMenuCard() (MenuStyle.kt) puts on the app's menus. Signature
// mirrors androidx.compose.material3.AlertDialog exactly (compose-bom 2024.02.00 → material3
// 1.2.0), so every call site can swap AlertDialog( → OutlinedAlertDialog( unchanged. The
// border shares the dialog's shape so its corner radius follows the rounded dialog.
@Composable
internal fun OutlinedAlertDialog(
onDismissRequest: () -> Unit,
@@ -6,21 +6,11 @@ import java.io.File
import java.io.RandomAccessFile
import kotlin.math.max
/**
* Extracts the embedded application icon from a Windows PE executable (.exe).
*
* Walks the PE resource directory to the first RT_GROUP_ICON, picks the largest /
* deepest-colour entry it references, then decodes that RT_ICON image. Icon images
* are either PNG (Vista+) - decoded directly - or a classic DIB (BITMAPINFOHEADER +
* XOR pixels + 1-bpp AND mask) - decoded by hand here.
*
* Everything is best-effort: any malformed/oversized/unsupported input returns null.
*/
object PeIconExtractor {
private const val RT_ICON = 3
private const val RT_GROUP_ICON = 14
private const val MAX_RES_SECTION = 64 * 1024 * 1024 // don't slurp absurd resource sections
private const val MAX_RES_SECTION = 64 * 1024 * 1024
private const val MAX_ICON_DIM = 1024
fun extract(file: File): Bitmap? = try {
@@ -31,11 +21,11 @@ object PeIconExtractor {
private fun parse(raf: RandomAccessFile): Bitmap? {
val dos = read(raf, 0, 0x40) ?: return null
if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null // "MZ"
if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null
val peOff = u32(dos, 0x3C).toInt()
val coff = read(raf, peOff.toLong(), 24) ?: return null
if (u8(coff, 0) != 0x50 || u8(coff, 1) != 0x45 || u8(coff, 2) != 0 || u8(coff, 3) != 0) return null // "PE\0\0"
if (u8(coff, 0) != 0x50 || u8(coff, 1) != 0x45 || u8(coff, 2) != 0 || u8(coff, 3) != 0) return null
val numSections = u16(coff, 6)
val sizeOpt = u16(coff, 20)
if (numSections <= 0 || numSections > 96 || sizeOpt <= 0) return null
@@ -43,8 +33,8 @@ object PeIconExtractor {
val optOff = peOff + 24L
val opt = read(raf, optOff, sizeOpt) ?: return null
val magic = u16(opt, 0)
val ddOff = if (magic == 0x20B) 112 else 96 // PE32+ vs PE32 data-directory offset
val resDirEntry = ddOff + 2 * 8 // data directory index 2 = resource table
val ddOff = if (magic == 0x20B) 112 else 96
val resDirEntry = ddOff + 2 * 8
if (resDirEntry + 8 > opt.size) return null
val resRVA = u32(opt, resDirEntry).toInt()
val resSize = u32(opt, resDirEntry + 4).toInt()
@@ -75,7 +65,6 @@ object PeIconExtractor {
val resDirStart = resRVA - secVA
if (resDirStart < 0 || resDirStart + 16 > res.size) return null
// RT_GROUP_ICON -> first group's data entry -> GRPICONDIR
val grpTypeDir = findIdSubdir(res, resDirStart, RT_GROUP_ICON, resDirStart) ?: return null
val grpData = firstDataEntry(res, grpTypeDir, resDirStart) ?: return null
val grp = dataEntryBytes(res, grpData, secVA) ?: return null
@@ -97,7 +86,6 @@ object PeIconExtractor {
}
if (bestId < 0) return null
// RT_ICON with the chosen id -> image bytes
val iconTypeDir = findIdSubdir(res, resDirStart, RT_ICON, resDirStart) ?: return null
val iconIdDir = findIdSubdir(res, iconTypeDir, bestId, resDirStart) ?: return null
val iconData = firstDataEntry(res, iconIdDir, resDirStart) ?: return null
@@ -106,9 +94,7 @@ object PeIconExtractor {
return decodeIcon(img)
}
// ── resource-directory navigation ──
/** Resolve the sub-directory under [dirIdx] whose id matches [wantId]; null if absent or not a directory. */
private fun findIdSubdir(res: ByteArray, dirIdx: Int, wantId: Int, resDirStart: Int): Int? {
if (dirIdx + 16 > res.size) return null
val total = u16(res, dirIdx + 12) + u16(res, dirIdx + 14)
@@ -126,7 +112,6 @@ object PeIconExtractor {
return null
}
/** Descend the first entry of each level until an IMAGE_RESOURCE_DATA_ENTRY; returns its index. */
private fun firstDataEntry(res: ByteArray, dirIdx: Int, resDirStart: Int): Int? {
if (dirIdx + 16 > res.size) return null
if (u16(res, dirIdx + 12) + u16(res, dirIdx + 14) == 0) return null
@@ -140,7 +125,6 @@ object PeIconExtractor {
}
}
/** Read the bytes an IMAGE_RESOURCE_DATA_ENTRY points at (its OffsetToData is an RVA). */
private fun dataEntryBytes(res: ByteArray, entryIdx: Int, secVA: Int): ByteArray? {
if (entryIdx < 0 || entryIdx + 8 > res.size) return null
val rva = u32(res, entryIdx).toInt()
@@ -150,7 +134,6 @@ object PeIconExtractor {
return res.copyOfRange(start, start + size)
}
// ── icon image decoding ──
private fun decodeIcon(b: ByteArray): Bitmap? {
if (b.size >= 8 && u8(b, 0) == 0x89 && u8(b, 1) == 0x50 && u8(b, 2) == 0x4E && u8(b, 3) == 0x47) {
@@ -164,7 +147,7 @@ object PeIconExtractor {
val headerSize = u32(b, 0).toInt()
val width = s32(b, 4)
val heightFull = s32(b, 8)
val height = heightFull / 2 // DIB icon height counts XOR + AND mask
val height = heightFull / 2
val bitCount = u16(b, 14)
if (width <= 0 || height <= 0 || width > MAX_ICON_DIM || height > MAX_ICON_DIM) return null
@@ -183,7 +166,6 @@ object PeIconExtractor {
val andRowSize = ((width + 31) / 32) * 4
val andStart = xorStart + rowSize * height
// 32-bit icons sometimes ship an all-zero alpha channel; fall back to the AND mask then.
var hasAlpha = false
if (bitCount == 32) {
var y = 0
@@ -245,7 +227,6 @@ object PeIconExtractor {
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
}
/** AND-mask alpha for a pixel: returns 0xFF000000 (opaque) or 0 (transparent), shifted into place. */
private fun maskAlpha(b: ByteArray, andStart: Int, andRowSize: Int, srcRow: Int, x: Int): Int {
val o = andStart + srcRow * andRowSize + x / 8
if (o >= b.size) return 0xFF shl 24
@@ -253,7 +234,6 @@ object PeIconExtractor {
return if (bit == 1) 0 else (0xFF shl 24)
}
// ── little-endian readers ──
private fun u8(b: ByteArray, off: Int): Int = b[off].toInt() and 0xFF
private fun u16(b: ByteArray, off: Int): Int = u8(b, off) or (u8(b, off + 1) shl 8)
@@ -8,52 +8,24 @@ import android.os.storage.StorageVolume
import com.droiddeck.launcher.R
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>()
}
@@ -62,7 +34,6 @@ object StorageRoots {
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 = context.getString(R.string.fm_drive_internal)
removable = false
@@ -72,7 +43,6 @@ object StorageRoots {
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 ->
@@ -86,14 +56,11 @@ object StorageRoots {
}
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
@@ -102,7 +69,6 @@ object StorageRoots {
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)
@@ -117,11 +83,9 @@ object StorageRoots {
}
private fun Volume.toRoot(context: Context): 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")
@@ -135,7 +99,6 @@ object StorageRoots {
private fun Volume.defaultLabel(context: Context): String = if (removable) context.getString(R.string.fm_drive_sd) 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 ->
@@ -143,7 +106,6 @@ object StorageRoots {
}
}
/** 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
@@ -154,7 +116,6 @@ object StorageRoots {
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) }
@@ -178,11 +139,6 @@ object StorageRoots {
}
}
/**
* 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 context.getString(R.string.fm_drive_internal)
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)