diff --git a/app/build.gradle b/app/build.gradle index dcc9db8519..568a8ab494 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -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' } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index ecf4d68c56..be31238ebf 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,7 @@ + diff --git a/app/src/main/assets/steam-startup/droiddeck-startup.webm b/app/src/main/assets/steam-startup/droiddeck-startup.webm new file mode 100644 index 0000000000..0c69191f9b Binary files /dev/null and b/app/src/main/assets/steam-startup/droiddeck-startup.webm differ diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 7ca19493c2..cde1deb0a9 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -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 @@ -42,6 +45,9 @@ 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 @@ -133,6 +139,8 @@ class MainActivity : ComponentActivity() { private var noXalia by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false) private var phantomWarning by mutableStateOf(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) @@ -254,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 { @@ -294,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) @@ -369,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() }, @@ -450,6 +505,7 @@ class MainActivity : ComponentActivity() { 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({ @@ -1150,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() { @@ -1217,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 diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index 498eb1fd24..9ff0c002a6 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -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", diff --git a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt new file mode 100644 index 0000000000..3c21f6ff63 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -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" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt new file mode 100644 index 0000000000..82b6e4d636 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt @@ -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() + val seen = mutableSetOf() + 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) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 5cd53d1b6f..fa2dc003c7 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 681af24aaa..b5d9bb716d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -136,6 +136,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 +178,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( @@ -209,6 +213,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, ) @@ -345,14 +357,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(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 { @@ -388,7 +421,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com // 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 @@ -402,14 +436,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) { @@ -430,10 +466,15 @@ 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()) { @@ -480,12 +521,50 @@ 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 } } @@ -699,6 +778,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 = when { @@ -720,7 +800,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) + } } } @@ -793,6 +876,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair 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 @@ -876,7 +960,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 { @@ -995,8 +1079,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(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" @@ -1007,6 +1111,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) @@ -1120,7 +1252,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. @@ -1147,14 +1285,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 @@ -1168,8 +1306,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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt new file mode 100644 index 0000000000..0f9a4f96e6 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -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>, + 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") } }, + ) +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 981440b836..28bd316d20 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -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() } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt new file mode 100644 index 0000000000..3153092e1a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt @@ -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(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 +} diff --git a/artwork/boot-animation-source/README.md b/artwork/boot-animation-source/README.md new file mode 100644 index 0000000000..72f7d0c1b4 --- /dev/null +++ b/artwork/boot-animation-source/README.md @@ -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, dark theme, 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. diff --git a/artwork/boot-animation-source/droiddeck-boot-sound.wav b/artwork/boot-animation-source/droiddeck-boot-sound.wav new file mode 100644 index 0000000000..a3f50bb11b Binary files /dev/null and b/artwork/boot-animation-source/droiddeck-boot-sound.wav differ diff --git a/artwork/boot-animation-source/droiddeck-boot.html b/artwork/boot-animation-source/droiddeck-boot.html new file mode 100644 index 0000000000..78d5e6f657 --- /dev/null +++ b/artwork/boot-animation-source/droiddeck-boot.html @@ -0,0 +1,699 @@ + + + + + +DroidDeck boot animation + + + + + + +
+
+
+

DroidDeck boot animation

+

6.3 s at 60 fps, with sound

+
+
+ + +
+
+
+ +
Tap to replay
+
+
+ +
+ +
+
+
+ 0.00 / 6.30 +
+ + + +
+ + +
+
+
+
+

Use it as the Steam startup movie

+
    +
  1. Put the .webm file in ~/.steam/root/config/uioverrides/movies/. Create the folders if they don’t exist.
  2. +
  3. In Steam, open Settings > Customization > Startup Movie and pick it.
  4. +
+
+
+

Which file to ship

+

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 .webm; the .mp4 files are for sharing. Everything is drawn and synthesized in code, so the included scripts can output any other size.

+
+
+
+ + + + + diff --git a/artwork/boot-animation-source/embed_sound.py b/artwork/boot-animation-source/embed_sound.py new file mode 100644 index 0000000000..7354e3c326 --- /dev/null +++ b/artwork/boot-animation-source/embed_sound.py @@ -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") diff --git a/artwork/boot-animation-source/events.py b/artwork/boot-animation-source/events.py new file mode 100644 index 0000000000..1aa51e3404 --- /dev/null +++ b/artwork/boot-animation-source/events.py @@ -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'}) diff --git a/artwork/boot-animation-source/render.py b/artwork/boot-animation-source/render.py new file mode 100644 index 0000000000..9c55b9b101 --- /dev/null +++ b/artwork/boot-animation-source/render.py @@ -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") diff --git a/artwork/boot-animation-source/sound.py b/artwork/boot-animation-source/sound.py new file mode 100644 index 0000000000..f0f7eb1b83 --- /dev/null +++ b/artwork/boot-animation-source/sound.py @@ -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('