Bannerlator's File Manager, a cog per launch mode with HDR10, leftover-process sweep, the drawer's Steam menu

The file picker is now Bannerlator's File Manager itself (files/FileManagerScreen.kt, carried over
whole with its rail, favourites, grid/list, copy/cut/paste, rename, delete, properties) minus what
has no meaning without a Wine container: run, add to shortcuts, C:/Z: drives, the archive
unpacker. StorageRoots, CollapsibleRail, FavoritesStore, PeIconExtractor, OutlinedAlertDialog and
MenuStyle come with it unchanged; FileOps carries the progress copy/move. A Files tile opens it;
its pick mode chooses the ROMs folder and imports drivers.

Play and Desktop each get a cog: resolution cap (1080p default, 900p, 720p, panel), shape, HDR10,
the mode's Linux runtime driver, the display driver, touch, and per mode the on-screen controls +
audio (Steam) or the renderer (desktop). The Graphics drivers and Audio tiles are gone into them.

HDR10: HdrSupport reads the panel's HDR types; the switch is greyed with the reason unless HDR10 is
listed. On, the activity feeds the compositor's gate (nativeSetHdrDisplay + nativeSetHdrRequest),
turns zero-copy on, sets BANNER_WAYLAND_HDR=1, and the session gets BL_HDR=1 (gamescope
--hdr-enabled) and DXVK_HDR=1.

OrphanReaper kills every process of our uid but the app at session start and on an app crash: a
tree left by a killed app held the rootfs, the GPU and Steam's lock, and the next session never
came up (Thor Pro report). The drawer gains Steam menu, which sends the Guide button.
This commit is contained in:
The412Banner committed 2026-09-21 23:03:57 -04:00
1 parent cb5a1b5a31
commit 9ad922348b
28 files changed
+3754 -566

No files matched your search

@@ -0,0 +1,449 @@
package com.steamdeck.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
val prefs = remember { androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) }
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.steamdeck.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.steamdeck.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.steamdeck.launcher.ui.SteamDeckTheme
/** 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 {
SteamDeckTheme {
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.steamdeck.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)
}
}
@@ -8,6 +8,7 @@ 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
@@ -15,7 +16,7 @@ import com.steamdeck.launcher.ui.SteamDeckTheme
import java.io.File
/**
* Themed host for [FilePickerScreen]. Launched through [InAppFilePicker] and answers with the
* Themed host for [FileManagerScreen] in pick mode. Launched through [InAppFilePicker] and answers with the
* picked path in [EXTRA_SELECTED_FILE] on RESULT_OK.
*
* Extras:
@@ -36,25 +37,24 @@ 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)
val prefs = getSharedPreferences("picker", MODE_PRIVATE)
val initialDir = (intent.getStringExtra(EXTRA_INITIAL_DIRECTORY) ?: prefs.getString("lastDir", null))
// 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 {
SteamDeckTheme {
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
FilePickerScreen(
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
FileManagerScreen(
pickMode = true,
pickDirMode = pickDir,
pickExtensions = extensions,
initialDir = initialDir,
title = title ?: if (pickDir) "Choose a folder" else "Choose a file",
pickerTitle = title ?: if (pickDir) "Choose a folder" else "Choose a file",
onPick = { file ->
val remembered = if (file.isDirectory) file else file.parentFile
remembered?.let { prefs.edit().putString("lastDir", it.absolutePath).apply() }
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
finish()
},
onCancel = { setResult(Activity.RESULT_CANCELED); finish() },
)
}
}
@@ -1,283 +0,0 @@
package com.steamdeck.launcher.files
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.steamdeck.launcher.core.FileUtils
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* The file picker, as Bannerlator's File Manager behaves in pick mode: a drive menu with every
* mounted volume ([StorageRoots]), the path with an up-arrow that stops at the drive's root so
* nobody is trapped in a subfolder, folders first, and either a tap on a matching file or "Use
* this folder". Nothing here edits, runs or copies anything; that is a file manager's job and
* this app does not have one.
*/
@Composable
fun FilePickerScreen(
pickDirMode: Boolean,
pickExtensions: List<String>,
initialDir: File?,
title: String,
onPick: (File) -> Unit,
onCancel: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val lowerExts = remember(pickExtensions) { pickExtensions.map { it.lowercase() } }
val start = remember { initialDir?.takeIf { it.isDirectory } ?: File(INTERNAL) }
var currentDir by remember { mutableStateOf(start) }
// The floor for up/back: the volume the folder is on, never the folder itself.
var currentRoot by remember { mutableStateOf(volumeRootOf(start)) }
var entries by remember { mutableStateOf<List<File>?>(null) }
var storageTick by remember { mutableStateOf(0) }
val drives = remember(storageTick) { StorageRoots.list(context) }
var showDrives by remember { mutableStateOf(false) }
fun matches(file: File): Boolean {
if (file.isDirectory) return true
if (pickDirMode) return false
if (lowerExts.isEmpty()) return true
val name = file.name.lowercase()
return lowerExts.any { name.endsWith(".$it") }
}
fun reload() {
entries = currentDir.listFiles()
?.filter { !it.name.startsWith(".") && matches(it) }
?.sortedWith(compareBy<File> { !it.isDirectory }.thenBy { it.name.lowercase() })
}
fun open(dir: File) {
currentDir = dir
reload()
}
fun openDrive(root: File) {
currentRoot = root
open(root)
}
fun goUp() {
val parent = currentDir.parentFile ?: return
if (currentDir.absolutePath == currentRoot.absolutePath) return
open(parent)
}
val atRoot = currentDir.absolutePath == currentRoot.absolutePath
LaunchedEffect(Unit) { reload() }
BackHandler { if (atRoot) onCancel() else goUp() }
Column(modifier = Modifier.fillMaxSize().systemBarsPadding()) {
// Header: back, title, drive menu, refresh.
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 4.dp, end = 4.dp, top = 4.dp),
) {
IconButton(onClick = onCancel) { Icon(Icons.Filled.ArrowBack, contentDescription = "Cancel") }
Text(
title, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
Box {
val driveLabel = drives.firstOrNull { currentRoot.absolutePath == it.dir.absolutePath }?.label
?: currentRoot.name.ifEmpty { "/" }
OutlinedButton(onClick = { showDrives = true }) {
Text(driveLabel, fontSize = 12.sp, maxLines = 1)
Icon(Icons.Filled.ArrowDropDown, contentDescription = null, modifier = Modifier.size(18.dp))
}
DropdownMenu(expanded = showDrives, onDismissRequest = { showDrives = false }) {
drives.forEach { drive ->
DropdownMenuItem(
text = {
Column {
Text(drive.label + if (drive.removable) " · SD" else "")
Text(
if (drive.readable) drive.dir.absolutePath else "mounted, not readable right now",
fontSize = 11.sp, color = colors.onSurfaceVariant,
)
}
},
enabled = drive.readable,
onClick = { showDrives = false; openDrive(drive.dir) },
)
}
}
}
IconButton(onClick = { storageTick++; reload() }) {
Icon(Icons.Filled.Refresh, contentDescription = "Refresh")
}
}
// The path, with up.
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),
) {
IconButton(onClick = { goUp() }, enabled = !atRoot) {
Icon(Icons.Filled.KeyboardArrowUp, contentDescription = "Up")
}
Text(
elideStart(currentDir.absolutePath, 60), fontSize = 12.sp, color = colors.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
HorizontalDivider(color = colors.surfaceVariant)
val list = entries
when {
list == null -> Message(
if (currentDir.canRead()) "Nothing to list here" else "Not readable — allow storage access for SteamDeck and try again",
Modifier.weight(1f),
)
list.isEmpty() -> Message(
when {
pickDirMode -> "No folders here — use this one, or go up"
lowerExts.isNotEmpty() -> "No ${lowerExts.joinToString(" / ") { ".$it" }} files here"
else -> "Empty folder"
},
Modifier.weight(1f),
)
else -> LazyColumn(modifier = Modifier.weight(1f).fillMaxWidth()) {
items(list, key = { it.absolutePath }) { file ->
EntryRow(file) { if (file.isDirectory) open(file) else onPick(file) }
}
}
}
if (pickDirMode) {
HorizontalDivider(color = colors.surfaceVariant)
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().padding(12.dp),
) {
OutlinedButton(onClick = onCancel, modifier = Modifier.weight(1f)) { Text("Cancel") }
Button(onClick = { onPick(currentDir) }, modifier = Modifier.weight(2f)) {
Text("Use this folder", maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
}
@Composable
private fun Message(text: String, modifier: Modifier) {
Box(modifier = modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
Text(text, color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 13.sp)
}
}
@Composable
private fun EntryRow(file: File, onTap: () -> Unit) {
val colors = MaterialTheme.colorScheme
val isDir = file.isDirectory
val detail = remember(file.absolutePath) {
val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(file.lastModified()))
if (isDir) stamp else "${FileUtils.sizeToString(file.length())} · $stamp"
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().clickable(onClick = onTap).padding(horizontal = 16.dp, vertical = 9.dp),
) {
Glyph(isDir, if (isDir) colors.primary else colors.onSurfaceVariant)
Spacer(Modifier.width(14.dp))
Column(modifier = Modifier.weight(1f)) {
Text(file.name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
HorizontalDivider(color = colors.surfaceVariant, modifier = Modifier.padding(start = 56.dp))
}
/** A folder or a page, drawn: the app ships no icon set beyond the few in Material's core. */
@Composable
private fun Glyph(folder: Boolean, tint: Color) {
Canvas(modifier = Modifier.size(26.dp)) {
val w = size.width
val h = size.height
if (folder) {
// Tab, then body.
drawRoundRect(tint, Offset(0f, h * 0.18f), Size(w * 0.42f, h * 0.2f), CornerRadius(w * 0.06f))
drawRoundRect(tint, Offset(0f, h * 0.28f), Size(w, h * 0.58f), CornerRadius(w * 0.08f))
} else {
val left = w * 0.15f
val top = h * 0.06f
drawRoundRect(
tint, Offset(left, top), Size(w * 0.7f, h * 0.88f), CornerRadius(w * 0.06f),
style = Stroke(width = w * 0.07f),
)
// Three lines of "text".
for (i in 0..2) {
val y = h * (0.38f + 0.17f * i)
drawLine(tint, Offset(w * 0.3f, y), Offset(w * 0.7f, y), strokeWidth = w * 0.06f)
}
}
}
}
private const val INTERNAL = "/storage/emulated/0"
/** `/storage/emulated/0/Download/x` -> `/storage/emulated/0`; `/storage/ABCD-1234/y` -> the card. */
private fun volumeRootOf(dir: File): File {
val abs = dir.absolutePath
return when {
abs == INTERNAL || abs.startsWith("$INTERNAL/") -> File(INTERNAL)
abs.startsWith("/storage/") -> {
val name = abs.removePrefix("/storage/").substringBefore('/')
if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else dir
}
else -> dir
}
}
private fun elideStart(path: String, max: Int): String =
if (path.length <= max) path else "…" + path.takeLast(max - 1)
@@ -0,0 +1,30 @@
package com.steamdeck.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.steamdeck.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.steamdeck.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
}
}