feat(onboarding): background first-run downloads, one setup card, no wait for Steam (#3091)

* feat(onboarding): one setup card, Steam client and Proton downloaded in the background, no component toast

* feat(onboarding): an optional Bluetooth controllers row in the setup card asks for the permission up front

* feat(onboarding): prefetch Steam's whole package cache, one foreground notification, child-process setup while downloads run

* test(steam): the cache pass keeps packages under Steam's names and is not repeated

* feat(onboarding): unpack the whole Steam client ahead of time and record it as installed, downloads no longer wait for a cool device

* feat(onboarding): setup progress on the Steam home page, Bluetooth asked only from the setup card, Steam unpacks its own files

* fix(onboarding): review fixes: removal does not report setup progress, cancel stops the whole prefetch, cache files are verified, no resume toast

* fix(onboarding): a cancelled prefetch is never a setup failure

* fix(onboarding): the Steam fact is updated atomically

* feat(onboarding): Bluetooth controllers moves into the Steam integration list
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-23 17:31:24 -05:00
1 parent 15b1e196af
commit 59e98afae7
22 files changed
+590 -37

No files matched your search

@@ -21,6 +21,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
checkAgain = null
checkComponentUpdates(again)
}
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; "))
refreshComponents()
}
}, "component-updates").start()
@@ -254,6 +254,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
refreshWifiDiscovery()
}
private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (!granted && !shouldShowRequestPermissionRationale(android.Manifest.permission.BLUETOOTH_CONNECT)) {
integrationSettings(SteamIntegration.appInfo(this))
}
integrationState = readIntegration()
}
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this)
}
@@ -375,6 +381,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SteamIntegration.Feature.SHORTCUTS -> {
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
}
SteamIntegration.Feature.BLUETOOTH -> {
if (SteamIntegration.bluetoothAllowed(this)) integrationSettings(SteamIntegration.appInfo(this))
else bluetoothPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT)
}
}
}
@@ -2166,9 +2176,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!OfflineMode.enabled(this)) {
val updated = runCatching { ComponentUpdater.ensure(this, force = false) }
.onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList())
if (updated.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
}
if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; "))
}
ui.post {
componentsQueueBusy = false
@@ -3209,6 +3217,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
ui.post { autoUpdateRuntime() }
Thread({ com.droiddeck.launcher.session.Onboarding.recheck(this) }, "onboarding-recheck").start()
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
@@ -3430,18 +3439,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun install(release: LinuxRuntimeInstaller.Release) {
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
}
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
private fun followRuntimeOperation(onboarding: Boolean = false, run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
busy = true
failed = false
stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
percent = -1
Thread({
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
if (onboarding) com.droiddeck.launcher.session.Onboarding.report(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, s, p)
ui.post { stage = s; percent = p }
})
if (onboarding) {
if (ok == false) com.droiddeck.launcher.session.Onboarding.fail(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, LinuxRuntimeInstaller.removalError() ?: "")
else com.droiddeck.launcher.session.Onboarding.finish(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME)
}
com.droiddeck.launcher.session.Onboarding.recheck(this)
ui.post {
busy = false
if (ok != null) failed = !ok
@@ -3450,7 +3465,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
refresh()
com.droiddeck.launcher.agent.AgentHost.refresh(this)
if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() }
}
}, "runtime-operation").start()
}
@@ -3461,9 +3476,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
if (release.version == installed) return
if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) ||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(this))) return
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself")
if (installed == null) protons.prefetchOwn()
install(release)
}
}
@@ -8,7 +8,9 @@ import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.Onboarding
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.SteamClientPrefetch
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionPhase
@@ -60,10 +62,15 @@ internal class ProtonMenu(
Thread({
val problem = runCatching {
installer(tool) { label, value ->
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
ui.post { protonStage = label; protonPercent = value }
}
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
if (tool.id == ProtonExtras.OWN) {
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
}
ui.post {
protonProblem = problem
protonBusyId = null
@@ -170,16 +177,46 @@ internal class ProtonMenu(
Operation.checking.set(false)
}
ensureAutoUpdates()
ensureSteamClient()
}
if (!published) Operation.checking.set(false)
}, "proton-updates").start()
}
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
fun prefetchOwn() {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
Thread({
val problem = runCatching {
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
ui.post { ensureAutoUpdates() }
}, "proton-prefetch").start()
}
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
fun ensureSteamClient() {
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
SteamClientPrefetch.start(
activity,
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
activity.getString(R.string.onboarding_steam_failed),
)
}
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN
protonProblem = null
@@ -936,11 +936,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
!SessionPrefs.bluetoothAsked(this)) {
SessionPrefs.setBluetoothAsked(this)
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
}
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
@Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
@@ -16,7 +16,7 @@ object SteamIntegration {
const val EXTRA_FEATURE = "integration_feature"
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
private const val SHORTCUTS_ASSET = "shortcuts.apk"
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH }
data class State(
val wifi: Boolean = false,
@@ -28,6 +28,7 @@ object SteamIntegration {
val shortcuts: Boolean = false,
val shortcutsRestricted: Boolean = false,
val shortcutsTried: Boolean = false,
val bluetooth: Boolean = false,
val suggested: Boolean = true,
)
@@ -39,9 +40,16 @@ object SteamIntegration {
home = HomeApp.isDefault(context),
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
shortcutsRestricted = restrictedSettings(context),
bluetooth = bluetoothAllowed(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
fun bluetoothAllowed(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching {
@@ -47,6 +47,7 @@ object AutoComponents {
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
@VisibleForTesting @Volatile internal var runNow = false
@@ -533,6 +534,10 @@ object AutoComponents {
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
fun powerSaveOrMetered(context: Context): Boolean =
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
fun constrained(context: Context): Boolean {
val power = context.getSystemService(PowerManager::class.java)
if (power?.isPowerSaveMode == true) return true
@@ -0,0 +1,102 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.runtime.RuntimeInstallService
import kotlinx.coroutines.flow.MutableStateFlow
/** What first run installs by itself, in the order it is needed, and how far each part has got. */
object Onboarding {
enum class Step { RUNTIME, PROTON, STEAM }
data class Progress(val label: String, val percent: Int)
data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true)
enum class State { DONE, ACTIVE, WAITING, FAILED }
data class Row(val step: Step, val state: State, val label: String?, val percent: Int)
val active = MutableStateFlow<Map<Step, Progress>>(emptyMap())
val failed = MutableStateFlow<Map<Step, String>>(emptyMap())
val facts = MutableStateFlow(Facts())
@Volatile private var appContext: Context? = null
private var hold: (() -> Unit)? = null
fun attach(context: Context) {
appContext = context.applicationContext
}
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
@Synchronized private fun keepAlive() {
val context = appContext ?: return
val running = active.value
if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) {
if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title))
val rows = rows(running, failed.value, facts.value)
RuntimeInstallService.packageProgress(running.values.first().label, overall(rows))
} else {
hold?.invoke()
hold = null
}
}
@Synchronized fun recheck(context: Context) {
val runtime = LinuxRuntime.isInstalled(context)
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
facts.value = Facts(
runtime = runtime,
proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(),
steam = runtime && !SteamClientPrefetch.pending(context),
)
}
fun report(step: Step, label: String, percent: Int) {
failed.value = failed.value - step
active.value = active.value + (step to Progress(label, percent))
keepAlive()
}
fun finish(step: Step) {
active.value = active.value - step
failed.value = failed.value - step
keepAlive()
}
fun fail(step: Step, message: String) {
active.value = active.value - step
failed.value = failed.value + (step to message)
keepAlive()
}
fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step ->
val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam }
val progress = active[step]
when {
progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent)
failed[step] != null -> Row(step, State.FAILED, failed[step], -1)
ready -> Row(step, State.DONE, null, 100)
else -> Row(step, State.WAITING, null, -1)
}
}
fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE }
/** The aggregate fraction of the whole first-run work, weighting each step by what it downloads. */
fun overall(rows: List<Row>): Int {
val weights = mapOf(Step.RUNTIME to 60, Step.PROTON to 15, Step.STEAM to 25)
val total = weights.values.sum()
val got = rows.sumOf { row ->
val w = weights.getValue(row.step)
when (row.state) {
State.DONE -> w
State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0
else -> 0
}
}
return got * 100 / total
}
}
@@ -23,6 +23,7 @@ object ProtonExtras {
const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile
var installInProgress = false
@Volatile var prefetching = false
private set
@Volatile
private var replacing = false
@@ -217,24 +218,12 @@ object ProtonExtras {
@Synchronized
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress) return context.getString(R.string.pextra_busy)
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
installInProgress = true
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
}
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
return context.getString(R.string.pextra_no_space, tool.name)
}
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
onProgress(downloading, 0)
var downloaded = false
@@ -252,6 +241,41 @@ object ProtonExtras {
}
}
if (!downloaded) return context.getString(R.string.pextra_download_failed)
return null
}
/** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */
@Synchronized
fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress) return context.getString(R.string.pextra_busy)
prefetching = true
try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false }
}
private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name)
return fetchArchive(context, tool, asset, archive, onProgress)
}
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
return context.getString(R.string.pextra_no_space, tool.name)
}
fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
if (asset.size > 0 && archive.length() != asset.size) {
if (archive.length() > asset.size) {
archive.delete()
@@ -95,7 +95,11 @@ object SessionFiles {
return all
}
fun stage(context: Context, root: File, startsSession: Boolean = false) {
private val STAGE_LOCK = Any()
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
GameEnvironmentStore.publish(context)
@@ -2705,6 +2705,7 @@ class SessionService : Service() {
gameId: String? = null,
displayId: Int = Display.DEFAULT_DISPLAY,
) {
SteamClientPrefetch.cancel()
SessionState.activityDisplayId = displayId
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
.putExtra(EXTRA_DISPLAY_ID, displayId)
@@ -0,0 +1,104 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import kotlinx.coroutines.flow.update
/**
* Downloads Valve's Steam client while the session is stopped, so the first Play does not wait on it.
* It runs the same droiddeck-steam-install the session runs, which keeps what arrived when it is cut
* short and resumes from there.
*/
object SteamClientPrefetch {
private const val TAG = "SteamClientPrefetch"
private val DOWNLOADING = Regex("""downloading Steam: .*, (\d+) of (\d+) MB""")
private const val CANCELLED = "cancelled"
private val lock = Any()
private var process: Process? = null
private var cancelled = false
@Volatile private var thread: Thread? = null
internal fun parse(line: String): Pair<Int, Int>? {
val match = DOWNLOADING.find(line) ?: return null
val done = match.groupValues[1].toLongOrNull() ?: return null
val total = match.groupValues[2].toLongOrNull()?.takeIf { it > 0 } ?: return null
return (done * 100 / total).toInt().coerceIn(0, 100) to total.toInt()
}
fun running(): Boolean = thread?.isAlive == true
private const val CACHED = "root/.local/share/Steam/package/droiddeck-cached"
fun installPending(context: Context): Boolean = SteamDownloadMonitor.clientInstallPending(LinuxRuntime.rootDir(context))
fun pending(context: Context): Boolean =
installPending(context) || !File(LinuxRuntime.rootDir(context), CACHED).isFile
/** Stops a running download so a session can take over; the script resumes the partial files. */
fun cancel() {
synchronized(lock) {
cancelled = true
process?.destroy()
}
}
private fun isCancelled() = synchronized(lock) { cancelled }
@Synchronized
fun start(context: Context, label: (Int) -> String, failedLabel: String) {
if (running() || SessionState.running || !LinuxRuntime.isInstalled(context) || !pending(context)) return
val app = context.applicationContext
synchronized(lock) { cancelled = false }
thread = Thread({
Onboarding.report(Onboarding.Step.STEAM, label(-1), -1)
val problem = runCatching { run(app, label) }.getOrElse { it.message ?: it.javaClass.simpleName }
synchronized(lock) { process = null }
if (problem == null && !pending(app)) Onboarding.finish(Onboarding.Step.STEAM)
else if (SessionState.running || problem == CANCELLED || isCancelled()) Onboarding.finish(Onboarding.Step.STEAM)
else Onboarding.fail(Onboarding.Step.STEAM, problem ?: failedLabel)
val steamReady = !pending(app)
Onboarding.facts.update { it.copy(steam = steamReady) }
}, "steam-client-prefetch").also { it.start() }
}
private fun run(context: Context, label: (Int) -> String): String? {
if (isCancelled()) return CANCELLED
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, root)
val install = installPending(context)
if (install) {
val problem = script(context, emptyList(), label, 0, 35)
if (problem != null) return problem
}
return script(context, listOf("--cache"), label, if (install) 35 else 0, 100)
}
private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? {
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share", "/usr/local/bin/droiddeck-steam-install",
) + args
if (isCancelled()) return CANCELLED
val child = ProtonExtras.guestProcess(context, guest).start()
synchronized(lock) {
if (cancelled) {
child.destroy()
return CANCELLED
}
process = child
}
child.inputStream.bufferedReader().useLines { lines ->
lines.forEach { line ->
Log.i(TAG, line)
val progress = parse(line)
if (progress != null) Onboarding.report(Onboarding.Step.STEAM, label(progress.second), from + progress.first * (to - from) / 100)
}
}
val status = child.waitFor()
return if (status == 0) null else "droiddeck-steam-install exited $status"
}
}
@@ -51,6 +51,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -248,6 +249,7 @@ internal fun SetupPanel(
if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) }
else when (tab) {
OVERVIEW_TAB -> {
OnboardingCard(limitBlocks, a.onShowPhantomGate)
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
@@ -1273,3 +1275,65 @@ private fun CustomColorRows() {
}
}
}
@Composable
internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Unit = {}) {
val active by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
val failed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
val facts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
val rows = com.droiddeck.launcher.session.Onboarding.rows(active, failed, facts)
val settling = com.droiddeck.launcher.session.Onboarding.pending(rows)
if (!settling) return
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val overall = com.droiddeck.launcher.session.Onboarding.overall(rows)
Column(Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 12.dp)) {
Text(stringResource(R.string.onboarding_title), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(stringResource(R.string.onboarding_summary, overall), fontSize = 13.sp, color = colors.onSurfaceVariant)
LinearProgressIndicator(progress = { overall / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(4.dp))
}
rows.forEach { row ->
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(
stringResource(when (row.step) {
com.droiddeck.launcher.session.Onboarding.Step.RUNTIME -> R.string.onboarding_step_runtime
com.droiddeck.launcher.session.Onboarding.Step.PROTON -> R.string.onboarding_step_proton
com.droiddeck.launcher.session.Onboarding.Step.STEAM -> R.string.onboarding_step_steam
}),
fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
)
val detail = when (row.state) {
com.droiddeck.launcher.session.Onboarding.State.ACTIVE -> row.label.orEmpty()
com.droiddeck.launcher.session.Onboarding.State.FAILED -> stringResource(R.string.onboarding_failed)
com.droiddeck.launcher.session.Onboarding.State.WAITING -> stringResource(R.string.onboarding_waiting)
com.droiddeck.launcher.session.Onboarding.State.DONE -> stringResource(R.string.onboarding_done)
}
Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (row.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE) {
if (row.percent >= 0) LinearProgressIndicator(progress = { row.percent / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
}
}
}
}
if (limitBlocks) {
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.setup_limit), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(stringResource(R.string.onboarding_limit_reason), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
PrimaryButton(stringResource(R.string.onboarding_limit_action), compact = true, onClick = onSetUpLimit)
}
}
}
}
@@ -31,6 +31,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
@@ -154,8 +155,24 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
words = {
val runtimeStatus: @Composable () -> Unit = {
if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s)
else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
val onboardingFacts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
val onboardingRows = com.droiddeck.launcher.session.Onboarding.rows(onboardingActive, onboardingFailed, onboardingFacts)
val settling = onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows)
if (settling || s.busy || (s.available != null && s.available != s.installed)) {
if (settling) {
val overall = com.droiddeck.launcher.session.Onboarding.overall(onboardingRows)
Chip(
stringResource(R.string.onboarding_chip, overall, onboardingRows.firstOrNull { it.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE }?.label.orEmpty()),
ok = false, fraction = overall / 100f,
)
} else RuntimeChip(s)
if (com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) {
SecondaryButton(stringResource(R.string.onboarding_limit_while_waiting), compact = true,
modifier = Modifier.testTag("setup-while-waiting"), onClick = a.onShowPhantomGate)
}
} else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
modifier = Modifier.testTag("play-needs-you")) { SetupTabs.openSection = SettingsSection.OVERVIEW }
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
@@ -23,6 +23,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Bluetooth
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.KeyboardCommandKey
import androidx.compose.material.icons.outlined.LightMode
@@ -61,6 +62,7 @@ internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) {
Feature.BRIGHTNESS -> brightness
Feature.HOME -> home
Feature.SHORTCUTS -> shortcuts
Feature.BLUETOOTH -> bluetooth
}
internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) }
@@ -116,6 +118,7 @@ private fun IntegrationRow(
feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint
feature == Feature.BRIGHTNESS -> R.string.integration_brightness_hint
feature == Feature.HOME -> R.string.integration_home_hint
feature == Feature.BLUETOOTH -> R.string.integration_bluetooth_hint
else -> R.string.integration_shortcuts_hint
})
Row(
@@ -164,6 +167,7 @@ private fun featureIcon(feature: Feature) = when (feature) {
Feature.BRIGHTNESS -> Icons.Outlined.LightMode
Feature.HOME -> Icons.Outlined.Home
Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey
Feature.BLUETOOTH -> Icons.Outlined.Bluetooth
}
private fun featureTitle(feature: Feature) = when (feature) {
@@ -171,6 +175,7 @@ private fun featureTitle(feature: Feature) = when (feature) {
Feature.BRIGHTNESS -> R.string.integration_brightness
Feature.HOME -> R.string.integration_home
Feature.SHORTCUTS -> R.string.integration_shortcuts
Feature.BLUETOOTH -> R.string.integration_bluetooth
}
@Composable
+18 -1
View File
@@ -36,7 +36,7 @@
<string name="wall_settings_match" translatable="false">Match screen</string>
<string name="wall_settings_speed" translatable="false">Scroll speed</string>
<string-array name="loading_hints">
<item>First run downloads Steam. This may take a few minutes.</item>
<item>DroidDeck downloads Steam in the background while you set up, so your first launch is quicker.</item>
<item>Your controller shows up to Steam as a Steam Deck controller. Switch it to a Steam Controller, DualShock 4, DualSense or Xbox 360 pad in the session settings; it applies next session.</item>
<item>Hold Back on your controller to open Steam\'s Quick Access menu. Hold Back for Steam shortcuts must be on in the session settings.</item>
<item>Background behavior decides what happens when you leave the app: Native readies Steam for sleep, Auto pauses it, Manual waits for Resume, Never keeps it running.</item>
@@ -4152,6 +4152,8 @@
<string name="integration_wifi_denied">Location denied · allow it in App info</string>
<string name="integration_brightness_hint">Steam’s slider sets screen brightness</string>
<string name="integration_home_hint">Home opens the Steam menu in a session</string>
<string name="integration_bluetooth">Bluetooth controllers</string>
<string name="integration_bluetooth_hint">Lets DroidDeck connect to Steam Controllers and other Bluetooth pads</string>
<string name="integration_shortcuts_hint">Alt+Tab, Win key and Home button stay in the session</string>
<string name="integration_shortcuts_maybe_restricted">Greyed out in Android? App info → ⋮ → Allow restricted settings</string>
<string name="integration_shortcuts_install_failed">System keys didn\'t install</string>
@@ -4399,4 +4401,19 @@
<string name="tabs_reset_title">Reset tabs</string>
<string name="tabs_reset_hint">Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More.</string>
<string name="tabs_reset_body">Your tab order and what sits under More or is hidden go back to the defaults.</string>
<string name="onboarding_title">Getting DroidDeck ready</string>
<string name="onboarding_summary">%1$d%% · you can keep using the app</string>
<string name="onboarding_step_runtime">Linux runtime</string>
<string name="onboarding_step_proton">DroidDeck Proton</string>
<string name="onboarding_step_steam">Steam client</string>
<string name="onboarding_waiting">Waiting</string>
<string name="onboarding_done">Ready</string>
<string name="onboarding_failed">Will retry</string>
<string name="onboarding_steam_downloading">Downloading the Steam client</string>
<string name="onboarding_steam_downloading_mb">Downloading the Steam client (%1$d MB)</string>
<string name="onboarding_steam_failed">The Steam client download will retry</string>
<string name="onboarding_limit_reason">Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish.</string>
<string name="onboarding_limit_action">Do it for me</string>
<string name="onboarding_limit_while_waiting">Set up while you wait</string>
<string name="onboarding_chip">Getting ready · %1$d%% · %2$s</string>
</resources>
@@ -35,6 +35,7 @@ import java.util.concurrent.atomic.AtomicInteger
class ProtonMenuAutoTest {
private val online = AutoComponents.online
private val constrained = AutoComponents.unfavourable
private val firstRunHeldBack = AutoComponents.firstRunHeldBack
private lateinit var activity: Activity
private lateinit var menu: ProtonMenu
private lateinit var root: File
@@ -49,6 +50,7 @@ class ProtonMenuAutoTest {
}
AutoComponents.online = { true }
AutoComponents.unfavourable = { false }
AutoComponents.firstRunHeldBack = { false }
SessionState.running = false
SessionState.phase = SessionPhase.IDLE
SessionState.stopRequested = false
@@ -77,6 +79,7 @@ class ProtonMenuAutoTest {
menu.protonPercent = -1
AutoComponents.online = online
AutoComponents.unfavourable = constrained
AutoComponents.firstRunHeldBack = firstRunHeldBack
SessionState.running = false
SessionState.phase = SessionPhase.IDLE
SessionState.stopRequested = false
@@ -0,0 +1,44 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.session.Onboarding.Facts
import com.droiddeck.launcher.session.Onboarding.Progress
import com.droiddeck.launcher.session.Onboarding.State
import com.droiddeck.launcher.session.Onboarding.Step
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class OnboardingTest {
private val none = Facts(runtime = false, proton = false, steam = false)
@Test fun everythingReadyShowsNothing() {
val rows = Onboarding.rows(emptyMap(), emptyMap(), Facts())
assertFalse(Onboarding.pending(rows))
assertEquals(100, Onboarding.overall(rows))
}
@Test fun stepsAreActiveFailedOrWaiting() {
val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), mapOf(Step.PROTON to "no"), none)
assertEquals(listOf(State.ACTIVE, State.FAILED, State.WAITING), rows.map { it.state })
assertTrue(Onboarding.pending(rows))
}
@Test fun anActiveStepStaysActiveWhenItsFactIsAlreadyTrue() {
val rows = Onboarding.rows(mapOf(Step.STEAM to Progress("x", -1)), emptyMap(), Facts())
assertEquals(State.ACTIVE, rows.first { it.step == Step.STEAM }.state)
}
@Test fun overallWeighsDownloadsBySize() {
val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), emptyMap(), Facts(runtime = false))
assertEquals(30 + 15 + 25, Onboarding.overall(rows))
}
@Test fun reportingClearsAPriorFailure() {
Onboarding.fail(Step.STEAM, "boom")
Onboarding.report(Step.STEAM, "again", 3)
assertTrue(Onboarding.failed.value[Step.STEAM] == null)
Onboarding.finish(Step.STEAM)
assertTrue(Onboarding.active.value[Step.STEAM] == null)
}
}
@@ -0,0 +1,22 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SteamClientPrefetchTest {
@Test fun readsPercentAndTotalFromTheInstallersStepLine() {
val line = "== STEP 14:21:07 downloading Steam: bins_linuxarm64.zip (2/5), 120 of 480 MB"
assertEquals(25 to 480, SteamClientPrefetch.parse(line))
}
@Test fun aRetryNoteDoesNotChangeTheReading() {
val line = "== STEP 14:21:07 downloading Steam: x.zip (1/3), 10 of 40 MB - retrying in 5s"
assertEquals(25 to 40, SteamClientPrefetch.parse(line))
}
@Test fun otherLinesAreIgnored() {
assertNull(SteamClientPrefetch.parse("== STEP 14:21:07 the Steam client now follows steamdeck_stable"))
assertNull(SteamClientPrefetch.parse("downloading Steam: x (1/1), 5 of 0 MB"))
}
}
@@ -41,7 +41,8 @@ class SteamIntegrationGroupTest {
compose.onNodeWithTag("integration-action-brightness").performClick()
compose.onNodeWithTag("integration-action-home").performClick()
compose.onNodeWithTag("integration-action-shortcuts").performClick()
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests)
compose.onNodeWithTag("integration-action-bluetooth").performClick()
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS, Feature.BLUETOOTH), requests)
}
@Test fun switchesReflectAndroidGrants() {
@@ -50,7 +51,8 @@ class SteamIntegrationGroupTest {
compose.onNodeWithTag("integration-action-brightness").assert(stateIs("On"))
compose.onNodeWithTag("integration-action-shortcuts").assert(stateIs("On"))
compose.onNodeWithTag("integration-action-wifi").assert(stateIs("Off"))
compose.onNodeWithText("3 of 4 on").assertExists()
compose.onNodeWithTag("integration-action-bluetooth").assert(stateIs("Off"))
compose.onNodeWithText("3 of 5 on").assertExists()
}
@Test fun shortcutsDoNotNeedHome() {