Compare commits

...
20 changed files with 386 additions and 60 deletions

No files matched your search

@@ -311,6 +311,7 @@ class MainActivity : ComponentActivity() {
private var steamChannel by mutableStateOf("steamdeck_publicbeta")
private var runSteamAtStartup by mutableStateOf(false)
private var theme by mutableStateOf("graphite")
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
private var hdrOn by mutableStateOf(false)
private var fpsLimit by mutableStateOf(0)
private var upscaler by mutableStateOf(0)
@@ -480,6 +481,7 @@ class MainActivity : ComponentActivity() {
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
theme = SessionPrefs.theme(this)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
@@ -489,7 +491,7 @@ class MainActivity : ComponentActivity() {
applyLauncherFullscreen()
updates.start()
setContent {
DroidDeckTheme(theme) {
DroidDeckTheme(theme, appScale = appScale) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
val sm = settingsMode
val page: (@Composable () -> Unit)? = when {
@@ -516,6 +518,7 @@ class MainActivity : ComponentActivity() {
lossless = lossless,
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
theme = theme,
appScale = appScale,
isHomeApp = homeAppSelected,
homeScreenEnabled = homeScreenEnabled,
defaultHomeLabel = defaultHomeLabel,
@@ -645,6 +648,10 @@ class MainActivity : ComponentActivity() {
},
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
onAppScale = { percent ->
com.droiddeck.launcher.core.AppUiPrefs.setScale(this, percent)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
},
onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on
@@ -0,0 +1,19 @@
package com.droiddeck.launcher.core
import android.content.Context
object AppUiPrefs {
const val DEFAULT_SCALE = 100
val scales = listOf(75, 85, 100, 115, 125, 150)
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
fun scale(context: Context): Int = normalizeScale(
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getInt("scale", DEFAULT_SCALE),
)
fun setScale(context: Context, percent: Int) {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit()
.putInt("scale", normalizeScale(percent)).apply()
}
}
@@ -22,7 +22,7 @@ class FileManagerActivity : ComponentActivity() {
}
val initialDir = intent.getStringExtra(EXTRA_START_DIR)?.let(::File)
setContent {
DroidDeckTheme {
DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) {
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
FileManagerScreen(initialDir = initialDir)
}
@@ -43,7 +43,7 @@ class FilePickerActivity : ComponentActivity() {
?.let { File(it) }?.takeIf { it.isDirectory }
setContent {
DroidDeckTheme {
DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) {
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
FileManagerScreen(
pickMode = true,
@@ -14,7 +14,7 @@ import kotlin.math.abs
* The client reads `/sys/class/power_supply/BAT<n>/...` - a laptop's or a Deck's naming and files
* (`energy_now`, `power_now`, `time_to_empty_now`, a `uevent` of `POWER_SUPPLY_*` lines). Android
* names its supply `battery` and lays it out differently, and on many phones an app may not read
* it at all, so the client showed no battery. This writes a `BAT0` (and a `BAT1`, the Deck's name)
* it at all, so the client showed no battery. This writes one `BAT1` (the Deck's name)
* from Android's own battery API - the same on every device - into a directory the session binds
* over `/sys/class/power_supply`, refreshed every few seconds while the session runs.
*
@@ -31,6 +31,8 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
private var thread: Thread? = null
override fun start() {
// Older builds exported the same aggregate battery twice; MangoHud counts both supplies.
File(dir, "BAT0").deleteRecursively()
running = true
write()
thread = Thread({
@@ -39,7 +41,7 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
if (running) write()
}
}, "battery-sysfs").apply { isDaemon = true; start() }
Log.i(TAG, "battery: BAT0/BAT1 written to ${dir.path} every ${PERIOD_MS / 1000} s")
Log.i(TAG, "battery: BAT1 written to ${dir.path} every ${PERIOD_MS / 1000} s")
}
override fun stop() {
@@ -87,7 +89,7 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
pct <= 15 -> "Low"
else -> "Normal"
}
for (name in listOf("BAT0", "BAT1")) {
for (name in listOf("BAT1")) {
val bat = File(dir, name).apply { mkdirs() }
val attrs = linkedMapOf(
"type" to "Battery",
@@ -6,6 +6,7 @@ import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
import java.security.MessageDigest
import java.util.Locale
import java.util.UUID
/** Android shared storage cannot create the links in Wine prefixes or native Steam depots. */
object SecondaryLibrary {
@@ -17,6 +18,30 @@ object SecondaryLibrary {
"3127680" to "FEX-Emu",
)
/** Some devices permit direct access to the backing volume; others require Android's FUSE path. */
fun contentPath(library: File): File {
val path = library.absolutePath
if (!path.startsWith("/storage/")) return library
return verifiedAlias(library, File("/mnt/media_rw/" + path.removePrefix("/storage/")))
}
internal fun verifiedAlias(library: File, candidate: File): File {
if (!candidate.isDirectory || !candidate.canRead() || !candidate.canWrite()) return library
var probe: File? = null
return try {
val created = File.createTempFile(".droiddeck-path-", ".probe", candidate)
probe = created
val token = UUID.randomUUID().toString()
created.writeText(token)
val visible = File(library, created.name)
if (visible.readText() == token && visible.delete() && !created.exists()) candidate else library
} catch (_: Exception) {
library
} finally {
probe?.delete()
}
}
fun privateRoot(files: File, library: File): File {
val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray())
.joinToString("") { "%02x".format(it.toInt() and 255) }
@@ -24,7 +49,7 @@ object SecondaryLibrary {
}
/** Parent binds come first; the more specific private directories override them in PRoot. */
fun binds(files: File, library: File): List<String> {
fun binds(files: File, library: File, content: File = library): List<String> {
val private = privateRoot(files, library)
val apps = File(library, "steamapps")
val tools = LinkedHashMap(bootstrapTools)
@@ -58,7 +83,7 @@ object SecondaryLibrary {
}
}
return listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd").flatMap { guest ->
listOf("${library.path}:$guest") + overrides.map { (host, relative) -> "${host.path}:$guest/$relative" }
listOf("${content.path}:$guest") + overrides.map { (host, relative) -> "${host.path}:$guest/$relative" }
}
}
@@ -799,9 +799,10 @@ class SessionService : Service() {
// Links, prefixes and Steam entries made before the rename still name the old path.
File(LinuxRuntime.rootDir(this), "mnt/bannerlator-sd").mkdirs()
try {
binds.addAll(SecondaryLibrary.binds(filesDir, File(library.path)))
storageDiagnosticLibrary = File(library.path)
Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\"); prefixes and native tools private")
val content = SecondaryLibrary.contentPath(File(library.path))
binds.addAll(SecondaryLibrary.binds(filesDir, File(library.path), content))
storageDiagnosticLibrary = content
Log.i(TAG, "game storage: ${content.path} -> /mnt/droiddeck-sd (\"${library.label}\"); prefixes and native tools private")
} catch (e: Exception) {
Log.w(TAG, "game storage: private directories could not be prepared; internal only this session", e)
}
@@ -816,9 +817,9 @@ class SessionService : Service() {
val device = StorageDiagnostics.writeSnapshot(
sessionDir, target,
selectedLibrary = if (storageDiagnosticLibrary != null) "secondary" else "internal",
removable = storageDiagnosticLibrary?.let {
runCatching { Environment.isExternalStorageRemovable(it) }.getOrDefault(false)
} ?: false,
removable = storageDiagnosticLibrary != null && library?.let {
runCatching { Environment.isExternalStorageRemovable(File(it.path)) }.getOrDefault(false)
} == true,
)
if (device != null) {
// guest already has the session command at this point. Put these with the `env -i`
@@ -0,0 +1,23 @@
package com.droiddeck.launcher.ui
import android.content.res.Configuration
import androidx.compose.ui.unit.Density
import com.droiddeck.launcher.core.AppUiPrefs
import kotlin.math.roundToInt
internal fun scaledAppDensity(base: Density, percent: Int): Density {
val scale = AppUiPrefs.normalizeScale(percent) / 100f
return if (scale == 1f) base else Density(base.density * scale, base.fontScale)
}
/** Responsive layouts and popup height limits must see the same dp space as the scaled UI. */
internal fun scaledAppConfiguration(base: Configuration, percent: Int): Configuration {
val scale = AppUiPrefs.normalizeScale(percent) / 100f
if (scale == 1f) return base
return Configuration(base).apply {
if (densityDpi > 0) densityDpi = (densityDpi * scale).roundToInt()
if (screenWidthDp > 0) screenWidthDp = (screenWidthDp / scale).roundToInt()
if (screenHeightDp > 0) screenHeightDp = (screenHeightDp / scale).roundToInt()
if (smallestScreenWidthDp > 0) smallestScreenWidthDp = (smallestScreenWidthDp / scale).roundToInt()
}
}
@@ -284,7 +284,7 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni
}
}
/** A page's title, with room at its right for a status chip. */
/** A page's title, with room at its right for controls or status. */
@Composable
internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit = {}) {
Row(
@@ -101,6 +101,7 @@ class FrontEndState(
val gameSyncFolder: String? = null,
val pageKey: String? = null,
val theme: String = Themes.GRAPHITE,
val appScale: Int = com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE,
val isHomeApp: Boolean = false,
val homeScreenEnabled: Boolean = false,
val defaultHomeLabel: String? = null,
@@ -168,6 +169,7 @@ class FrontEndActions(
val onOffline: () -> Unit,
val onPageBack: () -> Unit = {},
val onTheme: (String) -> Unit = {},
val onAppScale: (Int) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onStoreEnabled: (Boolean) -> Unit = {},
@@ -162,8 +162,6 @@ internal fun SetupPanel(
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val signedIn = s.offlineAccount != null
var showLimitDetails by rememberSaveable { mutableStateOf(false) }
val checks = 4
val readyCount = listOf(gpuOk, s.ready && !s.busy, !limitBlocks, signedIn).count { it }
// Four tabs instead of one long scroll; LB and RB turn them from anywhere on the page. Build
// and credits are on the Updates page.
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_session), stringResource(R.string.setup_tab_launcher))
@@ -187,9 +185,8 @@ internal fun SetupPanel(
),
) {
PageHeader(stringResource(R.string.setup_title)) {
Chip(if (readyCount == checks) stringResource(R.string.setup_all_set) else stringResource(R.string.setup_n_ready, readyCount, checks), ok = readyCount == checks)
TabStrip(tabs, tab, pick, Modifier.weight(1f), tabFocus)
}
TabStrip(tabs, tab, pick, Modifier.padding(bottom = 4.dp), tabFocus)
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
when (tab) {
0 -> {
@@ -314,6 +311,15 @@ internal fun SetupPanel(
}
3 -> {
SettingsGroup(stringResource(R.string.setup_launcher)) {
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent ->
percent to stringResource(
if (percent == com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) R.string.setup_app_scale_default
else R.string.ctrl_percent, percent,
)
}, s.appScale, onPick = a.onAppScale,
)
SettingsRow(stringResource(R.string.setup_theme), stringResource(R.string.setup_theme_hint)) {
Box {
ValueChip(Themes.byId(s.theme).label, host.open == "theme") { host.open = if (host.open == "theme") null else "theme" }
@@ -155,7 +155,7 @@ class ModeSettingsActions(
val onDismiss: () -> Unit,
)
private enum class SteamSettingsTab(val label: Int) {
private enum class ModeSettingsTab(val label: Int) {
DISPLAY(R.string.drawer_page_display),
CONTROLS(R.string.drawer_page_controls),
GAMES(R.string.game_settings_title),
@@ -171,34 +171,36 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
var confirmDeckyRemoval by remember { mutableStateOf(false) }
var explainWifiDiscovery by remember { mutableStateOf(false) }
var tabIndex by androidx.compose.runtime.saveable.rememberSaveable(s.mode) { mutableStateOf(0) }
val tabs = SteamSettingsTab.entries
val tabs = if (steam) ModeSettingsTab.entries else listOf(
ModeSettingsTab.DISPLAY, ModeSettingsTab.CONTROLS, ModeSettingsTab.SESSION,
)
val tab = tabs[tabIndex]
val scrolls = tabs.map { androidx.compose.foundation.rememberScrollState() }
val tabFocus = remember { tabs.map { androidx.compose.ui.focus.FocusRequester() } }
val tabFocus = remember(s.mode) { tabs.map { androidx.compose.ui.focus.FocusRequester() } }
val firstChip = remember { androidx.compose.ui.focus.FocusRequester() }
fun selectTab(index: Int) { host.open = null; tabIndex = index }
androidx.compose.runtime.LaunchedEffect(steam, tabIndex) {
androidx.compose.runtime.withFrameNanos { }
runCatching {
if (!steam || tab == SteamSettingsTab.DISPLAY) firstChip.requestFocus()
if (tab == ModeSettingsTab.DISPLAY) firstChip.requestFocus()
else tabFocus[tabIndex].requestFocus()
}
}
SettingsPage(
host,
title = if (steam) stringResource(R.string.mode_steam_title) else stringResource(R.string.mode_desktop_title),
title = null,
onBack = a.onDismiss,
scroll = scrolls[tabIndex],
modifier = if (steam) Modifier.bumpers(
modifier = Modifier.bumpers(
onPrevious = { selectTab((tabIndex + tabs.size - 1) % tabs.size) },
onNext = { selectTab((tabIndex + 1) % tabs.size) },
) else Modifier,
header = if (steam) ({
),
header = {
TabStrip(tabs.map { stringResource(it.label) }, tabIndex, ::selectTab,
modifier = Modifier.fillMaxWidth().padding(top = 12.dp), focusRequesters = tabFocus)
}) else null,
modifier = Modifier.fillMaxWidth(), focusRequesters = tabFocus)
},
) {
if (!steam || tab == SteamSettingsTab.DISPLAY) {
if (tab == ModeSettingsTab.DISPLAY) {
val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution)
SettingsGroup(stringResource(R.string.display_session)) {
ResolutionRow(host, s.resolution, s.panelSize, a.onResolution,
@@ -241,7 +243,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
}
}
}
if (!steam || tab == SteamSettingsTab.CONTROLS) {
if (tab == ModeSettingsTab.CONTROLS) {
SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) {
ChoiceRow(
host, "touch", stringResource(R.string.mode_touch), null,
@@ -277,7 +279,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
)
}
}
if (!steam || tab == SteamSettingsTab.SESSION) {
if (tab == ModeSettingsTab.SESSION) {
SettingsGroup(stringResource(R.string.mode_session)) {
ChoiceRow(
host, "suspend", stringResource(R.string.mode_suspend),
@@ -304,7 +306,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
)
}
}
if (steam && tab == SteamSettingsTab.STEAM) SettingsGroup(stringResource(R.string.mode_decky)) {
if (steam && tab == ModeSettingsTab.STEAM) SettingsGroup(stringResource(R.string.mode_decky)) {
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
s.deckyInstalled != s.deckyLatestRelease.tag
val status = when {
@@ -363,7 +365,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
)
}
}
if (steam && tab == SteamSettingsTab.STEAM && s.steamChannel != null) SettingsGroup(stringResource(R.string.mode_client)) {
if (steam && tab == ModeSettingsTab.STEAM && s.steamChannel != null) SettingsGroup(stringResource(R.string.mode_client)) {
ToggleRow(
host, "steamdeck", stringResource(R.string.mode_deck_mode),
stringResource(R.string.mode_deck_mode_hint),
@@ -389,7 +391,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
SecondaryButton(stringResource(R.string.mode_steam_repair_button), enabled = !s.steamRepairQueued, onClick = a.onSteamRepair)
}
}
if (steam && tab == SteamSettingsTab.STEAM && s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
if (steam && tab == ModeSettingsTab.STEAM && s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
val hint = when {
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
!s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied)
@@ -408,11 +410,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
}
}
}
if ((!steam || tab == SteamSettingsTab.GAMES) && s.forceFullscreen != null) SettingsGroup(stringResource(R.string.display_window_compatibility)) {
if ((tab == ModeSettingsTab.GAMES || (!steam && tab == ModeSettingsTab.DISPLAY)) && s.forceFullscreen != null) SettingsGroup(stringResource(R.string.display_window_compatibility)) {
ToggleRow(host, "fill", stringResource(R.string.display_force_fullscreen),
stringResource(R.string.display_force_fullscreen_hint), s.forceFullscreen, onChange = a.onForceFullscreen)
}
if (steam && tab == SteamSettingsTab.GAMES && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) {
if (steam && tab == ModeSettingsTab.GAMES && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) {
for (dir in s.addedGamesDirs) {
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") }
ActionRow(
@@ -437,7 +439,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
)
}
if (steam && tab == SteamSettingsTab.GAMES && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) {
if (steam && tab == ModeSettingsTab.GAMES && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) {
if (s.syncBackend != null) SettingsRow(
stringResource(R.string.sync_backend_title),
stringResource(R.string.sync_backend_hint),
@@ -460,7 +462,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
GameEnvironmentRow()
}
if (steam && tab == SteamSettingsTab.AUDIO && s.directAudio != null && s.mic != null) SettingsGroup(stringResource(R.string.mode_audio)) {
if (steam && tab == ModeSettingsTab.AUDIO && s.directAudio != null && s.mic != null) SettingsGroup(stringResource(R.string.mode_audio)) {
ToggleRow(host, "da", stringResource(R.string.mode_directaudio), stringResource(R.string.mode_directaudio_hint), s.directAudio, onChange = a.onDirectAudio)
ChoiceRow(
host, "clientAudio", stringResource(R.string.mode_client_audio), stringResource(R.string.mode_client_audio_hint),
@@ -469,7 +471,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
)
ToggleRow(host, "mic", stringResource(R.string.mode_mic), stringResource(R.string.mode_mic_hint), s.mic, onChange = a.onMic)
}
if (steam && tab == SteamSettingsTab.GAMES && s.gameStorage != null) SettingsGroup(stringResource(R.string.mode_storage)) {
if (steam && tab == ModeSettingsTab.GAMES && s.gameStorage != null) SettingsGroup(stringResource(R.string.mode_storage)) {
val custom = s.gameStorage.isNotEmpty() && s.gameStorage != "off" && s.storageOptions.none { it.second == s.gameStorage }
val options = buildList {
add("" to (if (s.storageOptions.isEmpty()) stringResource(R.string.mode_storage_auto_none) else stringResource(R.string.mode_storage_auto)))
@@ -505,7 +507,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
onChange = a.onStorageDiagnostics,
)
}
if (!steam && s.renderer != null) SettingsGroup(stringResource(R.string.mode_renderer)) {
if (!steam && tab == ModeSettingsTab.DISPLAY && s.renderer != null) SettingsGroup(stringResource(R.string.mode_renderer)) {
ChoiceRow(
host, "renderer", stringResource(R.string.mode_desktop_renderer), stringResource(R.string.mode_renderer_hint),
listOf("vulkan" to stringResource(R.string.mode_renderer_vulkan), "gles2" to stringResource(R.string.mode_renderer_gles2), "pixman" to stringResource(R.string.mode_renderer_pixman)), s.renderer,
@@ -308,7 +308,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
if (open || veil > 0.01f) Box(
modifier = Modifier.fillMaxSize().graphicsLayer { alpha = veil }.background(Color(0x8A000000))
modifier = Modifier.fillMaxSize()
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() },
)
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
@@ -598,7 +598,7 @@ fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit)
@Composable
fun SettingsPage(
host: MenuHost,
title: String,
title: String?,
onBack: () -> Unit,
eyebrow: String? = null,
lede: String? = null,
@@ -608,7 +608,7 @@ fun SettingsPage(
scroll: androidx.compose.foundation.ScrollState? = null,
scrollContent: Boolean = true,
compactLayout: Boolean = false,
/** Controls that remain below the title while the settings scroll, such as a tab strip. */
/** Fixed controls below the title, or beside Back when the title is omitted. */
header: (@Composable () -> Unit)? = null,
modifier: Modifier = Modifier,
content: @Composable ColumnScope.() -> Unit,
@@ -624,7 +624,18 @@ fun SettingsPage(
),
verticalArrangement = Arrangement.spacedBy(if (compactLayout) 2.dp else 0.dp),
) {
if (narrow) {
if (title == null) {
Rise(0) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth(),
) {
BackLink(stringResource(R.string.mode_back), compact = true, onClick = onBack)
if (header != null) Box(Modifier.weight(1f)) { header() }
}
}
} else if (narrow) {
// Back and the title share one line: a 4:3 screen has no height to spare.
Rise(0) {
Row(
@@ -683,7 +694,7 @@ fun SettingsPage(
}
}
}
if (header != null) header()
if (header != null && title != null) header()
Rise(3, Modifier.weight(1f).fillMaxWidth()) {
Column(
modifier = Modifier
@@ -5,9 +5,13 @@ import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.session.SessionPrefs
class Palette(
@@ -67,7 +71,7 @@ val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.GRAPHITE) }
val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03111F) else Color.White
@Composable
fun DroidDeckTheme(theme: String? = null, content: @Composable () -> Unit) {
fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, content: @Composable () -> Unit) {
val id = theme ?: SessionPrefs.theme(LocalContext.current)
val p = Themes.byId(id)
val scheme = darkColorScheme(
@@ -77,5 +81,13 @@ fun DroidDeckTheme(theme: String? = null, content: @Composable () -> Unit) {
surfaceVariant = p.surfaceVariant, onSurfaceVariant = p.onSurfaceVariant,
error = p.error,
)
CompositionLocalProvider(LocalPalette provides p) { MaterialTheme(colorScheme = scheme, content = content) }
val baseDensity = LocalDensity.current
val baseConfiguration = LocalConfiguration.current
val density = remember(baseDensity, appScale) { scaledAppDensity(baseDensity, appScale) }
val configuration = remember(baseConfiguration, appScale) { scaledAppConfiguration(baseConfiguration, appScale) }
CompositionLocalProvider(
LocalPalette provides p,
LocalDensity provides density,
LocalConfiguration provides configuration,
) { MaterialTheme(colorScheme = scheme, content = content) }
}
+3
View File
@@ -595,6 +595,9 @@
<string name="setup_offline">Offline mode</string>
<string name="setup_sign_in_first">Sign in to Steam first</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_app_scale">App scale</string>
<string name="setup_app_scale_hint">DroidDeck text and controls</string>
<string name="setup_app_scale_default">%1$d%% (Default)</string>
<string name="setup_theme">Theme</string>
<string name="setup_theme_hint">Launcher appearance</string>
<string name="setup_home">Use as Home screen</string>
@@ -0,0 +1,71 @@
package com.droiddeck.launcher.session
import android.content.Intent
import android.os.BatteryManager
import java.io.File
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class BatteryComponentTest {
@get:Rule val tmp = TemporaryFolder()
private var battery: BatteryComponent? = null
@After fun stop() { battery?.stop() }
@Test fun oneAggregateBatteryKeepsOverlayPowerAndLifetimeConsistentWithQam() {
val supplies = tmp.newFolder("power_supply")
val vpower = tmp.newFolder("vpower")
start(supplies, vpower, -2_000_000L)
assertTelemetry(supplies, vpower)
}
@Test fun upgradingRemovesTheDuplicateRatherThanLeavingItForOverlayDiscovery() {
val supplies = tmp.newFolder("power_supply")
val vpower = tmp.newFolder("vpower")
val legacy = File(supplies, "BAT0").apply { mkdirs() }
File(legacy, "power_now").writeText("8000000\n")
File(legacy, "charge_now").writeText("4000000\n")
start(supplies, vpower, 2_000_000L)
assertFalse(legacy.exists())
assertTelemetry(supplies, vpower)
}
private fun start(supplies: File, vpower: File, currentUa: Long) {
val context = RuntimeEnvironment.getApplication()
context.sendStickyBroadcast(Intent(Intent.ACTION_BATTERY_CHANGED).apply {
putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_DISCHARGING)
putExtra(BatteryManager.EXTRA_LEVEL, 50)
putExtra(BatteryManager.EXTRA_SCALE, 100)
putExtra(BatteryManager.EXTRA_VOLTAGE, 4000)
})
shadowOf(context.getSystemService(BatteryManager::class.java)).apply {
setLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER, 4_000_000L)
setLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW, currentUa)
setLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE, currentUa)
}
battery = BatteryComponent(supplies, vpower).also { it.attach(context); it.start() }
}
private fun assertTelemetry(supplies: File, vpower: File) {
val discovered = supplies.listFiles()!!.filter { it.name.contains("BAT") }
assertEquals(listOf("BAT1"), discovered.map { it.name })
fun read(name: String) = File(discovered.single(), name).readText().trim().toLong()
// One 4 Ah battery at 4 V drawing 2 A: 8 W and two hours, regardless of vendor current sign.
assertEquals(8_000_000L, read("power_now"))
assertEquals(16_000_000L, read("energy_now"))
assertEquals(7200L, read("time_to_empty_now"))
assertEquals("7200", File(vpower, "secs_until_shutdown_request").readText().trim())
assertEquals("50.00", File(vpower, "battery_percent").readText().trim())
}
}
@@ -10,6 +10,34 @@ import org.junit.rules.TemporaryFolder
class SecondaryLibraryTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun directContentKeepsTheConfiguredLibrarysPrivateDirectories() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("shared")
val content = tmp.newFolder("direct")
val private = SecondaryLibrary.privateRoot(files, library)
val binds = SecondaryLibrary.binds(files, library, content)
assertTrue(binds.contains("${content.path}:/mnt/droiddeck-sd"))
assertTrue(binds.contains("$private/steamapps/compatdata:/mnt/droiddeck-sd/steamapps/compatdata"))
assertFalse(SecondaryLibrary.privateRoot(files, content).exists())
}
@Test fun aWritableAliasIsSelectedAndItsProbeIsRemoved() {
val library = tmp.newFolder("shared")
val candidate = File(tmp.root, "direct")
Files.createSymbolicLink(candidate.toPath(), library.toPath())
assertEquals(candidate, SecondaryLibrary.verifiedAlias(library, candidate))
assertTrue(library.listFiles()!!.isEmpty())
}
@Test fun anUnrelatedOrMissingDirectoryCannotReplaceTheLibrary() {
val library = tmp.newFolder("shared")
val candidate = tmp.newFolder("other")
assertEquals(library, SecondaryLibrary.verifiedAlias(library, candidate))
assertTrue(candidate.listFiles()!!.isEmpty())
assertTrue(library.listFiles()!!.isEmpty())
assertEquals(library, SecondaryLibrary.verifiedAlias(library, File(tmp.root, "missing")))
}
@Test fun gamesStaySharedButPrefixesAndNativeDownloadsArePrivate() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("card")
@@ -0,0 +1,90 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.content.res.Configuration
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.AppUiPrefs
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class AppScaleTest {
private val context get() = RuntimeEnvironment.getApplication()
@Before fun clearScale() {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun defaultsToSystemDensityAndCanRestoreItAfterChoosingAnotherScale() {
assertEquals(100, AppUiPrefs.scale(context))
AppUiPrefs.setScale(context, 75)
assertEquals(75, AppUiPrefs.scale(context))
AppUiPrefs.setScale(context, 100)
assertEquals(100, AppUiPrefs.scale(context))
val density = Density(2f, 1.3f)
val configuration = Configuration(context.resources.configuration)
assertSame(density, scaledAppDensity(density, 100))
assertSame(configuration, scaledAppConfiguration(configuration, 100))
}
@Test fun invalidStoredOrRequestedScaleFallsBackToTheDefault() {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("scale", 0).commit()
assertEquals(100, AppUiPrefs.scale(context))
AppUiPrefs.setScale(context, 1000)
assertEquals(100, AppUiPrefs.scale(context))
}
@Test fun scalingDoesNotModifySessionPreferencesOrAndroidDisplayMetrics() {
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
session.edit().putString("resolution.steam", "1280x720").putInt("upscaler", 2).commit()
val before = session.all.toMap()
val density = context.resources.displayMetrics.density
val configuration = Configuration(context.resources.configuration)
AppUiPrefs.setScale(context, 150)
scaledAppConfiguration(context.resources.configuration, AppUiPrefs.scale(context))
assertEquals(before, session.all)
assertEquals(density, context.resources.displayMetrics.density, 0f)
assertEquals(configuration, context.resources.configuration)
}
@Test fun textAndControlsScaleTogetherWhilePreservingAccessibilityFontScale() {
val base = Density(2f, 1.3f)
for (percent in AppUiPrefs.scales) {
val scaled = scaledAppDensity(base, percent)
assertEquals(1.3f, scaled.fontScale, 0f)
assertEquals(base.run { 44.dp.toPx() } * percent / 100f, scaled.run { 44.dp.toPx() }, 0.001f)
assertEquals(base.run { 16.sp.toPx() } * percent / 100f, scaled.run { 16.sp.toPx() }, 0.001f)
}
}
@Test fun responsiveWidthAndPopupHeightFitTheSamePhysicalWindowAtEveryScale() {
val base = Configuration().apply {
densityDpi = 320
screenWidthDp = 960
screenHeightDp = 540
smallestScreenWidthDp = 540
fontScale = 1.3f
orientation = Configuration.ORIENTATION_LANDSCAPE
}
for (percent in AppUiPrefs.scales) {
val scaled = scaledAppConfiguration(base, percent)
val density = scaledAppDensity(Density(2f, 1.3f), percent).density
assertEquals(1920f, scaled.screenWidthDp * density, 2f)
assertEquals(1080f, scaled.screenHeightDp * density, 2f)
assertEquals(1080f, scaled.smallestScreenWidthDp * density, 2f)
assertEquals(1.3f, scaled.fontScale, 0f)
assertEquals(base.orientation, scaled.orientation)
}
assertEquals(960, base.screenWidthDp)
assertEquals(540, base.screenHeightDp)
assertEquals(320, base.densityDpi)
}
}
+36 -12
View File
@@ -9,14 +9,15 @@
*
* It decides nothing proot would decide differently. The guest path is mapped literally - the
* longest binding whose guest path is a prefix, else the rootfs - and the parent directory is
* opened O_PATH and must come back from /proc/self/fd as exactly that host path, which proves no
* component on the way was a symlink: proot would then have walked the same directories. The
* last component is looked at without following it, and a symlink there goes to proot. So does
* "..", a trailing "/", anything under /proc, any flag not handled here and any failure to
* decide: the real libc call runs, proot traps it and answers as it always has.
* opened O_PATH and checked against /proc/self/fd. A case-only difference is accepted only on
* FUSE or FAT and only after each differently spelled component is verified as a directory rather than
* a symlink. The last component is looked at without following it; other symlinks go to proot.
* So do "..", a trailing "/", anything under /proc, any flag not handled here and any failure
* to decide: the real libc call runs, proot traps it and answers as it always has.
*
* Only syscalls Android's app seccomp policy allows are used (openat, newfstatat, statx,
* faccessat, readlinkat, close) - not openat2 or faccessat2, which it answers with SIGSYS.
* faccessat, fstatfs, readlinkat, close) - not openat2 or faccessat2, which it answers with
* SIGSYS.
*
* Verified parents are remembered for PROOT_FP_TTL_MS (default 2000; 0 = verify every call): a
* parent directory replaced by a symlink within that window would be missed, the same trade the
@@ -33,6 +34,7 @@
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/magic.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
@@ -43,6 +45,8 @@
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/vfs.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
@@ -250,10 +254,28 @@ static long canonical_dir(const char *dir) {
char link[40], out[PATH_MAX];
snprintf(link, sizeof link, "/proc/self/fd/%ld", fd);
long n = sc(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0);
sc(SYS_close, fd, 0, 0, 0, 0);
if (n <= 0) return 0;
if (n <= 0) { sc(SYS_close, fd, 0, 0, 0, 0); return 0; }
out[n] = 0;
if (strcmp(out, dir) != 0) return 0;
if (strcmp(out, dir) != 0) {
struct statfs fs;
int case_alias = sc(SYS_fstatfs, fd, (long)&fs, 0, 0, 0) == 0 &&
(fs.f_type == FUSE_SUPER_MAGIC || fs.f_type == EXFAT_SUPER_MAGIC || fs.f_type == MSDOS_SUPER_MAGIC);
sc(SYS_close, fd, 0, 0, 0, 0);
if (!case_alias || strcasecmp(out, dir) != 0) return 0;
/* FUSE and FAT case aliases return the stored spelling from /proc/self/fd. Prove the final
* component and each parent so a case-only symlink path still goes to proot. */
struct stat st;
if (sc(SYS_newfstatat, AT_FDCWD, (long)dir, (long)&st, AT_SYMLINK_NOFOLLOW, 0) != 0 ||
!S_ISDIR(st.st_mode)) return 0;
char parent[PATH_MAX];
snprintf(parent, sizeof parent, "%s", dir);
char *slash = strrchr(parent, '/');
if (!slash || slash == parent) return 0;
*slash = 0;
if (canonical_dir(parent) != 1) return 0;
} else {
sc(SYS_close, fd, 0, 0, 0, 0);
}
remember(dir, h);
return 1;
}
@@ -474,14 +496,16 @@ static int access_common(int dirfd, const char *path, int mode, int flags) {
REAL(faccessat, int (*)(int, const char *, int, int));
char host[PATH_MAX];
struct stat st;
/* faccessat(2) has no flags: AT_EACCESS and AT_SYMLINK_NOFOLLOW stay with glibc and proot. */
long rs = flags == 0 ? resolve(dirfd, path, host) : FP_SLOW;
/* F_OK with AT_SYMLINK_NOFOLLOW asks only whether the last directory entry exists. */
int nofollow_exists = mode == F_OK && flags == AT_SYMLINK_NOFOLLOW;
long rs = flags == 0 || nofollow_exists ? resolve(dirfd, path, host) : FP_SLOW;
if (rs == -ENOENT) { hits++; return ret(rs); }
if (rs == 0) {
long k = kind(host, &st);
if (k != 1) {
if (k != 1 || nofollow_exists) {
hits++;
if (k < 0) return ret(k);
if (nofollow_exists) return 0;
return ret(sc(SYS_faccessat, AT_FDCWD, (long)host, mode, 0, 0));
}
}