diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index be2deadbed..58e7e12b2c 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt index e5e74f791f..79e2017962 100644 --- a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt @@ -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() diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index af3eddf8e7..9497fe0a68 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -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) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt index aaaa2cf34f..bb12dd31af 100644 --- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index a209bac123..dc0559251b 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt index cd10300f4f..f284c98d36 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt @@ -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 { diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt index d6fe58ad7f..4da77ee6d7 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt new file mode 100644 index 0000000000..5a3fb555dd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt @@ -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>(emptyMap()) + val failed = MutableStateFlow>(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, failed: Map, facts: Facts): List = 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): 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): 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 + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index 0d0e20c41d..f5a01d984d 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -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() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 1645851229..9ec5f5cba4 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 15d2844d34..144fad8894 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt new file mode 100644 index 0000000000..fecdc8e0b8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt @@ -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? { + 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, 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" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 70c49a5518..c99bee629d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -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) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index f9c81f4e42..2d995dda2f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt index 2827e3c7cd..e7b6a09b19 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt @@ -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 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1b57e5b281..44bdf9c825 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -36,7 +36,7 @@ Match screen Scroll speed - First run downloads Steam. This may take a few minutes. + DroidDeck downloads Steam in the background while you set up, so your first launch is quicker. 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. Hold Back on your controller to open Steam\'s Quick Access menu. Hold Back for Steam shortcuts must be on in the session settings. 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. @@ -4152,6 +4152,8 @@ Location denied · allow it in App info Steam’s slider sets screen brightness Home opens the Steam menu in a session + Bluetooth controllers + Lets DroidDeck connect to Steam Controllers and other Bluetooth pads Alt+Tab, Win key and Home button stay in the session Greyed out in Android? App info → ⋮ → Allow restricted settings System keys didn\'t install @@ -4399,4 +4401,19 @@ Reset tabs Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More. Your tab order and what sits under More or is hidden go back to the defaults. + Getting DroidDeck ready + %1$d%% · you can keep using the app + Linux runtime + DroidDeck Proton + Steam client + Waiting + Ready + Will retry + Downloading the Steam client + Downloading the Steam client (%1$d MB) + The Steam client download will retry + Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish. + Do it for me + Set up while you wait + Getting ready · %1$d%% · %2$s diff --git a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt index 2e06a6d8fe..4ea0a52d7f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt @@ -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 diff --git a/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt new file mode 100644 index 0000000000..dc2b0b5e10 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt @@ -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) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt new file mode 100644 index 0000000000..7b73b81e91 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt @@ -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")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt index 807b729f6d..76be29b5da 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt @@ -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() { diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index c58790f87a..642cc7a836 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -65,12 +65,14 @@ if [ -n "$repair" ]; then [ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part" done fi +cache_only= +[ "${1:-}" = --cache ] && cache_only=1 sync= if [ "${1:-}" = --sync ]; then case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac manifest=steam_client_${sync}_linuxarm64 fi -[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0 +[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0 work=$(mktemp -d) trap 'rm -rf "$work"' EXIT @@ -167,6 +169,46 @@ if ! fetch_manifest; then fallback=1 fetch_manifest || exit 1 fi +if [ -n "$cache_only" ]; then + cache=$steam_root/package + cached=$cache/droiddeck-cached + [ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0 + awk -F'"' ' + /^\t"/ && NF >= 3 && $4 == "" { block = $2 } + $2 == "file" { file[block] = $4 } + $2 == "sha2" { sha[block] = $4 } + $2 == "size" { size[block] = $4 } + $2 == "zipvz" { vz[block] = $4 } + $2 == "sha2vz" { vzsha[block] = $4 } + END { + for (b in file) { + f = file[b]; h = sha[b]; n = size[b] + 0 + if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 } + print b, f, h, n + } + } + ' "$work/manifest" | sort > "$work/cache" + mkdir -p "$cache" + total=$(grep -c . "$work/cache" 2>/dev/null || echo 0) + total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache") + done_bytes=0 + i=0 + while read -r block file sum size; do + i=$((i + 1)) + progress "$cache/$file" "$block" + fetched="" + for host in "${cdn_order[@]}"; do + if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then + fetched=$host + break + fi + done + [ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; } + done_bytes=$((done_bytes + size)) + done < "$work/cache" + echo "$version" > "$cached" + exit 0 +fi if [ -n "$sync" ]; then installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true) if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index f888b7ed13..4af6d09dd1 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -314,6 +314,46 @@ done(28 if end < len(data) else 0) def download(self): return self.steam / 'package/droiddeck-download' + def cache_manifest(self): + plain = b'plain-package' + packed = b'packed-package' + (self.cdn / 'a.zip.1111').write_bytes(plain) + (self.cdn / 'b.zip.vz.2222_14').write_bytes(packed) + (self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text( + '"linuxarm64"\n{\n\t"version" "123456"\n' + '\t"a_all"\n\t{\n' + f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(plain)}"\n\t\t"sha2" "{hashlib.sha256(plain).hexdigest()}"\n' + '\t}\n' + '\t"b_all"\n\t{\n' + '\t\t"file" "b.zip.9999"\n\t\t"size" "99"\n\t\t"sha2" "00"\n' + '\t\t"zipvz" "b.zip.vz.2222_14"\n' + f'\t\t"sha2vz" "{hashlib.sha256(packed).hexdigest()}"\n' + '\t}\n}\n') + + def test_the_cache_pass_keeps_every_package_under_the_names_steam_looks_for(self): + self.cache_manifest() + result = self.install(None, '--cache') + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes()) + self.assertEqual(b'packed-package', (package / 'b.zip.vz.2222_14').read_bytes()) + self.assertFalse((package / 'b.zip.9999').exists()) + self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + + def test_the_cache_pass_is_not_repeated_for_the_same_client_version(self): + self.cache_manifest() + self.assertEqual(0, self.install(None, '--cache').returncode) + requests = len(self.requests.read_text().splitlines()) + self.assertEqual(0, self.install(None, '--cache').returncode) + self.assertEqual(requests + 1, len(self.requests.read_text().splitlines())) + + def test_a_cached_package_is_not_fetched_again(self): + self.cache_manifest() + (self.steam / 'package').mkdir(parents=True) + (self.steam / 'package/a.zip.1111').write_bytes(b'plain-package') + self.assertEqual(0, self.install(None, '--cache').returncode) + self.assertNotIn('a.zip.1111', self.requests.read_text()) + def test_progress_is_counted_in_megabytes_across_parts(self): self.two_parts() result = self.install()