Compare commits

...
Author SHA1 Message Date
The412Banner ae570cd5b7 Components drawer: stacked rows so long names never squeeze the text, a focusable Running now card the pad can reach, and only the Proton a game actually runs on counts as running 2026-09-26 05:30:02 -04:00
The412Banner 0fd1dc4fce Proton wrappers: run the components check for non-Steam shortcuts too - decide by the game's own prefix rather than the app id, which is 0 for a shortcut 2026-09-26 05:15:36 -04:00
The412Banner f0854e8518 Merge org main into feat/components-manager 2026-09-26 04:41:10 -04:00
The412Banner ceffd3f759 Merge org main into feat/components-manager
Keeps both onResume additions: the phantom status refresh from main and the queued component swaps.
2026-09-26 04:36:02 -04:00
Kurt Himebauch dc1816612c Merge pull request #28 from Droid-Deck/fix/session-desktop-button-label
Keep the session Desktop button on one line
2026-09-26 00:53:17 -04:00
xXJsonDeruloXx 1d04a7e0e3 Keep session desktop button label on one line 2026-09-26 00:52:53 -04:00
Kurt Himebauch 1e523c4e93 Merge pull request #27 from Droid-Deck/fix/boot-video-pitch-black
Set boot movie background to pitch black
2026-09-26 00:36:22 -04:00
xXJsonDeruloXx d83f766cf3 Set boot movie background to pitch black 2026-09-26 00:35:54 -04:00
The412Banner bb5e1ae63d Proton wrappers: run the components check only for a real game launch (waitforexitandrun, non-zero app id)
With the check reached from the client's own runs right after login, the Steam client segfaulted
within seconds, four sessions out of four; the same build without the check (test/bisect-no-launch-check)
and the last build before it both reach Big Picture. Now every run that is not a game launch -
the client's probes, app id 0 - is left exactly as before. Each check logs one line.
2026-09-26 00:28:49 -04:00
Kurt Himebauch f27a4f6c95 Merge pull request #26 from Droid-Deck/ui/build-info-top-bar
Show build identity in the launcher top bar
2026-09-26 00:24:39 -04:00
The412Banner d7ff92106a Remove a stray __pycache__ from the overlay scripts and ignore it 2026-09-26 00:20:41 -04:00
xXJsonDeruloXx 34a17acaba Show build identity in launcher top bar 2026-09-26 00:03:56 -04:00
The412Banner 110aec0b6f Proton wrappers: drop the per-tool prefix for Steam's tool-0 runs - the client segfaulted right after its probe started (first in 25 sessions); keep the launch-time component check 2026-09-26 00:03:45 -04:00
The412Banner 06502bb49b Components: choices enforced at every game launch; Steam's tool-0 probes get their own prefix per Proton
Steam runs its graphics probe through every registered Proton at once after login, all in
compatdata/0. Prefix system32 links point into the Proton that set it up last, and the other
Protons' Wines, running outside Proton's pfx.lock, wrote their builtin DLLs through them into that
Proton's tree (device: GE's FEX DLLs became Proton Experimental's at session start).

- bannerlator-steam-compat: both wrappers (Valve's depot launcher and the third-party
  bannerlator-proton-wrap) give a tool-0 run STEAM_COMPAT_DATA_PATH=.../compatdata/0-<tool>, and
  before every other launch check the Proton's files against the app's desired.tsv and put back
  anything that differs (same Proton build only), logging to reapplied.log.
- ComponentsManager writes desired.tsv plus unpacked copies of the packages in use into the
  runtime after every change; the page and the drawer show 're-applied at launch'.
2026-09-25 23:54:10 -04:00
Kurt Himebauch c20a166134 Merge pull request #21 from Droid-Deck/fix/phantom-process-setup-gate
Gate Steam sessions on Android process limit
2026-09-25 23:51:11 -04:00
xXJsonDeruloXx 162fa8e2de Merge remote-tracking branch 'origin/main' into fix/phantom-process-setup-gate 2026-09-25 23:50:57 -04:00
xXJsonDeruloXx ae5614d212 Reuse saved wireless ADB pairing and connection 2026-09-25 23:48:47 -04:00
xXJsonDeruloXx b72d8a8bab Clarify Wireless debugging connection address after pairing 2026-09-25 23:39:31 -04:00
Kurt Himebauch d4cf890d8a feat: set DroidDeck startup movie by default (#25) 2026-09-25 23:36:29 -04:00
xXJsonDeruloXx 82e494269d Improve wireless ADB text input 2026-09-25 23:17:28 -04:00
The412Banner c982d65675 Session drawer: tab spacing fits the room between LB and RB, so all four tabs show 2026-09-25 22:59:50 -04:00
The412Banner f4e606fb15 Components: the pad's LB / RB step through FEX, DXVK and VKD3D-Proton (wrapping), with LB / RB badges beside the tabs 2026-09-25 22:49:10 -04:00
The412Banner 9dbdb5e771 Components: fixed columns so details and Download buttons line up; focused button is a solid blue fill with a white outline 2026-09-25 22:37:07 -04:00
The412Banner fa12478fdd Components: compact layout - one toolbar line (title, Proton drop-down, component tabs, in use, (i), refresh) and one list of short rows for installed and available packages 2026-09-25 22:27:25 -04:00
The412Banner c3b0d8ef03 Merge pull request #23 from Droid-Deck/docs/progress-log-0925
Progress log: 2026-09-25
2026-09-25 22:06:23 -04:00
The412Banner cbb9a168e6 Components: FEX, DXVK and VKD3D-Proton per Proton
A Components entry under Desktop opens a page built like the driver pages: a
Proton drop-down, FEX / DXVK / VKD3D-Proton tabs, what is in use, the installed
rows (each Proton build's original bundle and the stored packages; tap to
swap in, trash to delete), downloads from the Nightlies -Linux releases behind
the refresh button, and Import .wcp.

The session drawer gets a fourth tab, Components, for quick swaps between
what is installed. A swap into the Proton a running game uses waits until the
game closes and is applied then (drawer refresh, or the main screen on resume).

ComponentsManager keeps the same package format, originals layout and state as
the Decky Components Manager plugin and takes its data over once. A swap clears
only the component's own DLLs, so files a Proton keeps beside them stay.
2026-09-25 22:04:38 -04:00
The412Banner 73e2fc58a0 Merge pull request #24 from Droid-Deck/feat/drawer-tab-icons
Session drawer: QAM-style page tabs (Display, Controls, Settings)
2026-09-25 21:55:16 -04:00
The412Banner 500f4c69eb Session drawer: QAM-style page tabs - Display, Controls, Settings
The three page dots between LB and RB become icons standing in a line in page order, as in
Steam's Quick Access Menu. The selected one steps forward (full size, bright, a soft glow in the
accent), the others step back to half size and fade, and the line leans a little toward the
selection; tapping or picking a tab with the pad, and LB / RB, turn the page as before. The
first page's heading becomes Display to match its icon.
2026-09-25 18:11:04 -04:00
xXJsonDeruloXx aa843b5a31 Merge remote-tracking branch 'origin/main' into fix/phantom-process-setup-gate 2026-09-25 17:23:08 -04:00
xXJsonDeruloXx f249acc50f Compact Steam process limit recovery for split screen 2026-09-25 17:21:43 -04:00
xXJsonDeruloXx 9422608960 Replace process gate dialogs with compact pages 2026-09-25 16:34:30 -04:00
Kurt Himebauch de37ddcfb5 Merge branch 'main' into fix/phantom-process-setup-gate 2026-09-25 16:28:53 -04:00
xXJsonDeruloXx 4c90196890 Replace process gate dialogs with pages 2026-09-25 16:28:15 -04:00
xXJsonDeruloXx 30f6ca6ffc Replace wireless ADB modal with setup page 2026-09-25 16:19:01 -04:00
xXJsonDeruloXx ecff3240a6 Add reversible process limit controls 2026-09-25 14:52:04 -04:00
xXJsonDeruloXx ddd4a0c24d Add wireless ADB process-limit repair 2026-09-25 14:35:37 -04:00
xXJsonDeruloXx 019949847a Auto-dismiss process limit gate after status clears 2026-09-25 13:55:04 -04:00
xXJsonDeruloXx 4dcbf269d2 Gate Steam sessions on Android process limit 2026-09-25 13:49:58 -04:00
27 changed files with 4119 additions and 118 deletions

No files matched your search

+1
View File
@@ -28,3 +28,4 @@ app/src/main/jniLibs/arm64-v8a/libproot-loader.so
!keystore/testkey.p12
droiddeck-release-key/
password.txt
__pycache__/
+7
View File
@@ -121,6 +121,10 @@ android {
}
packagingOptions {
resources {
// Kadb's Bouncy Castle artifacts repeat the same multi-release JAR manifest.
excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF']
}
jniLibs {
// The PulseAudio daemon is executed from the native library directory and its
// libraries are read out of the apk by the class loader: both want the old,
@@ -160,6 +164,9 @@ dependencies {
implementation 'androidx.compose.material:material-icons-extended'
implementation 'io.coil-kt:coil-compose:2.6.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
// ADB-over-Wi-Fi pairing and authenticated shell client. Users still approve pairing from
// Android's Wireless debugging screen; DroidDeck only runs its one fixed setting command.
implementation 'com.flyfishxu:kadb-android:1.2.1'
// Android terminal view/emulator used by the in-session secondary-display Linux shell.
implementation 'com.termux.termux-app:terminal-view:0.118.0'
}
+1
View File
@@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Session logs go to Downloads so a failed run can be handed over as one folder. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
@@ -1,7 +1,10 @@
package com.droiddeck.launcher
import android.Manifest
import android.app.ActivityOptions
import android.content.Intent
import android.content.ClipData
import android.content.ClipboardManager
import java.io.File
import android.content.pm.PackageManager
import android.hardware.display.DisplayManager
@@ -12,6 +15,7 @@ import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Display
import android.view.KeyEvent
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
@@ -34,11 +38,16 @@ import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.ui.PackageRow
import com.droiddeck.launcher.session.OfflineMode
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.ProtonPage
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.core.CpuCores
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.core.WirelessAdbFix
import com.droiddeck.launcher.ui.CoreRow
import com.droiddeck.launcher.ui.PerformancePage
import com.droiddeck.launcher.ui.ModeSettingsPage
@@ -89,6 +98,16 @@ class MainActivity : ComponentActivity() {
private var steamDeckMode by mutableStateOf(false)
private var showCredits by mutableStateOf(false)
private var showProtons by mutableStateOf(false)
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
private var showComponents by mutableStateOf(false)
private var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null)
private var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
private var compCatalogAt by mutableStateOf(0L)
private var compProton by mutableStateOf<String?>(null)
private var compComp by mutableStateOf("dxvk")
private var compChecking by mutableStateOf(false)
private var compBusy by mutableStateOf<String?>(null)
private var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
private var deckyInstalled by mutableStateOf<String?>(null)
private var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
private var deckyChecking by mutableStateOf(false)
@@ -120,6 +139,8 @@ class MainActivity : ComponentActivity() {
private var noXalia by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var phantomWarning by mutableStateOf<String?>(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var clientDirectAudio by mutableStateOf(false)
private var forceFullscreen by mutableStateOf(true)
@@ -140,6 +161,9 @@ class MainActivity : ComponentActivity() {
// The app's own picker (files/), once per kind of pick: the two driver lists validate
// differently, and the reason a zip is refused names the list it belongs in.
private val pickComponent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importComponent(it) }
}
private val pickLinuxDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = true) }
}
@@ -238,6 +262,7 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
theme = SessionPrefs.theme(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
setContent {
@@ -247,6 +272,7 @@ class MainActivity : ComponentActivity() {
sm != null -> { { ModeSettingsHost(sm) } }
showPerformance -> { { PerformanceHost() } }
showProtons -> { { ProtonHost() } }
showComponents -> { { ComponentsHost() } }
showMapping -> { { MappingHost() } }
else -> null
}
@@ -260,7 +286,7 @@ class MainActivity : ComponentActivity() {
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
frameGenEngine = FrameGen.engine(this), frameGenMultiplier = FrameGen.multiplier(this),
lsfgReady = LsfgNative.isInstalled(this),
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showMapping) "controller-mapping" else null,
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
theme = theme,
isHomeApp = homeAppSelected,
homeScreenEnabled = homeScreenEnabled,
@@ -277,19 +303,21 @@ class MainActivity : ComponentActivity() {
buildLabel = BuildConfig.BUILD_LABEL,
oscMode = oscMode,
controller = controllerSettings,
phantomProcessStatus = phantomProcessStatus,
showPhantomGate = showPhantomGate,
),
FrontEndActions(
onPlay = { startSession(Intent(this, SessionActivity::class.java)) },
onPlay = { startSession(Intent(this, SessionActivity::class.java), steamSession = true) },
// Steam's desktop client as a window on the desktop: under gamescope the
// client puts itself into Big Picture whatever it is started with.
onPlayDesktopUi = {
startSession(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"))
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
},
onSteamGame = { g ->
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"))
startSession(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"), steamSession = true)
},
onDesktop = {
startSession(Intent(this, SessionActivity::class.java)
@@ -315,7 +343,8 @@ class MainActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this)
},
onProtons = { openProtons() },
onPerformance = { refreshCores(); showProtons = false; showMapping = false; showPerformance = true },
onComponents = { openComponents() },
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true },
onRoms = { showRoms = true },
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
onLogs = {
@@ -336,7 +365,7 @@ class MainActivity : ComponentActivity() {
offline = OfflineMode.enabled(this)
},
onCredits = { showCredits = true },
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showMapping = false },
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
onHomeApp = { manageHomeApp() },
onHomeScreen = { on ->
@@ -351,6 +380,50 @@ class MainActivity : ComponentActivity() {
onCheckLatestBuild = {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml")))
},
onRefreshPhantomStatus = { refreshPhantomStatus() },
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
onWirelessAdbPair = { host, port, code, complete ->
Thread({
val result = runCatching {
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
}
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB pairing failed" }
ui.post { complete(error) }
}, "wireless-adb-pair").start()
},
onFindWirelessAdbPort = { host, complete ->
Thread({
val port = WirelessAdbFix.findConnectPort(this@MainActivity, host)
ui.post { complete(port) }
}, "wireless-adb-discovery").start()
},
onWirelessAdbApply = { host, port, enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB command failed" }
ui.post {
if (error == null) refreshPhantomStatus()
complete(error)
}
}, "wireless-adb-fix").start()
},
onSetPhantomProcessLimit = { enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB is unavailable" }
ui.post {
if (error == null) refreshPhantomStatus()
complete(error)
}
}, "wireless-adb-setting").start()
},
onCopyPhantomCommand = { enabled ->
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
ClipData.newPlainText("DroidDeck child-process setting", PhantomProcessLimit.adbCommand(enabled)),
)
android.widget.Toast.makeText(this, "ADB command copied", android.widget.Toast.LENGTH_SHORT).show()
},
onDismissPhantomGate = { showPhantomGate = false },
controller = ControllerActions(
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() },
@@ -360,7 +433,7 @@ class MainActivity : ComponentActivity() {
onAdaptiveSticks = { on -> ControllerPrefs.setAdaptiveSticks(this, on); refreshController() },
onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showMapping = true },
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = true },
onResetAll = { ControllerPrefs.resetAll(this); refreshController() },
),
),
@@ -417,8 +490,31 @@ class MainActivity : ComponentActivity() {
}, "finish-abandoned").start()
}
/** On the Components page the pad's LB / RB step through FEX, DXVK and VKD3D-Proton, wrapping around. */
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
val all = ComponentsManager.COMPONENTS
val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1
compComp = all[(all.indexOf(compComp).coerceAtLeast(0) + step) % all.size]
}
return true
}
return super.dispatchKeyEvent(event)
}
override fun onResume() {
super.onResume()
refreshPhantomStatus()
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
// session has just ended). Cheap when nothing is queued.
if (!SessionState.running) Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
if (applied.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
if (showComponents) refreshComponents()
}
}, "components-queue").start()
oscMode = SessionPrefs.oscMode(this)
refreshController()
refreshHomeAppState()
@@ -492,6 +588,7 @@ class MainActivity : ComponentActivity() {
private fun openProtons() {
settingsMode = null
showPerformance = false
showComponents = false
showMapping = false
showProtons = true
refreshProtons()
@@ -543,6 +640,106 @@ class MainActivity : ComponentActivity() {
)
}
private fun openComponents() {
settingsMode = null
showPerformance = false
showProtons = false
showMapping = false
showComponents = true
refreshComponents(snapshotFirst = true)
}
/** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */
private fun refreshComponents(snapshotFirst: Boolean = false) {
Thread({
if (snapshotFirst) runCatching { ComponentsManager.snapshotAll(this) }
runCatching { ComponentsManager.applyQueued(this) }
val snap = runCatching { ComponentsManager.snapshot(this) }.onFailure { Log.w(TAG, "components", it) }.getOrNull()
val cat = runCatching { ComponentsManager.catalog(this, false) }.getOrNull()
ui.post {
compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList())
if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) compProton = snap?.protons?.firstOrNull()?.proton?.id
}
}, "components").start()
}
private fun componentAction(label: String, work: () -> String) {
if (compBusy != null) return
compBusy = label
Thread({
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
ui.post {
compBusy = null
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
refreshComponents()
}
}, "components-action").start()
}
private fun refreshComponentCatalog() {
if (compChecking) return
compChecking = true
Thread({
val cat = runCatching { ComponentsManager.catalog(this, true) }.getOrNull()
ui.post {
compChecking = false
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(this, "The Nightlies could not be reached", android.widget.Toast.LENGTH_LONG).show()
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
}
}, "components-catalog").start()
}
private fun downloadComponent(item: ComponentsManager.CatalogItem) {
if (compDownloads.containsKey(item.file)) return
compDownloads = compDownloads + (item.file to -1)
Thread({
val message = runCatching {
val pkg = ComponentsManager.download(this, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
"Stored ${pkg.version}"
}.getOrElse { e -> "Download failed: ${e.message ?: e.javaClass.simpleName}" }
ui.post {
compDownloads = compDownloads - item.file
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
refreshComponents()
}
}, "components-download").start()
}
private fun importComponent(uri: Uri) {
val name = displayNameOf(uri) ?: "imported.wcp"
componentAction("Importing") {
val tmp = File(cacheDir, "component-import.wcp")
contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("cannot read the file")
try { "Imported ${ComponentsManager.importPackage(this, tmp, name).version}" } finally { tmp.delete() }
}
}
@Composable
private fun ComponentsHost() {
ComponentsPage(
snapshot = compSnapshot,
catalog = compCatalog,
catalogAt = compCatalogAt,
protonId = compProton,
comp = compComp,
checking = compChecking,
busy = compBusy,
downloads = compDownloads,
onProton = { compProton = it },
onComp = { compComp = it },
onSwap = { file -> compProton?.let { pid -> componentAction("Swapping") { ComponentsManager.swap(this, pid, file) } } },
onRestore = { version -> compProton?.let { pid -> componentAction("Restoring") { ComponentsManager.restore(this, pid, compComp, version) } } },
onCancelQueued = { compProton?.let { pid -> componentAction("Cancelling") { ComponentsManager.cancelQueued(this, pid, compComp); "The waiting swap was cancelled." } } },
onDeletePackage = { file -> componentAction("Deleting") { ComponentsManager.deletePackage(this, file) } },
onDeleteOriginal = { version -> compProton?.let { pid -> componentAction("Deleting") { ComponentsManager.deleteOriginal(this, pid, compComp, version) } } },
onDownload = { downloadComponent(it) },
onRefresh = { refreshComponentCatalog() },
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
onBack = { showComponents = false },
)
}
@Composable
private fun ProtonHost() {
ProtonPage(
@@ -781,6 +978,7 @@ class MainActivity : ComponentActivity() {
private fun openModeSettings(mode: String) {
showPerformance = false
showProtons = false
showComponents = false
showMapping = false
refreshDrivers()
resolutionCap = SessionPrefs.resolutionCap(this, mode)
@@ -1008,17 +1206,7 @@ class MainActivity : ComponentActivity() {
zinkLazy = SessionPrefs.zinkLazy(this)
noXalia = SessionPrefs.noXalia(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
// Android 12 kills the children an app forks itself once there are more than a handful.
// A session is nothing but those, so where this is on the OS ends the session and no log
// of ours says why. We cannot change a secure setting from here - only say so.
phantomWarning = runCatching {
android.provider.Settings.Global.getString(contentResolver, "settings_enable_monitor_phantom_procs")
}.getOrNull().let { v ->
when (v?.lowercase()) {
"false", "0" -> null
else -> "Android 12 and later kill the extra processes an app starts for itself once there are more than a few, and a session is made of dozens: proot, gamescope, the client and its helpers, Wine. Where that is left on, the client dies with nothing in its log, because nothing in the session did it. Some phones have a \"restrict child processes\" switch in Developer options - turn it off. Otherwise, over adb:\n\n adb shell settings put global settings_enable_monitor_phantom_procs false\n\nThis phone " + (if (v == null) "has not been set either way, so the ROM's default applies." else "currently reports it as on.")
}
}
refreshPhantomStatus()
}
private fun refreshProtons() {
@@ -1075,12 +1263,41 @@ class MainActivity : ComponentActivity() {
}
/** Starts a session; with no runtime on a non-Adreno, the same warning Setup gives comes first, before any download. */
private fun startSession(intent: Intent) {
private fun startSession(intent: Intent, steamSession: Boolean = false) {
refreshPhantomStatus()
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
showPhantomGate = true
return
}
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
if (warn && available != null) showNonAdreno = available
else startActivity(intent)
}
private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(contentResolver)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
"${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.ADB_COMMAND}"
} else null
}
private fun openDeveloperOptions(displayId: Int?) {
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
if (displayId == null) startActivity(intent)
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
} catch (error: Exception) {
if (displayId != null) {
runCatching { startActivity(intent) }
android.widget.Toast.makeText(this, "Could not open Settings on the bottom screen; opened it on the main screen.", android.widget.Toast.LENGTH_LONG).show()
} else {
startActivity(Intent(android.provider.Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
android.widget.Toast.makeText(this, "Open Developer options in Settings", android.widget.Toast.LENGTH_LONG).show()
}
}
}
private fun install(release: LinuxRuntimeInstaller.Release) {
busy = true
failed = false
@@ -1108,5 +1325,6 @@ class MainActivity : ComponentActivity() {
private const val TAG = "MainActivity"
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
private val ZIP_EXT = listOf("zip")
private val WCP_EXT = listOf("wcp")
}
}
@@ -69,6 +69,8 @@ import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.DRAWER_PAGES
import kotlin.math.abs
/**
@@ -140,6 +142,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// Compose reads these; the activity writes them.
private var drawerOpen by mutableStateOf(false)
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
private var drawerPage by mutableIntStateOf(0)
private var drawerControllerActive by mutableStateOf(false)
private var backActionsInverted by mutableStateOf(false)
@@ -342,6 +346,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
onClose = { drawerOpen = false },
components = drawerComponents,
onComponentsRefresh = { refreshDrawerComponents() },
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
))
if (SessionState.suspended) SessionPausedOverlay {
SessionService.resume(this@SessionActivity)
@@ -424,6 +431,40 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
}
/** Re-reads the Protons for the drawer's Components tab, first running swaps a closed game was holding back. */
private fun refreshDrawerComponents() {
Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
val snap = runCatching { ComponentsManager.snapshot(this) }.getOrNull()
uiHandler.post {
drawerComponents = snap
if (applied.isNotEmpty()) android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
}
}, "drawer-components").start()
}
private fun swapDrawerComponent(protonId: String, comp: String, value: String) {
Thread({
val message = runCatching {
val snap = ComponentsManager.snapshot(this)
val queued = snap.protons.firstOrNull { it.proton.id == protonId }?.components?.get(comp)?.queued
val active = snap.protons.firstOrNull { it.proton.id == protonId }?.components?.get(comp)?.activeFile
val build = snap.protons.firstOrNull { it.proton.id == protonId }?.proton?.version?.let(ComponentsManager::safeName)
val current = active ?: "orig:$build"
if (queued != null && value == current) {
// Picking what is already in place again cancels the swap waiting for the game.
ComponentsManager.cancelQueued(this, protonId, comp); "The waiting swap was cancelled."
} else if (value.startsWith("orig:")) ComponentsManager.restore(this, protonId, comp, value.removePrefix("orig:"))
else ComponentsManager.swap(this, protonId, value)
}.getOrElse { e -> "Swap failed: ${e.message ?: e.javaClass.simpleName}" }
uiHandler.post {
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
refreshDrawerComponents()
}
}, "drawer-components-swap").start()
}
private fun shareCurrentSessionLogs() {
val folder = SessionPaths.current()
if (folder == null || !folder.isDirectory) {
@@ -854,7 +895,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (drawerOpen) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else 2) % 3
drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else DRAWER_PAGES - 1) % DRAWER_PAGES
releaseDrawerDirection()
}
return true
@@ -5,7 +5,6 @@ import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.provider.Settings
import android.util.Log
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
@@ -162,21 +161,7 @@ object DeviceReport {
})
h("Android process limits")
// Android 12 kills "phantom" processes - the children an app forks itself rather than
// starting through the framework - once there are more than a handful of them. A session is
// nothing but those: proot, gamescope, Xwayland, the client, its helpers, Wine, FEX. Where
// this is left on, the OS kills the session and nothing in our logs says why, because
// nothing in the session did it. Some ROMs expose it in Developer options as a
// "restrict child processes" switch; otherwise it is
// adb shell settings put global settings_enable_monitor_phantom_procs false
val phantom = runCatching {
Settings.Global.getString(context.contentResolver, "settings_enable_monitor_phantom_procs")
}.getOrNull()
k("Phantom proc monitor", when (phantom?.lowercase()) {
"false", "0" -> "disabled (good - the OS will not kill the session's children)"
null, "" -> "not set (ROM default, usually ENABLED - see the note below)"
else -> "ENABLED (the OS may kill the session with no log; turn off \"restrict child processes\")"
})
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context.contentResolver)))
h("Device switch files in Download")
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
@@ -0,0 +1,71 @@
package com.droiddeck.launcher.core
import android.content.ContentResolver
import android.os.Build
import android.provider.Settings
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */
enum class PhantomProcessStatus {
NOT_APPLICABLE,
DISABLED,
ENABLED,
UNSET,
UNREADABLE,
}
object PhantomProcessLimit {
const val ADB_COMMAND = "adb shell settings put global settings_enable_monitor_phantom_procs false"
const val SHELL_COMMAND = "settings put global settings_enable_monitor_phantom_procs false"
private const val SETTING = "settings_enable_monitor_phantom_procs"
fun adbCommand(enabled: Boolean): String =
"adb shell settings put global $SETTING ${if (enabled) "true" else "false"}"
fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
val value = try {
Settings.Global.getString(resolver, SETTING)
} catch (_: Exception) {
return PhantomProcessStatus.UNREADABLE
}
return when (value?.trim()?.lowercase()) {
"false", "0" -> PhantomProcessStatus.DISABLED
null, "" -> PhantomProcessStatus.UNSET
else -> PhantomProcessStatus.ENABLED
}
}
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
fun title(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
PhantomProcessStatus.UNREADABLE -> "Child-process limit could not be checked"
PhantomProcessStatus.DISABLED -> "Child-process limit is off"
PhantomProcessStatus.NOT_APPLICABLE -> "Child-process limit not required"
}
fun instructions(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.UNSET -> "This setting is unset, so the ROM default applies and may enforce the limit. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not read the setting. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.DISABLED -> "Steam sessions can start."
PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit."
}
fun gateInstructions(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options."
PhantomProcessStatus.UNSET -> "The ROM default may enforce this limit. Explicitly turn off “Restrict child processes” in Developer options."
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not check this setting. Turn off “Restrict child processes” in Developer options."
else -> instructions(status)
}
fun reportValue(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
}
}
@@ -0,0 +1,185 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import com.flyfishxu.kadb.Kadb
import com.flyfishxu.kadb.cert.KadbCert
import java.io.File
import java.net.InetAddress
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.ArrayDeque
/** A narrowly scoped Wireless debugging client for the child-process setting repair. */
object WirelessAdbFix {
private const val CERT_FILE = "wireless-adb-cert.pem"
private const val KEY_FILE = "wireless-adb-key.pem"
private const val HOST_FILE = "wireless-adb-host.txt"
private const val CONNECTION_FILE = "wireless-adb-connection.txt"
private data class SavedConnection(val host: String, val port: Int?)
@Synchronized
private fun loadOrCreateIdentity(context: Context) {
val directory = context.noBackupFilesDir
val cert = File(directory, CERT_FILE)
val key = File(directory, KEY_FILE)
if (cert.isFile && key.isFile) {
KadbCert.set(cert.readBytes(), key.readBytes())
return
}
val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650))
KadbCert.set(identity.first, identity.second)
writeAtomically(cert, identity.first)
writeAtomically(key, identity.second)
}
private fun writeAtomically(destination: File, contents: ByteArray) {
val temporary = File(destination.parentFile, "${destination.name}.tmp")
temporary.writeBytes(contents)
check(temporary.renameTo(destination)) { "Could not save Wireless debugging identity" }
}
suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) {
loadOrCreateIdentity(context.applicationContext)
Kadb.pair(host, port, pairingCode, "DroidDeck")
writeAtomically(File(context.noBackupFilesDir, HOST_FILE), host.toByteArray())
writeAtomically(File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
}
private fun savedConnection(context: Context): SavedConnection? {
val directory = context.applicationContext.noBackupFilesDir
if (!File(directory, CERT_FILE).isFile || !File(directory, KEY_FILE).isFile) return null
val host = File(directory, HOST_FILE).takeIf(File::isFile)?.readText()?.trim()
?.takeIf(String::isNotEmpty) ?: return null
val lines = File(directory, CONNECTION_FILE).takeIf(File::isFile)?.readLines()
val port = lines?.takeIf { it.size == 2 && it[0] == host }
?.get(1)?.toIntOrNull()?.takeIf { it in 1..65535 }
return SavedConnection(host, port)
}
/** A saved pairing skips the PIN; an unknown connection port can be filled in from Settings. */
fun savedConnectionAddress(context: Context): String? = savedConnection(context)?.let { saved ->
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
"$host:${saved.port ?: ""}"
}
private fun saveConnection(context: Context, host: String, port: Int) {
writeAtomically(
File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE),
"$host\n$port".toByteArray(),
)
}
/** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */
fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12): Int? {
val manager = context.applicationContext.getSystemService(Context.NSD_SERVICE) as NsdManager
val expectedAddress = runCatching { InetAddress.getByName(pairedHost).address }.getOrNull() ?: return null
val resolvedPort = AtomicInteger(-1)
val finished = AtomicBoolean(false)
val latch = CountDownLatch(1)
val queue = ArrayDeque<NsdServiceInfo>()
val seen = mutableSetOf<String>()
var resolving = false
val lock = Any()
lateinit var resolveNext: () -> Unit
resolveNext = {
val next = synchronized(lock) {
if (finished.get() || resolving || queue.isEmpty()) null
else queue.removeFirst().also { resolving = true }
}
if (next != null) {
val listener = object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
synchronized(lock) { resolving = false }
resolveNext()
}
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
val address = serviceInfo.host?.address
if (address != null && address.contentEquals(expectedAddress) && finished.compareAndSet(false, true)) {
resolvedPort.set(serviceInfo.port)
latch.countDown()
} else {
synchronized(lock) { resolving = false }
resolveNext()
}
}
}
runCatching { manager.resolveService(next, listener) }.onFailure {
synchronized(lock) { resolving = false }
resolveNext()
}
}
}
val discoveryListener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = Unit
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
if (serviceInfo.serviceType?.contains("_adb-tls-connect._tcp") == true) {
synchronized(lock) {
if (seen.add(serviceInfo.serviceName)) queue.addLast(serviceInfo)
}
resolveNext()
}
}
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
override fun onDiscoveryStopped(serviceType: String) { latch.countDown() }
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
}
try {
manager.discoverServices("_adb-tls-connect._tcp.", NsdManager.PROTOCOL_DNS_SD, discoveryListener)
latch.await(timeoutSeconds, TimeUnit.SECONDS)
} catch (_: Exception) {
return null
} finally {
runCatching { manager.stopServiceDiscovery(discoveryListener) }
}
return resolvedPort.get().takeIf { it in 1..65535 }
}
fun setChildProcessLimit(context: Context, host: String, port: Int, enabled: Boolean) {
loadOrCreateIdentity(context.applicationContext)
Kadb.create(host, port).use { adb ->
val value = if (enabled) "true" else "false"
val change = adb.shell("settings put global settings_enable_monitor_phantom_procs $value")
check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
val result = adb.shell("settings get global settings_enable_monitor_phantom_procs")
check(result.exitCode == 0 && result.output.trim() == value) {
"Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}"
}
}
saveConnection(context, host, port)
}
/** Tries the app's saved pairing without asking for a new pairing code. */
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
val appContext = context.applicationContext
val saved = savedConnection(appContext)
?: error("No Wireless debugging pairing is saved")
val cachedPort = saved.port
if (cachedPort != null) {
val cachedResult = runCatching {
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
}
if (cachedResult.isSuccess) return
val discoveredPort = findConnectPort(appContext, saved.host)
if (discoveredPort != null && discoveredPort != cachedPort) {
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
} else {
cachedResult.getOrThrow()
}
} else {
val discoveredPort = findConnectPort(appContext, saved.host)
?: error("Enter the current Wireless debugging IP address & Port")
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
}
}
}
@@ -0,0 +1,664 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.security.MessageDigest
/**
* FEX, DXVK and VKD3D-Proton per Proton, for the Linux Steam client.
*
* Every Proton the client runs games with keeps its own copy of these three inside its tree. This
* lists them, stores packages (.wcp: tar + zstd with a profile.json) downloaded from the Nightlies
* "-Linux" releases or imported, swaps one into a Proton, keeps the Proton's shipped files as
* "original bundles" - one per Proton build, so a Steam update adds a new one instead of replacing
* the last - restores those, and deletes stored packages.
*
* Where a Proton reads each component (its own `proton` script, ARM64 host):
* DXVK files/lib/wine/dxvk/{aarch64,i386}-windows -> the prefix's system32 / syswow64
* VKD3D files/lib/wine/vkd3d-proton/{aarch64,i386}-windows -> the same, on every launch
* FEX files/lib/wine/aarch64-windows/lib{arm64ec,wow64}fex.dll
* files/lib/wine/aarch64-unix/lib{arm64ec,wow64}fex.so (FEX 2607 and newer)
* Proton copies DXVK and VKD3D into the prefix on every normal launch, so a swap applies the next
* time a game starts. A swap into a Proton a running game is using waits until that game exits.
*
* Same formats and data layout as the Decky "Components Manager" plugin, whose data is taken over
* once on first use.
*/
object ComponentsManager {
private const val TAG = "Components"
private const val NIGHTLIES = "The412Banner/Nightlies"
/** Release tag -> component. Only the Linux repacks: the Android releases carry bionic unixlibs. */
private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk",
"Dxvk-arm64ec-Linux" to "dxvk",
"Dxvk-gplasync-Linux" to "dxvk",
"Vkd3d-proton-Linux" to "vkd3d",
)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
private const val WINE = "files/lib/wine"
private val FEX_FILES = listOf(
"$WINE/aarch64-windows/libarm64ecfex.dll",
"$WINE/aarch64-windows/libwow64fex.dll",
"$WINE/aarch64-unix/libarm64ecfex.so",
"$WINE/aarch64-unix/libwow64fex.so",
)
private val COMP_DIR = mapOf("dxvk" to "$WINE/dxvk", "vkd3d" to "$WINE/vkd3d-proton")
/** The folders a Proton reads on ARM64. */
private val PE_ARCHES = listOf("aarch64-windows", "i386-windows")
/**
* The DLLs that ARE the component. A swap clears exactly these before unpacking, so no file of
* the previous version is left mixed in; anything else a Proton keeps beside them - GE's
* openvr_api_dxvk.dll, which its launcher copies into every prefix and aborts without - stays.
*/
private val COMP_DLLS = mapOf(
"dxvk" to setOf("d3d8.dll", "d3d9.dll", "d3d10.dll", "d3d10_1.dll", "d3d10core.dll", "d3d11.dll", "dxgi.dll"),
"vkd3d" to setOf("d3d12.dll", "d3d12core.dll"),
)
private const val PLUGIN_DATA = "root/homebrew/data/decky-components-manager"
data class Proton(val id: String, val name: String, val dir: File, val guestPath: String, val version: String, val valve: Boolean)
data class Component(val detected: String, val detail: String, val inUse: String, val activeFile: String?, val queued: String?)
data class Original(val comp: String, val protonVersion: String, val label: String, val size: Long)
data class Package(val file: String, val comp: String, val version: String, val description: String, val size: Long)
data class CatalogItem(val file: String, val comp: String, val release: String, val url: String, val size: Long, val digest: String)
data class ProtonView(
val proton: Proton, val components: Map<String, Component>, val originals: List<Original>, val inUseByGame: Boolean,
/** When a launch last had to put this Proton's chosen files back (epoch seconds), or 0. */
val reappliedAt: Long = 0,
)
data class Snapshot(val protons: List<ProtonView>, val packages: List<Package>)
data class Catalog(val items: List<CatalogItem>, val fetchedAt: Long)
private val lock = Any()
// ------------------------------------------------------------------ paths
private fun root(context: Context) = LinuxRuntime.rootDir(context)
private fun steam(context: Context) = File(root(context), "root/.local/share/Steam")
private fun host(context: Context, guest: String) = File(root(context), guest.removePrefix("/"))
private fun dataDir(context: Context) = File(context.filesDir, "components").apply { mkdirs() }
private fun packagesDir(context: Context) = File(dataDir(context), "packages").apply { mkdirs() }
private fun originalsDir(context: Context) = File(dataDir(context), "originals").apply { mkdirs() }
private fun stateFile(context: Context) = File(dataDir(context), "state.json")
private fun catalogFile(context: Context) = File(dataDir(context), "catalog.json")
/**
* Inside the Linux runtime, read by the Proton launch wrappers (bannerlator-steam-compat's
* bl_components) before every game launch: desired.tsv + an unpacked copy of each package in use.
*/
private const val LAUNCH_DIR = "root/.local/share/bannerlator-components"
private fun launchDir(context: Context) = File(root(context), LAUNCH_DIR)
fun safeName(s: String): String = s.replace(Regex("[^A-Za-z0-9._+-]+"), "_").trim('_').ifEmpty { "unnamed" }
// ------------------------------------------------------------------ state
private fun loadState(context: Context): JSONObject =
runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
if (!has("active")) put("active", JSONObject())
if (!has("queued")) put("queued", JSONObject())
}
private fun saveState(context: Context, state: JSONObject) {
val f = stateFile(context)
val tmp = File(f.parentFile, f.name + ".tmp")
tmp.writeText(state.toString(2))
tmp.renameTo(f)
// Every change of choice reaches the launch wrappers at once.
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
}
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
/** Takes over the Decky plugin's packages, originals and swap records, once. */
private fun migratePlugin(context: Context) {
val marker = File(dataDir(context), ".plugin-imported")
if (marker.isFile) return
val plugin = File(root(context), PLUGIN_DATA)
if (plugin.isDirectory) {
runCatching {
File(plugin, "packages").listFiles()?.forEach { f ->
if (f.isFile && f.name.endsWith(".wcp")) {
val dst = File(packagesDir(context), f.name)
if (!dst.exists()) f.copyTo(dst)
}
}
val originals = File(plugin, "originals")
if (originals.isDirectory) originals.copyRecursively(originalsDir(context), overwrite = false)
val ps = File(plugin, "state.json")
if (ps.isFile && !stateFile(context).isFile) ps.copyTo(stateFile(context))
Log.i(TAG, "took over the Decky plugin's data from $plugin")
}.onFailure { Log.w(TAG, "plugin data import", it) }
}
marker.writeText("1\n")
}
// ------------------------------------------------------------------ Protons
private fun libraryRoots(context: Context): List<File> {
val roots = mutableListOf(steam(context))
val vdf = File(steam(context), "steamapps/libraryfolders.vdf")
runCatching {
Regex("\"path\"\\s+\"([^\"]+)\"").findAll(vdf.readText()).forEach {
val h = host(context, it.groupValues[1])
if (roots.none { r -> r.canonicalPath == h.canonicalPath }) roots.add(h)
}
}
return roots
}
private fun displayName(dir: File): String = runCatching {
Regex("\"display_name\"\\s+\"([^\"]+)\"").find(File(dir, "compatibilitytool.vdf").readText())?.groupValues?.get(1)
}.getOrNull() ?: dir.name
private fun protonVersion(dir: File): String = runCatching {
val parts = File(dir, "version").useLines { it.firstOrNull() ?: "" }.trim().split(Regex("\\s+"))
if (parts.size > 1) parts[1] else parts.firstOrNull()?.ifEmpty { null } ?: "unknown"
}.getOrDefault("unknown")
/** Every Proton tree with a Wine inside. Launch wrappers pointing at another Proton are left out. */
fun protons(context: Context): List<Proton> {
val found = LinkedHashMap<String, Proton>()
val bases = listOf(File(steam(context), "compatibilitytools.d") to false) +
libraryRoots(context).map { File(it, "steamapps/common") to true }
// Not canonical: /data/user/0 is a link to /data/data on many devices, and the guest path is
// what is left after removing the rootfs prefix exactly as the paths were built.
val rootPath = root(context).absolutePath.trimEnd('/')
for ((base, valve) in bases) {
val entries = base.listFiles()?.sortedBy { it.name } ?: continue
for (dir in entries) {
if (!File(dir, WINE).isDirectory || !File(dir, "proton").isFile) continue
val real = runCatching { dir.canonicalPath }.getOrDefault(dir.path)
if (found.containsKey(real)) continue
val guest = if (dir.absolutePath.startsWith(rootPath)) dir.absolutePath.removePrefix(rootPath) else dir.absolutePath
found[real] = Proton(safeName(dir.name), displayName(dir), dir, guest, protonVersion(dir), valve)
}
}
return found.values.toList()
}
private fun proton(context: Context, id: String) = protons(context).firstOrNull { it.id == id }
?: throw IllegalStateException("No Proton with id $id")
/**
* Is anything running on this Proton right now - a game, or the client's own start-up runs,
* whose Wine processes can outlive them? Swaps wait while it is. Read from the command lines.
*/
fun inUse(proton: Proton): Boolean = anyProcess(proton) { needle, text -> text.contains(needle + "proton ") || text.contains(needle + "files/bin") }
/**
* Is a game running on this Proton? Only a launch runs proton with the verb waitforexitandrun
* (Proton's own script stays up until the game exits); the client's start-up runs do not.
*/
fun gameRunning(proton: Proton): Boolean = anyProcess(proton) { needle, text -> text.contains(needle + "proton waitforexitandrun") }
private fun anyProcess(proton: Proton, match: (String, String) -> Boolean): Boolean {
val needle = proton.guestPath.trimEnd('/') + "/"
val procs = File("/proc").listFiles() ?: return false
for (p in procs) {
if (!p.name.all(Char::isDigit)) continue
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
if (cmd.isEmpty()) continue
if (match(needle, String(cmd).replace('\u0000', ' '))) return true
}
return false
}
// ------------------------------------------------------------------ component files
private fun readVersionFile(f: File): String = runCatching {
val text = f.readText().trim()
Regex("\\(([^)]+)\\)").find(text)?.groupValues?.get(1) ?: text.split(Regex("\\s+")).last()
}.getOrDefault("")
private fun fexVersion(dir: File): String {
val dll = File(dir, FEX_FILES[0])
if (!dll.isFile) return ""
val text = runCatching { String(dll.readBytes(), Charsets.ISO_8859_1) }.getOrDefault("")
return Regex("FEX-\\d{4}(?:\\.\\d+)?(?:-\\d+-g[0-9a-f]{6,})?").findAll(text).map { it.value }.maxByOrNull { it.length }
?: "FEX (build without a version name)"
}
private fun compFiles(dir: File, comp: String): List<String> {
if (comp == "fex") return FEX_FILES.filter { File(dir, it).isFile }
val base = File(dir, COMP_DIR.getValue(comp))
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).path }.sorted().toList()
}
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
private fun sha256(f: File): String {
val md = MessageDigest.getInstance("SHA-256")
FileInputStream(f).use { input ->
val buf = ByteArray(1 shl 16)
while (true) { val n = input.read(buf); if (n < 0) break; md.update(buf, 0, n) }
}
return md.digest().joinToString("") { "%02x".format(it.toInt() and 255) }
}
private fun fingerprint(dir: File, comp: String): Map<String, String> =
compFiles(dir, comp).filter { owned(comp, it) }.associateWith { sha256(File(dir, it)) }
// ------------------------------------------------------------------ packages
private fun normalize(name: String) = name.removePrefix("./").trimStart('/')
private inline fun <T> readWcp(f: File, block: (TarArchiveInputStream) -> T): T =
TarArchiveInputStream(ZstdInputStream(BufferedInputStream(FileInputStream(f), 1 shl 16))).use(block)
private fun readProfile(f: File): JSONObject = readWcp(f) { tar ->
while (true) {
val e = tar.nextTarEntry ?: break
if (!e.isDirectory && normalize(e.name) == "profile.json") return@readWcp JSONObject(tar.readBytes().decodeToString())
}
throw IllegalArgumentException("no profile.json in ${f.name}")
}
private fun packageInfo(f: File): Package {
val prof = readProfile(f)
val comp = TYPES[prof.optString("type")] ?: throw IllegalArgumentException("${f.name} is not a Linux component package (type ${prof.optString("type")})")
return Package(f.name, comp, prof.optString("versionName", f.nameWithoutExtension), prof.optString("description"), f.length())
}
fun packages(context: Context): List<Package> = packagesDir(context).listFiles()
?.filter { it.isFile && it.name.endsWith(".wcp") }?.sortedBy { it.name }
?.mapNotNull { f -> runCatching { packageInfo(f) }.onFailure { Log.w(TAG, "skipping ${f.name}", it) }.getOrNull() }
?: emptyList()
/** Unpacks a package's files/ into a Proton; for DXVK/VKD3D the component's own DLLs are replaced as a set. */
private fun installFiles(context: Context, dir: File, comp: String, wcp: File): Map<String, String> {
val staged = File(dataDir(context), "staging-${System.nanoTime()}")
try {
readWcp(wcp) { tar ->
while (true) {
val e = tar.nextTarEntry ?: break
val rel = normalize(e.name)
if (e.isDirectory || !rel.startsWith("files/")) continue
require(rel.split('/').none { it == ".." }) { "unsafe path $rel" }
val out = File(staged, rel)
out.parentFile?.mkdirs()
FileOutputStream(out).use { tar.copyTo(it) }
}
}
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
COMP_DIR[comp]?.let { compDir ->
for (arch in PE_ARCHES) {
val target = File(dir, "$compDir/$arch")
if (!File(staged, "$compDir/$arch").isDirectory || !target.isDirectory) continue
target.listFiles()?.filter { it.name.lowercase() in COMP_DLLS.getValue(comp) }?.forEach { it.delete() }
}
}
val hashes = LinkedHashMap<String, String>()
File(staged, "files").walkTopDown().filter { it.isFile }.forEach { src ->
val rel = src.relativeTo(staged).path
val dst = File(dir, rel)
dst.parentFile?.mkdirs()
val tmp = File(dst.parentFile, dst.name + ".dcm-new")
src.copyTo(tmp, overwrite = true)
if (rel.endsWith(".so")) tmp.setExecutable(true, false)
tmp.setReadable(true, false)
if (!tmp.renameTo(dst)) { dst.delete(); check(tmp.renameTo(dst)) { "could not place $rel" } }
hashes[rel] = sha256(dst)
}
return hashes
} finally {
staged.deleteRecursively()
}
}
private fun writeWcp(dest: File, profile: JSONObject, dir: File, rels: List<String>) {
val tmp = File(dest.parentFile, dest.name + ".part")
TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(tmp), 1 shl 16), 9)).use { tar ->
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX)
val bytes = profile.toString(2).toByteArray()
tar.putArchiveEntry(TarArchiveEntry("./profile.json").apply { size = bytes.size.toLong() })
tar.write(bytes); tar.closeArchiveEntry()
for (rel in rels) {
val f = File(dir, rel)
tar.putArchiveEntry(TarArchiveEntry(f, "./$rel"))
FileInputStream(f).use { it.copyTo(tar) }
tar.closeArchiveEntry()
}
}
tmp.renameTo(dest)
}
// ------------------------------------------------------------------ originals
private fun originalFile(context: Context, p: Proton, comp: String) =
File(originalsDir(context), "${p.id}/${safeName(p.version)}/$comp.wcp").apply { parentFile?.mkdirs() }
fun originals(context: Context, protonId: String): List<Original> {
val base = File(originalsDir(context), protonId)
val versions = base.listFiles()?.filter { it.isDirectory }?.sortedByDescending { it.lastModified() } ?: return emptyList()
return versions.flatMap { v ->
COMPONENTS.mapNotNull { comp ->
val f = File(v, "$comp.wcp")
if (!f.isFile) null else Original(comp, v.name, runCatching { readProfile(f).optString("description") }.getOrDefault(""), f.length())
}
}
}
/**
* Saves a Proton's shipped files for this component before they are first replaced in this
* Proton build. A build already swapped into is not saved again: its files are ours.
*/
private fun ensureOriginal(context: Context, p: Proton, comp: String, state: JSONObject) {
val dest = originalFile(context, p, comp)
if (dest.isFile) return
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
if (active != null && active.optString("protonVersion") == p.version) return
val rels = compFiles(p.dir, comp)
if (rels.isEmpty()) return
val current = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
val profile = JSONObject()
.put("type", TYPE_OF.getValue(comp))
.put("versionName", "original-${p.version}")
.put("versionCode", 0)
.put("description", "Original · ${p.name} · ${p.version} · ${LABEL.getValue(comp)} $current".trim())
.put("files", JSONArray(rels.map { JSONObject().put("source", it).put("target", "\${proton}/$it") }))
writeWcp(dest, profile, p.dir, rels)
Log.i(TAG, "saved original $comp of ${p.name} ${p.version}")
}
/** Saves the originals of every Proton build not seen yet (first open, and after a Steam update). */
fun snapshotAll(context: Context) = synchronized(lock) {
migratePlugin(context)
val state = loadState(context)
for (p in protons(context)) for (comp in COMPONENTS) {
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
}
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
}
// ------------------------------------------------------------------ view
fun snapshot(context: Context): Snapshot = synchronized(lock) {
migratePlugin(context)
val state = loadState(context)
val reapplied = HashMap<String, Long>()
runCatching {
File(launchDir(context), "reapplied.log").forEachLine { line ->
val parts = line.split('\t')
if (parts.size >= 2) parts[0].toLongOrNull()?.let { reapplied[parts[1]] = maxOf(reapplied[parts[1]] ?: 0, it) }
}
}
val views = protons(context).map { p ->
val comps = COMPONENTS.associateWith { comp ->
val detected = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
val detail = if (comp == "fex") (if (File(p.dir, FEX_FILES[2]).isFile) "with Linux helpers" else "DLLs only") else ""
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
val inUseLabel = when {
active == null -> "Original"
active.optString("protonVersion") != p.version -> "Original (Proton updated since the last swap)"
else -> {
val want = active.optJSONObject("files") ?: JSONObject()
val fp = fingerprint(p.dir, comp)
if (want.keys().asSequence().all { fp[it] == want.optString(it) }) active.optString("label", active.optString("file"))
else "Changed outside Components"
}
}
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
Component(
detected.ifEmpty { "not present" }, detail, inUseLabel,
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
q?.optString("label"),
)
}
ProtonView(p, comps, originals(context, p.id), gameRunning(p), reapplied[p.dir.name] ?: 0)
}
Snapshot(views, packages(context))
}
// ------------------------------------------------------------------ launch-time enforcement
/**
* Writes what each Proton should be using for the launch wrappers: desired.tsv, one line per
* file (tool dir, Proton build, component, file, sha256, source copy), and an unpacked copy of
* every package or older-build original in use to copy from. Rebuilt whole after every change, so
* a restored or deleted choice simply stops being enforced. The Proton's own current-build
* originals are not listed: the wrappers also give Steam's probe runs their own prefix, which is
* what overwrote files in the first place.
*/
private fun syncLaunchState(context: Context, state: JSONObject) {
val dir = launchDir(context)
val store = File(dir, "store").apply { mkdirs() }
val all = protons(context)
val lines = StringBuilder()
val keep = HashSet<String>()
val active = state.sub("active")
for (pid in active.keys()) {
val p = all.firstOrNull { it.id == pid } ?: continue
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) {
val a = comps.optJSONObject(comp) ?: continue
if (a.optString("protonVersion") != p.version) continue
val file = a.optString("file")
val (key, wcp) = if (file.startsWith("original ")) {
val v = file.removePrefix("original ")
"original-$pid-${safeName(v)}-$comp" to File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp")
} else safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
if (!wcp.isFile) continue
val unpacked = File(store, key)
if (!File(unpacked, ".complete").isFile) {
unpacked.deleteRecursively()
readWcp(wcp) { tar ->
while (true) {
val e = tar.nextTarEntry ?: break
val rel = normalize(e.name)
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
val out = File(unpacked, rel)
out.parentFile?.mkdirs()
FileOutputStream(out).use { tar.copyTo(it) }
}
}
File(unpacked, ".complete").writeText("1\n")
}
keep += key
val files = a.optJSONObject("files") ?: continue
for (rel in files.keys()) {
val src = File(unpacked, rel)
if (!src.isFile) continue
val guestSrc = "/" + src.absolutePath.removePrefix(root(context).absolutePath.trimEnd('/')).trimStart('/')
lines.append(p.dir.name).append('\t').append(p.version).append('\t').append(comp).append('\t')
.append(rel).append('\t').append(files.optString(rel)).append('\t').append(guestSrc).append('\n')
}
}
}
store.listFiles()?.filter { it.isDirectory && it.name !in keep }?.forEach { it.deleteRecursively() }
val list = File(dir, "desired.tsv")
val tmp = File(dir, "desired.tsv.tmp")
tmp.writeText(lines.toString())
tmp.renameTo(list)
}
// ------------------------------------------------------------------ actions
/** Applies a package now, or queues it when a game is running on that Proton. Returns what happened. */
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(wcp)
val state = loadState(context)
if (inUse(p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
saveState(context, state)
return "${LABEL[info.comp]} ${info.version} goes into ${p.name} when the game running on it closes."
}
applyPackage(context, p, info, wcp, state)
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
saveState(context, state)
"${LABEL[info.comp]} ${info.version} is now in ${p.name}. It applies the next time a game starts."
}
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject()
.put("file", wcp.name).put("label", info.version).put("protonVersion", p.version)
.put("files", JSONObject(hashes.filterKeys { owned(info.comp, it) } as Map<*, *>))
.put("at", System.currentTimeMillis() / 1000))
Log.i(TAG, "swapped ${info.comp} ${info.version} into ${p.name} ${p.version}")
}
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(wcp.isFile) { "That original bundle is not stored" }
val state = loadState(context)
if (inUse(p)) {
state.sub("queued").sub(p.id).put(comp, JSONObject().put("kind", "original").put("protonVersion", protonVersion).put("label", "Original $protonVersion"))
saveState(context, state)
return "${LABEL[comp]} of ${p.name} goes back to its original when the game running on it closes."
}
applyOriginal(context, p, comp, protonVersion, wcp, state)
state.sub("queued").optJSONObject(p.id)?.remove(comp)
saveState(context, state)
"${LABEL[comp]} of ${p.name} restored from its $protonVersion original."
}
private fun applyOriginal(context: Context, p: Proton, comp: String, protonVersion: String, wcp: File, state: JSONObject) {
val current = protonVersion == safeName(p.version)
if (!current) ensureOriginal(context, p, comp, state)
installFiles(context, p.dir, comp, wcp)
val active = state.sub("active").sub(p.id)
if (current) active.remove(comp)
else active.put(comp, JSONObject().put("file", "original $protonVersion").put("label", "Original from $protonVersion")
.put("protonVersion", p.version).put("files", JSONObject(fingerprint(p.dir, comp) as Map<*, *>)).put("at", System.currentTimeMillis() / 1000))
}
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
fun applyQueued(context: Context): List<String> = synchronized(lock) {
val state = loadState(context)
val queued = state.sub("queued")
if (queued.length() == 0) return emptyList()
val done = mutableListOf<String>()
val all = protons(context)
for (pid in queued.keys().asSequence().toList()) {
val p = all.firstOrNull { it.id == pid } ?: run { queued.remove(pid); null } ?: continue
if (inUse(p)) continue
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val q = comps.optJSONObject(comp) ?: continue
runCatching {
if (q.optString("kind") == "original") {
val v = q.optString("protonVersion")
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
} else {
val wcp = File(packagesDir(context), q.optString("file"))
applyPackage(context, p, packageInfo(wcp), wcp, state)
}
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
comps.remove(comp)
}
if (comps.length() == 0) queued.remove(pid)
}
saveState(context, state)
done
}
fun cancelQueued(context: Context, protonId: String, comp: String) = synchronized(lock) {
val state = loadState(context)
state.sub("queued").optJSONObject(protonId)?.remove(comp)
saveState(context, state)
}
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val active = state.sub("active")
for (pid in active.keys()) {
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { "$name is in use in $pid. Swap that Proton to something else first." }
}
val f = File(packagesDir(context), name)
check(f.isFile) { "$name is not stored" }
f.delete()
"Deleted $name."
}
fun deleteOriginal(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
val p = proton(context, protonId)
check(safeName(p.version) != protonVersion) { "The installed build's original is kept: it is the way back." }
val f = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(f.isFile) { "Not stored" }
f.delete()
f.parentFile?.takeIf { it.listFiles().isNullOrEmpty() }?.delete()
"Deleted the $protonVersion original of ${LABEL[comp]}."
}
/** Imports a -linux .wcp from anywhere the app can read (the file picker hands over a copy). */
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
val info = packageInfo(source)
val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" })
source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest)
info.copy(file = dest.name)
}
// ------------------------------------------------------------------ catalog
/** The Nightlies listing: cached on disk, fetched again only when [force] (the refresh button). */
fun catalog(context: Context, force: Boolean): Catalog {
val cache = catalogFile(context)
if (!force && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
if (!force) return Catalog(emptyList(), 0)
val items = JSONArray()
for ((tag, comp) in RELEASES) {
val body = Downloader.downloadString("https://api.github.com/repos/$NIGHTLIES/releases/tags/$tag") ?: continue
val assets = runCatching { JSONObject(body).optJSONArray("assets") }.getOrNull() ?: continue
for (i in 0 until assets.length()) {
val a = assets.getJSONObject(i)
val name = a.optString("name")
if (!name.endsWith(".wcp")) continue
items.put(JSONObject().put("file", name).put("comp", comp).put("release", tag)
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
}
}
val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000)
val tmp = File(cache.parentFile, cache.name + ".tmp")
tmp.writeText(out.toString()); tmp.renameTo(cache)
return parseCatalog(out)
}
private fun parseCatalog(o: JSONObject): Catalog {
val arr = o.optJSONArray("items") ?: JSONArray()
val items = (0 until arr.length()).map { arr.getJSONObject(it) }.map {
CatalogItem(it.optString("file"), it.optString("comp"), it.optString("release"), it.optString("url"), it.optLong("size"), it.optString("digest"))
}.sortedWith(compareBy({ it.comp }, { it.release }, { it.file }))
return Catalog(items, o.optLong("fetchedAt"))
}
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { "Downloads come only from the Nightlies releases" }
val dest = File(packagesDir(context), safeName(item.file))
val part = File(dest.parentFile, dest.name + ".part")
part.delete()
check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { "Download failed" }
if (item.digest.startsWith("sha256:")) {
if (!sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error("Checksum mismatch") }
}
val info = runCatching { packageInfo(part) }.getOrElse { part.delete(); throw it }
synchronized(lock) { part.renameTo(dest) }
return info.copy(file = dest.name)
}
}
@@ -148,8 +148,142 @@ object SessionFiles {
staged.delete()
Log.e(TAG, "could not write ld.so.preload")
}
val startupMovie = File(root, "root/.local/share/Steam/config/uioverrides/movies/droiddeck-startup.webm")
val stagedMovie = File(startupMovie.parentFile, startupMovie.name + ".staged")
var movieInstalled = false
try {
startupMovie.parentFile?.mkdirs()
context.assets.open("steam-startup/droiddeck-startup.webm").use { input ->
stagedMovie.outputStream().use { output -> FileUtils.copy(input, output) }
}
movieInstalled = stagedMovie.setReadable(true, false) && stagedMovie.renameTo(startupMovie)
} catch (e: Exception) {
Log.w(TAG, "could not stage Steam startup movie", e)
} finally {
if (!movieInstalled) stagedMovie.delete()
}
if (!movieInstalled) Log.e(TAG, "Steam startup movie NOT staged")
if (movieInstalled) ensureStartupMovieDefault(File(root, "root/.local/share/Steam/config/config.vdf"))
}
private data class VdfBlock(val keyStart: Int, val open: Int, val close: Int)
private fun ensureStartupMovieDefault(config: File) {
val path = "/uioverrides/movies/droiddeck-startup.webm"
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config for startup movie", it)
return
} else ""
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val movie = findObject(text, "StartupMovie", 0, text.length)
if (movie != null) {
val block = text.substring(movie.keyStart, movie.close + 1)
val selectedId = scalar(block, "MovieID")
val selectedPath = scalar(block, "LocalPath")
if (selectedPath == path) {
Log.i(TAG, "Steam startup movie is set to DroidDeck")
return
}
if ((!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()) {
Log.i(TAG, "Steam startup movie selection preserved")
return
}
val updated = setScalar(block, "MovieID", "0", newline)
.let { setScalar(it, "LocalPath", path, newline) }
text = text.replaceRange(movie.keyStart, movie.close + 1, updated)
} else {
val steam = findSteamBlock(text)
if (steam == null) {
if (text.isNotBlank()) {
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
return
}
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
val section = startupMovieSection("\t\t\t\t", path, newline)
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
val section = startupMovieSection(indent + "\t", path, newline)
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
}
}
val staged = File(config.parentFile, config.name + ".staged")
try {
config.parentFile?.mkdirs()
staged.writeText(text)
if (!staged.renameTo(config)) {
staged.delete()
Log.e(TAG, "could not write Steam startup movie selection")
} else {
Log.i(TAG, "Steam startup movie default selected")
}
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write Steam startup movie selection", e)
}
}
private fun findSteamBlock(text: String): VdfBlock? {
val install = findObject(text, "InstallConfigStore", 0, text.length) ?: return null
val software = findObject(text, "Software", install.open + 1, install.close) ?: return null
val valve = findObject(text, "Valve", software.open + 1, software.close) ?: return null
return findObject(text, "Steam", valve.open + 1, valve.close)
}
private fun findObject(text: String, key: String, start: Int, end: Int): VdfBlock? {
val pattern = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]*(?:\\r?\\n[\\t ]*)?\\{")
val match = pattern.find(text, start)?.takeIf { it.range.first < end && it.range.last < end } ?: return null
val open = text.indexOf('{', match.range.first).takeIf { it < end } ?: return null
var depth = 0
var quoted = false
var escaped = false
for (index in open until end) {
val char = text[index]
if (quoted) {
if (escaped) escaped = false
else if (char == '\\') escaped = true
else if (char == '\"') quoted = false
} else {
when (char) {
'\"' -> quoted = true
'{' -> depth++
'}' -> {
depth--
if (depth == 0) return VdfBlock(match.range.first, open, index)
}
}
}
}
return null
}
private fun scalar(block: String, key: String): String? {
val pattern = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]+\"([^\"\\r\\n]*)\"")
return pattern.find(block)?.groupValues?.get(1)
}
private fun setScalar(block: String, key: String, value: String, newline: String): String {
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*)$")
val match = pattern.find(block)
if (match != null) return block.replaceRange(match.range, match.groupValues[1] + "\"" + value + "\"" + match.groupValues[2])
val close = block.lastIndexOf('}')
if (close < 0) return block
val lineStart = block.lastIndexOf('\n', close).let { if (it < 0) 0 else it + 1 }
val indent = block.substring(lineStart, close).takeWhile { it == '\t' || it == ' ' } + "\t"
val entry = indent + "\"" + key + "\"\t\t\"" + value + "\"" + newline
return block.substring(0, lineStart) + entry + block.substring(lineStart)
}
private fun startupMovieSection(indent: String, path: String, newline: String): String = listOf(
indent + "\"StartupMovie\"",
indent + "{",
indent + "\t\"MovieID\"\t\t\"0\"",
indent + "\t\"LocalPath\"\t\t\"" + path + "\"",
indent + "}",
).joinToString(newline)
/**
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
* folder rather than dug out of app-private storage - but the session script redirects its own
@@ -0,0 +1,450 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.ComponentsManager.CatalogItem
import com.droiddeck.launcher.session.ComponentsManager.Snapshot
import java.text.DateFormat
import java.util.Date
/** One installed row: a Proton's original bundle (one per Proton build) or a stored package. */
private class InstalledItem(
val name: String, val detail: String, val tag: String,
val selected: Boolean, val removable: Boolean,
/** Stored package file, or null for an original. */
val file: String?,
/** The Proton build an original belongs to. */
val protonVersion: String?,
)
private val ROW_HEIGHT: Dp = 40.dp
private val DETAIL_WIDTH: Dp = 260.dp
private val ACTION_WIDTH: Dp = 112.dp
private val GOLD = Color(0xFFF2C66D)
/**
* FEX, DXVK and VKD3D-Proton per Proton, as a full page opened from the rail's "Components" entry.
* Compact on purpose (layout A of the mock): title, Proton drop-down, component tabs, what is in
* use and refresh share one toolbar line, the explanation sits behind the (i), and installed rows
* and the Nightlies' downloads run as one list of short rows - a landscape screen shows a dozen or
* more instead of two. Tapping an installed row swaps it in; the refresh button is the only thing
* that goes online.
*/
@Composable
fun ComponentsPage(
snapshot: Snapshot?,
catalog: List<CatalogItem>,
catalogAt: Long,
protonId: String?,
comp: String,
checking: Boolean,
busy: String?,
downloads: Map<String, Int>,
onProton: (String) -> Unit,
onComp: (String) -> Unit,
onSwap: (String) -> Unit,
onRestore: (String) -> Unit,
onCancelQueued: () -> Unit,
onDeletePackage: (String) -> Unit,
onDeleteOriginal: (String) -> Unit,
onDownload: (CatalogItem) -> Unit,
onRefresh: () -> Unit,
onImport: () -> Unit,
onBack: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
BackHandler(onBack = onBack)
var confirm by remember { mutableStateOf<Pair<String, () -> Unit>?>(null) }
var confirmTitle by remember { mutableStateOf("") }
var about by remember { mutableStateOf(false) }
var protonMenu by remember { mutableStateOf(false) }
fun ask(title: String, body: String, action: () -> Unit) { confirmTitle = title; confirm = body to action }
val views = snapshot?.protons ?: emptyList()
val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull()
val label = ComponentsManager.LABEL[comp] ?: comp
val checked = if (catalogAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(catalogAt * 1000)) else "never"
Column(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 8.dp)) {
// ---- the toolbar: one line ------------------------------------------------------------
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) {
FocusText("‹ Back", colors.onSurfaceVariant, onClick = onBack)
Text("Components", fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
if (view != null) {
Box {
ValueChip(view.proton.name, protonMenu, modifier = Modifier.widthIn(max = 260.dp)) { protonMenu = !protonMenu }
AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = "Proton",
note = "Valve's own Proton is replaced when Steam updates it; its originals are kept per build.") { first ->
views.forEachIndexed { i, v ->
val swaps = v.components.values.count { it.activeFile != null }
MenuItem(
v.proton.name, checked = v.proton.id == view.proton.id,
detail = v.proton.version + (if (swaps > 0) " · $swaps swapped" else " · all original") + (if (v.inUseByGame) " · game running" else ""),
focusRequester = if (i == 0) first else null,
) { onProton(v.proton.id); protonMenu = false }
}
}
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
BumperHint("LB")
Segmented(ComponentsManager.COMPONENTS.map { it to ComponentsManager.LABEL.getValue(it) }, comp, onComp)
BumperHint("RB")
}
val st = view.components.getValue(comp)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
Box(Modifier.size(8.dp).background(if (st.queued != null) Color(0xFFFFB86B) else pal.good, CircleShape))
Spacer(Modifier.width(6.dp))
val fixedAt = if (view.reappliedAt > 0) " · re-applied at launch " + DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(view.reappliedAt * 1000)) else ""
Text(
(if (st.queued != null) "Next: ${st.queued} · after the game" else "In use: ${st.inUse}") + fixedAt,
fontSize = 12.5.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false),
)
if (st.queued != null) { Spacer(Modifier.width(8.dp)); FocusText("Cancel", pal.signal, onClick = onCancelQueued) }
}
} else Spacer(Modifier.weight(1f))
Text(if (busy != null) "$busy…" else "Nightlies · $checked", fontSize = 11.5.sp, color = colors.onSurfaceVariant, maxLines = 1)
ToolIcon(Icons.Outlined.Info, "About Components") { about = true }
ToolIcon(Icons.Outlined.Refresh, "Check the Nightlies for new packages", busy = checking, enabled = !checking, onClick = onRefresh)
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
// ---- the list ---------------------------------------------------------------------------
when {
snapshot == null -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp)) {
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(12.dp))
Text("Reading the Protons…", fontSize = 13.sp, color = colors.onSurfaceVariant)
}
view == null -> Text(
"No Proton is installed in the Linux runtime yet. Start the Steam client once so it downloads its ARM64 Proton, or add GE-Proton / CachyOS from Setup.",
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(16.dp),
)
else -> {
val p = view.proton
val st = view.components.getValue(comp)
val build = ComponentsManager.safeName(p.version)
val originals = view.originals.filter { it.comp == comp }
val stored = snapshot.packages.filter { it.comp == comp }
val activeIsOriginal = st.activeFile == null
val rows = originals.map { o ->
val isCurrent = o.protonVersion == build
InstalledItem(
"Original · ${o.protonVersion}",
o.label.substringAfterLast(" · ", "").ifEmpty { o.label } + if (isCurrent) " · this build" else " · earlier build",
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + stored.map { s ->
InstalledItem(s.version, String.format("%.1f MB", s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
}
val storedNames = snapshot.packages.map { it.file }.toSet()
val available = catalog.filter { it.comp == comp && ComponentsManager.safeName(it.file) !in storedNames }
val first = remember { FocusRequester() }
LaunchedEffect(p.id, comp) { runCatching { first.requestFocus() } }
LazyColumn(Modifier.fillMaxWidth().weight(1f)) {
item { SectionLabel("Installed · ${rows.size}") }
if (rows.isEmpty()) item {
Text("Nothing stored for $label yet. This Proton's own files are saved as its original when the page opens.",
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp))
}
items(rows.size) { i ->
val item = rows[i]
InstalledLine(
item, modifier = if (i == 0) Modifier.focusRequester(first) else Modifier,
onSelect = {
if (item.selected) return@InstalledLine
val waits = if (view.inUseByGame) " A game is running on this Proton, so it waits until the game closes." else " It applies the next time a game starts."
if (item.file != null) ask("Swap $label?", "Put ${item.name} into ${p.name}? Its shipped files stay saved as an original bundle.$waits") { onSwap(item.file) }
else ask("Restore $label?", "Put the ${item.protonVersion} original back into ${p.name}?$waits") { onRestore(item.protonVersion!!) }
},
onDelete = {
if (item.file != null) ask("Delete ${item.name}?", "Its package file is removed from the app. You can download it again any time.") { onDeletePackage(item.file) }
else ask("Delete this original?", "The ${item.protonVersion} original of $label belongs to an earlier build of ${p.name}. The installed build's original is always kept.") { onDeleteOriginal(item.protonVersion!!) }
},
)
}
item { SectionLabel("Available on the Nightlies · ${available.size}") }
if (available.isEmpty()) item {
Text(if (catalogAt == 0L) "Tap refresh to list the packages on the Nightlies." else "Nothing new from the last check.",
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp))
}
items(available.size) { i ->
val d = available[i]
AvailableLine(d, downloads[d.file], enabled = busy == null) { onDownload(d) }
}
item {
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = 8.dp, vertical = 10.dp)) {
SmallButton("Import .wcp", onClick = onImport)
if (!activeIsOriginal && originals.any { it.protonVersion == build }) FocusText("Restore this Proton's original", pal.signal) {
ask("Restore $label?", "Put ${p.name}'s original $label back?") { onRestore(build) }
}
}
}
}
}
}
}
if (about) AlertDialog(
onDismissRequest = { about = false },
title = { Text("Components") },
text = {
Text(
"FEX, DXVK and VKD3D-Proton for each Proton the Steam client runs games with.\n\n" +
"Tap an installed row to swap it in; it applies the next time a game starts. If a game is running on that Proton, the swap waits until it closes.\n\n" +
"Your choices are also checked right before every game launch: if anything changed a Proton's files (Steam's start-up tests, for one), they are put back first, and the page says \"re-applied at launch\".\n\n" +
"Each Proton build's own files are kept as its ORIGINAL, so a Steam update never loses them. Packages come from the Nightlies \"-Linux\" releases (refresh) or Import .wcp.",
fontSize = 13.sp,
)
},
confirmButton = { FocusText("OK", pal.signal) { about = false } },
)
confirm?.let { (body, action) ->
AlertDialog(
onDismissRequest = { confirm = null },
title = { Text(confirmTitle) },
text = { Text(body, fontSize = 13.sp) },
// Opens on Cancel, so a stray A press on a controller never swaps or deletes anything.
confirmButton = {
val del = confirmTitle.startsWith("Delete")
FocusText(if (del) "Delete" else if (confirmTitle.startsWith("Restore")) "Restore" else "Swap", if (del) colors.error else pal.signal) { confirm = null; action() }
},
dismissButton = {
val cancelFocus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { cancelFocus.requestFocus() } }
FocusText("Cancel", colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
},
)
}
}
/** The pad's bumper that turns the component tabs, as a small badge beside them. */
@Composable
private fun BumperHint(text: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Text(
text, fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.5.sp, color = colors.onSurfaceVariant, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(5.dp)).border(1.dp, pal.line2, RoundedCornerShape(5.dp)).padding(horizontal = 5.dp, vertical = 2.dp),
)
}
@Composable
private fun SectionLabel(text: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 10.dp, bottom = 4.dp)) {
Text(text.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.6.sp, color = colors.onSurfaceVariant)
Box(Modifier.weight(1f).height(1.dp).background(pal.line))
}
}
@Composable
private fun Segmented(options: List<Pair<String, String>>, selected: String, onPick: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(Modifier.clip(RoundedCornerShape(9.dp)).background(colors.surfaceVariant).border(1.dp, pal.line2, RoundedCornerShape(9.dp)).padding(2.dp)) {
for ((key, text) in options) {
val on = key == selected
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val pick = { onPick(key) }
Text(
text, fontSize = 12.5.sp, fontWeight = FontWeight.Bold, maxLines = 1,
color = if (on) Color.White else if (hot) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier.clip(RoundedCornerShape(7.dp))
.background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.18f) else Color.Transparent)
.border(if (hot && !on) 1.dp else 0.dp, if (hot && !on) pal.signal else Color.Transparent, RoundedCornerShape(7.dp))
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 12.dp, vertical = 5.dp),
)
}
}
}
@Composable
private fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(34.dp).clip(RoundedCornerShape(9.dp))
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line2, RoundedCornerShape(9.dp))
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick),
) {
if (busy) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
else Icon(icon, contentDescription = description, tint = colors.onBackground, modifier = Modifier.size(18.dp))
}
}
/**
* A small button. Resting: grey outline (blue text when [accent]). Focused or hovered: a solid blue
* fill, white text and a white outline - unmistakable in a column of identical buttons.
*/
@Composable
private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = (src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value) && enabled
Box(
contentAlignment = Alignment.Center,
modifier = modifier.clip(RoundedCornerShape(8.dp))
.background(if (hot) pal.signal else colors.surfaceVariant)
.border(2.dp, if (hot) Color.White else pal.line2, RoundedCornerShape(8.dp))
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 10.dp, vertical = 5.dp),
) {
Text(
text, fontSize = 12.sp, fontWeight = FontWeight.Bold, maxLines = 1,
color = if (!enabled) colors.onSurfaceVariant else if (hot) Color.White else if (accent) Color(0xFF5E9BFF) else colors.onBackground,
)
}
}
@Composable
private fun Tag(text: String) {
val colors = MaterialTheme.colorScheme
val (fg, bg) = when (text) {
"ORIGINAL" -> GOLD to Color(0x22F2C66D)
"IN USE" -> Color.White to LocalPalette.current.signal
"NEW" -> LocalPalette.current.good to Color(0x224CD37F)
else -> colors.onSurfaceVariant to Color.White.copy(alpha = 0.07f)
}
Text(
text, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.8.sp, color = fg, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(4.dp)).background(bg).padding(horizontal = 5.dp, vertical = 1.dp),
)
}
@Composable
private fun InstalledLine(item: InstalledItem, modifier: Modifier = Modifier, onSelect: () -> Unit, onDelete: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val shape = RoundedCornerShape(8.dp)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = ROW_HEIGHT).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else if (item.selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent)
.border(2.dp, if (hot) pal.signal else Color.Transparent, shape),
) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.weight(1f).heightIn(min = ROW_HEIGHT).then(modifier)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect)
.controllerConfirm(onClick = onSelect)
.padding(horizontal = 10.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(16.dp).border(2.dp, if (item.selected) pal.signal else colors.onSurfaceVariant, CircleShape)) {
if (item.selected) Box(Modifier.size(7.dp).background(pal.signal, CircleShape))
}
Text(
item.name, fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (item.selected) Color(0xFF5E9BFF) else colors.onBackground, modifier = Modifier.weight(1f),
)
Box(Modifier.width(72.dp)) { Tag(item.tag) }
Text(item.detail, fontSize = 11.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.width(DETAIL_WIDTH))
Box(Modifier.width(56.dp), contentAlignment = Alignment.CenterEnd) { if (item.selected) Tag("IN USE") }
}
// The trash column is always there (empty when the row can't be deleted) so rows line up.
if (!item.removable) Spacer(Modifier.padding(end = 4.dp).size(32.dp))
else {
val delSrc = remember { MutableInteractionSource() }
val delHot = delSrc.collectIsFocusedAsState().value || delSrc.collectIsHoveredAsState().value
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(end = 4.dp).size(32.dp).clip(RoundedCornerShape(8.dp))
.border(2.dp, if (delHot) colors.error else Color.Transparent, RoundedCornerShape(8.dp))
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete)
.controllerConfirm(onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = "Delete", tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(17.dp)) }
}
}
Box(Modifier.fillMaxWidth().padding(horizontal = 8.dp).height(1.dp).background(pal.line.copy(alpha = 0.5f)))
}
@Composable
private fun AvailableLine(d: CatalogItem, progress: Int?, enabled: Boolean, onDownload: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = ROW_HEIGHT).padding(horizontal = 10.dp),
) {
// Fixed columns so every row's details and button line up: name | details | button.
Tag("NEW")
Text(d.file.removeSuffix(".wcp"), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text("${d.release} · " + String.format("%.1f MB", d.size / 1048576.0), fontSize = 11.5.sp, color = colors.onSurfaceVariant,
fontFamily = FontFamily.Default, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.width(DETAIL_WIDTH))
if (progress == null) SmallButton("Download", enabled = enabled, accent = true, modifier = Modifier.width(ACTION_WIDTH), onClick = onDownload)
else Column(horizontalAlignment = Alignment.End, modifier = Modifier.width(ACTION_WIDTH)) {
Text(if (progress < 0) "…" else "$progress%", fontSize = 11.sp, color = colors.onSurfaceVariant)
Spacer(Modifier.height(3.dp))
if (progress < 0) LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
else LinearProgressIndicator(progress = { progress / 100f }, modifier = Modifier.fillMaxWidth())
}
}
Box(Modifier.fillMaxWidth().padding(horizontal = 8.dp).height(1.dp).background(pal.line.copy(alpha = 0.5f)))
}
@@ -221,7 +221,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
/** A text button that shows where controller focus is: an outline in its own colour. */
@Composable
private fun FocusText(text: String, color: Color, modifier: Modifier = Modifier, onClick: () -> Unit) {
internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier, onClick: () -> Unit) {
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val shape = RoundedCornerShape(8.dp)
@@ -71,6 +71,7 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -136,6 +137,8 @@ import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import kotlin.math.roundToInt
@@ -176,6 +179,8 @@ class FrontEndState(
val buildLabel: String = "local",
val oscMode: String = SessionPrefs.OSC_AUTO,
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val showPhantomGate: Boolean = false,
)
class FrontEndActions(
@@ -193,6 +198,8 @@ class FrontEndActions(
val onRuntime: () -> Unit,
val onFrameGenPick: (engine: String, multiplier: Int) -> Unit,
val onProtons: () -> Unit,
/** The Components page: FEX / DXVK / VKD3D-Proton per Proton. */
val onComponents: () -> Unit,
val onPerformance: () -> Unit,
val onRoms: () -> Unit,
val onFiles: () -> Unit,
@@ -207,6 +214,14 @@ class FrontEndActions(
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
val onBackActionsInverted: (Boolean) -> Unit = {},
val onCheckLatestBuild: () -> Unit = {},
val onRefreshPhantomStatus: () -> Unit = {},
val onOpenDeveloperOptions: (Int?) -> Unit = {},
val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless ADB is unavailable") },
val onFindWirelessAdbPort: (String, (Int?) -> Unit) -> Unit = { _, done -> done(null) },
val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless ADB is unavailable") },
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit = { _, done -> done("Wireless ADB is unavailable") },
val onCopyPhantomCommand: (Boolean) -> Unit = {},
val onDismissPhantomGate: () -> Unit = {},
val controller: ControllerActions? = null,
)
@@ -343,14 +358,35 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
var selected by rememberSaveable { mutableStateOf("steam") }
var navOpen by rememberSaveable { mutableStateOf(false) }
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
val colors = MaterialTheme.colorScheme
val ctx = LocalContext.current
BackHandler(enabled = s.pageKey != null && page != null) { a.onPageBack() }
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
val requestDeveloperOptions = {
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
else showDeveloperDisplayChoice = true
}
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
wirelessAdbDesiredEnabled = enabled
showWirelessAdbFix = true
}
LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) {
if (phantomGateVisible) {
while (true) {
kotlinx.coroutines.delay(2_000)
a.onRefreshPhantomStatus()
}
}
}
BackHandler(enabled = !processSettingsPageVisible && s.pageKey != null && page != null) { a.onPageBack() }
// Back (and B) from a game or an emulator steps out one level, as its "‹" link does, instead
// of leaving the app: a game -> its emulator (or Steam), an emulator -> Desktop.
BackHandler(
enabled = (s.pageKey == null || page == null) &&
enabled = !processSettingsPageVisible && (s.pageKey == null || page == null) &&
(selected.startsWith("app:") || selected.startsWith("emu:") || selected.startsWith("rom:")),
) {
selected = when {
@@ -374,14 +410,20 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
else -> s.pageKey ?: selected
}
val onRailSelect: (String) -> Unit = { key ->
if (s.pageKey != null) a.onPageBack()
selected = key
// Components is a full page like Protons or Performance, opened over the current rail
// selection rather than replacing it.
if (key == "components") a.onComponents()
else {
if (s.pageKey != null) a.onPageBack()
selected = key
}
navOpen = false
}
// Start controllers on the current page's main action; the rail is initially collapsed.
val window = LocalWindowInfo.current
val inputMode = LocalInputModeManager.current
LaunchedEffect(Unit) {
LaunchedEffect(processSettingsPageVisible) {
if (processSettingsPageVisible) return@LaunchedEffect
snapshotFlow { window.isWindowFocused }.first { it }
repeat(20) {
if (anyFocused) return@LaunchedEffect
@@ -395,14 +437,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
// the pad then had nothing to move from (a press landed back on the rail's first item). So
// once the new page is in, a controller lands on its main button.
val inputModeManager = LocalInputModeManager.current
LaunchedEffect(selected, s.pageKey) {
LaunchedEffect(selected, s.pageKey, processSettingsPageVisible) {
if (processSettingsPageVisible) return@LaunchedEffect
kotlinx.coroutines.delay(450)
if (!anyFocused && inputModeManager.inputMode == InputMode.Keyboard) runCatching {
if (frontFocus.primaryAttached > 0) frontFocus.primary.requestFocus()
else frontFocus.menuToggle.requestFocus()
}
}
LaunchedEffect(navOpen, railSelection) {
LaunchedEffect(navOpen, railSelection, processSettingsPageVisible) {
if (processSettingsPageVisible) return@LaunchedEffect
if (navOpen) {
frontFocus.focusedRail = null
repeat(12) {
@@ -423,14 +467,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
.focusProperties { enter = { frontFocus.paneEntry() } }
.focusGroup()
val content: @Composable (Modifier) -> Unit = { m ->
Pane(s, selected, a, page, m.then(paneFocus), { selected = it }) { app ->
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
else appToChooseDisplay = app
}
Pane(
s, selected, a, page, m.then(paneFocus), { selected = it },
onAndroidAppClick = { app ->
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
else appToChooseDisplay = app
},
onOpenDeveloperOptions = requestDeveloperOptions,
onRequestWirelessAdb = requestWirelessAdbFix,
)
}
Box(modifier = Modifier.fillMaxSize()) {
Column(modifier = Modifier.fillMaxSize()) {
LauncherTopBar(frontFocus.menuToggle) { navOpen = true }
LauncherTopBar(frontFocus.menuToggle, s.buildLabel, a.onCheckLatestBuild) { navOpen = true }
content(Modifier.weight(1f).fillMaxWidth())
}
AnimatedVisibility(
@@ -473,17 +522,60 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
onDismiss = { appToChooseDisplay = null },
)
}
if (phantomGateVisible && !showWirelessAdbFix) {
Box(Modifier.fillMaxSize().background(colors.background)) {
PhantomProcessGatePage(
status = s.phantomProcessStatus,
onDismiss = a.onDismissPhantomGate,
onOpenDeveloperOptions = requestDeveloperOptions,
onSetUpWirelessAdb = { requestWirelessAdbFix(false) },
)
}
}
if (showWirelessAdbFix) {
Box(Modifier.fillMaxSize().background(colors.background)) {
WirelessAdbFixPage(
onBack = { showWirelessAdbFix = false },
desiredEnabled = wirelessAdbDesiredEnabled,
onOpenDeveloperOptions = requestDeveloperOptions,
onPair = a.onWirelessAdbPair,
onFindConnectPort = a.onFindWirelessAdbPort,
onApply = a.onWirelessAdbApply,
)
}
}
if (showDeveloperDisplayChoice) {
DeveloperDisplayChoiceDialog(
displays = s.secondScreenDisplays.map { display ->
display.id to if (s.secondScreenDisplays.size == 1) "Bottom screen" else display.label
},
onMainScreen = {
showDeveloperDisplayChoice = false
a.onOpenDeveloperOptions(null)
},
onSecondaryScreen = { displayId ->
showDeveloperDisplayChoice = false
a.onOpenDeveloperOptions(displayId)
},
onDismiss = { showDeveloperDisplayChoice = false },
)
}
}
BackHandler(enabled = navOpen) { navOpen = false }
BackHandler(enabled = navOpen && !processSettingsPageVisible) { navOpen = false }
val hasBackTarget = (s.pageKey != null && page != null) ||
((s.pageKey == null || page == null) &&
(selected.startsWith("app:") || selected.startsWith("emu:") || selected.startsWith("rom:")))
BackHandler(enabled = !navOpen && !hasBackTarget) { navOpen = true }
BackHandler(enabled = !processSettingsPageVisible && !navOpen && !hasBackTarget) { navOpen = true }
}
@Composable
private fun LauncherTopBar(menuRequester: FocusRequester, onMenu: () -> Unit) {
private fun LauncherTopBar(
menuRequester: FocusRequester,
buildLabel: String,
onCheckLatestBuild: () -> Unit,
onMenu: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val palette = LocalPalette.current
var menuFocused by remember { mutableStateOf(false) }
@@ -502,6 +594,12 @@ private fun LauncherTopBar(menuRequester: FocusRequester, onMenu: () -> Unit) {
Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(24.dp))
Spacer(Modifier.width(8.dp))
Text("DroidDeck", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Spacer(Modifier.weight(1f))
BuildStatus(
label = buildLabel,
onCheckLatest = onCheckLatestBuild,
modifier = Modifier.widthIn(max = 220.dp).padding(start = 12.dp, end = 8.dp),
)
}
}
@@ -580,6 +678,7 @@ private fun Rail(
}
NavItem("Steam", "steam", selected == "steam", count = s.steamGames.size, register = register, unregister = unregister) { onSelect("steam") }
NavItem("Desktop", "desktop", selected == "desktop", count = s.emulators.count { it.installed }, register = register, unregister = unregister) { onSelect("desktop") }
NavItem("Components", "components", selected == "components", register = register, unregister = unregister) { onSelect("components") }
NavItem("Setup", "setup", selected == "setup", register = register, unregister = unregister) { onSelect("setup") }
Spacer(Modifier.height(6.dp))
}
@@ -595,11 +694,6 @@ private fun Rail(
.padding(horizontal = 10.dp, vertical = 8.dp),
)
}
BuildStatus(
label = s.buildLabel,
onCheckLatest = a.onCheckLatestBuild,
modifier = Modifier.align(Alignment.Start).padding(start = 8.dp, top = 4.dp, bottom = 2.dp),
)
}
}
@@ -691,6 +785,7 @@ private fun NavItem(
private fun Pane(
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
) {
Box(modifier = modifier) {
val wash: Pair<File?, Float> = when {
@@ -712,7 +807,10 @@ private fun Pane(
.apply { targetContentZIndex = 1f }
},
label = "pane",
) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick) }
) { key ->
if (page != null && key == s.pageKey) page()
else Content(s, key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb)
}
}
}
@@ -749,11 +847,11 @@ private fun BuildStatus(label: String, onCheckLatest: () -> Unit, modifier: Modi
horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier.fillMaxWidth(),
) {
Text(branch, modifier = Modifier.weight(1f), fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = if (hot) colors.onSurfaceVariant else colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis)
if (commit.isNotEmpty()) Text("@$commit", fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1)
Text(branch, modifier = Modifier.weight(1f), fontSize = 10.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = if (hot) colors.onSurfaceVariant else colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis)
if (commit.isNotEmpty()) Text("@$commit", fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1)
Icon(Icons.Filled.Refresh, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.82f), modifier = Modifier.size(12.dp))
}
if (context.isNotEmpty()) Text(context, fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1)
if (context.isNotEmpty()) Text(context, fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@@ -785,6 +883,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L
private fun Content(
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
@@ -868,7 +967,7 @@ private fun Content(
ArtGrid(s.emulators.map { e -> Tile(e.name, if (e.installed) (if (e.id == "retroarch") null else "${e.games.size} game${if (e.games.size == 1) "" else "s"}") else "Select to install", null, "emu:${e.id}", e.iconRes, dim = !e.installed) { onSelect("emu:${e.id}") } })
}
}
selected == "setup" -> SetupPanel(s, a)
selected == "setup" -> SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
selected.startsWith("emu:") -> {
val e = s.emulators.firstOrNull { "emu:${it.id}" == selected }
if (e == null) Note("Not installed.") else {
@@ -987,8 +1086,28 @@ private fun Content(
}
@Composable
private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
private fun SetupPanel(
s: FrontEndState,
a: FrontEndActions,
onOpenDeveloperOptions: () -> Unit,
onRequestWirelessAdb: (Boolean) -> Unit,
) {
val host = rememberMenuHost()
var processLimitBusy by remember { mutableStateOf(false) }
var processLimitMessage by remember { mutableStateOf<String?>(null) }
val setProcessLimit: (Boolean) -> Unit = { enabled ->
processLimitBusy = true
processLimitMessage = null
a.onSetPhantomProcessLimit(enabled) { error ->
processLimitBusy = false
if (error == null) {
a.onRefreshPhantomStatus()
} else {
processLimitMessage = "Check the Wireless debugging IP address & Port, or pair again if Android removed this device."
onRequestWirelessAdb(enabled)
}
}
}
val runtime = when {
s.busy -> "Working…"
!s.ready -> "Install"
@@ -999,6 +1118,34 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
Rise(0) { Eyebrow("Setup") }
Rise(1) { Title("Setup") }
SettingsGroup("Android process limit") {
Text(
PhantomProcessLimit.title(s.phantomProcessStatus),
fontWeight = FontWeight.SemiBold,
color = if (PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onBackground,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
)
Text(
"Enabling restores Android’s child-process limit. Disabling it is recommended for Steam sessions.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp),
)
if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) {
SecondaryButton("Enable limit", enabled = !processLimitBusy && s.phantomProcessStatus != PhantomProcessStatus.ENABLED) { setProcessLimit(true) }
SecondaryButton("Disable limit", enabled = !processLimitBusy && s.phantomProcessStatus != PhantomProcessStatus.DISABLED) { setProcessLimit(false) }
}
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp))
processLimitMessage?.let { Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp)) }
}
Text(PhantomProcessLimit.instructions(s.phantomProcessStatus), color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp))
Text(PhantomProcessLimit.ADB_COMMAND, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) {
SecondaryButton("Developer options", onClick = onOpenDeveloperOptions)
SecondaryButton("Check again", onClick = a.onRefreshPhantomStatus)
SecondaryButton("Copy ADB", onClick = { a.onCopyPhantomCommand(false) })
}
}
SettingsGroup("Launcher tools") {
ActionRow("Files", "Browse and manage files", "Open", a.onFiles)
ActionRow("Compatibility tools", "Install ARM64 Proton builds", "Manage", a.onProtons)
@@ -1112,7 +1259,13 @@ private fun Chip(t: String, ok: Boolean) {
private fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
@Composable
private fun PrimaryButton(text: String, enabled: Boolean = true, main: Boolean = false, onClick: () -> Unit) {
internal fun PrimaryButton(
text: String,
enabled: Boolean = true,
main: Boolean = false,
compact: Boolean = false,
onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
// The page's main button is where the pane is entered from the rail.
@@ -1139,14 +1292,14 @@ private fun PrimaryButton(text: String, enabled: Boolean = true, main: Boolean =
// controller is on it, as the other controls are.
.border(2.dp, if (hot) pal.signal else Color.Transparent, Shape12)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.padding(horizontal = 18.dp, vertical = 11.dp),
.padding(horizontal = if (compact) 10.dp else 18.dp, vertical = if (compact) 7.dp else 11.dp),
) {
Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = if (enabled) colors.onPrimary else colors.onSurfaceVariant, maxLines = 1)
Text(text, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = if (enabled) colors.onPrimary else colors.onSurfaceVariant, maxLines = 1)
}
}
@Composable
internal fun SecondaryButton(text: String, enabled: Boolean = true, onClick: () -> Unit) {
internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boolean = false, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && enabled
@@ -1160,8 +1313,8 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, onClick: ()
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 16.dp, vertical = 11.dp),
) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
.padding(horizontal = if (compact) 10.dp else 16.dp, vertical = if (compact) 7.dp else 11.dp),
) { Text(text, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
}
@Composable
@@ -0,0 +1,182 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
@Composable
fun PhantomProcessGatePage(
status: PhantomProcessStatus,
onDismiss: () -> Unit,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
BackHandler(onBack = onDismiss)
BoxWithConstraints(Modifier.fillMaxWidth()) {
val compact = maxWidth < 620.dp && maxHeight < 500.dp
SettingsPage(
host = rememberMenuHost(),
title = if (compact) "Steam paused" else "Steam cannot start yet",
eyebrow = "Steam",
lede = if (compact) compactStatus(status) else "${PhantomProcessLimit.title(status)} · checking again every two seconds",
onBack = onDismiss,
scrollContent = false,
compactLayout = compact,
) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 620.dp
Column(
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
when {
compact -> CompactGateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
wide -> Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) {
Column(Modifier.weight(1f)) {
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
}
Column(Modifier.weight(1f)) { AdbFallback() }
}
else -> {
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
AdbFallback()
}
}
}
}
}
}
}
private fun compactStatus(status: PhantomProcessStatus): String {
val state = when (status) {
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
PhantomProcessStatus.UNREADABLE -> "Child-process limit is unreadable"
else -> PhantomProcessLimit.title(status)
}
return "$state · retrying every 2 sec"
}
@Composable
private fun CompactGateInstructions(
status: PhantomProcessStatus,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
SettingsGroup("1 · Developer options", compact = true) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp),
verticalArrangement = Arrangement.spacedBy(5.dp),
) {
Text(
PhantomProcessLimit.gateInstructions(status),
style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton("Use on-device ADB", compact = true, onClick = onSetUpWirelessAdb)
}
}
}
SettingsGroup("3 · Computer ADB last resort", compact = true) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp),
verticalArrangement = Arrangement.spacedBy(3.dp),
) {
Text(
"If the setting is missing and Wireless debugging is unavailable, run this from a computer:",
style = MaterialTheme.typography.bodySmall.copy(fontSize = 11.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
PhantomProcessLimit.ADB_COMMAND,
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace, fontSize = 9.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
private fun GateInstructions(
status: PhantomProcessStatus,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
SettingsGroup("1 · Developer options first") {
Column(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
PhantomProcessLimit.gateInstructions(status),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
SecondaryButton("Use on-device ADB", onClick = onSetUpWirelessAdb)
}
}
}
@Composable
private fun AdbFallback() {
SettingsGroup("3 · Computer ADB last resort") {
Column(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
"Use this only if Developer options has no setting and Wireless debugging is unavailable. Connect this device to a computer with ADB and run:",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
Text(
PhantomProcessLimit.ADB_COMMAND,
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
fun DeveloperDisplayChoiceDialog(
displays: List<Pair<Int, String>>,
onMainScreen: () -> Unit,
onSecondaryScreen: (Int) -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Open Developer options") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
Text("Choose which display to open Android Settings on.")
TextButton(modifier = Modifier.fillMaxWidth(), onClick = onMainScreen) { Text("Main screen") }
displays.forEach { (id, label) ->
TextButton(modifier = Modifier.fillMaxWidth(), onClick = { onSecondaryScreen(id) }) { Text(label) }
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@@ -1,5 +1,15 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.offset
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material3.Icon
import androidx.compose.ui.draw.clipToBounds
import android.view.Display
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
@@ -55,6 +65,7 @@ import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
@@ -82,16 +93,19 @@ import androidx.compose.ui.text.style.TextOverflow
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import kotlinx.coroutines.flow.collect
private val drawerPageTitles = listOf("Now", "Controls", "Session")
private val drawerPageEntries = listOf("hud", "touch", "suspend")
private val drawerPageTitles = listOf("Display", "Controls", "Components", "Settings")
/** One icon per drawer page, in page order (QAM-style tabs). */
private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings)
private val drawerPageEntries = listOf("hud", "touch", "cmp-proton", "suspend")
private class DrawerFocus {
private val requesters = HashMap<String, FocusRequester>()
private val last = arrayOfNulls<String>(3)
private val last = arrayOfNulls<String>(DRAWER_PAGES)
var focused by mutableStateOf<String?>(null)
private set
@@ -229,6 +243,12 @@ class DrawerActions(
val onShareLogs: () -> Unit,
val onStop: () -> Unit,
val onClose: () -> Unit,
/** Components tab: every Proton with what it uses; null until first read. */
val components: ComponentsManager.Snapshot? = null,
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
val onComponentsRefresh: () -> Unit = {},
/** Swaps [value] ("orig:<build>" or a stored package file) into a Proton's component. */
val onComponentSwap: (protonId: String, comp: String, value: String) -> Unit = { _, _, _ -> },
)
@OptIn(ExperimentalComposeUiApi::class)
@@ -240,7 +260,7 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
var androidAppsExpanded by rememberSaveable { mutableStateOf(false) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
var confirmStop by remember { mutableStateOf(false) }
val pageScroll = remember { List(3) { ScrollState(0) } }
val pageScroll = remember { List(DRAWER_PAGES) { ScrollState(0) } }
val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil")
val focus = remember { DrawerFocus() }
val inputModeManager = LocalInputModeManager.current
@@ -250,6 +270,7 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
}
BackHandler(enabled = open && confirmStop) { confirmStop = false }
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
LaunchedEffect(open, page) { if (open && page == DRAWER_PAGE_COMPONENTS) a.onComponentsRefresh() }
LaunchedEffect(open, controllerActive) {
if (open && !controllerActive) focusManager.clearFocus(force = true)
}
@@ -331,10 +352,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
a.onSteamMenu.invoke()
},
shape = RoundedCornerShape(12.dp),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
border = BorderStroke(if (steamHot) 2.dp else 1.dp, if (steamHot) pal.signal else colors.outline),
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (steamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
) {
Text("STEAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
Text("STEAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, maxLines = 1)
}
OutlinedButton(
onClick = {
@@ -349,10 +371,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
a.onQam.invoke()
},
shape = RoundedCornerShape(12.dp),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
border = BorderStroke(if (qamHot) 2.dp else 1.dp, if (qamHot) pal.signal else colors.outline),
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (qamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
) {
Text("QAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
Text("QAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, maxLines = 1)
}
// Big Picture's own "Switch to Desktop" waits on SteamOS Manager for ever
// here; this does the switch without the client.
@@ -368,10 +391,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
a.onSwitchToDesktop.invoke()
},
shape = RoundedCornerShape(12.dp),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp),
border = BorderStroke(if (deskHot) 2.dp else 1.dp, if (deskHot) pal.signal else colors.outline),
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (deskHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
) {
Text("DESKTOP", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
Text("DESKTOP", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, maxLines = 1)
}
}
}
@@ -382,36 +406,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
) {
DrawerOutlineButton("LB ‹", modifier = Modifier.height(48.dp).then(focus.track(page, "prev"))) {
host.open = null; onPageChange((page + 2) % 3)
}
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f),
) {
drawerPageTitles.forEachIndexed { index, title ->
val dotSource = remember { MutableInteractionSource() }
val dotFocused = dotSource.collectIsFocusedAsState().value
val select = { host.open = null; onPageChange(index) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(38.dp)
.semantics { contentDescription = "$title page" }
.hoverable(dotSource)
.clickable(interactionSource = dotSource, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
) {
Box(
Modifier.size(if (index == page) 16.dp else 10.dp)
.clip(CircleShape)
.background(if (index == page) pal.signal else colors.onSurfaceVariant)
.border(if (dotFocused) 2.dp else 0.dp, colors.onBackground, CircleShape),
)
}
}
host.open = null; onPageChange((page + DRAWER_PAGES - 1) % DRAWER_PAGES)
}
DrawerPageTabs(page = page, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
DrawerOutlineButton("› RB", modifier = Modifier.height(48.dp).then(focus.track(page, "next"))) {
host.open = null; onPageChange((page + 1) % 3)
host.open = null; onPageChange((page + 1) % DRAWER_PAGES)
}
}
@@ -419,7 +418,7 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll[page]),
) {
when (page) {
0 -> SettingsGroup("Now") {
0 -> SettingsGroup("Display") {
ToggleRow(host, "hud", "Performance HUD", null, a.hudOn,
chipModifier = focus.track(page, "hud"), onChange = a.onHud)
if (a.fillScreen != null) ToggleRow(
@@ -444,6 +443,7 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
}
}
}
DRAWER_PAGE_COMPONENTS -> ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
1 -> {
SettingsGroup("Controls") {
ChoiceRow(host, "touch", "Touch", null,
@@ -637,3 +637,195 @@ private fun ShareSessionLogsButton(modifier: Modifier = Modifier, onClick: () ->
color = if (hot) pal.signal else colors.onSurfaceVariant, maxLines = 1)
}
}
/**
* The drawer's page tabs, QAM-style: one icon per page standing in a line in page order. The
* selected one steps forward - full size, bright, a soft glow - while the others step back to
* half size and fade, and the whole line leans a little toward the selection. LB / RB still turn
* the page (the buttons beside it and the pad's bumpers); a tab can be tapped or picked with the
* pad like the dots it replaces.
*/
@Composable
private fun DrawerPageTabs(page: Int, modifier: Modifier = Modifier, onSelect: (Int) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val count = drawerPageIcons.size
val middle = (count - 1) / 2f
val motion = tween<Float>(durationMillis = 340, easing = FastOutSlowInEasing)
androidx.compose.foundation.layout.BoxWithConstraints(
contentAlignment = Alignment.Center,
modifier = modifier.height(64.dp).clipToBounds(),
) {
// Fit the line to the room between LB and RB. Worst case is an end tab selected: full size
// (56 dp) and pushed outward by the lean, which scales with the spacing. So
// (count-1) * spacing * (1 + lean/64) + 56 <= width
// - never more than the mock's 64 dp, never tighter than 32 dp.
val spacing = ((maxWidth.value - 56f) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(32f, DRAWER_TAB_SPACING_DP)
val leanStep = DRAWER_TAB_LEAN_DP * spacing / DRAWER_TAB_SPACING_DP
val lean by animateFloatAsState(-(page - middle) * leanStep, motion, label = "tabLean")
drawerPageIcons.forEachIndexed { index, icon ->
val selected = index == page
val source = remember { MutableInteractionSource() }
val focused = source.collectIsFocusedAsState().value
val scale by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale")
val alpha by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha")
val glow by animateFloatAsState(if (selected) 1f else 0f, motion, label = "tabGlow")
val tint by animateColorAsState(if (selected) colors.onBackground else colors.onSurfaceVariant, tween(340), label = "tabTint")
val select = { onSelect(index) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.offset(x = ((index - middle) * spacing + lean).dp)
.size(56.dp)
.graphicsLayer { scaleX = scale; scaleY = scale; this.alpha = alpha }
.clip(RoundedCornerShape(16.dp))
.background(
Brush.radialGradient(
listOf(pal.signal.copy(alpha = 0.34f * glow), pal.signal.copy(alpha = 0.10f * glow), Color.Transparent),
),
)
.border(if (focused) 2.dp else 0.dp, if (focused) colors.onBackground else Color.Transparent, RoundedCornerShape(16.dp))
.semantics { contentDescription = "${drawerPageTitles[index]} page" }
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
) {
Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(30.dp))
}
}
}
}
/** Display, Controls, Components, Settings. */
const val DRAWER_PAGES = 4
private const val DRAWER_PAGE_COMPONENTS = 2
/**
* The drawer's Components tab: quick swaps between what is already installed, per Proton. A swap
* into the Proton a running game uses waits until that game closes; downloading, importing and
* deleting stay on the Components page in the app.
*/
@Composable
private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val snap = a.components
if (snap == null) {
SettingsGroup("Components") {
Text("Reading the Protons…", fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(14.dp))
}
return
}
val running = snap.protons.filter { it.inUseByGame }
var pick by rememberSaveable { mutableStateOf<String?>(null) }
val view = snap.protons.firstOrNull { it.proton.id == pick } ?: running.firstOrNull() ?: snap.protons.firstOrNull()
// Focusable, so the pad can climb from the Proton box up to it and the page scrolls it into view.
SettingsGroup("Running now") {
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value
val pal = LocalPalette.current
Column(
modifier = Modifier.fillMaxWidth().then(track("cmp-running"))
.focusable(interactionSource = src)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.padding(horizontal = 14.dp, vertical = 11.dp),
) {
if (running.isEmpty()) {
Text("No game is running on a Proton", fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text("Changes apply the next time a game starts.", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
} else for (r in running) {
Text(r.proton.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
for (comp in ComponentsManager.COMPONENTS) {
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
Text(ComponentsManager.LABEL.getValue(comp), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(96.dp))
Text(r.components.getValue(comp).inUse, fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
}
if (view == null) {
SettingsGroup("Components") {
Text("No Proton is installed yet.", fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(14.dp))
}
return
}
val p = view.proton
SettingsGroup("Components") {
DrawerStackedChoice(
host, "cmp-proton", "Proton",
listOfNotNull(
p.version,
"game running".takeIf { view.inUseByGame },
view.reappliedAt.takeIf { it > 0 }?.let { "re-applied at launch " + java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(it * 1000)) },
).joinToString(" · "),
snap.protons.map { it.proton.id to it.proton.name }, p.id,
chipModifier = track("cmp-proton"), onPick = { pick = it },
)
val build = ComponentsManager.safeName(p.version)
for (comp in ComponentsManager.COMPONENTS) {
val st = view.components.getValue(comp)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) "Original" else "Original · ${it.protonVersion}") } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (options.isEmpty()) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
DrawerStackedChoice(
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
// The box already shows the choice: only say more when there is more to say.
st.queued?.let { "Next: $it · after the game closes" } ?: st.inUse.takeIf { it != shown },
options, current,
note = if (view.inUseByGame) "A game is running on this Proton: the change waits until it closes." else "Applies the next time a game starts.",
chipModifier = track("cmp-$comp"),
onPick = { v -> if (v != current || st.queued != null) a.onComponentSwap(p.id, comp, v) },
)
}
}
Text(
"Downloads, importing and deleting are on the Components page in the app.",
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
)
}
/**
* A choice for the drawer's narrow column: label, then the box across the full width, then the
* detail underneath - so a long Proton or package name never squeezes the text beside it.
*/
@Composable
private fun <T> DrawerStackedChoice(
host: MenuHost, key: String, label: String, hint: String?,
options: List<Pair<T, String>>, selected: T, note: String? = null,
chipModifier: Modifier = Modifier, onPick: (T) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = host.open == key
Column(
modifier = Modifier.fillMaxWidth()
.background(if (open) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
.padding(horizontal = 14.dp, vertical = 10.dp),
) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Box(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, modifier = chipModifier.fillMaxWidth()) {
host.open = if (open) null else key
}
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
options.forEachIndexed { index, (value, text) ->
MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) {
onPick(value)
host.open = null
}
}
}
}
if (hint != null) Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 5.dp))
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
/** The tab row's measure, from the approved mock: side tabs at half size, a little faded. */
private const val DRAWER_TAB_SPACING_DP = 64f
private const val DRAWER_TAB_LEAN_DP = 12f
private const val DRAWER_TAB_SIDE_SCALE = 0.5f
private const val DRAWER_TAB_SIDE_ALPHA = 0.7f
@@ -235,10 +235,14 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
}
@Composable
fun SettingsGroup(title: String, content: @Composable ColumnScope.() -> Unit) {
fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 6.dp)) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 10.dp),
modifier = Modifier.fillMaxWidth().padding(top = if (compact) 4.dp else 16.dp, bottom = if (compact) 3.dp else 6.dp),
) {
Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant)
Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line))
}
@@ -332,24 +336,32 @@ fun SettingsPage(
action: (@Composable () -> Unit)? = null,
/** Pass one held above the page to keep its scroll position across a page opened over it. */
scroll: androidx.compose.foundation.ScrollState? = null,
scrollContent: Boolean = true,
compactLayout: Boolean = false,
content: @Composable ColumnScope.() -> Unit,
) {
val scrollState = scroll ?: rememberScrollState()
val colors = MaterialTheme.colorScheme
val dim by animateFloatAsState(if (host.open != null) 0.6f else 1f, Motion.tw(220), label = "pageDim")
Column(modifier = Modifier.fillMaxSize().padding(horizontal = 22.dp, vertical = 18.dp)) {
Column(
modifier = Modifier.fillMaxSize().padding(
horizontal = if (compactLayout) 14.dp else 22.dp,
vertical = if (compactLayout) 6.dp else 18.dp,
),
verticalArrangement = Arrangement.spacedBy(if (compactLayout) 2.dp else 0.dp),
) {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically) {
// Outlined when a controller's focus is on it, like every other control here.
val backSrc = remember { MutableInteractionSource() }
val backHot = backSrc.collectIsFocusedAsState().value || backSrc.collectIsHoveredAsState().value
Text(
"‹ Back", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
"‹ Back", fontSize = if (compactLayout) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold,
color = if (backHot) LocalPalette.current.signal else colors.onSurfaceVariant,
modifier = Modifier.clip(RoundedCornerShape(8.dp))
.border(2.dp, if (backHot) LocalPalette.current.signal else Color.Transparent, RoundedCornerShape(8.dp))
.hoverable(backSrc).clickable(interactionSource = backSrc, indication = null, onClick = onBack)
.padding(horizontal = 6.dp, vertical = 4.dp),
.padding(horizontal = 6.dp, vertical = if (compactLayout) 2.dp else 4.dp),
)
if (eyebrow != null) {
Spacer(Modifier.width(10.dp))
@@ -359,13 +371,44 @@ fun SettingsPage(
}
Rise(1) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.weight(1f)) { Title(title) }
Box(Modifier.weight(1f)) {
if (compactLayout) {
Text(
title,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
color = colors.onBackground,
modifier = Modifier.padding(vertical = 2.dp),
)
} else {
Title(title)
}
}
if (action != null) action()
}
}
if (lede != null) Rise(2) { Lede(lede) }
if (lede != null) Rise(2) {
if (compactLayout) {
Text(
lede,
fontSize = 11.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(bottom = 3.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
} else {
Lede(lede)
}
}
Rise(3, Modifier.weight(1f).fillMaxWidth()) {
Column(modifier = Modifier.fillMaxSize().graphicsLayer { alpha = dim }.verticalScroll(scrollState).padding(bottom = 24.dp)) { content() }
Column(
modifier = Modifier
.fillMaxSize()
.graphicsLayer { alpha = dim }
.then(if (scrollContent) Modifier.verticalScroll(scrollState) else Modifier)
.padding(bottom = if (compactLayout) 0.dp else 24.dp),
) { content() }
}
}
}
@@ -0,0 +1,538 @@
package com.droiddeck.launcher.ui
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.WirelessAdbFix
import kotlin.math.min
import kotlin.math.roundToInt
@Composable
fun WirelessAdbFixPage(
onBack: () -> Unit,
desiredEnabled: Boolean,
onOpenDeveloperOptions: () -> Unit,
onPair: (String, Int, String, (String?) -> Unit) -> Unit,
onFindConnectPort: (String, (Int?) -> Unit) -> Unit,
onApply: (String, Int, Boolean, (String?) -> Unit) -> Unit,
) {
val context = LocalContext.current
val savedAddress = remember { WirelessAdbFix.savedConnectionAddress(context) }
var step by rememberSaveable { mutableStateOf(if (savedAddress == null) 0 else 1) }
var pairingAddress by rememberSaveable { mutableStateOf("") }
var connectionAddress by rememberSaveable { mutableStateOf(savedAddress.orEmpty()) }
var pairingCode by rememberSaveable { mutableStateOf("") }
var busy by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
var messageIsError by remember { mutableStateOf(false) }
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
val pairingEndpoint = parseAdbAddress(pairingAddress)
val pairNow: () -> Unit = {
parseAdbAddress(pairingAddress)?.let { endpoint ->
keyboardController?.hide()
focusManager.clearFocus()
busy = true
editing = false
message = null
messageIsError = false
onPair(endpoint.host, endpoint.port, pairingCode) { error ->
pairingCode = ""
if (error != null) {
busy = false
message = error
messageIsError = true
} else {
step = 1
busy = true
message = "Paired. Finding the Wireless debugging port…"
onFindConnectPort(endpoint.host) { discoveredPort ->
if (discoveredPort == null) {
connectionAddress = formatAddressHost(endpoint.host) + ":"
busy = false
message = "Paired. Enter the port from Settings."
} else {
connectionAddress = formatAdbAddress(endpoint.host, discoveredPort)
message = "Device found. Applying the setting…"
onApply(endpoint.host, discoveredPort, desiredEnabled) { applyError ->
busy = false
if (applyError == null) {
step = 2
message = null
} else {
message = "Could not apply automatically. Check the address below and retry. $applyError"
messageIsError = true
}
}
}
}
}
}
}
}
val applyAddress: () -> Unit = {
parseAdbAddress(connectionAddress)?.let { endpoint ->
keyboardController?.hide()
focusManager.clearFocus()
busy = true
editing = false
message = null
messageIsError = false
onApply(endpoint.host, endpoint.port, desiredEnabled) { error ->
busy = false
if (error == null) {
step = 2
message = null
} else {
message = error
messageIsError = true
}
}
}
}
val pairAgain: () -> Unit = {
step = 0
pairingAddress = ""
pairingCode = ""
message = null
messageIsError = false
}
BackHandler { if (!busy) onBack() }
BoxWithConstraints(Modifier.fillMaxSize()) {
val compactSplit = maxWidth < 620.dp && maxHeight < 500.dp
val form: @Composable () -> Unit = {
WirelessStepForm(
step = step,
pairingAddress = pairingAddress,
onPairingAddressChange = { pairingAddress = it },
pairingCode = pairingCode,
onPairingCodeChange = { pairingCode = it.filter(Char::isDigit).take(6) },
connectionAddress = connectionAddress,
onConnectionAddressChange = { connectionAddress = it },
busy = busy,
message = message,
messageIsError = messageIsError,
compact = compactSplit,
editing = editing,
onEditingChanged = { editing = it },
focusManager = focusManager,
desiredEnabled = desiredEnabled,
canPair = pairingEndpoint != null && pairingCode.length == 6,
onPair = pairNow,
onApply = applyAddress,
onPairAgain = pairAgain,
)
}
SettingsPage(
host = rememberMenuHost(),
title = when {
compactSplit && step < 2 -> "Wireless ADB"
step == 2 -> "Wireless ADB ready"
else -> "Set up on-device ADB"
},
eyebrow = "Setup",
lede = when {
compactSplit && step == 0 -> "If the option is missing, pair over Wireless debugging."
compactSplit && step == 1 -> "Paired. Check IP address & Port in Wireless debugging."
compactSplit -> "The child-process limit was updated."
step == 0 -> "Use step 2 if Developer options has no child-process setting. In Android Settings, open Developer options → Wireless debugging → Pair device with pairing code."
step == 1 -> "Paired. Use the address below; update it from Wireless debugging → IP address & Port if needed."
else -> "The child-process limit was updated over Wireless debugging."
},
onBack = { if (!busy) onBack() },
action = if (compactSplit && step < 2) {
{ SecondaryButton("Developer options", compact = true, enabled = !busy, onClick = onOpenDeveloperOptions) }
} else null,
scrollContent = !compactSplit,
compactLayout = compactSplit,
) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 620.dp
if (step == 2) {
Column(
modifier = Modifier.widthIn(max = 680.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
SettingsGroup("Child-process limit", compact = compactSplit) {
Text(
"Android confirmed the limit is ${if (desiredEnabled) "enabled" else "disabled"}.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(14.dp),
)
}
PrimaryButton("Done", enabled = !busy, onClick = onBack)
}
} else if (compactSplit) {
Column(
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
form()
if (!editing) CompactComputerFallback(desiredEnabled)
}
} else {
val routes: @Composable () -> Unit = {
FallbackOrder(desiredEnabled, busy, onOpenDeveloperOptions)
}
if (wide) {
Row(
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalAlignment = Alignment.Top,
) {
Column(Modifier.weight(1f)) { routes() }
Column(Modifier.weight(1f)) { form() }
}
} else {
Column(
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
routes()
form()
}
}
}
}
}
}
}
@Composable
private fun WirelessStepForm(
step: Int,
pairingAddress: String,
onPairingAddressChange: (String) -> Unit,
pairingCode: String,
onPairingCodeChange: (String) -> Unit,
connectionAddress: String,
onConnectionAddressChange: (String) -> Unit,
busy: Boolean,
message: String?,
messageIsError: Boolean,
compact: Boolean,
editing: Boolean,
onEditingChanged: (Boolean) -> Unit,
focusManager: FocusManager,
desiredEnabled: Boolean,
canPair: Boolean,
onPair: () -> Unit,
onApply: () -> Unit,
onPairAgain: () -> Unit,
) {
if (step == 0) {
SettingsGroup("2 · Pair Wireless debugging", compact = compact) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
) {
AdbTextField(
value = pairingAddress,
onValueChange = onPairingAddressChange,
label = "Pairing pop-up IP address & Port",
placeholder = "192.168.1.42:37123",
keyboardType = KeyboardType.Ascii,
imeAction = ImeAction.Next,
compact = compact,
onFocusChange = onEditingChanged,
onNext = { focusManager.moveFocus(FocusDirection.Next) },
)
Row(
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth(),
) {
AdbTextField(
value = pairingCode,
onValueChange = onPairingCodeChange,
label = "Pairing code (PIN)",
placeholder = "6 digits",
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done,
compact = compact,
onFocusChange = onEditingChanged,
onDone = {
focusManager.clearFocus()
},
modifier = Modifier.weight(1f),
)
PrimaryButton("Pair", compact = compact, enabled = !busy && canPair, onClick = onPair)
}
StatusMessage(busy, message, isError = messageIsError)
}
}
} else {
SettingsGroup("2 · Apply over Wireless debugging", compact = compact) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
) {
AdbTextField(
value = connectionAddress,
onValueChange = onConnectionAddressChange,
label = "Connection IP address & Port",
placeholder = "192.168.1.42:45678",
keyboardType = KeyboardType.Ascii,
imeAction = ImeAction.Done,
compact = compact,
onFocusChange = onEditingChanged,
onDone = { focusManager.clearFocus() },
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth(),
) {
StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError)
SecondaryButton("Pair again", compact = compact, enabled = !busy, onClick = onPairAgain)
PrimaryButton(
if (desiredEnabled) "Enable limit" else "Disable limit",
compact = compact,
enabled = !busy && parseAdbAddress(connectionAddress) != null,
onClick = onApply,
)
}
}
}
}
}
@Composable
private fun AdbTextField(
value: String,
onValueChange: (String) -> Unit,
label: String,
keyboardType: KeyboardType,
imeAction: ImeAction,
modifier: Modifier = Modifier,
placeholder: String? = null,
compact: Boolean = false,
onFocusChange: (Boolean) -> Unit = {},
onNext: (() -> Unit)? = null,
onDone: (() -> Unit)? = null,
) {
val context = LocalContext.current
val palette = LocalPalette.current
val onValueChangeLatest = rememberUpdatedState(onValueChange)
val onNextLatest = rememberUpdatedState(onNext)
val onDoneLatest = rememberUpdatedState(onDone)
val onFocusChangeLatest = rememberUpdatedState(onFocusChange)
var focused by remember { mutableStateOf(false) }
val shape = RoundedCornerShape(8.dp)
val inputHeight = if (compact) 44.dp else 52.dp
val colors = MaterialTheme.colorScheme
Column(modifier = modifier.fillMaxWidth()) {
Text(
label,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Medium,
color = colors.onSurfaceVariant,
maxLines = 1,
)
Box(
modifier = Modifier
.fillMaxWidth()
.height(inputHeight)
.background(colors.surfaceVariant, shape)
.border(1.dp, if (focused) palette.signal else palette.line2, shape)
.padding(horizontal = 10.dp),
contentAlignment = Alignment.CenterStart,
) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { viewContext ->
EditText(viewContext).apply {
isSingleLine = true
setHorizontallyScrolling(true)
background = null
setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0)
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f)
setTextColor(colors.onBackground.toArgb())
setHintTextColor(colors.onSurfaceVariant.toArgb())
contentDescription = label
inputType = if (keyboardType == KeyboardType.Number) {
InputType.TYPE_CLASS_NUMBER
} else {
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
}
imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
hint = placeholder
setOnEditorActionListener { _, actionId, event ->
val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER
when {
imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> {
onNextLatest.value?.invoke()
true
}
imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> {
onDoneLatest.value?.invoke()
true
}
else -> false
}
}
setOnFocusChangeListener { _, hasFocus ->
focused = hasFocus
onFocusChangeLatest.value(hasFocus)
}
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable?) {
onValueChangeLatest.value(s?.toString().orEmpty())
}
})
}
},
update = { editText ->
editText.setTextColor(colors.onBackground.toArgb())
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
editText.hint = placeholder
editText.contentDescription = label
if (editText.text.toString() != value) {
val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length
editText.setText(value)
editText.setSelection(min(cursor, value.length))
}
},
)
}
}
}
@Composable
private fun FallbackOrder(
desiredEnabled: Boolean,
busy: Boolean,
onOpenDeveloperOptions: () -> Unit,
) {
SettingsGroup("Other ways to change it") {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text("1 · Developer options (try first)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
Text("Set “Restrict child processes” ${if (desiredEnabled) "on" else "off"}.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
SecondaryButton("Open Developer options", enabled = !busy, onClick = onOpenDeveloperOptions)
Text("3 · Computer ADB (last resort)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
Text("Only if Wireless debugging is unavailable.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
PhantomProcessLimit.adbCommand(desiredEnabled),
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
private fun CompactComputerFallback(desiredEnabled: Boolean) {
SettingsGroup("3 · Computer ADB last resort", compact = true) {
Text(
PhantomProcessLimit.adbCommand(desiredEnabled),
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp),
)
}
}
@Composable
private fun StatusMessage(busy: Boolean, message: String?, modifier: Modifier = Modifier, isError: Boolean = false) {
if (busy) {
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
Text(message ?: "Working…", style = MaterialTheme.typography.bodySmall)
}
} else {
message?.let {
Text(
it,
modifier = modifier,
style = MaterialTheme.typography.bodySmall,
color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
private data class AdbEndpoint(val host: String, val port: Int)
private fun parseAdbAddress(value: String): AdbEndpoint? {
val address = value.trim()
val host: String
val portText: String
if (address.startsWith("[")) {
val closingBracket = address.indexOf(']')
if (closingBracket <= 1 || address.getOrNull(closingBracket + 1) != ':') return null
host = address.substring(1, closingBracket)
if (':' !in host) return null
portText = address.substring(closingBracket + 2)
} else {
val colon = address.lastIndexOf(':')
if (colon <= 0 || address.indexOf(':') != colon) return null
host = address.substring(0, colon)
portText = address.substring(colon + 1)
}
if (host.isBlank() || host.any(Char::isWhitespace)) return null
val port = portText.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null
return AdbEndpoint(host, port)
}
private fun formatAddressHost(host: String): String = if (':' in host) "[$host]" else host
private fun formatAdbAddress(host: String, port: Int): String = "${formatAddressHost(host)}:$port"
private fun imeActionFlag(action: ImeAction): Int = when (action) {
ImeAction.Next -> EditorInfo.IME_ACTION_NEXT
ImeAction.Done -> EditorInfo.IME_ACTION_DONE
ImeAction.Go -> EditorInfo.IME_ACTION_GO
ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH
else -> EditorInfo.IME_ACTION_UNSPECIFIED
}
+68
View File
@@ -0,0 +1,68 @@
# DroidDeck boot animation
This source accompanies the single Steam startup movie bundled by the app:
`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1920×1080, pitch black background, VP9 video
with Opus audio). `droiddeck-boot.html` is the editable animation; the scripts and WAV below
reproduce the selected render. No alternate MP4 or WebM exports are kept in the repository.
From the repository root, render the movie with:
python3 artwork/boot-animation-source/render.py 1920 1080 60 app/src/main/assets/steam-startup/droiddeck-startup.webm dark
The app stages that file into Steam's `config/uioverrides/movies` folder before each session. If
Steam still has its built-in startup movie selected, DroidDeck sets this movie as the device's
startup default before Steam starts. A custom startup movie the user selected later is preserved.
To regenerate the soundtrack, run these commands from this directory:
python3 events.py
python3 sound.py
The animation and audio are both procedurally generated; the included WAV is the soundtrack used
for the bundled render.
`droiddeck-boot.html` holds the whole animation. Every frame is a pure function of time, so the
preview page and the video render draw exactly the same thing. Open it in a browser to scrub, slow
it down or step frame by frame (arrow keys).
## Re-render the video
pip install playwright && playwright install chromium # ffmpeg with libvpx-vp9 also required
python3 render.py 1280 800 60 droiddeck-boot-1280x800.webm
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.webm
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.mp4 # .mp4 = H.264 for sharing
python3 render.py 1280 800 60 droiddeck-boot-dark-1280x800.webm dark # dark version
Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP9 for .webm or H.264 for .mp4, both BT.709,
so the orb stays #1A9FFF after compression.
## Sound
Every sound is synthesized in `sound.py` (no samples) and placed on the exact physics events the
animation reports, so hits stay frame-accurate even after you change the timing. Key: D major.
python3 events.py # export impact times, rocking, piece speeds from the animation
python3 sound.py # -> droiddeck-boot-sound.wav (-18 LUFS, -1 dBFS peak)
python3 embed_sound.py # put it in the preview page
python3 render.py ... # muxes the wav in automatically (Opus in .webm, AAC in .mp4)
The soundtrack is built from the final chord. Each piece lands on one of its notes as a soft, muted
tone (legs D, ball A with a quieter echo, bowl F#), the wobble and jump play in silence, and the
lock lands with the same soft voice and plays all the notes together. Tweak the cue sheet in `sound.py`: the `tock(...)` calls under
`# 1. the stack`, the chord list under `# 4. lock`, and the room reverb mix (`.14 * wet`).
## Where to tweak
- Timing of the drops: `archDrop`, `ballDrop`, `domeDrop` (start time, height, bounciness `e`).
- The balancing act: `SWAY` keyframes (time, lean). Bigger values = bigger wobble. The bowl leads,
the ball chases it (`sway(t - .12)`), the legs follow (`sway(t - .10)`).
- The catch-hop on the big wobble: `HOP` (start time, duration, sideways distance, height).
- Crouch before the jump: `crouchA/B/D`.
- Jump and lock-in: `FL` (rise time, apex height, lock time, how far pieces spread).
- Colors for each version (pieces, background, shadows, lock glow): `THEMES` (light, dark).
- Total length: `DUR`.
## Install as the Steam startup movie
Put the .webm in `~/.steam/root/config/uioverrides/movies/`, then pick it in
Steam > Settings > Customization > Startup Movie.
@@ -0,0 +1,700 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>DroidDeck boot animation</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap" rel="stylesheet">
<style>
:root{
box-sizing:border-box;
padding-top:env(safe-area-inset-top,0px);
padding-bottom:env(safe-area-inset-bottom,0px);
--page:#E2E8EE; --panel:#F3F6F9; --ink:#131a21; --muted:#56636F; --line:rgba(19,26,33,.12);
--track:rgba(19,26,33,.14); --accent:#1A9FFF; --accent-ink:#0B6FC2; --stage-edge:rgba(19,26,33,.10);
--font:"Sora", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
--code:ui-monospace, "SF Mono", Menlo, Consolas, monospace;
}
@media (prefers-color-scheme: dark){
:root:not([data-theme="light"]){
--page:#0D1319; --panel:#151D25; --ink:#DCE5ED; --muted:#8A98A6; --line:rgba(220,229,237,.12);
--track:rgba(220,229,237,.16); --accent-ink:#5CB8FF; --stage-edge:rgba(0,0,0,.5);
}
}
:root[data-theme="dark"]{
--page:#0D1319; --panel:#151D25; --ink:#DCE5ED; --muted:#8A98A6; --line:rgba(220,229,237,.12);
--track:rgba(220,229,237,.16); --accent-ink:#5CB8FF; --stage-edge:rgba(0,0,0,.5);
}
*,*::before,*::after{box-sizing:inherit}
html{scroll-padding-top:env(safe-area-inset-top,0px)}
body{margin:0;background:var(--page);color:var(--ink);font-family:var(--font);font-size:15px;line-height:1.55;-webkit-font-smoothing:antialiased}
main{max-width:980px;margin:0 auto;padding:28px 20px 40px}
header{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:18px}
h1{font-size:1.35rem;font-weight:600;letter-spacing:-.01em;margin:0}
.meta{color:var(--muted);font-size:.9rem;margin:0}
.stage{position:relative;width:100%;aspect-ratio:16/10;border-radius:14px;overflow:hidden;background:#D6E1EA;box-shadow:0 0 0 1px var(--stage-edge),0 18px 50px -24px rgba(10,20,30,.45)}
.stage canvas{display:block;width:100%;height:100%;cursor:pointer}
.stage.dark{background:#000}
.stage.dark .hint{color:#C9D3DD}
.head-l{display:flex;align-items:baseline;gap:14px;flex-wrap:wrap}
.version{display:inline-flex;border-radius:999px;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:3px}
.version button{border:0;background:none;border-radius:999px;padding:5px 14px;font-size:.85rem;cursor:pointer;color:var(--muted)}
.version button[aria-pressed="true"]{background:var(--ink);color:var(--page)}
.version button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
.stage .hint{position:absolute;inset:auto 0 14px 0;text-align:center;font-size:.85rem;color:#2c3a47;opacity:0;transition:opacity .25s}
.stage.ended .hint{opacity:.75}
.controls{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:14px;margin-top:16px}
button{font:inherit;color:inherit}
.play{display:inline-flex;align-items:center;gap:8px;border:0;background:var(--accent);color:#fff;border-radius:999px;padding:9px 16px 9px 12px;font-weight:600;font-size:.9rem;cursor:pointer}
.play svg{width:18px;height:18px}
.play:hover{filter:brightness(1.06)}
.play:focus-visible,.speed button:focus-visible,.beat:focus-visible,input[type=range]:focus-visible,.fs:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
.scrub{position:relative;padding-bottom:22px}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:28px;background:transparent;margin:0;cursor:pointer}
input[type=range]::-webkit-slider-runnable-track{height:4px;border-radius:4px;background:linear-gradient(to right,var(--accent) var(--p,0%),var(--track) var(--p,0%))}
input[type=range]::-moz-range-track{height:4px;border-radius:4px;background:linear-gradient(to right,var(--accent) var(--p,0%),var(--track) var(--p,0%))}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;border-radius:50%;background:var(--ink);margin-top:-6px;border:3px solid var(--page)}
input[type=range]::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:var(--ink);border:3px solid var(--page)}
.beats{position:absolute;left:8px;right:8px;bottom:0;height:20px}
.beat{position:absolute;transform:translateX(-50%);border:0;background:none;padding:0 2px;font-size:.74rem;color:var(--muted);cursor:pointer;white-space:nowrap}
.beat:first-child{transform:translateX(-4px)}
.beat:first-child::before{left:4px}
.beat::before{content:"";position:absolute;left:50%;top:-9px;width:1px;height:6px;background:var(--muted);opacity:.6}
.beat:hover,.beat.on{color:var(--ink)}
.right{display:flex;align-items:center;gap:10px}
.time{font-variant-numeric:tabular-nums;font-size:.85rem;color:var(--muted);min-width:78px;text-align:right}
.speed{display:inline-flex;border-radius:999px;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:3px}
.speed button{border:0;background:none;border-radius:999px;padding:4px 10px;font-size:.8rem;cursor:pointer;color:var(--muted)}
.speed button[aria-pressed="true"]{background:var(--ink);color:var(--page)}
.snd{display:inline-flex;align-items:center;gap:6px;border:0;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);border-radius:999px;height:32px;padding:0 12px 0 9px;font-size:.8rem;cursor:pointer;color:var(--ink)}
.snd svg{width:18px;height:18px}
.snd[aria-pressed="true"]{background:var(--accent);color:#fff;box-shadow:none}
.snd:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
.fs{border:0;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);border-radius:999px;width:32px;height:32px;display:grid;place-items:center;cursor:pointer;color:var(--ink)}
.fs svg{width:16px;height:16px}
.install{margin-top:34px;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:28px;border-top:1px solid var(--line);padding-top:24px}
.install h2{font-size:1rem;font-weight:600;margin:0 0 8px}
.install p,.install ol{margin:0;color:var(--muted);font-size:.9rem;max-width:62ch}
.install ol{padding-left:1.2em}
.install li+li{margin-top:6px}
code{font-family:var(--code);font-size:.84em;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:1px 6px;border-radius:6px;color:var(--ink);overflow-wrap:anywhere}
@media (max-width:640px){
main{padding:18px 14px 32px}
.controls{grid-template-columns:auto 1fr;row-gap:6px}
.right{grid-column:1 / -1;justify-content:space-between}
.install{grid-template-columns:1fr}
.beat{font-size:.68rem}
.snd span{display:none}
.snd{padding:0 8px}
.right{gap:8px}
}
body.render{background:#000;margin:0}
body.render main{display:none}
</style>
</head>
<body>
<main>
<header>
<div class="head-l">
<h1>DroidDeck boot animation</h1>
<p class="meta" id="meta">6.3 s at 60 fps, with sound</p>
</div>
<div class="version" role="group" aria-label="Version">
<button data-v="light" aria-pressed="true">Light</button>
<button data-v="dark" aria-pressed="false">Dark</button>
</div>
</header>
<div class="stage" id="stage">
<canvas id="cv" aria-label="DroidDeck boot animation: three logo pieces stack into a little droid balancing a bowl on its head, then jump and lock into the DroidDeck mark"></canvas>
<div class="hint" id="hint">Tap to replay</div>
</div>
<div class="controls">
<button class="play" id="play" aria-label="Pause">
<svg viewBox="0 0 24 24" aria-hidden="true"><path id="playIcon" fill="currentColor" d="M7 5h4v14H7zM13 5h4v14h-4z"/></svg>
<span id="playLabel">Pause</span>
</button>
<div class="scrub">
<input type="range" id="scrub" min="0" max="1000" step="1" value="0" aria-label="Timeline">
<div class="beats" id="beats"></div>
</div>
<div class="right">
<span class="time" id="time">0.00 / 6.30</span>
<div class="speed" role="group" aria-label="Playback speed">
<button data-s="1" aria-pressed="true">1×</button>
<button data-s="0.5" aria-pressed="false">½×</button>
<button data-s="0.25" aria-pressed="false">¼×</button>
</div>
<button class="snd" id="snd" aria-pressed="false" aria-label="Sound">
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M3 9.5h4l5-4.2v13.4l-5-4.2H3z"/><path id="sndMark" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M16 9.5l5 5M21 9.5l-5 5"/></svg>
<span>Sound</span>
</button>
<button class="fs" id="fs" aria-label="Full screen" hidden>
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>
</button>
</div>
</div>
<section class="install">
<div>
<h2>Use it as the Steam startup movie</h2>
<ol>
<li>Put the <code>.webm</code> file in <code>~/.steam/<wbr>root/<wbr>config/<wbr>uioverrides/<wbr>movies/</code>. Create the folders if they don’t exist.</li>
<li>In Steam, open Settings &gt; Customization &gt; Startup Movie and pick it.</li>
</ol>
</div>
<div>
<h2>Which file to ship</h2>
<p>Ship the dark version if your Steam UI is dark: it hands off to the library without a bright flash. The 1280×800 cut matches Steam Deck and is the safe default. The 1920×1080 cut is sharper on phones and TVs. Steam needs the <code>.webm</code>; the <code>.mp4</code> files are for sharing. Everything is drawn and synthesized in code, so the included scripts can output any other size.</p>
</div>
</section>
</main>
<script>
/* =====================================================================
DroidDeck boot animation engine
Every frame is a pure function of time t, so the live preview and the
offline video render draw exactly the same thing.
Units: logo units from droiddeck-mark.svg. World origin = frame centre,
y points down. The frame is always 690 units tall.
===================================================================== */
const DD = (() => {
'use strict';
const deg = Math.PI / 180;
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
const eio = t => { t = clamp(t); return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
const eInQ = t => { t = clamp(t); return t * t; };
const eOutC = t => { t = clamp(t); return 1 - Math.pow(1 - t, 3); };
// ---- 2D affine helpers. m = [a,b,c,d,e,f] (canvas setTransform order)
const mul = (m, n) => [
m[0]*n[0] + m[2]*n[1], m[1]*n[0] + m[3]*n[1],
m[0]*n[2] + m[2]*n[3], m[1]*n[2] + m[3]*n[3],
m[0]*n[4] + m[2]*n[5] + m[4], m[1]*n[4] + m[3]*n[5] + m[5]];
const T = (x, y) => [1, 0, 0, 1, x, y];
const R = a => { const c = Math.cos(a), s = Math.sin(a); return [c, s, -s, c, 0, 0]; };
const S = (x, y) => [x, 0, 0, y, 0, 0];
const chain = (...ms) => ms.reduce(mul);
const ap = (m, p) => ({ x: m[0]*p.x + m[2]*p.y + m[4], y: m[1]*p.x + m[3]*p.y + m[5] });
const rv = (a, x, y) => { const c = Math.cos(a), s = Math.sin(a); return { x: c*x - s*y, y: s*x + c*y }; };
// ---- Geometry straight from the SVG
const G = { L: -31.98, B: 223.72, slotL: 56.055, slotR: 71.885, cy: 111.86,
dcx: 63.97, dR: 111.86, hcx: 63.98, hR: 71.81, ocx: 63.98, oR: 55.98 };
const ORB = '#1A9FFF';
const THEMES = {
light: { ink: '#1b1b1b', bg: ['#EDF3F8', '#DCE6EE', '#B6C7D6'], shadow: '22,40,58', shadowK: 1, ringA: 1, ringGlow: 0, glow: 0, noise: 3 },
// Keep the shipped Steam render black between and around the animated pieces.
dark: { ink: '#FFFFFF', bg: ['#000000', '#000000', '#000000'], shadow: '0,0,0', shadowK: 2.3, ringA: 1.5, ringGlow: 14, glow: .34, noise: 0 },
};
let TH = THEMES.light, THN = 'light';
const setTheme = n => { THN = THEMES[n] ? n : 'light'; TH = THEMES[THN]; };
const ORB_C = { x: G.ocx, y: G.cy };
function archPath() { // left piece: the "bridge"
const p = new Path2D();
const dx = G.slotL - G.hcx, hy = Math.sqrt(G.hR*G.hR - dx*dx);
p.moveTo(G.L, 0); p.lineTo(G.slotL, 0); p.lineTo(G.slotL, G.cy - hy);
p.arc(G.hcx, G.cy, G.hR, Math.atan2(-hy, dx), Math.atan2(hy, dx), true);
p.lineTo(G.slotL, G.B); p.lineTo(G.L, G.B); p.closePath();
return p;
}
function domePath() { // right piece: the curve of the D
const dxo = G.slotR - G.dcx, hyo = Math.sqrt(G.dR*G.dR - dxo*dxo);
const dxi = G.slotR - G.hcx, hyi = Math.sqrt(G.hR*G.hR - dxi*dxi);
const p = new Path2D();
p.moveTo(G.slotR, G.cy - hyo);
p.arc(G.dcx, G.cy, G.dR, Math.atan2(-hyo, dxo), Math.atan2(hyo, dxo), false);
p.lineTo(G.slotR, G.cy + hyi);
p.arc(G.hcx, G.cy, G.hR, Math.atan2(hyi, dxi), Math.atan2(-hyi, dxi), true);
p.closePath();
return p;
}
function orbPath() { const p = new Path2D(); p.arc(G.ocx, G.cy, G.oR, 0, Math.PI*2); return p; }
const PATH = { arch: archPath(), dome: domePath(), orb: orbPath() };
// centroids (numerical, symmetric in y)
function centroid(path, x0, x1) {
const c = document.createElement('canvas').getContext('2d');
let n = 0, sx = 0;
for (let x = x0; x <= x1; x += .5) for (let y = 0; y <= G.B; y += .5)
if (c.isPointInPath(path, x, y)) { n++; sx += x; }
return { x: sx / n, y: G.cy };
}
const CEN = { arch: centroid(PATH.arch, G.L, G.slotL), dome: centroid(PATH.dome, G.slotR, 176) };
// anchors: the point of each piece that touches whatever it stands on
const ANC = { arch: { x: G.slotL, y: G.cy }, ball: { x: G.ocx, y: G.cy + G.oR }, dome: { x: G.hcx + G.hR, y: G.cy } };
const HA = G.slotL - G.L; // arch height when standing (88.035)
const WA = G.cy; // arch half width (111.86)
const FOOT_HALF = (G.cy - (G.cy - Math.sqrt(G.hR*G.hR - (G.slotL-G.hcx)**2))) ; // unused helper
const FEET = [{ x: G.slotL, y: 20.24 }, { x: G.slotL, y: G.B - 20.24 }]; // foot centres (piece coords)
// ---- Scene constants
const VIEW_H = 690; // world units visible vertically
const FLOOR = 150;
const GRAV = 6500;
const DUR = 6.30;
const T_L = 4.00; // lift-off
// ------------------------------------------------------------------
// Drops: exact ballistic bounces (height above whatever you land on)
// ------------------------------------------------------------------
function drop(o) {
const g = GRAV, segs = [], impacts = [];
let t = o.t0, v = o.v0;
let tau = (-v + Math.sqrt(v*v + 2*g*o.h0)) / g;
segs.push({ ts: t, te: t + tau, h0: o.h0, vu: -v });
t += tau; v = v + g*tau; impacts.push({ t, v });
for (;;) {
const vu = o.e * v; if (vu < o.minV) break;
const d = 2*vu / g; segs.push({ ts: t, te: t + d, h0: 0, vu });
t += d; v = vu; impacts.push({ t, v });
}
const rest = t;
const seg = tt => { for (const s of segs) if (tt < s.te) return s; return null; };
return {
o, impacts, rest, land: impacts[0].t,
h(tt) { if (tt <= o.t0) return o.h0; const s = seg(tt); if (!s) return 0; const u = tt - s.ts; return Math.max(0, s.h0 + s.vu*u - .5*g*u*u); },
v(tt) { if (tt <= o.t0 || tt >= rest) return 0; const s = seg(tt); return s ? s.vu - g*(tt - s.ts) : 0; },
air(tt) { return tt > o.t0 && tt < rest; }
};
}
const archDrop = drop({ t0: 0.10, h0: 520, v0: 250, e: 0.20, minV: 300 });
const ballDrop = drop({ t0: 0.50, h0: 440, v0: 250, e: 0.45, minV: 170 });
const domeDrop = drop({ t0: 1.15, h0: 330, v0: 250, e: 0.24, minV: 250 });
// ------------------------------------------------------------------
// The balancing act: one master sway curve, everything else follows it
// through springs so the parts lag, overshoot and settle on their own.
// ------------------------------------------------------------------
const SWAY = [[1.60, 0], [1.90, .42], [2.24, -.70], [2.62, .95], [2.82, 1.10],
[3.08, -.44], [3.30, .16], [3.50, 0]];
function sway(t) {
if (t <= SWAY[0][0] || t >= SWAY[SWAY.length-1][0]) return 0;
for (let i = 0; i < SWAY.length - 1; i++) {
const [ta, va] = SWAY[i], [tb, vb] = SWAY[i+1];
if (t < tb) { const p = (t - ta)/(tb - ta); return va + (vb - va)*(.5 - .5*Math.cos(Math.PI*p)); }
}
return 0;
}
// legs hop sideways to get back under the bowl on the big wobble
const HOP = { t: 2.70, d: .19, dx: 26, h: 16 };
const hopX = t => HOP.dx*eio((t - HOP.t)/HOP.d);
const hopH = t => (t > HOP.t && t < HOP.t + HOP.d) ? HOP.h*Math.sin(Math.PI*(t - HOP.t)/HOP.d) : 0;
// crouch before the jump (added straight onto squash)
function crouch(t, amt, a, b, hold) {
if (t < a || t >= T_L) return 0;
if (t < b) return amt * eio((t - a)/(b - a));
if (t < hold) return amt;
return amt * (1 - eInQ((t - hold)/(T_L - hold)));
}
const crouchA = t => crouch(t, .17, 3.56, 3.84, 3.91);
const crouchB = t => crouch(t, .12, 3.60, 3.86, 3.91);
const crouchD = t => crouch(t, .09, 3.64, 3.88, 3.91);
const PHI_FALL = 5*deg, PSI_FALL = -6*deg, U0 = 12;
const ROLL = G.oR/G.dR; // bowl radius is 2x the ball: it turns 1.5x as it rolls
const DT = 1/1200, N = Math.ceil((DUR + .2)/DT);
const SIG = { phi: new Float32Array(N), u: new Float32Array(N), psi: new Float32Array(N),
qA: new Float32Array(N), qB: new Float32Array(N), qD: new Float32Array(N) };
function peakFactor(w, z) { // peak of a unit-velocity kick
const wd = w*Math.sqrt(1 - z*z), ts = Math.atan(wd/(z*w))/wd;
return Math.exp(-z*w*ts)*Math.sin(wd*ts)/wd;
}
const SPR = { A: [40, .32], B: [34, .28], D: [36, .34] };
const kick = (k, peak) => peak / peakFactor(SPR[k][0], SPR[k][1]);
(function simulate() {
const K = [];
const v1a = archDrop.impacts[0].v, v1b = ballDrop.impacts[0].v, v1d = domeDrop.impacts[0].v;
archDrop.impacts.forEach(i => K.push({ t: i.t, k: 'A', dv: kick('A', .13 * i.v/v1a) }));
ballDrop.impacts.forEach(i => { const r = i.v/v1b;
K.push({ t: i.t, k: 'B', dv: kick('B', .24*r) }); K.push({ t: i.t, k: 'A', dv: kick('A', .06*r) });
K.push({ t: i.t, k: 'phi', dv: .55*r }); });
domeDrop.impacts.forEach(i => { const r = i.v/v1d;
K.push({ t: i.t, k: 'D', dv: kick('D', .11*r) }); K.push({ t: i.t, k: 'B', dv: kick('B', .17*r) });
K.push({ t: i.t, k: 'A', dv: kick('A', .07*r) }); });
K.push({ t: HOP.t + HOP.d, k: 'A', dv: kick('A', .07) }); K.push({ t: HOP.t + HOP.d, k: 'B', dv: kick('B', .06) });
K.push({ t: HOP.t + HOP.d, k: 'D', dv: kick('D', .04) });
K.sort((a, b) => a.t - b.t);
let phi = PHI_FALL, phiV = 0, phiA = 0, u = U0, uV = 0, psi = PSI_FALL, psiV = 0;
const q = { A: [0, 0], B: [0, 0], D: [0, 0] };
let ki = 0, crossings = 0, lastSign = 1;
for (let i = 0; i < N; i++) {
const t = i*DT;
while (ki < K.length && K[ki].t <= t) {
const k = K[ki++];
if (k.k === 'phi') phiV += k.dv; else q[k.k][1] += k.dv;
}
const s = sway(t);
// arch rocking on its feet
if (t < archDrop.land) { phi = PHI_FALL; phiV = 0; phiA = 0; }
else {
const w = 20, z = .38, tgt = 5.6*deg*sway(t - .10);
phiA = -w*w*(phi - tgt) - 2*z*w*phiV; phiV += phiA*DT; phi += phiV*DT;
const sg = Math.sign(phi) || lastSign;
if (sg !== lastSign && crossings < 2 && t < 1.0) { q.A[1] += kick('A', .035); crossings++; }
lastSign = sg;
}
// ball rolling along the arch top
if (t < ballDrop.rest) { u = U0; uV = 0; }
else { const w = 13, z = .5, tgt = 24*sway(t - .12); const a = -w*w*(u - tgt) - 2*z*w*uV; uV += a*DT; u += uV*DT; }
// dome: floppy hat with inertia (it lags the body)
if (t < domeDrop.land) { psi = PSI_FALL; psiV = 0; }
else { const w = 13, z = .22, tgt = 11*deg*s; const a = -w*w*(psi - tgt) - 2*z*w*psiV - .6*phiA; psiV += a*DT; psi += psiV*DT; }
// squash springs; falling pieces stretch along their velocity
const tgA = archDrop.air(t) ? -Math.min(.12, Math.abs(archDrop.v(t))*4.6e-5) : 0;
const tgB = ballDrop.air(t) ? -Math.min(.14, Math.abs(ballDrop.v(t))*6.5e-5) : 0;
const tgD = domeDrop.air(t) ? -Math.min(.10, Math.abs(domeDrop.v(t))*4.0e-5) : 0;
for (const [k, tg] of [['A', tgA], ['B', tgB], ['D', tgD]]) {
const [w, z] = SPR[k]; const st = q[k];
const a = -w*w*(st[0] - tg) - 2*z*w*st[1]; st[1] += a*DT; st[0] += st[1]*DT;
}
SIG.phi[i] = phi; SIG.u[i] = u; SIG.psi[i] = psi;
SIG.qA[i] = q.A[0]; SIG.qB[i] = q.B[0]; SIG.qD[i] = q.D[0];
}
})();
const sig = (name, t) => {
const x = clamp(t/DT, 0, N - 1.001), i = Math.floor(x), f = x - i, a = SIG[name];
return a[i] + (a[i+1] - a[i])*f;
};
// ------------------------------------------------------------------
// Standing pose: a kinematic chain floor → arch → ball → dome
// ------------------------------------------------------------------
function standPose(t) {
const hA = archDrop.h(t) + hopH(t), hx = hopX(t), phi = sig('phi', t), u = sig('u', t), psi = sig('psi', t);
const qA = sig('qA', t) + crouchA(t), qB = sig('qB', t) + crouchB(t), qD = sig('qD', t) + crouchD(t);
const hB = ballDrop.h(t), hD = domeDrop.h(t);
const sxA = 1 + .55*qA, syA = 1 - qA;
const side = phi >= 0 ? 1 : -1; // rock on the outer corner of one foot
const piv = { x: hx + side*WA*sxA, y: FLOOR - hA };
const off = rv(phi, -side*WA*sxA, 0);
const A = { x: piv.x + off.x, y: piv.y + off.y };
const mA = chain(T(A.x, A.y), R(phi), S(sxA, syA), R(90*deg), T(-ANC.arch.x, -ANC.arch.y));
const top = rv(phi, u, -HA*syA);
const cB = { x: A.x + top.x, y: A.y + top.y - hB };
const sxB = 1 + .8*qB, syB = 1 - qB;
const mB = chain(T(cB.x, cB.y), R(phi), S(sxB, syB), T(-ANC.ball.x, -ANC.ball.y));
const bc = rv(phi, 0, -G.oR*syB), O = { x: cB.x + bc.x, y: cB.y + bc.y };
// bowl: outer curve resting on the ball, rolling without slipping
const ang = phi + psi, dd = rv(ang, 0, -G.oR*syB);
const cD = { x: O.x + dd.x, y: O.y + dd.y - hD };
const sxD = 1 + .6*qD, syD = 1 - qD;
const mD = chain(T(cD.x, cD.y), R(ang), S(sxD, syD), T(0, -G.dR), R(psi*ROLL), R(90*deg), T(-G.dcx, -G.cy));
return { arch: mA, ball: mB, dome: mD, O, hA };
}
// ------------------------------------------------------------------
// Flight: lift-off, unfold around the orb, magnetic clack, hover settle
// ------------------------------------------------------------------
const FL = { TR: .34, APEX: -108, TC: .44, X: 48, ROT: .40 };
const H0 = (() => {
const p = standPose(T_L), O = p.O, h = { O };
for (const k of ['arch', 'dome']) {
const c = ap(p[k], CEN[k]), m = p[k];
const fin = { x: CEN[k].x - ORB_C.x, y: 0 };
h[k] = { a0: Math.atan2(c.y - O.y, c.x - O.x), r0: Math.hypot(c.x - O.x, c.y - O.y),
th0: Math.atan2(m[1], m[0]), aF: k === 'arch' ? Math.PI : 0, rF: Math.abs(fin.x) };
}
return h;
})();
const damp = (s, w, z) => { const wd = w*Math.sqrt(1 - z*z); return Math.exp(-z*w*s)*Math.sin(wd*s)/wd; };
const fromRest = (x0, s, w, z) => { const wd = w*Math.sqrt(1 - z*z);
return Math.exp(-z*w*s)*(x0*Math.cos(wd*s) + (z*w*x0/wd)*Math.sin(wd*s)); };
function flightPose(t) {
const tau = t - T_L, sC = tau - FL.TC;
const done = tau > 1.7;
let Oy = tau < FL.TR ? H0.O.y + (FL.APEX - H0.O.y)*(1 - (1 - tau/FL.TR)**2)
: fromRest(FL.APEX, tau - FL.TR, 9.5, .75);
let Ox = H0.O.x*(1 - eio(tau/.4));
if (done) { Ox = 0; Oy = 0; }
const O = { x: Ox, y: Oy };
const st = -Math.sin(Math.PI*clamp(tau/.30))*.085; // stretch on the way up
const gs = sC > 0 && !done ? 1 + .05*Math.exp(-6*sC)*Math.sin(20*sC) : 1;
const G_ = chain(T(O.x, O.y), S(gs, gs), T(-O.x, -O.y));
const piece = (k, jsign, kq) => {
const h = H0[k];
const a = h.a0 + (h.aF - h.a0)*eio(tau/FL.ROT);
let r = h.rF + (h.r0 - h.rF)*(1 - smooth(0, .30, tau));
r += FL.X*smooth(0, .22, tau)*(1 - eInQ((tau - .30)/(FL.TC - .30)));
if (sC > 0 && !done) r += 3.6*Math.exp(-14*sC)*Math.abs(Math.sin(38*sC)); // hard stop, tiny rebound
let th = h.th0 + (0 - h.th0)*eio((tau - .02)/FL.ROT);
if (done) { r = h.rF; th = 0; }
const q = st*kq, c = CEN[k];
const C = { x: O.x + r*Math.cos(done ? h.aF : a), y: O.y + r*Math.sin(done ? h.aF : a) };
return mul(G_, chain(T(C.x, C.y), S(1 + .6*q, 1 - q), R(th), T(-c.x, -c.y)));
};
const qb = st*1.1;
const ball = mul(G_, chain(T(O.x, O.y), S(1 + .8*qb, 1 - qb), T(-ORB_C.x, -ORB_C.y)));
return { arch: piece('arch', 1, .8), dome: piece('dome', -1, .8), ball, O, tau };
}
function pose(t) {
t = clamp(t, 0, DUR);
const p = t < T_L ? standPose(t) : flightPose(t);
// contact shadows
const fade = t < T_L ? 1 : 1 - smooth(0, .2, t - T_L);
const sh = [];
if (fade > 0) {
let lowest = Infinity, cx = 0;
for (const f of FEET) {
const w = ap(p.arch, f), hf = Math.max(0, FLOOR - w.y);
lowest = Math.min(lowest, hf); cx += w.x/2;
sh.push({ x: w.x, rx: 30 + hf*.35, ry: 5.5 + hf*.05, a: .34*Math.exp(-hf/22)*fade });
}
sh.unshift({ x: cx, rx: 150 + lowest*.35, ry: 15 + lowest*.03, a: .17*Math.exp(-lowest/210)*fade });
}
p.shadows = sh;
// shock ring when the pieces lock
const sC = t - (T_L + FL.TC);
p.sC = sC;
p.ring = sC > 0 && sC < .8 ? { O: p.O, r: 118 + 210*eOutC(sC/.8), a: .34*(1 - sC/.8)**2, w: 4*(1 - .7*sC/.8) } : null;
return p;
}
// ------------------------------------------------------------------
// Drawing
// ------------------------------------------------------------------
function makeBG(W, H, noise) {
const c = document.createElement('canvas'); c.width = W; c.height = H;
const g = c.getContext('2d');
const cx = W/2, cy = H*.47, R = Math.hypot(W, H)*.6;
const gr = g.createRadialGradient(cx, cy, 0, cx, cy, R);
gr.addColorStop(0, TH.bg[0]); gr.addColorStop(.42, TH.bg[1]); gr.addColorStop(1, TH.bg[2]);
g.fillStyle = gr; g.fillRect(0, 0, W, H);
if (noise) { // static dither: kills banding in the video
const id = g.getImageData(0, 0, W, H), d = id.data; let s = 1337;
for (let i = 0; i < d.length; i += 4) {
s = (s*1664525 + 1013904223) >>> 0; const n = ((s >>> 24)/255 - .5)*noise;
d[i] += n; d[i+1] += n; d[i+2] += n;
}
g.putImageData(id, 0, 0);
}
return c;
}
function draw(ctx, W, H, t, bg) {
const px = H/VIEW_H, base = [px, 0, 0, px, W/2, H/2];
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(bg, 0, 0, W, H);
const p = pose(t);
for (const s of p.shadows) {
if (s.a < .003) continue;
ctx.setTransform(...mul(base, [s.rx, 0, 0, s.ry, s.x, FLOOR]));
const g = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
const a = Math.min(.9, s.a*TH.shadowK), c = TH.shadow;
g.addColorStop(0, `rgba(${c},${a})`); g.addColorStop(.55, `rgba(${c},${a*.45})`); g.addColorStop(1, `rgba(${c},0)`);
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, 1, 0, Math.PI*2); ctx.fill();
}
if (p.ring) {
ctx.setTransform(...base);
ctx.strokeStyle = `rgba(26,159,255,${Math.min(1, p.ring.a*TH.ringA)})`; ctx.lineWidth = p.ring.w;
if (TH.ringGlow) { ctx.shadowColor = `rgba(26,159,255,${Math.min(1, p.ring.a*2)})`; ctx.shadowBlur = TH.ringGlow*px; }
ctx.beginPath(); ctx.arc(p.ring.O.x, p.ring.O.y, p.ring.r, 0, Math.PI*2); ctx.stroke();
ctx.shadowBlur = 0; ctx.shadowColor = 'transparent';
}
if (TH.glow && p.sC > 0 && p.sC < 1.4) { // dark only: the orb flashes on at lock, light leaks through the halo gap
const ga = TH.glow*Math.min(1, p.sC/.03)*Math.exp(-p.sC/.32)*(1 - smooth(1.0, 1.4, p.sC));
ctx.setTransform(...base);
const g = ctx.createRadialGradient(p.O.x, p.O.y, G.oR*.9, p.O.x, p.O.y, G.oR*2.6);
g.addColorStop(0, `rgba(26,159,255,${ga})`); g.addColorStop(.35, `rgba(26,159,255,${ga*.45})`); g.addColorStop(1, 'rgba(26,159,255,0)');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(p.O.x, p.O.y, G.oR*2.6, 0, Math.PI*2); ctx.fill();
}
ctx.fillStyle = TH.ink;
ctx.setTransform(...mul(base, p.arch)); ctx.fill(PATH.arch);
ctx.setTransform(...mul(base, p.dome)); ctx.fill(PATH.dome);
ctx.fillStyle = ORB;
ctx.setTransform(...mul(base, p.ball)); ctx.fill(PATH.orb);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
// how far (px) things move during an exposure: drives motion-blur sample count
const PROBE = { arch: [{x:G.L,y:0},{x:G.L,y:G.B},{x:G.slotL,y:0},{x:G.slotL,y:G.B}],
dome: [{x:G.slotR,y:0},{x:G.slotR,y:G.B},{x:176,y:G.cy}],
ball: [{x:G.ocx-G.oR,y:G.cy},{x:G.ocx+G.oR,y:G.cy},{x:G.ocx,y:G.cy-G.oR},{x:G.ocx,y:G.cy+G.oR}] };
function motionPx(t0, t1, H) {
const a = pose(t0), b = pose(t1), px = H/VIEW_H; let m = 0;
for (const k of ['arch', 'dome', 'ball']) for (const q of PROBE[k]) {
const p0 = ap(a[k], q), p1 = ap(b[k], q); m = Math.max(m, Math.hypot(p1.x - p0.x, p1.y - p0.y));
}
if (b.ring) m = Math.max(m, Math.abs(b.ring.r - (a.ring ? a.ring.r : 116)));
return m*px;
}
// Offline render with real motion blur (180° shutter, adaptive samples)
let RC = null;
function renderFrame(i, fps = 60, shutter = .5) {
const cv = document.getElementById('cv'), W = cv.width, H = cv.height;
if (!RC || RC.W !== W || RC.H !== H || RC.theme !== THN) {
const ctx = cv.getContext('2d', { willReadFrequently: true });
RC = { W, H, theme: THN, ctx, bg: makeBG(W, H, TH.noise), acc: new Uint16Array(W*H*4) };
}
const t = i/fps, ex = shutter/fps;
const t0 = Math.max(0, t - ex/2), t1 = Math.min(DUR, t + ex/2);
const n = Math.max(1, Math.min(48, Math.ceil(motionPx(t0, t1, H)/.45)));
if (n === 1) { draw(RC.ctx, W, H, t, RC.bg); }
else {
const acc = RC.acc; acc.fill(0);
for (let k = 0; k < n; k++) {
draw(RC.ctx, W, H, t0 + (k + .5)/n*(t1 - t0), RC.bg);
const d = RC.ctx.getImageData(0, 0, W, H).data;
for (let j = 0; j < d.length; j++) acc[j] += d[j];
}
const out = RC.ctx.createImageData(W, H), o = out.data;
for (let j = 0; j < o.length; j++) o[j] = (acc[j] + (n >> 1))/n;
RC.ctx.putImageData(out, 0, 0);
}
return { url: cv.toDataURL('image/png'), samples: n };
}
return { DUR, T_L, HOP, setTheme, get theme() { return THN; }, draw, makeBG, renderFrame, pose, sig, sway, drops: { archDrop, ballDrop, domeDrop },
BEATS: [['Drop', .10], ['Wobble', 1.60], ['Jump', 3.56], ['Lock', T_L + FL.TC]],
frameCount: fps => Math.round(DUR*fps) + 1, CEN, H0 };
})();
/* =====================================================================
Preview player (or bare canvas when ?render=1)
===================================================================== */
(() => {
const qs = new URLSearchParams(location.search);
const cv = document.getElementById('cv');
if (qs.get('render')) {
document.body.classList.add('render');
DD.setTheme(qs.get('theme') || 'light');
document.body.appendChild(cv);
cv.width = +qs.get('w') || 1280; cv.height = +qs.get('h') || 800;
cv.style.width = cv.width + 'px'; cv.style.height = cv.height + 'px';
return;
}
const stage = document.getElementById('stage'), ctx = cv.getContext('2d');
const scrub = document.getElementById('scrub'), timeEl = document.getElementById('time');
const playBtn = document.getElementById('play'), playIcon = document.getElementById('playIcon'), playLabel = document.getElementById('playLabel');
const beatsEl = document.getElementById('beats'), fsBtn = document.getElementById('fs');
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const sndBtn = document.getElementById('snd'), sndMark = document.getElementById('sndMark'), hint = document.getElementById('hint');
let W = 0, H = 0, bg = null, t = reduce ? DD.DUR : 0, playing = !reduce, speed = 1, last = 0, raf = 0;
// Soundtrack through Web Audio. When it's playing, the audio clock drives the picture.
const Sound = (() => {
let ctx = null, buf = null, src = null, on = false, pending = null, t0 = 0, c0 = 0, rate = 1;
const bytes = () => { const b = atob(DD_SOUND), u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u.buffer; };
async function ensure() { // call from a tap: browsers only allow sound after one
if (!ctx) { const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return false; ctx = new AC(); }
if (ctx.state !== 'running') { try { await ctx.resume(); } catch (e) {} }
if (!buf) { pending = pending || new Promise((ok, no) => ctx.decodeAudioData(bytes(), ok, no));
try { buf = await pending; } catch (e) { pending = null; return false; } }
return ctx.state === 'running';
}
function stop() { if (src) { try { src.stop(); } catch (e) {} src.disconnect(); src = null; } }
function start(at, r) {
stop(); if (!on || !buf || !ctx || ctx.state !== 'running' || at >= buf.duration) return;
src = ctx.createBufferSource(); src.buffer = buf; src.playbackRate.value = r; src.connect(ctx.destination);
c0 = ctx.currentTime; t0 = at; rate = r; src.start(c0, at);
}
function clock() { return src ? t0 + Math.max(0, ctx.currentTime - c0 - (ctx.outputLatency || 0))*rate : null; }
return { ensure, start, stop, clock, get on() { return on; }, set on(v) { on = v; if (!v) stop(); } };
})();
// version: remembered per viewer, otherwise follows the system theme
let ver = null; try { ver = localStorage.getItem('dd-version'); } catch (e) {}
if (ver !== 'light' && ver !== 'dark') ver = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
function setVersion(v) {
ver = v; DD.setTheme(v); stage.classList.toggle('dark', v === 'dark');
document.querySelectorAll('.version button').forEach(b => b.setAttribute('aria-pressed', b.dataset.v === v));
if (W) bg = DD.makeBG(W, H, 0);
try { localStorage.setItem('dd-version', v); } catch (e) {}
}
document.querySelectorAll('.version button').forEach(b => b.onclick = () => { setVersion(b.dataset.v); render(); });
setVersion(ver);
function size() {
const r = stage.getBoundingClientRect(), dpr = Math.min(window.devicePixelRatio || 1, 2.5);
const w = Math.round(r.width*dpr), h = Math.round(r.height*dpr);
if (w !== W || h !== H) { W = cv.width = w; H = cv.height = h; bg = DD.makeBG(W, H, 0); }
render();
}
const ICON = { pause: 'M7 5h4v14H7zM13 5h4v14h-4z', play: 'M8 5.5v13l11-6.5z', replay: 'M12 5a7 7 0 1 1-6.6 4.7l1.9.6A5 5 0 1 0 12 7v3L7.5 6 12 2z' };
function ui() {
const ended = t >= DD.DUR - 1e-6;
const mode = playing ? 'pause' : ended ? 'replay' : 'play';
playIcon.setAttribute('d', ICON[mode]);
playLabel.textContent = mode === 'pause' ? 'Pause' : mode === 'replay' ? 'Replay' : 'Play';
playBtn.setAttribute('aria-label', playLabel.textContent);
stage.classList.toggle('ended', ended && !playing);
hint.textContent = Sound.on ? 'Tap to replay' : 'Turn on Sound to hear it';
sndBtn.setAttribute('aria-pressed', Sound.on);
sndMark.setAttribute('d', Sound.on ? 'M15.5 9.2a4 4 0 0 1 0 5.6M18.3 6.6a7.6 7.6 0 0 1 0 10.8' : 'M16 9.5l5 5M21 9.5l-5 5');
const p = t/DD.DUR; scrub.value = Math.round(p*1000); scrub.style.setProperty('--p', (p*100) + '%');
timeEl.textContent = `${t.toFixed(2)} / ${DD.DUR.toFixed(2)}`;
let cur = -1; DD.BEATS.forEach((b, i) => { if (t >= b[1]) cur = i; });
[...beatsEl.children].forEach((el, i) => el.classList.toggle('on', i === cur));
}
function render() { if (bg) DD.draw(ctx, W, H, t, bg); ui(); }
function loop(now) {
raf = 0;
if (playing) {
const heard = Sound.clock();
if (heard !== null) t = Math.min(DD.DUR, heard);
else t = Math.min(DD.DUR, t + Math.min(.05, (now - last)/1000)*speed);
if (t >= DD.DUR) playing = false;
}
last = now; render();
if (playing) raf = requestAnimationFrame(loop);
}
function play() {
if (t >= DD.DUR - 1e-6) t = 0;
playing = true; Sound.start(t, speed); last = performance.now();
if (!raf) raf = requestAnimationFrame(loop);
}
function pause() { playing = false; Sound.stop(); render(); }
sndBtn.onclick = async () => {
if (Sound.on) { Sound.on = false; ui(); return; }
Sound.on = true; ui();
if (!(await Sound.ensure())) { Sound.on = false; ui(); return; }
t = 0; play(); // replay from the top so it's heard in sync
};
playBtn.onclick = () => playing ? pause() : play();
cv.onclick = () => playing ? pause() : play();
scrub.oninput = () => { playing = false; Sound.stop(); t = scrub.value/1000*DD.DUR; render(); };
document.querySelectorAll('.speed button').forEach(b => b.onclick = () => {
speed = +b.dataset.s; document.querySelectorAll('.speed button').forEach(x => x.setAttribute('aria-pressed', x === b));
if (playing) Sound.start(t, speed);
});
DD.BEATS.forEach(([name, bt]) => {
const b = document.createElement('button'); b.className = 'beat'; b.textContent = name;
b.style.left = (bt/DD.DUR*100) + '%'; b.onclick = () => { t = bt; play(); };
beatsEl.appendChild(b);
});
addEventListener('keydown', e => {
if (e.target.closest('input,button') && e.key !== ' ') return;
if (e.key === ' ') { e.preventDefault(); playing ? pause() : play(); }
else if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
e.preventDefault(); playing = false; Sound.stop(); t = Math.max(0, Math.min(DD.DUR, t + (e.key === 'ArrowRight' ? 1 : -1)/60)); render();
}
});
if (stage.requestFullscreen) {
fsBtn.hidden = false;
fsBtn.onclick = () => document.fullscreenElement ? document.exitFullscreen() : stage.requestFullscreen().catch(() => {});
}
new ResizeObserver(size).observe(stage);
addEventListener('resize', size);
size();
if (playing) play();
})();
</script>
<script id="dd-sound">/* soundtrack: MP3, base64. Rebuild with embed_sound.py */
const DD_SOUND = /*SOUND*/"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYwLjE2LjEwMAAAAAAAAAAAAAAA//uUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAEJAAGPAAADBggLDhATFhgaHR8iJScqLS8yNDY5Oz5BQ0ZJS01QUlVYWl1gYmVnaWxucXR2eXx+gIOFiIuNkJOVmJqcn6Gkp6msr7Gztri7vsDDxsjLzc/S1Nfa3N/i5Obp6+7x8/b5+/4AAAAATGF2YzYwLjMxAAAAAAAAAAAAAAAAJAXgAAAAAAABjwC+eaeUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//uUZAAP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xLine truncated
</script>
</body>
</html>
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""Embed droiddeck-boot-sound.wav into droiddeck-boot.html (MP3, base64) for the preview page."""
import base64, re, subprocess
from pathlib import Path
here = Path(__file__).parent
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(here / "droiddeck-boot-sound.wav"),
"-c:a", "libmp3lame", "-b:a", "128k", str(here / "_snd.mp3")], check=True)
b64 = base64.b64encode((here / "_snd.mp3").read_bytes()).decode(); (here / "_snd.mp3").unlink()
html = (here / "droiddeck-boot.html").read_text()
html = re.sub(r'/\*SOUND\*/".*?"/\*END\*/', lambda m: f'/*SOUND*/"{b64}"/*END*/', html, flags=re.S)
(here / "droiddeck-boot.html").write_text(html)
print(f"embedded {len(b64)/1024:.0f} KB of sound")
+20
View File
@@ -0,0 +1,20 @@
import json
from pathlib import Path
from playwright.sync_api import sync_playwright
JS = """(() => {
const d = DD.drops, c = (m, q) => ({x: m[0]*q.x + m[2]*q.y + m[4], y: m[1]*q.x + m[3]*q.y + m[5]});
const ev = {DUR: DD.DUR, T_L: DD.T_L, LOCK: DD.BEATS[3][1], HOP: DD.HOP,
drops: Object.fromEntries(['archDrop','ballDrop','domeDrop'].map(k => [k, {t0: d[k].o.t0, impacts: d[k].impacts}]))};
const tr = {t:[], phi:[], u:[], psi:[], ax:[], ay:[], bx:[], by:[], dx:[], dy:[]}, dt = 1/1200;
for (let i = 0; i*dt <= DD.DUR + 1e-9; i++) { const t = i*dt, p = DD.pose(t);
const a = c(p.arch, DD.CEN.arch), b = c(p.ball, {x: 63.98, y: 111.86}), q = c(p.dome, DD.CEN.dome);
tr.t.push(t); tr.phi.push(DD.sig('phi', t)); tr.u.push(DD.sig('u', t)); tr.psi.push(DD.sig('psi', t));
tr.ax.push(a.x); tr.ay.push(a.y); tr.bx.push(b.x); tr.by.push(b.y); tr.dx.push(q.x); tr.dy.push(q.y); }
ev.tr = tr; return ev; })()"""
with sync_playwright() as p:
b = p.chromium.launch(); pg = b.new_page()
pg.goto(Path(__file__).with_name('droiddeck-boot.html').resolve().as_uri() + '?render=1&w=320&h=200')
pg.wait_for_function("typeof DD !== 'undefined'", timeout=15000)
ev = pg.evaluate(JS); b.close()
json.dump(ev, open('events.json', 'w'))
print({k: v for k, v in ev.items() if k != 'tr'})
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Render the DroidDeck boot animation to .webm (Steam) or .mp4 (H.264).
Usage: python3 render.py [WIDTH] [HEIGHT] [FPS] [OUT] [light|dark]
python3 render.py 1280 800 60 droiddeck-boot.webm
python3 render.py 1920 1080 60 droiddeck-boot.mp4
python3 render.py 1280 800 60 droiddeck-boot-dark.webm dark
Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx-vp9.
The animation is drawn by droiddeck-boot.html (same folder); each frame gets real
motion blur (180-degree shutter, up to 48 sub-frames when things move fast).
"""
import base64, os, shutil, subprocess, sys, tempfile, time
from pathlib import Path
from playwright.sync_api import sync_playwright
W = int(sys.argv[1]) if len(sys.argv) > 1 else 1280
H = int(sys.argv[2]) if len(sys.argv) > 2 else 800
FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 60
OUT = sys.argv[4] if len(sys.argv) > 4 else f"droiddeck-boot-{W}x{H}.webm"
THEME = sys.argv[5] if len(sys.argv) > 5 else "light" # light | dark
ONLY = [int(x) for x in os.environ.get("FRAMES", "").split(",") if x] # debug: render some frames only
html = Path(__file__).with_name("droiddeck-boot.html").resolve()
tmp = Path(os.environ["FRAMEDIR"]) if os.environ.get("FRAMEDIR") else Path(tempfile.mkdtemp(prefix="ddframes_"))
tmp.mkdir(parents=True, exist_ok=True) # FRAMEDIR=... makes a long render resumable
t0 = time.time()
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(viewport={"width": W, "height": H})
page.goto(f"{html.as_uri()}?render=1&w={W}&h={H}&theme={THEME}")
page.wait_for_function("typeof DD !== 'undefined'", timeout=30000)
n = page.evaluate(f"DD.frameCount({FPS})")
frames = ONLY or range(n)
for i in frames:
if (tmp / f"f{i:05d}.png").exists() and not ONLY:
continue
r = page.evaluate(f"DD.renderFrame({i}, {FPS})")
(tmp / f"f{i:05d}.png").write_bytes(base64.b64decode(r["url"].split(",", 1)[1]))
if i % 30 == 0 or ONLY:
print(f"frame {i+1}/{n} blur samples {r['samples']:>2} {time.time()-t0:5.1f}s", flush=True)
browser.close()
if ONLY:
print("frames left in", tmp); sys.exit(0)
COLOR = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"]
SOUND = Path(__file__).with_name("droiddeck-boot-sound.wav") # made by sound.py; muxed in if present
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-framerate", str(FPS), "-i", str(tmp / "f%05d.png")]
if SOUND.exists():
cmd += ["-i", str(SOUND), "-map", "0:v", "-map", "1:a"]
cmd += ["-c:a", "aac", "-b:a", "192k"] if OUT.lower().endswith(".mp4") else ["-c:a", "libopus", "-b:a", "160k"]
cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int,format=yuv420p"]
if OUT.lower().endswith(".mp4"): # H.264 for sharing, previews and anything that won't play webm
cmd += ["-c:v", "libx264", "-preset", "slow", "-crf", "15", "-profile:v", "high", "-tune", "animation",
"-g", str(FPS * 2), "-movflags", "+faststart"]
else: # VP9 webm for Steam's startup movie
cmd += ["-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "18", "-deadline", "good", "-cpu-used", "2",
"-row-mt", "1", "-g", str(FPS * 2)]
cmd += COLOR + ([] if SOUND.exists() else ["-an"]) + [OUT]
subprocess.run(cmd, check=True)
if not os.environ.get("FRAMEDIR"):
shutil.rmtree(tmp)
print(f"wrote {OUT} ({os.path.getsize(OUT)/1e6:.2f} MB) in {time.time()-t0:.0f}s")
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env python3
"""DroidDeck boot animation: procedural sound design.
Every sound is synthesized (no samples) and placed on the exact physics events the animation
engine reports (events.json, exported by events.py). Key: D major.
legs (arch) lands on a muted D
ball lands on A, the second bounce a quieter echo
bowl lands on F#
balancing silence
jump silence
lock a soft landing in the same voice, then all those notes together as the D chord
Usage: python3 sound.py [events.json] [out.wav]
"""
import json, sys
import numpy as np
from scipy import signal
SR = 48000
FPS = 60
ev = json.load(open(sys.argv[1] if len(sys.argv) > 1 else 'events.json'))
OUT = sys.argv[2] if len(sys.argv) > 2 else 'droiddeck-boot-sound.wav'
FRAMES = round(ev['DUR'] * FPS) + 1
N = int(np.ceil(FRAMES / FPS * SR)) # exactly the video length
rng = np.random.default_rng(20260925)
# note frequencies
def hz(n): return 440.0 * 2 ** ((n - 69) / 12)
D2 = 440.0 * 2 ** ((38 - 69) / 12)
D3, A3, D4, E4, Fs4, A4, B4, Cs5, D5, E5, Fs5, A5, D6 = [hz(n) for n in (50, 57, 62, 64, 66, 69, 71, 73, 74, 76, 78, 81, 86)]
# ------------------------------------------------------------------ building blocks
def tt(dur): return np.arange(int(dur * SR)) / SR
def edge(x, a_ms=1.0, r_ms=4.0):
"""Click-free start and end."""
na, nr = max(1, int(a_ms * SR / 1000)), max(1, int(r_ms * SR / 1000))
x[:na] *= np.sin(np.linspace(0, np.pi / 2, na)) ** 2
x[-nr:] *= np.cos(np.linspace(0, np.pi / 2, nr)) ** 2
return x
def bp(x, lo, hi, order=2):
return signal.sosfilt(signal.butter(order, [lo, min(hi, SR * .45)], 'bandpass', fs=SR, output='sos'), x)
def lp(x, f, order=2): return signal.sosfilt(signal.butter(order, f, 'lowpass', fs=SR, output='sos'), x)
def hp(x, f, order=2): return signal.sosfilt(signal.butter(order, f, 'highpass', fs=SR, output='sos'), x)
def modal(freqs, decays, amps, dur):
t = tt(dur); y = np.zeros_like(t)
for f, d, a in zip(freqs, decays, amps):
if f < SR * .45: y += a * np.sin(2 * np.pi * f * t) * np.exp(-t / d)
return y
def glide(f0, f1, tau, dur):
"""Sine whose pitch moves exponentially from f0 to f1."""
t = tt(dur); f = f1 + (f0 - f1) * np.exp(-t / tau)
return np.sin(2 * np.pi * np.cumsum(f) / SR)
def noise_burst(dur, lo, hi, tau):
t = tt(dur); return bp(rng.standard_normal(len(t)), lo, hi) * np.exp(-t / tau)
def pan(x, p):
p = np.clip(p, -1, 1); a = (p + 1) * np.pi / 4
return np.stack([x * np.cos(a), x * np.sin(a)])
MIX = np.zeros((2, N))
def put(t0, st, gain=1.0):
i = int(round(t0 * SR))
if i >= N: return
j = min(N, i + st.shape[1]); MIX[:, i:j] += gain * st[:, :j - i]
# ------------------------------------------------------------------ instruments
def wood(amp, f0=520, size=1.0, thump=0.0, dur=.35):
"""Hard wood / toy-block clack. thump adds body for heavy landings."""
r = [1, 1.93, 2.81, 4.13, 5.62]
y = modal([f0 * k for k in r], [s * size for s in (.055, .034, .022, .014, .009)], [1, .55, .42, .26, .16], dur)
y += .7 * noise_burst(dur, 1400, 7500, .0035)
if thump: y += thump * glide(118, 52, .035, dur) * np.exp(-tt(dur) / .075)
return edge(y * amp)
def bonk(amp, f):
"""Hollow rubber ball on a board: round pitched body, soft click, tiny board knock."""
d = .42; t = tt(d)
y = glide(f * 1.28, f, .018, d) * np.exp(-t / (.09 + .05 * amp))
y += .22 * glide(f * 2.45, f * 2.3, .02, d) * np.exp(-t / .035)
y += .55 * glide(95, 60, .03, d) * np.exp(-t / .045)
y += .22 * noise_burst(d, 1800, 5000, .002)
y += .25 * wood(1, f0=640, size=.6, dur=d)
return edge(y * amp, a_ms=.6)
def bowl_ring(amp, f=A4, dur=2.4, dscale=1.0):
"""Struck metal bowl: inharmonic partials, each split in two for the slow beating shimmer."""
t = tt(dur); y = np.zeros_like(t)
for k, dec, a, beat in zip((1, 2.71, 5.12, 8.21), tuple(d * dscale for d in (1.25, .62, .3, .15)), (1, .45, .24, .12), (.9, 1.7, 2.6, 3.1)):
for s in (-1, 1):
y += .5 * a * np.sin(2 * np.pi * (f * k + s * beat / 2) * t + (s > 0) * .8) * np.exp(-t / dec)
return edge(y * amp, a_ms=.8, r_ms=30)
def clonk(amp, ring):
d = .5; t = tt(d)
y = .8 * glide(160, 92, .03, d) * np.exp(-t / .06) + .45 * wood(1, f0=880, size=.7, dur=d)
return edge(y * amp), bowl_ring(ring)
def marimba(f, amp, damp=1.0):
d = 1.2; t = tt(d)
tau = .55 * (440 / f) ** .5 * damp
y = modal([f, f * 3.93, f * 9.2], [tau, tau * .22, .03], [1, .32, .07], d)
y += .05 * lp(rng.standard_normal(len(t)), 2500) * np.exp(-t / .002)
return edge(y * amp, a_ms=1.5, r_ms=40)
def svf_whoosh(env, fc, q=.9):
"""Noise through a band-pass whose centre follows fc(t): air moving past a spinning piece."""
x = rng.standard_normal(len(env)); y = np.zeros_like(x); ic1 = ic2 = 0.0
for i in range(len(x)):
g = np.tan(np.pi * min(fc[i], SR * .45) / SR); k = 1 / q
a1 = 1 / (1 + g * (g + k)); a2 = g * a1; a3 = g * a2
v3 = x[i] - ic2; v1 = a1 * ic1 + a2 * v3; v2 = ic2 + a2 * ic1 + a3 * v3
ic1 = 2 * v1 - ic1; ic2 = 2 * v2 - ic2; y[i] = v1
return y * env
def epiano(f, amp, dur=2.8, decay=1.5):
"""FM electric piano: bright tine at the strike that mellows as the index falls."""
t = tt(dur)
idx = 1.7 * np.exp(-t / .22) + .22
y = np.sin(2 * np.pi * f * t + idx * np.sin(2 * np.pi * f * t))
y += .18 * np.sin(2 * np.pi * f * t + .9 * np.exp(-t / .012) * np.sin(2 * np.pi * 14 * f * t)) * np.exp(-t / .05)
return edge(y * np.exp(-t / decay) * amp, a_ms=3, r_ms=60)
def tock(f, amp, decay=.42, sub=0.0):
"""A landing as a muted note in the chord's own FM e-piano voice: felt contact, no pitch bend."""
d = 1.5; t = tt(d)
idx = 1.3 * np.exp(-t / .07) + .18
y = np.sin(2 * np.pi * f * t + idx * np.sin(2 * np.pi * f * t)) * np.exp(-t / decay)
y = lp(y, 2600)
y += .30 * lp(rng.standard_normal(len(t)), 1600) * np.exp(-t / .0016)
if sub: y += sub * np.sin(2 * np.pi * D2 * t) * np.exp(-t / .075)
return edge(y * amp, a_ms=1.5, r_ms=80)
def bell(f, amp, dur=1.6):
t = tt(dur)
y = np.sin(2 * np.pi * f * t + 1.1 * np.exp(-t / .3) * np.sin(2 * np.pi * 3.5 * f * t)) * np.exp(-t / .7)
return edge(y * amp, a_ms=2, r_ms=40)
# ------------------------------------------------------------------ tracks from the engine
tr = {k: np.array(v) for k, v in ev['tr'].items()}
TT = tr['t']; dT = TT[1] - TT[0]
def at(name, t): return np.interp(t, TT, tr[name])
def speed(xk, yk):
return np.hypot(np.gradient(tr[xk], dT), np.gradient(tr[yk], dT))
X2PAN = 1 / 330 # world units to stereo pan
drops = ev['drops']; T_L = ev['T_L']; LOCK = ev['LOCK']; HOP = ev['HOP']
events_log = []
def log(t, what): events_log.append((round(t, 3), what))
# ------------------------------------------------------------------ cue sheet
# Kept deliberately sparse: one sound per story beat, with silence between them.
tsamp = np.arange(N) / SR
# 1. the stack: each piece lands on a muted note of the final chord (D, A, A-echo, F#);
# the lock then plays them all together
ai = drops['archDrop']['impacts']
put(ai[0]['t'], pan(tock(D3, .40, decay=.5, sub=.8), .1)); log(ai[0]['t'], 'legs land: D')
bi = drops['ballDrop']['impacts']
for k, imp in enumerate(bi[:2]):
a = .32 * (imp['v'] / bi[0]['v']) ** .9
put(imp['t'], pan(tock(A3, a, decay=.36, sub=.3 * a / .32), 0)); log(imp['t'], f'ball: A {a:.2f}')
di = drops['domeDrop']['impacts']
put(di[0]['t'], pan(tock(Fs4, .28, decay=.45, sub=.45), -.05)); log(di[0]['t'], 'bowl lands: F#')
# 2-3. the balancing act and the jump play in silence: the stack and the lock carry it
# 4. lock: one snap, then a four-note chord that rings out
put(LOCK, pan(tock(D3, .24, decay=.28, sub=.8), 0)); log(LOCK, 'lock: soft landing in the stack voice')
for f, a, p, off in ((D3, .24, -.1, 0), (A3, .28, .2, .02), (D4, .30, -.2, .04), (Fs4, .26, .15, .06)):
put(LOCK + .018 + off, pan(epiano(f, a, decay=1.3 if f < 300 else 1.1), p))
log(LOCK + .018, 'D chord')
# ------------------------------------------------------------------ room, master
def room_ir(dur=1.1, rt60=.75):
t = tt(dur); tau = rt60 / 6.9; irs = []
for ch in range(2):
n = rng.standard_normal(len(t))
ir = lp(n, 7000) * np.exp(-t / (tau * .6)) * .5 + lp(n, 2200) * np.exp(-t / tau)
ir[:int(.011 * SR)] = 0 # pre-delay
for d_ms, g in ((13, .5), (19, .35), (27, .3), (38, .2)):
ir[int((d_ms + ch * 1.3) * SR / 1000)] += g
irs.append(ir / np.sqrt(np.sum(ir ** 2)))
return irs
irs = room_ir()
wet = np.stack([signal.fftconvolve(MIX[ch], irs[ch])[:N] for ch in range(2)])
out = MIX + .14 * wet
out = hp(out, 28)
fade = np.ones(N); nf = int(.45 * SR); fade[-nf:] = np.cos(np.linspace(0, np.pi / 2, nf)) ** 2
out *= fade
# gentle peak control: soft-knee compress only the loudest transients, then normalise
pk = np.max(np.abs(out)); x = out / pk
knee = .5; ax = np.abs(x); over = ax > knee
x[over] = np.sign(x[over]) * (knee + (1 - knee) * np.tanh((ax[over] - knee) / (1 - knee)))
L0, L1 = int((LOCK + .06) * SR), int((LOCK + .76) * SR)
body_rms = np.sqrt(np.mean(x[:, L0:L1].mean(0) ** 2))
out = x * (10 ** (-14.9 / 20) / body_rms) # chord body held at the level the team liked (-14.9 dB RMS)
assert np.max(np.abs(out)) < 10 ** (-1 / 20), 'would clip'
import wave
pcm = (np.clip(out.T, -1, 1) * 32767).astype('<i2')
with wave.open(OUT, 'wb') as w:
w.setnchannels(2); w.setsampwidth(2); w.setframerate(SR); w.writeframes(pcm.tobytes())
json.dump(sorted(events_log), open('sound_events.json', 'w'), indent=0)
print(f'wrote {OUT}: {N / SR:.3f}s, {len(events_log)} cues')
for t, w_ in sorted(events_log): print(f' {t:6.3f} {w_}')
+2 -2
View File
@@ -6,7 +6,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:8.8.0'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
classpath 'org.jetbrains.kotlin:compose-compiler-gradle-plugin:2.0.21'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.0'
classpath 'org.jetbrains.kotlin:compose-compiler-gradle-plugin:2.1.0'
}
}
@@ -70,6 +70,60 @@ TOOL_MANIFEST_VDF = """"manifest"
}
""" % LAUNCHER
# Steam runs its own graphics probe through EVERY registered tool at once, ~40 s after logging in,
# all with STEAM_COMPAT_DATA_PATH=.../compatdata/0, and those concurrent Protons can write their
# builtin DLLs through each other's prefix links into each other's trees (seen: GE's FEX DLLs became
# Proton Experimental's). Moving those runs to a prefix per tool was tried and crashed the Steam
# client right after the probe started (segfault, rc 139, first ever in 25 sessions), so the client
# relies on compatdata/0 itself. The launch-time check below is the protection instead.
# The Components page's choices, enforced in the one place every game launch passes: the app keeps
# desired.tsv (tool dir, Proton build, component, file, sha256, source copy) and an unpacked copy of
# each package in use. A file that no longer matches - whatever changed it - is put back before
# Proton starts. Only for the Proton build the choice was made for: after a Steam update the build
# differs and the Proton's own new files are left alone until the user chooses again.
BL_COMPONENTS_SETUP = """
bl_components() {
base=$1
cm_dir="${HOME:-/root}/.local/share/bannerlator-components"
cm_list="$cm_dir/desired.tsv"
# A real game launch only: the verb the client starts a game with and the game's own prefix. Every
# other run - above all the client's own probes right after login, which all share compatdata/0 -
# is left exactly as it was: with this check running through them, the client segfaulted (rc 139)
# within seconds of starting its probes, four sessions out of four. The prefix decides rather than
# the app id because a non-Steam shortcut launches with app id 0 but still gets a prefix of its own.
[ "${verb:-}" = waitforexitandrun ] || return 0
case "${STEAM_COMPAT_DATA_PATH:-}" in ''|*/compatdata/0|*/compatdata/0/|*/compatdata/0-*) return 0 ;; esac
[ -f "$cm_list" ] || return 0
cm_app=${STEAM_COMPAT_DATA_PATH%/}
cm_app=${cm_app##*/}
cm_tool=${base##*/}
cm_build=$(awk 'NR == 1 { print $2 }' "$base/version" 2>/dev/null)
cm_fixed=0
cm_checked=0
while IFS=$'\\t' read -r t want comp rel sum src; do
[ "$t" = "$cm_tool" ] && [ "$want" = "$cm_build" ] || continue
cm_checked=$((cm_checked + 1))
f="$base/$rel"
if [ -f "$f" ] && [ "$(sha256sum "$f" | cut -d' ' -f1)" = "$sum" ]; then continue; fi
if [ ! -f "$src" ]; then
echo "bannerlator-proton: components: $comp source missing ($src), left as it is" >&2
continue
fi
mkdir -p "$(dirname "$f")"
cp -f "$src" "$f.bl-new" && mv -f "$f.bl-new" "$f" || continue
case "$rel" in *.so) chmod 755 "$f" ;; *) chmod 644 "$f" ;; esac
cm_fixed=$((cm_fixed + 1))
done < "$cm_list"
[ "$cm_checked" -gt 0 ] && echo "bannerlator-proton: components: checked $cm_checked file(s) in $cm_tool for app $cm_app" >&2
if [ "$cm_fixed" -gt 0 ]; then
echo "bannerlator-proton: components: re-applied $cm_fixed of $cm_checked file(s) in $cm_tool before this launch" >&2
printf '%s\\t%s\\t%s\\n' "$(date +%s)" "$cm_tool" "$cm_fixed" >> "$cm_dir/reapplied.log"
fi
}
"""
# Resolves the depot at launch time, so the tool can be registered before the depot exists and
# survives the client updating or replacing it. Proton takes its base directory from
# dirname(sys.argv[0]) without resolving it, so it is run from the depot itself.
@@ -175,6 +229,7 @@ fi
for name in %s; do
depot="$steam_root/steamapps/common/$name"
if [ -d "$depot/files/bin-arm64" ] && [ -x "$depot/proton" ]; then
bl_components "$depot"
bl_directaudio "$depot"
bl_game_cpus
bl_idtech3 "$@"
@@ -188,7 +243,8 @@ exit 1
# and a % format would eat that into a single %, leaving a shell expansion that silently does
# something else.
LAUNCHER_SH = LAUNCHER_SH.replace(
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP, 1)
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_COMPONENTS_SETUP, 1)
# A third-party Proton dropped into compatibilitytools.d - GE-Proton, proton-cachyos, anything of
# that shape - is adopted rather than used as shipped, for the same two reasons Valve's ARM64 depot
@@ -220,6 +276,7 @@ if [ -f "$fake" ]; then
*) LD_PRELOAD="$fake${LD_PRELOAD:+:$LD_PRELOAD}"; export LD_PRELOAD ;;
esac
fi
bl_components "$here"
bl_directaudio "$here"
bl_game_cpus
bl_idtech3 "$@"
@@ -384,7 +441,8 @@ def adopt_extras(tools):
# ${major%%.*} of its own, and putting it through the format would eat both.
body = (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP, 1)
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_COMPONENTS_SETUP, 1)
with open(wrapper, "w", encoding="utf-8") as f:
f.write(body)
os.chmod(wrapper, 0o755)