diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index dd3aa5c06..86a4f4617 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -130,8 +130,6 @@ - diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 6549d677e..53f1f82c0 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -1047,15 +1047,13 @@ class MainActivity : ComponentActivity() { } private fun refreshPhantomStatus() { - phantomProcessStatus = PhantomProcessLimit.read(contentResolver) + phantomProcessStatus = PhantomProcessLimit.read(this) phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { - "${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.ADB_COMMAND}" + "${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.adbCommand()}" } else null } private fun openDeveloperOptions(displayId: Int?) { - // Settings scrolls to and highlights the key it is given; the wireless pairing flow wants - // Wireless debugging, and the toggle on Android 14+ is further down the same page. val highlight = if (PhantomProcessLimit.hasDeveloperToggle() && WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) null else "toggle_adb_wireless" val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS) 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 4505f5cd4..80550be44 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -162,7 +162,7 @@ object DeviceReport { }) h("Android process limits") - k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context.contentResolver))) + k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context))) 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 index b16ee2ff6..4155a29dd 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -1,6 +1,6 @@ package com.droiddeck.launcher.core -import android.content.ContentResolver +import android.content.Context import android.os.Build import android.provider.Settings @@ -14,17 +14,53 @@ enum class PhantomProcessStatus { } 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"}" + private const val MAX_PHANTOM = "2147483647" + private const val PREFS = "phantom-process-limit" + private const val PREF_ANDROID_12_OFF = "android12-off" - fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus { + fun usesDeviceConfig(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk == Build.VERSION_CODES.S + + fun shellCommands(enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): List = when { + usesDeviceConfig(sdk) && enabled -> listOf( + "device_config delete activity_manager max_phantom_processes", + "device_config set_sync_disabled_for_tests none", + ) + usesDeviceConfig(sdk) -> listOf( + "device_config set_sync_disabled_for_tests persistent", + "device_config put activity_manager max_phantom_processes $MAX_PHANTOM", + ) + else -> listOf("settings put global $SETTING ${if (enabled) "true" else "false"}") + } + + fun verifyCommand(sdk: Int = Build.VERSION.SDK_INT): String = + if (usesDeviceConfig(sdk)) "device_config get activity_manager max_phantom_processes" + else "settings get global $SETTING" + + fun verified(output: String, enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): Boolean { + val value = output.trim() + return if (usesDeviceConfig(sdk)) (value == MAX_PHANTOM) != enabled + else value == if (enabled) "true" else "false" + } + + fun adbCommand(enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): String = + shellCommands(enabled, sdk).joinToString(" && ") { "adb shell $it" } + + fun adbCommand(): String = adbCommand(false) + + fun rememberAndroid12(context: Context, off: Boolean) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(PREF_ANDROID_12_OFF, off).apply() + } + + fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus { if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE + if (usesDeviceConfig(sdk)) { + val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false) + return if (off) PhantomProcessStatus.DISABLED else PhantomProcessStatus.UNREADABLE + } val global = try { - Settings.Global.getString(resolver, SETTING) + Settings.Global.getString(context.contentResolver, SETTING) } catch (_: Exception) { return PhantomProcessStatus.UNREADABLE } @@ -57,10 +93,6 @@ object PhantomProcessLimit { null } - /** - * Developer options gained "Disable child process restrictions" in Android 14. On 12 and 13 - * (the AYN Odin 2 and Thor, the Retroid Pocket 5) the flag exists but only ADB can set it. - */ fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE fun blocksSteam(status: PhantomProcessStatus): Boolean = @@ -75,20 +107,20 @@ object PhantomProcessLimit { } 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.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence() + " If that is not possible, 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." + PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence() else -> instructions(status) } + fun fixSentence(sdk: Int = Build.VERSION.SDK_INT): String = + if (hasDeveloperToggle(sdk)) "Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards." + else "This Android version has no switch for it. Use Wireless debugging to change it from this device." + 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)" diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt index 82b6e4d63..e2f0b4cf9 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt @@ -6,7 +6,9 @@ import android.net.nsd.NsdServiceInfo import com.flyfishxu.kadb.Kadb import com.flyfishxu.kadb.cert.KadbCert import java.io.File +import java.net.Inet4Address import java.net.InetAddress +import java.net.NetworkInterface import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean @@ -19,6 +21,7 @@ object WirelessAdbFix { 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" + const val LOOPBACK = "127.0.0.1" private data class SavedConnection(val host: String, val port: Int?) @@ -76,9 +79,18 @@ object WirelessAdbFix { } /** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */ + fun isLocalAddress(address: InetAddress): Boolean = runCatching { + if (address.isLoopbackAddress) return true + NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().any { network -> + network.inetAddresses.toList().any { it.address.contentEquals(address.address) } + } + }.getOrDefault(address is Inet4Address) + 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 paired = runCatching { InetAddress.getByName(pairedHost) }.getOrNull() ?: return null + val matches: (InetAddress) -> Boolean = + if (paired.isLoopbackAddress) ::isLocalAddress else { address -> address.address.contentEquals(paired.address) } val resolvedPort = AtomicInteger(-1) val finished = AtomicBoolean(false) val latch = CountDownLatch(1) @@ -101,8 +113,8 @@ object WirelessAdbFix { } override fun onServiceResolved(serviceInfo: NsdServiceInfo) { - val address = serviceInfo.host?.address - if (address != null && address.contentEquals(expectedAddress) && finished.compareAndSet(false, true)) { + val address = serviceInfo.host + if (address != null && matches(address) && finished.compareAndSet(false, true)) { resolvedPort.set(serviceInfo.port) latch.countDown() } else { @@ -148,14 +160,16 @@ object WirelessAdbFix { 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) { + PhantomProcessLimit.shellCommands(enabled).forEach { command -> + val change = adb.shell(command) + check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } } + } + val result = adb.shell(PhantomProcessLimit.verifyCommand()) + check(result.exitCode == 0 && PhantomProcessLimit.verified(result.output, enabled)) { "Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}" } } + if (PhantomProcessLimit.usesDeviceConfig()) PhantomProcessLimit.rememberAndroid12(context, !enabled) saveConnection(context, host, port) } diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt index d9cbb706b..5e4ecc51f 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt @@ -18,22 +18,11 @@ import com.droiddeck.launcher.MainActivity import com.droiddeck.launcher.R import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow -import java.net.Inet4Address -import java.net.InetAddress -import java.net.NetworkInterface -/** - * Pairs Wireless debugging without the user leaving Android Settings. Settings closes its pairing - * pop-up as soon as another app comes forward, so instead of asking for the pop-up's address in - * DroidDeck, this finds the pairing port over mDNS while the pop-up is open and takes the 6-digit - * code as an inline reply on its notification. It then applies the child-process setting and ends. - */ class WirelessAdbPairingService : Service() { sealed interface Stage { data object Idle : Stage - /** Waiting for the user to open "Pair device with pairing code". */ data object Waiting : Stage - /** The pop-up is open; the notification asks for its code. */ data class CodeNeeded(val error: String? = null) : Stage data class Working(val step: String) : Stage data object Done : Stage @@ -99,8 +88,7 @@ class WirelessAdbPairingService : Service() { override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit override fun onServiceResolved(serviceInfo: NsdServiceInfo) { val address = serviceInfo.host ?: return - // Only this device's own pop-up: another phone pairing on the same Wi-Fi is not ours. - if (!isLocalAddress(address)) return + if (!WirelessAdbFix.isLocalAddress(address)) return main.post { if (working || current.value == Stage.Done) return@post pairingHost = address.hostAddress @@ -125,22 +113,24 @@ class WirelessAdbPairingService : Service() { working = true show(Stage.Working("Pairing…")) Thread({ - val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, host, port, code) } } + val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } } if (paired.isFailure) { main.post { working = false - // A wrong code closes the pop-up on most builds; the next one it opens is found again. pairingPort = null show(Stage.CodeNeeded("That code didn't work. Open the pairing pop-up again and enter its new code.")) } return@Thread } - main.post { show(Stage.Working("Paired. Connecting…")) } + main.post { + stopDiscovery() + show(Stage.Working("Paired. Connecting…")) + } val result = runCatching { - val connectPort = WirelessAdbFix.findConnectPort(this, host) + val connectPort = WirelessAdbFix.findConnectPort(this, WirelessAdbFix.LOOPBACK) ?: error("Paired, but the Wireless debugging port was not found. Keep Wireless debugging on and try again.") main.post { show(Stage.Working("Applying the setting…")) } - WirelessAdbFix.setChildProcessLimit(this, host, connectPort, false) + WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false) } main.post { working = false @@ -154,7 +144,6 @@ class WirelessAdbPairingService : Service() { getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, notification(stage)) } - /** Ends the service; a result the user should see stays behind as a normal notification. */ private fun finish(stage: Stage) { main.removeCallbacks(timeout) stopDiscovery() @@ -181,7 +170,6 @@ class WirelessAdbPairingService : Service() { private fun notification(stage: Stage): Notification { val manager = getSystemService(NotificationManager::class.java) - // High importance so each step heads up over Settings, where the user is looking. manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Wireless debugging setup", NotificationManager.IMPORTANCE_HIGH).apply { description = "Asks for the Wireless debugging pairing code while Settings is open" @@ -260,7 +248,6 @@ class WirelessAdbPairingService : Service() { fun start(context: Context) { context.getSystemService(NotificationManager::class.java)?.cancel(RESULT_NOTIFICATION_ID) - // Now, not when the service gets going: the Settings intent sent next reads it. publish(Stage.Waiting) val intent = Intent(context, WirelessAdbPairingService::class.java) if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent) @@ -276,12 +263,5 @@ class WirelessAdbPairingService : Service() { fun notificationsEnabled(context: Context): Boolean = context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false - - private fun isLocalAddress(address: InetAddress): Boolean = runCatching { - if (address.isLoopbackAddress) return true - NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().any { network -> - network.inetAddresses.toList().any { it.address.contentEquals(address.address) } - } - }.getOrDefault(address is Inet4Address) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt index 781361044..cae45fa48 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -39,11 +39,6 @@ import com.droiddeck.launcher.core.PhantomProcessStatus import com.droiddeck.launcher.core.WirelessAdbPairingService import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage -/** - * Stops a Steam launch until Android's child-process limit is off. One primary route, chosen by - * what this Android version offers: the Developer options toggle on 14+, and on 12 and 13 (no - * toggle) pairing Wireless debugging through a notification. Everything else sits under Other ways. - */ @Composable fun PhantomProcessGatePage( status: PhantomProcessStatus, @@ -57,7 +52,6 @@ fun PhantomProcessGatePage( BackHandler(onBack = onDismiss) val context = LocalContext.current val stage by WirelessAdbPairingService.stage.collectAsState() - // Wi-Fi and notifications can change while the user is in Settings; recheck with the status. val environment by produceState(GateEnvironment.read(context)) { while (true) { value = GateEnvironment.read(context) @@ -137,7 +131,7 @@ private fun FixGroup( when { pairing -> PairingProgress(stage, onCancel) hasToggle -> { - Body("Turn off “Disable child process restrictions”, then come back. DroidDeck notices on its own.") + Body("Turn on “Disable child process restrictions”, then come back. Keep Developer options on afterwards: turning them off turns the switch back off.") PrimaryButton("Open Developer options", compact = compact, onClick = onOpenDeveloperOptions) } else -> { @@ -245,7 +239,7 @@ private fun OtherWays( SecondaryButton("Enter address manually", compact = true, onClick = onEnterAddressManually) Body("From a computer with ADB:") Text( - PhantomProcessLimit.ADB_COMMAND, + PhantomProcessLimit.adbCommand(), style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp), color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/app/src/main/res/drawable/ic_stat_session.xml b/app/src/main/res/drawable/ic_stat_session.xml index 3b3415de2..0efa80f6c 100644 --- a/app/src/main/res/drawable/ic_stat_session.xml +++ b/app/src/main/res/drawable/ic_stat_session.xml @@ -1,11 +1,8 @@ - - + android:viewportWidth="239.92" android:viewportHeight="239.92"> + + + diff --git a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt index a7cfc80a9..e930f85e5 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt @@ -1,6 +1,8 @@ package com.droiddeck.launcher.core import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test class PhantomProcessLimitTest { @@ -26,4 +28,33 @@ class PhantomProcessLimitTest { assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status(null, null)) assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status("", "")) } + + @Test + fun android12UsesDeviceConfig() { + assertEquals( + listOf( + "device_config set_sync_disabled_for_tests persistent", + "device_config put activity_manager max_phantom_processes 2147483647", + ), + PhantomProcessLimit.shellCommands(enabled = false, sdk = 31), + ) + assertTrue(PhantomProcessLimit.verified("2147483647\n", enabled = false, sdk = 31)) + assertFalse(PhantomProcessLimit.verified("null", enabled = false, sdk = 31)) + } + + @Test + fun android12LAndLaterUseTheFlag() { + assertEquals( + listOf("settings put global settings_enable_monitor_phantom_procs false"), + PhantomProcessLimit.shellCommands(enabled = false, sdk = 33), + ) + assertTrue(PhantomProcessLimit.verified("false", enabled = false, sdk = 34)) + assertFalse(PhantomProcessLimit.verified("null", enabled = false, sdk = 33)) + } + + @Test + fun developerToggleStartsAtAndroid14() { + assertFalse(PhantomProcessLimit.hasDeveloperToggle(33)) + assertTrue(PhantomProcessLimit.hasDeveloperToggle(34)) + } }