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

@@ -34,10 +34,11 @@ import com.steamdeck.launcher.session.SessionPrefs
import com.steamdeck.launcher.ui.ProtonDialog
import com.steamdeck.launcher.ui.ProtonRow
import com.steamdeck.launcher.core.CpuCores
import com.steamdeck.launcher.ui.AudioDialog
import com.steamdeck.launcher.ui.CoreRow
import com.steamdeck.launcher.ui.PerformanceDialog
import com.steamdeck.launcher.ui.DriverDialog
import com.steamdeck.launcher.ui.ModeSettingsDialog
import com.steamdeck.launcher.ui.ModeSettings
import com.steamdeck.launcher.ui.ModeSettingsActions
import com.steamdeck.launcher.ui.DriverRow
import com.steamdeck.launcher.ui.ConfirmDialog
import com.steamdeck.launcher.ui.CreditsDialog
@@ -80,8 +81,6 @@ class MainActivity : ComponentActivity() {
private var offlineAccount by mutableStateOf<String?>(null)
private var offline by mutableStateOf(false)
private var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
private var showDrivers by mutableStateOf(false)
private var showAudio by mutableStateOf(false)
private var showPerformance by mutableStateOf(false)
private var clientOverride by mutableStateOf(false)
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
@@ -113,6 +112,15 @@ class MainActivity : ComponentActivity() {
romsDir = path
}
}
// The mode whose settings dialog is open, with what it shows; refreshed by openModeSettings().
private var settingsMode by mutableStateOf<String?>(null)
private var resolutionCap by mutableStateOf(1080)
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
private var hdrOn by mutableStateOf(false)
private var hdrReason by mutableStateOf<String?>(null)
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var renderer by mutableStateOf("pixman")
private var romsDir by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true)
private var showRoms by mutableStateOf(false)
@@ -145,10 +153,11 @@ class MainActivity : ComponentActivity() {
onRuntime = { onRuntimeButton() },
onFrameGen = { showFrameGen = true },
onProtons = { refreshProtons(); showProtons = true },
onDrivers = { refreshDrivers(); showDrivers = true },
onAudio = { directAudio = SessionPrefs.directAudio(this); mic = SessionPrefs.micEnabled(this); showAudio = true },
onSteamSettings = { openModeSettings(SessionService.MODE_STEAM) },
onDesktopSettings = { openModeSettings(SessionService.MODE_DESKTOP) },
onPerformance = { refreshCores(); showPerformance = true },
onRoms = { showRoms = true },
onFiles = { startActivity(Intent(this, com.steamdeck.launcher.files.FileManagerActivity::class.java)) },
onLogs = {
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
logsEnabled = SessionPrefs.logsEnabled(this)
@@ -177,31 +186,47 @@ class MainActivity : ComponentActivity() {
onRemove = { id -> ProtonExtras.tools.first { it.id == id }.let { ProtonExtras.remove(this, it) }; refreshProtons() },
onDismiss = { showProtons = false },
)
if (showDrivers) DriverDialog(
linuxRows = linuxRows, linuxSteam = linuxSteam, linuxDesktop = linuxDesktop,
androidRows = androidRows, androidSelected = androidSelected,
onSelectLinux = { mode, id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() },
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
onRemoveLinux = { id -> LinuxVulkanDriverManager(this).removeDriver(id); refreshDrivers() },
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() },
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
onRemoveAndroid = { id -> TurnipDriver(this).remove(id); refreshDrivers() },
onDismiss = { showDrivers = false },
)
if (showAudio) AudioDialog(
directAudio = directAudio, mic = mic,
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
onMic = { on ->
SessionPrefs.setMicEnabled(this, on)
mic = on
// The session checks the grant itself at start; asking here means the
// answer is in before the first session that wants it.
if (on && checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 2)
}
},
onDismiss = { showAudio = false },
)
settingsMode?.let { mode ->
ModeSettingsDialog(
ModeSettings(
mode = mode, resolutionCap = resolutionCap, shapeMode = shapeMode,
hdr = hdrOn, hdrReason = hdrReason,
linuxRows = linuxRows,
linuxSelected = if (mode == SessionService.MODE_STEAM) linuxSteam else linuxDesktop,
androidRows = androidRows, androidSelected = androidSelected,
touchMode = touchMode,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
mic = if (mode == SessionService.MODE_STEAM) mic else null,
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
),
ModeSettingsActions(
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() },
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
onRemoveLinux = { id -> LinuxVulkanDriverManager(this).removeDriver(id); refreshDrivers() },
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() },
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
onRemoveAndroid = { id -> TurnipDriver(this).remove(id); refreshDrivers() },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
onMic = { on ->
SessionPrefs.setMicEnabled(this, on)
mic = on
// The session checks the grant itself at start; asking here means the
// answer is in before the first session that wants it.
if (on && checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 2)
}
},
onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
onDismiss = { settingsMode = null },
),
)
}
if (showPerformance) PerformanceDialog(
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores,
@@ -293,6 +318,21 @@ class MainActivity : ComponentActivity() {
}
/** Both driver lists as the dialog shows them, re-read from disk so an import or removal shows at once. */
/** Everything the mode's cog shows, read fresh, then the dialog. */
private fun openModeSettings(mode: String) {
refreshDrivers()
resolutionCap = SessionPrefs.resolutionCap(this, mode)
shapeMode = SessionPrefs.shapeMode(this)
hdrOn = SessionPrefs.hdr(this, mode)
hdrReason = com.steamdeck.launcher.wayland.HdrSupport.probe(this).reason
touchMode = SessionPrefs.touchMode(this)
oscMode = SessionPrefs.oscMode(this)
directAudio = SessionPrefs.directAudio(this)
mic = SessionPrefs.micEnabled(this)
renderer = SessionPrefs.desktopRenderer(this)
settingsMode = mode
}
private fun refreshDrivers() {
val lm = LinuxVulkanDriverManager(this)
linuxRows = LinuxVulkanDriver.optionValues(this).map { id ->
@@ -37,6 +37,7 @@ import com.steamdeck.launcher.session.PerfHud
import com.steamdeck.launcher.session.ProtonExtras
import com.steamdeck.launcher.session.SessionPrefs
import com.steamdeck.launcher.session.SessionPaths
import com.steamdeck.launcher.wayland.HdrSupport
import com.steamdeck.launcher.session.SessionService
import com.steamdeck.launcher.session.SessionState
import com.steamdeck.launcher.ui.CursorOverlay
@@ -158,6 +159,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onFrameGen = { showFrameGen = true },
onKeyboard = { drawerOpen = false; keyboard?.toggle() },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({
// The Guide button, the way the on-screen ◉ sends it: a device with no
// Xbox button, or a pad the client hides the controls for, has no other
// way to open the client's menu in a game.
drawerOpen = false
padBridge?.applyTouch { st -> st.setPressed(com.steamdeck.launcher.input.GamepadState.IDX_BUTTON_MODE, true) }
Handler(Looper.getMainLooper()).postDelayed({
padBridge?.applyTouch { st -> st.setPressed(com.steamdeck.launcher.input.GamepadState.IDX_BUTTON_MODE, false) }
}, 90)
}) else null,
onProtons = { refreshProtons(); showProtons = true },
onOsc = {
val next = when (SessionPrefs.oscMode(this@SessionActivity)) {
@@ -285,6 +296,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
}
}
// HDR10: the gate is decided once, when the compositor starts (it lives for the whole app
// process), from the panel's own word and the mode's setting. Zero-copy presentation is
// what puts an HDR frame on a display layer tagged BT2020_PQ, so it is turned on with it.
if (!CompositorHost.isStarted) {
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
val probe = HdrSupport.probe(this)
WaylandCompositor.nativeSetHdrDisplay(
probe.displayId, probe.name, probe.formats, probe.hdr10,
probe.maxLuminance, probe.maxAverageLuminance, probe.minLuminance,
probe.ratioAvailable, probe.ratio, Build.VERSION.SDK_INT,
)
val wanted = SessionPrefs.hdr(this, mode)
val on = wanted && probe.reason == null
SessionState.hdr = on
if (on) {
try { android.system.Os.setenv("BANNER_WAYLAND_HDR", "1", true) } catch (e: Exception) { Log.w(TAG, "BANNER_WAYLAND_HDR", e) }
WaylandCompositor.nativeSetZeroCopy(true)
}
WaylandCompositor.nativeSetHdrRequest(
if (on) WaylandCompositor.HDR_MODE_ON else WaylandCompositor.HDR_MODE_OFF,
"$mode session settings" + (if (wanted && !on) " (refused: ${probe.reason})" else ""),
on, on,
)
Log.i(TAG, "hdr: " + (if (on) "on" else if (wanted) "wanted but ${probe.reason}" else "off") + " · display ${probe.formats.ifEmpty { "SDR" }}")
}
CompositorHost.startOrAttach(
holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
@@ -344,9 +380,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// compositor letterboxes onto a squarer panel.
val aspect = if (SessionPrefs.shapeMode(this) == SessionPrefs.SHAPE_WIDE) 16f / 9f
else maxOf(panelW / panelH, 16f / 9f)
// 1080 tall at most: the client's CEF is the heaviest thing in the session, and above
// 1080p it costs frames for nothing anyone can see on a handheld panel.
val height = minOf(panelH, 1080f).toInt()
// 1080 tall at most by default: the client's CEF is the heaviest thing in the session, and
// above 1080p it costs frames for nothing anyone can see on a handheld panel. The mode's
// settings (the cog beside Play / Desktop) can lower the cap or lift it to the panel.
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
val cap = SessionPrefs.resolutionCap(this, mode)
val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt()
val width = (height * aspect).toInt()
// Odd sizes upset the scaler; both dimensions even is what every mode here would be.
return Pair(width and 1.inv(), height and 1.inv())
@@ -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
}
}
@@ -34,6 +34,8 @@ object CrashHandler {
worker.start()
worker.join(8000)
}
// The session's tree would outlive us otherwise, and block the next launch.
OrphanReaper.reap("app crash")
} catch (e: Throwable) {
// Nothing more to do for a crash inside the crash handler.
} finally {
@@ -0,0 +1,51 @@
package com.steamdeck.launcher.session
import android.util.Log
import java.io.File
/**
* Kills every process of this app's uid other than the app itself.
*
* A session is a tree of processes under proot, and proot dies with the app only when the app's
* own teardown runs. When the app is killed or crashes instead, the tree stays: proot holding the
* rootfs, gamescope holding the GPU, Steam holding its lock file - and the next session never
* comes up, or comes up beside a client that is already running. A user on a Thor Pro had to
* force-stop the app before every launch. Everything of ours that should be alive between
* sessions is inside the app process, so at session start anything else under our uid is a
* leftover, and this sweeps it. Each pid is checked by uid at kill time, never by name.
*/
object OrphanReaper {
private const val TAG = "OrphanReaper"
fun reap(reason: String): Int {
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
var killed = 0
File("/proc").listFiles()?.forEach { entry ->
val pid = entry.name.toIntOrNull() ?: return@forEach
if (pid == me || pid <= 1) return@forEach
if (uidOf(pid) != uid) return@forEach
val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" }
try {
android.os.Process.killProcess(pid)
killed++
Log.i(TAG, "killed leftover $pid ($name) - $reason")
} catch (e: Exception) {
Log.w(TAG, "could not kill $pid ($name)", e)
}
}
if (killed > 0) Log.i(TAG, "$killed leftover process(es) from an earlier session - $reason")
return killed
}
private fun uidOf(pid: Int): Int {
return try {
File("/proc/$pid/status").useLines { lines ->
lines.firstOrNull { it.startsWith("Uid:") }
?.substringAfter("Uid:")?.trim()?.split(Regex("\\s+"))?.firstOrNull()?.toIntOrNull() ?: -1
}
} catch (e: Exception) {
-1
}
}
}
@@ -181,4 +181,40 @@ object SessionPrefs {
fun setLogsEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("logs", on).apply()
}
// ── Per-mode display ────────────────────────────────────────────────────────────────────
/**
* The tallest the session's display may be, in pixels, for MODE_STEAM / MODE_DESKTOP:
* 0 = the panel's own height, otherwise a cap. 1080 is the default the app always had - the
* client's CEF is the heaviest thing in a session and above 1080p it costs frames for nothing
* a handheld panel can show. Read once, when the session's display is sized.
*/
fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 1080)
fun setResolutionCap(context: Context, mode: String, cap: Int) {
prefs(context).edit().putInt("resolutionCap.$mode", cap).apply()
}
/**
* What the desktop shell composites with: pixman (software, the default - the Adreno stand-in
* is not a DRM render node, so labwc's gbm allocator cannot use it), or gles2 / vulkan for a
* device that has a real node. `Download/steamdeck-wlr-renderer` still overrides it.
*/
fun desktopRenderer(context: Context): String = prefs(context).getString("desktopRenderer", "pixman") ?: "pixman"
fun setDesktopRenderer(context: Context, renderer: String) {
prefs(context).edit().putString("desktopRenderer", renderer).apply()
}
/**
* HDR10 output for MODE_STEAM / MODE_DESKTOP. Off by default. Honoured only when the panel
* lists HDR10 (HdrSupport), and decided when the compositor starts, which is once per app
* process: a change applies after the app is fully closed and opened again.
*/
fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean("hdr.$mode", false)
fun setHdr(context: Context, mode: String, on: Boolean) {
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
}
}
@@ -72,7 +72,13 @@ class SessionService : Service() {
SessionState.running = true
SessionState.firstFrameSeen = false
acquireLocks()
Thread({ runSession() }, "session-start").start()
Thread({
// A tree the last session left behind (the app was killed or crashed, so its teardown
// never ran) would hold the rootfs, the GPU and Steam's lock: nothing of ours should
// be alive between sessions outside this process.
OrphanReaper.reap("session starting")
runSession()
}, "session-start").start()
// The activity or the notification stops us; the system must not resurrect a session whose
// guest processes are long gone.
return START_NOT_STICKY
@@ -238,6 +244,13 @@ class SessionService : Service() {
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
if (SessionState.hdr) {
// The activity opened the compositor's HDR gate: gamescope offers HDR to its clients
// and DXVK takes the HDR10 swapchain when a game asks for one.
guest.add("BL_HDR=1")
guest.add("DXVK_HDR=1")
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
}
guest.add("BL_FPS=0")
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
@@ -272,7 +285,7 @@ class SessionService : Service() {
if (SessionState.mode == MODE_DESKTOP) {
val override = File(Environment.getExternalStorageDirectory(), "Download/steamdeck-wlr-renderer")
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }
guest.add("BL_WLR_RENDERER=" + (override?.takeIf { it.isNotEmpty() } ?: "pixman"))
guest.add("BL_WLR_RENDERER=" + (override?.takeIf { it.isNotEmpty() } ?: SessionPrefs.desktopRenderer(this)))
}
guest.add(LinuxRuntime.SESSION_SCRIPT)
guest.add(SessionState.mode)
@@ -10,6 +10,9 @@ import java.io.File
object SessionState {
@Volatile
var running = false
/** HDR10 was asked for and the panel can show it: the compositor was told, and the session
* gets DXVK_HDR=1 and gamescope --hdr-enabled. Decided by the activity before the compositor starts. */
@JvmStatic var hdr = false
/** Which session this is: SessionService.MODE_STEAM or MODE_DESKTOP. */
@Volatile
@@ -1,69 +0,0 @@
package com.steamdeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
/**
* The two audio opt-ins. The client always has PulseAudio; these change what the games get and
* whether anything can record. Both apply at the next session start.
*/
@Composable
fun AudioDialog(
directAudio: Boolean,
mic: Boolean,
onDirectAudio: (Boolean) -> Unit,
onMic: (Boolean) -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Audio") },
text = {
Column {
Text(
"The Steam client itself always plays through PulseAudio. These two change what happens around it, at the next session start.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(12.dp))
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
Column(modifier = Modifier.weight(1f)) {
Text("DirectAudio for games", style = MaterialTheme.typography.bodyMedium)
Text(
"Replaces Wine's audio driver inside the games the client launches with one that talks straight to Android — lower latency, no PulseAudio in between. Wine 11 Protons only (Valve's ARM64, GE, cachyos); on anything else it stays off rather than play silence. A game's first launch after turning this on still uses Proton's own audio; the second uses this.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(checked = directAudio, onCheckedChange = onDirectAudio)
}
Spacer(Modifier.height(8.dp))
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
Column(modifier = Modifier.weight(1f)) {
Text("Microphone", style = MaterialTheme.typography.bodyMedium)
Text(
"Gives the session Android's microphone: the Steam client shows an input device named DirectAudioMic, for voice chat. Asks for the recording permission; with it off, nothing in the session can record and Android's indicator stays off.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(checked = mic, onCheckedChange = onMic)
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } },
)
}
@@ -1,140 +0,0 @@
package com.steamdeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.steamdeck.launcher.session.SessionService
/** One driver as the dialog shows it. [removable] is false for the runtime's own and the bundled builds. */
class DriverRow(val id: String, val name: String, val detail: String, val removable: Boolean)
/**
* The two driver choices a session has, each its own list, because a zip for one cannot serve the
* other: the glibc Turnip the runtime draws with (chosen per mode — Steam and the desktop can
* differ), and the bionic Turnip the app's compositor puts the frame on the panel with. Imports
* are validated where they land, so a "-Linux" zip dropped in the Android list is refused with
* the reason rather than becoming a black session.
*/
@Composable
fun DriverDialog(
linuxRows: List<DriverRow>,
linuxSteam: String,
linuxDesktop: String,
androidRows: List<DriverRow>,
androidSelected: String,
onSelectLinux: (mode: String, id: String) -> Unit,
onImportLinux: () -> Unit,
onRemoveLinux: (String) -> Unit,
onSelectAndroid: (String) -> Unit,
onImportAndroid: () -> Unit,
onRemoveAndroid: (String) -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Graphics drivers") },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Text("Linux runtime driver", style = MaterialTheme.typography.titleSmall)
Text(
"What the Steam client, its games and the desktop's programs render on, inside the runtime. " +
"\"-Linux\" Turnip zips only — these are Linux processes and cannot load an Android driver. " +
"Applies at the next session start.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(6.dp))
Row(modifier = Modifier.fillMaxWidth()) {
Spacer(Modifier.weight(1f))
Text("Steam", style = MaterialTheme.typography.labelSmall, modifier = Modifier.width(52.dp), fontWeight = FontWeight.Bold)
Text("Desktop", style = MaterialTheme.typography.labelSmall, modifier = Modifier.width(60.dp), fontWeight = FontWeight.Bold)
}
for (row in linuxRows) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
Column(modifier = Modifier.weight(1f)) {
Text(row.name, style = MaterialTheme.typography.bodyMedium)
if (row.detail.isNotEmpty()) Text(
row.detail,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (row.removable) TextButton(
onClick = { onRemoveLinux(row.id) },
contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp),
) { Text("Remove", style = MaterialTheme.typography.labelSmall) }
}
RadioButton(
selected = row.id == linuxSteam,
onClick = { onSelectLinux(SessionService.MODE_STEAM, row.id) },
modifier = Modifier.width(52.dp),
)
RadioButton(
selected = row.id == linuxDesktop,
onClick = { onSelectLinux(SessionService.MODE_DESKTOP, row.id) },
modifier = Modifier.width(60.dp),
)
}
}
OutlinedButton(onClick = onImportLinux, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) {
Text("Import \"-Linux\" Turnip zip…")
}
Spacer(Modifier.height(14.dp))
HorizontalDivider()
Spacer(Modifier.height(10.dp))
Text("Display driver (Android)", style = MaterialTheme.typography.titleSmall)
Text(
"What the app's compositor puts frames on the screen with — the last step of every session. " +
"AdrenoTools zips only. The compositor loads its driver once per app process, so a change " +
"applies after the app is fully closed and opened again.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(6.dp))
for (row in androidRows) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
Column(modifier = Modifier.weight(1f)) {
Text(row.name, style = MaterialTheme.typography.bodyMedium)
if (row.detail.isNotEmpty()) Text(
row.detail,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (row.removable) TextButton(
onClick = { onRemoveAndroid(row.id) },
contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp),
) { Text("Remove", style = MaterialTheme.typography.labelSmall) }
}
RadioButton(
selected = row.id == androidSelected,
onClick = { onSelectAndroid(row.id) },
)
}
}
OutlinedButton(onClick = onImportAndroid, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) {
Text("Import AdrenoTools zip…")
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } },
)
}
@@ -15,7 +15,11 @@ 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.layout.widthIn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Icon
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
@@ -77,11 +81,12 @@ fun MainScreen(
onRuntime: () -> Unit,
onFrameGen: () -> Unit,
onProtons: () -> Unit,
onDrivers: () -> Unit,
onAudio: () -> Unit,
onSteamSettings: () -> Unit,
onDesktopSettings: () -> Unit,
onPerformance: () -> Unit,
onOffline: () -> Unit,
onRoms: () -> Unit,
onFiles: () -> Unit,
onLogs: () -> Unit,
onCredits: () -> Unit,
) {
@@ -148,14 +153,36 @@ fun MainScreen(
Spacer(Modifier.height(14.dp * k))
val buttonHeight = 40.dp * k
Button(
onClick = onPlay, enabled = state.ready && !state.busy,
modifier = Modifier.fillMaxWidth().height(buttonHeight),
) { Text("Play", fontSize = 14.sp * k) }
// Each launch button has its own cog: what only matters for that mode lives there.
Row(horizontalArrangement = Arrangement.spacedBy(6.dp * k), modifier = Modifier.fillMaxWidth()) {
Button(
onClick = onPlay, enabled = state.ready && !state.busy,
modifier = Modifier.weight(1f).height(buttonHeight),
) { Text("Play", fontSize = 14.sp * k) }
CogButton(k, onSteamSettings)
}
Row(horizontalArrangement = Arrangement.spacedBy(6.dp * k), modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k)) {
OutlinedButton(
onClick = onDesktop, enabled = state.ready && !state.busy && state.desktopInstalled,
modifier = Modifier.weight(1f).height(buttonHeight),
) { Text(if (state.desktopInstalled) "Desktop" else "Desktop — install it under Desktop & apps", fontSize = 13.sp * k, maxLines = 1, overflow = TextOverflow.Ellipsis) }
CogButton(k, onDesktopSettings)
}
// Offline is read while the client starts, so it is decided here rather than in the
// session's drawer, and it needs credentials from an earlier sign-in to be possible.
OutlinedButton(
onClick = onDesktop, enabled = state.ready && !state.busy && state.desktopInstalled,
onClick = onOffline, enabled = state.offlineAccount != null,
modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight),
) { Text(if (state.desktopInstalled) "Desktop" else "Desktop — install it under Desktop & apps", fontSize = 13.sp * k) }
) {
Text(
when {
state.offlineAccount == null -> "Start offline — sign in once first"
state.offline -> "Start offline: on · ${state.offlineAccount}"
else -> "Start offline: off"
},
fontSize = 13.sp * k,
)
}
Spacer(Modifier.height(8.dp * k))
val runtimeLabel = when {
@@ -175,11 +202,6 @@ fun MainScreen(
MenuTile("Compatibility tools", null, k, Modifier.weight(1f), onClick = onProtons)
}
Spacer(Modifier.height(6.dp * k))
Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) {
MenuTile("Graphics drivers", null, k, Modifier.weight(1f), onClick = onDrivers)
MenuTile("Audio", null, k, Modifier.weight(1f), onClick = onAudio)
}
Spacer(Modifier.height(6.dp * k))
Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) {
MenuTile("Performance", null, k, Modifier.weight(1f), onClick = onPerformance)
// The folder's own name is the value; the whole path is in the dialog.
@@ -190,17 +212,7 @@ fun MainScreen(
}
Spacer(Modifier.height(6.dp * k))
Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) {
// Offline is read while the client starts, so it is decided here rather than in the
// session's drawer, and it needs credentials from an earlier sign-in to be possible.
MenuTile(
"Start offline",
when {
state.offlineAccount == null -> "sign in once first"
state.offline -> "on · ${state.offlineAccount}"
else -> "off"
},
k, Modifier.weight(1f), enabled = state.offlineAccount != null, onClick = onOffline,
)
MenuTile("Files", null, k, Modifier.weight(1f), onClick = onFiles)
MenuTile(
"Session logs", if (state.logsEnabled) "on · Download/SteamDeck" else "off",
k, Modifier.weight(1f), onClick = onLogs,
@@ -216,6 +228,16 @@ fun MainScreen(
}
}
/** The cog beside a launch button. */
@Composable
private fun CogButton(k: Float, onClick: () -> Unit) {
OutlinedButton(
onClick = onClick,
modifier = Modifier.width(44.dp * k).height(40.dp * k),
contentPadding = PaddingValues(0.dp),
) { Icon(Icons.Filled.Settings, contentDescription = "Settings", modifier = Modifier.size(18.dp * k)) }
}
/** One tile of the two-column menu: what it is, and under it what it is set to. */
@Composable
private fun MenuTile(
@@ -0,0 +1,214 @@
package com.steamdeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.steamdeck.launcher.session.SessionService
/** One driver as the dialog shows it. [removable] is false for the runtime's own and the bundled builds. */
class DriverRow(val id: String, val name: String, val detail: String, val removable: Boolean)
/** Everything one mode's settings dialog shows; the activity owns the values. */
class ModeSettings(
val mode: String,
val resolutionCap: Int,
val shapeMode: String,
val hdr: Boolean,
/** Why HDR cannot be offered on this display, or null when it can. */
val hdrReason: String?,
val linuxRows: List<DriverRow>,
val linuxSelected: String,
val androidRows: List<DriverRow>,
val androidSelected: String,
val touchMode: String,
/** Steam only. */
val oscMode: String?,
val directAudio: Boolean?,
val mic: Boolean?,
/** Desktop only. */
val renderer: String?,
)
class ModeSettingsActions(
val onResolution: (Int) -> Unit,
val onShape: (String) -> Unit,
val onHdr: (Boolean) -> Unit,
val onSelectLinux: (String) -> Unit,
val onImportLinux: () -> Unit,
val onRemoveLinux: (String) -> Unit,
val onSelectAndroid: (String) -> Unit,
val onImportAndroid: () -> Unit,
val onRemoveAndroid: (String) -> Unit,
val onTouch: (String) -> Unit,
val onOsc: (String) -> Unit,
val onDirectAudio: (Boolean) -> Unit,
val onMic: (Boolean) -> Unit,
val onRenderer: (String) -> Unit,
val onDismiss: () -> Unit,
)
/**
* The cog beside Play / Desktop: what only matters for that one mode, in one place - the display
* the session is sized to, HDR, the driver inside the runtime, the display driver, and the input
* and audio choices - so the main screen is left with what applies to both.
*/
@Composable
fun ModeSettingsDialog(s: ModeSettings, a: ModeSettingsActions) {
val steam = s.mode == SessionService.MODE_STEAM
AlertDialog(
onDismissRequest = a.onDismiss,
title = { Text(if (steam) "Steam session" else "Desktop session") },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Section("Display", "Takes effect at the next session: gamescope sizes its display once, when it starts.")
Text("Resolution", style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 4.dp))
listOf(
1080 to "Up to 1080p — the default",
900 to "Up to 900p",
720 to "Up to 720p — lighter on the GPU",
0 to "The panel's own — above 1080p costs frames for nothing a handheld can show",
).forEach { (cap, label) ->
Choice(label, s.resolutionCap == cap) { a.onResolution(cap) }
}
Text("Shape", style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 6.dp))
Choice("The panel's shape (never narrower than 16:9)", s.shapeMode == "auto") { a.onShape("auto") }
Choice("16:9 — for a foldable, with bars on either panel", s.shapeMode == "16:9") { a.onShape("16:9") }
Spacer(Modifier.height(6.dp))
SwitchRow(
"HDR10 output",
s.hdrReason ?: (if (steam) "The compositor offers games HDR10 and gamescope passes it on; a game that renders HDR shows as HDR. Applies after the app is closed and opened again."
else "Offered to the desktop's programs; labwc itself composites in SDR, so only a program that presents HDR directly shows it. Applies after the app is closed and opened again."),
checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr,
)
Divider()
Section(
"Linux runtime driver",
"What " + (if (steam) "the Steam client and its games" else "the desktop's programs") +
" render on, inside the runtime. \"-Linux\" Turnip zips only. Applies at the next session start.",
)
for (row in s.linuxRows) DriverChoice(row, row.id == s.linuxSelected, { a.onSelectLinux(row.id) }, { a.onRemoveLinux(row.id) })
OutlinedButton(onClick = a.onImportLinux, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) {
Text("Import \"-Linux\" Turnip zip…")
}
Divider()
Section(
"Display driver (Android)",
"What the app's compositor puts frames on the screen with, the last step of every session; shared by both modes. " +
"AdrenoTools zips only. Applies after the app is fully closed and opened again.",
)
for (row in s.androidRows) DriverChoice(row, row.id == s.androidSelected, { a.onSelectAndroid(row.id) }, { a.onRemoveAndroid(row.id) })
OutlinedButton(onClick = a.onImportAndroid, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) {
Text("Import AdrenoTools zip…")
}
Divider()
Section("Touch", "How a finger drives the pointer. Also in the session's drawer.")
Choice("Auto — touchpad on the desktop, direct in Steam", s.touchMode == "auto") { a.onTouch("auto") }
Choice("Touchpad — drag moves the pointer, tap clicks", s.touchMode == "touchpad") { a.onTouch("touchpad") }
Choice("Direct — the pointer jumps under the finger", s.touchMode == "direct") { a.onTouch("direct") }
if (steam && s.oscMode != null) {
Spacer(Modifier.height(6.dp))
Text("On-screen controls", style = MaterialTheme.typography.labelLarge)
Choice("Auto — shown when no controller is attached", s.oscMode == "auto") { a.onOsc("auto") }
Choice("Always", s.oscMode == "always") { a.onOsc("always") }
Choice("Never", s.oscMode == "never") { a.onOsc("never") }
}
if (steam && s.directAudio != null && s.mic != null) {
Divider()
Section("Audio", null)
SwitchRow(
"DirectAudio for games",
"Games play straight to the device, bypassing PulseAudio: lower latency. Off = PulseAudio for everything.",
s.directAudio, true, a.onDirectAudio,
)
SwitchRow(
"Microphone",
"The device's microphone for voice chat, as the client's input device. Asks for the permission once.",
s.mic, true, a.onMic,
)
}
if (!steam && s.renderer != null) {
Divider()
Section(
"Desktop renderer",
"How labwc composites the desktop. pixman is software and works everywhere; gles2 / vulkan need a real DRM render node, which the Adreno stand-in is not on most devices.",
)
Choice("pixman — software, the default", s.renderer == "pixman") { a.onRenderer("pixman") }
Choice("gles2", s.renderer == "gles2") { a.onRenderer("gles2") }
Choice("vulkan", s.renderer == "vulkan") { a.onRenderer("vulkan") }
}
}
},
confirmButton = { TextButton(onClick = a.onDismiss) { Text("Done") } },
)
}
@Composable
private fun Section(title: String, detail: String?) {
Text(title, style = MaterialTheme.typography.titleSmall)
if (detail != null) Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
@Composable
private fun Divider() {
Spacer(Modifier.height(12.dp))
HorizontalDivider()
Spacer(Modifier.height(10.dp))
}
@Composable
private fun Choice(label: String, selected: Boolean, onClick: () -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
RadioButton(selected = selected, onClick = onClick)
Text(label, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
}
}
@Composable
private fun SwitchRow(label: String, detail: String, checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
Column(modifier = Modifier.weight(1f)) {
Text(label, style = MaterialTheme.typography.bodyMedium)
Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Switch(checked = checked, enabled = enabled, onCheckedChange = onChange)
}
}
@Composable
private fun DriverChoice(row: DriverRow, selected: Boolean, onSelect: () -> Unit, onRemove: () -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
RadioButton(selected = selected, onClick = onSelect)
Column(modifier = Modifier.weight(1f)) {
Text(row.name, style = MaterialTheme.typography.bodyMedium)
if (row.detail.isNotEmpty()) Text(row.detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
if (row.removable) TextButton(onClick = onRemove, contentPadding = PaddingValues(0.dp)) {
Text("Remove", style = MaterialTheme.typography.labelSmall)
}
}
}
}
@@ -94,6 +94,8 @@ class DrawerActions(
val onHud: (Boolean) -> Unit,
val onFrameGen: () -> Unit,
val onKeyboard: () -> Unit,
/** Sends the Guide button (the client's menu); null on the desktop, where there is none. */
val onSteamMenu: (() -> Unit)?,
val onProtons: () -> Unit,
val onOsc: () -> Unit,
val onTouch: () -> Unit,
@@ -136,6 +138,9 @@ fun SessionDrawer(a: DrawerActions) {
OutlinedButton(onClick = a.onKeyboard, modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) {
Text("Keyboard", fontSize = 13.sp)
}
if (a.onSteamMenu != null) OutlinedButton(onClick = a.onSteamMenu, modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
Text("Steam menu ◉", fontSize = 13.sp)
}
OutlinedButton(onClick = a.onFrameGen, modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
Text("Frame generation: ${a.frameGenLabel}", fontSize = 13.sp)
}
@@ -0,0 +1,67 @@
package com.steamdeck.launcher.wayland
import android.content.Context
import android.os.Build
import android.view.Display
import android.view.WindowManager
/**
* What the panel says about HDR, read from android.view.Display: the gate the compositor's HDR10
* output sits behind (banner_color.h). A property of the display, not the device - and the
* settings screen greys the HDR switch out with the reason when it is not there, rather than
* offering a switch that a session would then silently ignore.
*/
class HdrProbe(
val hdr10: Boolean,
val formats: String,
val maxLuminance: Float,
val maxAverageLuminance: Float,
val minLuminance: Float,
val ratioAvailable: Boolean,
val ratio: Float,
val displayId: Int,
val name: String,
) {
/** Why HDR cannot be offered, or null when it can. */
val reason: String? = when {
Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a colour space)"
!hdr10 -> if (formats.isEmpty()) "this display reports no HDR support" else "this display supports $formats, not HDR10"
else -> null
}
}
object HdrSupport {
fun probe(context: Context): HdrProbe {
val display: Display? = if (Build.VERSION.SDK_INT >= 30) {
try { context.display } catch (e: Exception) { null }
} else {
@Suppress("DEPRECATION")
(context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
}
if (display == null) return HdrProbe(false, "", 0f, 0f, 0f, false, -1f, -1, "none")
val caps = try { display.hdrCapabilities } catch (e: Exception) { null }
val types = caps?.supportedHdrTypes ?: IntArray(0)
val formats = types.joinToString(", ") { typeName(it) }
val ratioAvailable = Build.VERSION.SDK_INT >= 34 && try { display.isHdrSdrRatioAvailable } catch (e: Exception) { false }
val ratio = if (ratioAvailable) try { display.hdrSdrRatio } catch (e: Exception) { -1f } else -1f
return HdrProbe(
hdr10 = types.contains(Display.HdrCapabilities.HDR_TYPE_HDR10),
formats = formats,
maxLuminance = caps?.desiredMaxLuminance ?: 0f,
maxAverageLuminance = caps?.desiredMaxAverageLuminance ?: 0f,
minLuminance = caps?.desiredMinLuminance ?: 0f,
ratioAvailable = ratioAvailable,
ratio = ratio,
displayId = display.displayId,
name = display.name ?: "display",
)
}
private fun typeName(t: Int): String = when (t) {
Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION -> "Dolby Vision"
Display.HdrCapabilities.HDR_TYPE_HDR10 -> "HDR10"
Display.HdrCapabilities.HDR_TYPE_HLG -> "HLG"
Display.HdrCapabilities.HDR_TYPE_HDR10_PLUS -> "HDR10+"
else -> "HDR"
}
}