mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 14:26:00 +00:00
Rename the app SteamDeck → DroidDeck
App name, app ID and code package: DroidDeck, com.droiddeck.launcher (sources moved to com/droiddeck/launcher, the 68 JNI functions renamed with them). The new app ID installs beside SteamDeck rather than over it. Everywhere the name was the app's own: the sidebar title, the session report, share zips, the shell title, wake-lock and log tags, User-Agents, the Compose theme, the Download folder and switch files (droiddeck-env, -osc, -driver, -tu-debug, -no-pad, -pad-log, -no-hud, -wlr-renderer; the old names are not read), and inside the runtime (droiddeck-desktop, Firefox's droiddeck.js, the shortcuts tag, the rumble socket, debug and cache paths). Build scripts, CI artifact (droiddeck-apk), CMake project, README and the progress log follow. Kept on purpose: Valve's Steam Deck (the -steamdeck flag, steamdeck_publicbeta/stable, 'Steam Deck mode', the steamos.cloud package URLs) and names inside the hosted desktop package (steamdeck.png, steamdeck-steam, steamdeck-bigpicture). 'Desktop installed' now tests for labwc instead of the launcher the app stages itself. A committed __pycache__ .pyc is removed.
This commit is contained in:
1 parent
bd51571530
commit
ae6dcc9798
118 files changed
+498
-487
No files matched your search
@@ -0,0 +1,450 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
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.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Badge
|
||||
import androidx.compose.material3.BadgedBox
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.annotation.DrawableRes
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/** 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,
|
||||
// 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
|
||||
"WIN COMPONENTS" -> return "WIN COMP"
|
||||
"Downloads" -> return "Downlds"
|
||||
}
|
||||
if (label.contains(' ')) return label // multi-word → wraps to 2 lines
|
||||
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) {
|
||||
BadgedBox(
|
||||
badge = {
|
||||
Badge(
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary,
|
||||
) { Text(if (item.badge > 9) "9+" else item.badge.toString(), fontSize = 8.sp) }
|
||||
},
|
||||
) {
|
||||
Icon(item.icon, contentDescription = item.label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
} else {
|
||||
Icon(item.icon, contentDescription = item.label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** 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,
|
||||
)
|
||||
|
||||
@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)
|
||||
}
|
||||
|
||||
if (!isLandscape) {
|
||||
return RailState(collapsed = true, portraitLocked = true, onToggle = {})
|
||||
}
|
||||
return RailState(
|
||||
collapsed = landscapeCollapsed,
|
||||
portraitLocked = false,
|
||||
onToggle = {
|
||||
landscapeCollapsed = !landscapeCollapsed
|
||||
userChose = true
|
||||
prefs.edit()
|
||||
.putBoolean(choseKey, true)
|
||||
.putBoolean(collapsedKey, landscapeCollapsed)
|
||||
.apply()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
title: String,
|
||||
sections: List<RailSection>,
|
||||
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
|
||||
val width by animateDpAsState(if (collapsed) 58.dp else 190.dp, label = "railWidth")
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.width(width)
|
||||
.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,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = if (collapsed) 0.dp else 10.dp, vertical = 8.dp)
|
||||
) {
|
||||
if (headerIcon != null) {
|
||||
Icon(
|
||||
painter = painterResource(headerIcon),
|
||||
contentDescription = title,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(22.dp)
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(MaterialTheme.colorScheme.primary)
|
||||
)
|
||||
}
|
||||
if (!collapsed) {
|
||||
Spacer(Modifier.width(9.dp))
|
||||
Text(
|
||||
title,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (!state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) {
|
||||
Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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)) {
|
||||
links.forEach { link ->
|
||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) {
|
||||
Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
links.forEach { link ->
|
||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) {
|
||||
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(link.label, fontSize = 11.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
.verticalScroll(rememberScrollState())
|
||||
) {
|
||||
sections.forEach { section ->
|
||||
if (!collapsed && section.header != null) {
|
||||
Text(
|
||||
section.header,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
|
||||
fontSize = 9.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.6.sp,
|
||||
modifier = Modifier.padding(start = 14.dp, top = 10.dp, bottom = 2.dp),
|
||||
)
|
||||
} else if (collapsed && section.header != null && section != sections.first()) {
|
||||
HorizontalDivider(
|
||||
color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f),
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
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) {
|
||||
base
|
||||
.padding(horizontal = 6.dp, vertical = 3.dp)
|
||||
.clip(shape)
|
||||
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.16f) else MaterialTheme.colorScheme.surface.copy(alpha = 0.4f))
|
||||
.border(
|
||||
1.dp,
|
||||
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
|
||||
shape,
|
||||
)
|
||||
.clickable(onClick = item.onClick)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
|
||||
} else {
|
||||
base
|
||||
.clickable(onClick = item.onClick)
|
||||
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
|
||||
}
|
||||
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,
|
||||
) {
|
||||
RailItemIcon(item, iconTint)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
collapsedLabel(item.label),
|
||||
color = labelColor,
|
||||
fontSize = 7.5.sp,
|
||||
lineHeight = 8.5.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
textAlign = TextAlign.Center,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
modifier = styled,
|
||||
) {
|
||||
RailItemIcon(item, iconTint)
|
||||
Spacer(Modifier.width(11.dp))
|
||||
Text(
|
||||
item.label,
|
||||
color = labelColor,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.3.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>,
|
||||
modifier: Modifier = Modifier,
|
||||
links: List<RailLink> = emptyList(),
|
||||
) {
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
items.forEach { item ->
|
||||
TopTabCell(
|
||||
icon = item.icon,
|
||||
label = item.label,
|
||||
selected = item.selected,
|
||||
onClick = item.onClick,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
if (links.isNotEmpty()) {
|
||||
// Faint separator: everything past here is an action button, not a tab.
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 2.dp)
|
||||
.width(1.dp)
|
||||
.height(30.dp)
|
||||
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
|
||||
)
|
||||
links.forEach { link ->
|
||||
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
|
||||
/** 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,
|
||||
label: String,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(vertical = 6.dp, horizontal = 1.dp),
|
||||
) {
|
||||
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
label,
|
||||
color = tint,
|
||||
fontSize = 8.5.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.2.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.height(2.dp)
|
||||
.width(if (selected) 16.dp else 0.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
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"
|
||||
private const val KEY = "file_manager_favorites"
|
||||
|
||||
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 {
|
||||
val arr = JSONArray(raw)
|
||||
buildList { for (i in 0 until arr.length()) add(arr.getString(i)) }
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
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
|
||||
save(context, current + path)
|
||||
}
|
||||
|
||||
fun remove(context: Context, path: String) {
|
||||
val current = list(context)
|
||||
if (!current.contains(path)) return
|
||||
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
|
||||
} else {
|
||||
add(context, path); true
|
||||
}
|
||||
|
||||
private fun save(context: Context, paths: List<String>) {
|
||||
val arr = JSONArray()
|
||||
paths.forEach { arr.put(it) }
|
||||
prefs(context).edit().putString(KEY, arr.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.Manifest
|
||||
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.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
|
||||
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
|
||||
class FileManagerActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
||||
FileManagerScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,130 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
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(bytes: Long): String {
|
||||
if (bytes <= 0) return "0 bytes"
|
||||
val units = arrayOf("bytes", "KB", "MB", "GB", "TB")
|
||||
val group = (Math.log10(bytes.toDouble()) / Math.log10(1024.0)).toInt().coerceIn(0, units.lastIndex)
|
||||
return String.format(Locale.ENGLISH, "%.2f", bytes / Math.pow(1024.0, group.toDouble())) + " " + units[group]
|
||||
}
|
||||
|
||||
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)) {
|
||||
if (!clear(target)) return false
|
||||
}
|
||||
return target.delete()
|
||||
}
|
||||
|
||||
fun clear(dir: File): Boolean {
|
||||
val children = dir.listFiles() ?: return true
|
||||
var ok = true
|
||||
for (child in children) if (!delete(child)) ok = false
|
||||
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)) {
|
||||
progress?.onProgress(1, 1)
|
||||
return true
|
||||
}
|
||||
if (!copyWithProgress(src, dst, progress)) return false
|
||||
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)
|
||||
}
|
||||
|
||||
private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?): Boolean {
|
||||
if (isSymlink(src)) return true
|
||||
if (sameFile(src, dst)) return true
|
||||
if (src.isDirectory && isWithin(dst, src)) {
|
||||
Log.e(TAG, "Refusing to copy directory into itself: $src -> $dst")
|
||||
return false
|
||||
}
|
||||
if (src.isDirectory) {
|
||||
if (!dst.exists() && !dst.mkdirs()) return false
|
||||
var allOk = true
|
||||
src.list()?.forEach { name ->
|
||||
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress)) {
|
||||
Log.e(TAG, "Failed to copy: ${File(src, name)}")
|
||||
allOk = false
|
||||
}
|
||||
}
|
||||
return allOk
|
||||
}
|
||||
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
|
||||
try {
|
||||
FileInputStream(src).channel.use { input ->
|
||||
FileOutputStream(dst).channel.use { output ->
|
||||
val size = input.size()
|
||||
var position = 0L
|
||||
while (position < size) {
|
||||
val transferred = input.transferTo(position, minOf(chunk, size - position), output)
|
||||
if (transferred <= 0) break
|
||||
position += transferred
|
||||
done[0] += transferred
|
||||
progress?.onProgress(done[0], total)
|
||||
}
|
||||
if (position < size) throw IOException("Incomplete copy: $position/$size bytes")
|
||||
}
|
||||
}
|
||||
return true
|
||||
} catch (e: IOException) {
|
||||
Log.e(TAG, "Failed to copy file: $src to $dst", e)
|
||||
dst.delete()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
return c == a || c.startsWith(a + File.separator)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.droiddeck.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.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.ui.Modifier
|
||||
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 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)
|
||||
// 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 }
|
||||
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
||||
FileManagerScreen(
|
||||
pickMode = true,
|
||||
pickDirMode = pickDir,
|
||||
pickExtensions = extensions,
|
||||
initialDir = initialDir,
|
||||
pickerTitle = title ?: if (pickDir) "Choose a folder" else "Choose a file",
|
||||
onPick = { file ->
|
||||
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
|
||||
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,44 @@
|
||||
package com.droiddeck.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,30 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
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
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
return this
|
||||
.clip(shape)
|
||||
.background(cs.surfaceContainer)
|
||||
.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))
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
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,
|
||||
confirmButton: @Composable () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
dismissButton: (@Composable () -> Unit)? = null,
|
||||
icon: (@Composable () -> Unit)? = null,
|
||||
title: (@Composable () -> Unit)? = null,
|
||||
text: (@Composable () -> Unit)? = null,
|
||||
shape: Shape = AlertDialogDefaults.shape,
|
||||
containerColor: Color = AlertDialogDefaults.containerColor,
|
||||
iconContentColor: Color = AlertDialogDefaults.iconContentColor,
|
||||
titleContentColor: Color = AlertDialogDefaults.titleContentColor,
|
||||
textContentColor: Color = AlertDialogDefaults.textContentColor,
|
||||
tonalElevation: Dp = AlertDialogDefaults.TonalElevation,
|
||||
properties: DialogProperties = DialogProperties()
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismissRequest,
|
||||
confirmButton = confirmButton,
|
||||
modifier = modifier.border(1.dp, MaterialTheme.colorScheme.outline, shape),
|
||||
dismissButton = dismissButton,
|
||||
icon = icon,
|
||||
title = title,
|
||||
text = text,
|
||||
shape = shape,
|
||||
containerColor = containerColor,
|
||||
iconContentColor = iconContentColor,
|
||||
titleContentColor = titleContentColor,
|
||||
textContentColor = textContentColor,
|
||||
tonalElevation = tonalElevation,
|
||||
properties = properties
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
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_ICON_DIM = 1024
|
||||
|
||||
fun extract(file: File): Bitmap? = try {
|
||||
RandomAccessFile(file, "r").use { parse(it) }
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
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"
|
||||
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"
|
||||
val numSections = u16(coff, 6)
|
||||
val sizeOpt = u16(coff, 20)
|
||||
if (numSections <= 0 || numSections > 96 || sizeOpt <= 0) return null
|
||||
|
||||
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
|
||||
if (resDirEntry + 8 > opt.size) return null
|
||||
val resRVA = u32(opt, resDirEntry).toInt()
|
||||
val resSize = u32(opt, resDirEntry + 4).toInt()
|
||||
if (resRVA == 0 || resSize == 0) return null
|
||||
|
||||
val secTabOff = optOff + sizeOpt
|
||||
val secTab = read(raf, secTabOff, numSections * 40) ?: return null
|
||||
|
||||
var secVA = 0
|
||||
var secPtr = 0L
|
||||
var secRaw = 0
|
||||
var found = false
|
||||
for (i in 0 until numSections) {
|
||||
val o = i * 40
|
||||
if (o + 40 > secTab.size) break
|
||||
val va = u32(secTab, o + 12).toInt()
|
||||
val vSize = u32(secTab, o + 8).toInt()
|
||||
val raw = u32(secTab, o + 16).toInt()
|
||||
val pRaw = u32(secTab, o + 20)
|
||||
val span = max(vSize, raw)
|
||||
if (resRVA >= va && resRVA < va + span) {
|
||||
secVA = va; secPtr = pRaw; secRaw = raw; found = true; break
|
||||
}
|
||||
}
|
||||
if (!found || secRaw <= 0 || secRaw > MAX_RES_SECTION) return null
|
||||
|
||||
val res = read(raf, secPtr, secRaw) ?: return null
|
||||
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
|
||||
if (grp.size < 6) return null
|
||||
|
||||
val count = u16(grp, 4)
|
||||
if (count <= 0) return null
|
||||
var bestId = -1
|
||||
var bestScore = -1L
|
||||
for (i in 0 until count) {
|
||||
val e = 6 + i * 14
|
||||
if (e + 14 > grp.size) break
|
||||
var w = u8(grp, e); if (w == 0) w = 256
|
||||
var h = u8(grp, e + 1); if (h == 0) h = 256
|
||||
val bits = u16(grp, e + 6)
|
||||
val id = u16(grp, e + 12)
|
||||
val score = w.toLong() * h * 1000 + bits
|
||||
if (score > bestScore) { bestScore = score; bestId = id }
|
||||
}
|
||||
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
|
||||
val img = dataEntryBytes(res, iconData, secVA) ?: return null
|
||||
|
||||
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)
|
||||
val start = dirIdx + 16
|
||||
for (i in 0 until total) {
|
||||
val e = start + i * 8
|
||||
if (e + 8 > res.size) break
|
||||
val id = u32(res, e)
|
||||
val off = u32(res, e + 4)
|
||||
if (id and 0x80000000L == 0L && id.toInt() == wantId) {
|
||||
if (off and 0x80000000L != 0L) return resDirStart + (off and 0x7FFFFFFFL).toInt()
|
||||
return null
|
||||
}
|
||||
}
|
||||
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
|
||||
val e = dirIdx + 16
|
||||
if (e + 8 > res.size) return null
|
||||
val off = u32(res, e + 4)
|
||||
return if (off and 0x80000000L != 0L) {
|
||||
firstDataEntry(res, resDirStart + (off and 0x7FFFFFFFL).toInt(), resDirStart)
|
||||
} else {
|
||||
resDirStart + off.toInt()
|
||||
}
|
||||
}
|
||||
|
||||
/** 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()
|
||||
val size = u32(res, entryIdx + 4).toInt()
|
||||
val start = rva - secVA
|
||||
if (size <= 0 || start < 0 || start + size > res.size) return null
|
||||
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) {
|
||||
return runCatching { BitmapFactory.decodeByteArray(b, 0, b.size) }.getOrNull()
|
||||
}
|
||||
return runCatching { decodeDib(b) }.getOrNull()
|
||||
}
|
||||
|
||||
private fun decodeDib(b: ByteArray): Bitmap? {
|
||||
if (b.size < 40) return null
|
||||
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 bitCount = u16(b, 14)
|
||||
if (width <= 0 || height <= 0 || width > MAX_ICON_DIM || height > MAX_ICON_DIM) return null
|
||||
|
||||
val clrUsed = u32(b, 32).toInt()
|
||||
val numColors = if (bitCount <= 8) (if (clrUsed != 0) clrUsed else 1 shl bitCount) else 0
|
||||
val paletteOff = headerSize
|
||||
val palette = IntArray(numColors)
|
||||
for (i in 0 until numColors) {
|
||||
val o = paletteOff + i * 4
|
||||
if (o + 4 > b.size) break
|
||||
palette[i] = (0xFF shl 24) or (u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o)
|
||||
}
|
||||
|
||||
val xorStart = paletteOff + numColors * 4
|
||||
val rowSize = ((bitCount * width + 31) / 32) * 4
|
||||
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
|
||||
loop@ while (y < height && !hasAlpha) {
|
||||
var x = 0
|
||||
while (x < width) {
|
||||
val o = xorStart + y * rowSize + x * 4 + 3
|
||||
if (o < b.size && b[o].toInt() != 0) { hasAlpha = true; break@loop }
|
||||
x++
|
||||
}
|
||||
y++
|
||||
}
|
||||
}
|
||||
|
||||
val pixels = IntArray(width * height)
|
||||
for (y in 0 until height) {
|
||||
val srcRow = height - 1 - y
|
||||
for (x in 0 until width) {
|
||||
val argb: Int = when (bitCount) {
|
||||
32 -> {
|
||||
val o = xorStart + srcRow * rowSize + x * 4
|
||||
if (o + 4 > b.size) 0 else {
|
||||
val color = (u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o)
|
||||
if (hasAlpha) (u8(b, o + 3) shl 24) or color
|
||||
else maskAlpha(b, andStart, andRowSize, srcRow, x) or color
|
||||
}
|
||||
}
|
||||
24 -> {
|
||||
val o = xorStart + srcRow * rowSize + x * 3
|
||||
if (o + 3 > b.size) 0 else
|
||||
maskAlpha(b, andStart, andRowSize, srcRow, x) or
|
||||
(u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o)
|
||||
}
|
||||
8 -> {
|
||||
val o = xorStart + srcRow * rowSize + x
|
||||
val idx = if (o < b.size) u8(b, o) else 0
|
||||
val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF
|
||||
maskAlpha(b, andStart, andRowSize, srcRow, x) or col
|
||||
}
|
||||
4 -> {
|
||||
val o = xorStart + srcRow * rowSize + x / 2
|
||||
val byte = if (o < b.size) u8(b, o) else 0
|
||||
val idx = if (x % 2 == 0) byte shr 4 else byte and 0x0F
|
||||
val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF
|
||||
maskAlpha(b, andStart, andRowSize, srcRow, x) or col
|
||||
}
|
||||
1 -> {
|
||||
val o = xorStart + srcRow * rowSize + x / 8
|
||||
val byte = if (o < b.size) u8(b, o) else 0
|
||||
val idx = (byte shr (7 - x % 8)) and 1
|
||||
val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF
|
||||
maskAlpha(b, andStart, andRowSize, srcRow, x) or col
|
||||
}
|
||||
else -> return null
|
||||
}
|
||||
pixels[y * width + x] = argb
|
||||
}
|
||||
}
|
||||
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
|
||||
val bit = (b[o].toInt() shr (7 - x % 8)) and 1
|
||||
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)
|
||||
private fun u32(b: ByteArray, off: Int): Long =
|
||||
u8(b, off).toLong() or (u8(b, off + 1).toLong() shl 8) or
|
||||
(u8(b, off + 2).toLong() shl 16) or (u8(b, off + 3).toLong() shl 24)
|
||||
|
||||
private fun s32(b: ByteArray, off: Int): Int = u32(b, off).toInt()
|
||||
|
||||
private fun read(raf: RandomAccessFile, pos: Long, len: Int): ByteArray? {
|
||||
if (len <= 0 || pos < 0) return null
|
||||
val fileLen = raf.length()
|
||||
if (pos >= fileLen) return null
|
||||
val n = minOf(len.toLong(), fileLen - pos).toInt()
|
||||
if (n <= 0) return null
|
||||
val buf = ByteArray(n)
|
||||
raf.seek(pos)
|
||||
raf.readFully(buf)
|
||||
return buf
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package com.droiddeck.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