From 14e6a673b539263c1cfc86b7c56b2cace52731f0 Mon Sep 17 00:00:00 2001 From: xXJsonDeruloXx Date: Mon, 28 Sep 2026 21:03:54 -0400 Subject: [PATCH] feat: pair wireless debugging from a notification for the child-process gate --- app/src/main/AndroidManifest.xml | 5 + .../com/droiddeck/launcher/MainActivity.kt | 12 + .../launcher/core/PhantomProcessLimit.kt | 6 + .../core/WirelessAdbPairingService.kt | 287 ++++++++++++++++++ .../droiddeck/launcher/ui/FrontEndScreen.kt | 10 +- .../launcher/ui/PhantomProcessGatePage.kt | 277 ++++++++++++----- 6 files changed, 512 insertions(+), 85 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index fba4727ba..dd3aa5c06 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -130,6 +130,11 @@ + + SessionPrefs.setOscMode(this, o); oscMode = o }, onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() }, @@ -1047,8 +1054,13 @@ class MainActivity : ComponentActivity() { } 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) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) } try { if (displayId == null) startActivity(intent) else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle()) 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 103bf0556..b16ee2ff6 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -57,6 +57,12 @@ 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 = status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt new file mode 100644 index 000000000..d9cbb706b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt @@ -0,0 +1,287 @@ +package com.droiddeck.launcher.core + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.RemoteInput +import android.app.Service +import android.content.Context +import android.content.Intent +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo +import android.os.Build +import android.os.Handler +import android.os.IBinder +import android.os.Looper +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 + data class Failed(val error: String) : Stage + } + + private val main = Handler(Looper.getMainLooper()) + private var nsd: NsdManager? = null + private var discovery: NsdManager.DiscoveryListener? = null + private var pairingHost: String? = null + private var pairingPort: Int? = null + @Volatile private var working = false + private val timeout = Runnable { finish(Stage.Failed("Timed out waiting for the pairing pop-up. Try again from DroidDeck.")) } + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_CODE -> { + val code = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_CODE) + ?.filter(Char::isDigit)?.toString().orEmpty() + onCode(code) + } + ACTION_CANCEL -> finish(Stage.Idle) + else -> begin() + } + return START_NOT_STICKY + } + + private fun begin() { + pairingHost = null + pairingPort = null + working = false + publish(Stage.Waiting) + startForeground(NOTIFICATION_ID, notification(Stage.Waiting)) + startDiscovery() + main.removeCallbacks(timeout) + main.postDelayed(timeout, TIMEOUT_MS) + } + + private fun startDiscovery() { + stopDiscovery() + val manager = getSystemService(Context.NSD_SERVICE) as NsdManager + val listener = object : NsdManager.DiscoveryListener { + override fun onDiscoveryStarted(serviceType: String) = Unit + override fun onServiceFound(serviceInfo: NsdServiceInfo) { + if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return + runCatching { manager.resolveService(serviceInfo, resolveListener()) } + } + override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit + override fun onDiscoveryStopped(serviceType: String) = Unit + override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { + main.post { finish(Stage.Failed("Could not look for the pairing pop-up ($errorCode). Check that Wi-Fi is on.")) } + } + override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit + } + runCatching { manager.discoverServices("$PAIRING_TYPE.", NsdManager.PROTOCOL_DNS_SD, listener) } + .onSuccess { nsd = manager; discovery = listener } + .onFailure { finish(Stage.Failed("Could not look for the pairing pop-up: ${it.localizedMessage}")) } + } + + private fun resolveListener() = object : NsdManager.ResolveListener { + 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 + main.post { + if (working || current.value == Stage.Done) return@post + pairingHost = address.hostAddress + pairingPort = serviceInfo.port + if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded()) + } + } + } + + private fun onCode(code: String) { + val host = pairingHost + val port = pairingPort + if (working) return + if (host == null || port == null) { + show(Stage.Waiting) + return + } + if (code.length != 6) { + show(Stage.CodeNeeded("Enter all 6 digits of the code")) + return + } + working = true + show(Stage.Working("Pairing…")) + Thread({ + val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, host, 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…")) } + val result = runCatching { + val connectPort = WirelessAdbFix.findConnectPort(this, host) + ?: 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) + } + main.post { + working = false + finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: "Wireless debugging command failed") } ?: Stage.Done) + } + }, "wireless-adb-pairing").start() + } + + private fun show(stage: Stage) { + publish(stage) + 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() + publish(stage) + val manager = getSystemService(NotificationManager::class.java) + @Suppress("DEPRECATION") + stopForeground(true) + if (stage is Stage.Done || stage is Stage.Failed) manager?.notify(RESULT_NOTIFICATION_ID, notification(stage)) + stopSelf() + } + + private fun stopDiscovery() { + val listener = discovery ?: return + runCatching { nsd?.stopServiceDiscovery(listener) } + discovery = null + } + + override fun onDestroy() { + main.removeCallbacks(timeout) + stopDiscovery() + if (current.value.let { it is Stage.Waiting || it is Stage.CodeNeeded || it is Stage.Working }) publish(Stage.Idle) + super.onDestroy() + } + + 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" + setShowBadge(false) + setSound(null, null) + enableVibration(false) + }) + val open = PendingIntent.getActivity(this, 0, + Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), + PendingIntent.FLAG_IMMUTABLE) + val cancel = PendingIntent.getService(this, 1, + Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE) + val builder = Notification.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_stat_session) + .setContentIntent(open) + .setShowWhen(false) + .setCategory(Notification.CATEGORY_STATUS) + when (stage) { + Stage.Waiting, Stage.Idle -> builder + .setContentTitle("Pair Wireless debugging") + .setContentText("Turn on Wireless debugging, then tap “Pair device with pairing code”.") + .setStyle(Notification.BigTextStyle().bigText( + "Turn on Wireless debugging, then tap “Pair device with pairing code”. Stay in Settings: the code goes in this notification.")) + .setOngoing(true) + .setOnlyAlertOnce(true) + .addAction(Notification.Action.Builder(null, "Cancel", cancel).build()) + is Stage.CodeNeeded -> { + val reply = PendingIntent.getService(this, 2, + Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CODE), + if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + else PendingIntent.FLAG_UPDATE_CURRENT) + val input = RemoteInput.Builder(KEY_CODE).setLabel("6-digit pairing code").build() + val text = stage.error ?: "Tap Enter code and type the 6 digits shown in Settings." + builder + .setContentTitle(if (stage.error == null) "Enter the Wi-Fi pairing code" else "Try the code again") + .setContentText(text) + .setStyle(Notification.BigTextStyle().bigText(text)) + .setOngoing(true) + .addAction(Notification.Action.Builder(null, "Enter code", reply).addRemoteInput(input).build()) + .addAction(Notification.Action.Builder(null, "Cancel", cancel).build()) + } + is Stage.Working -> builder + .setContentTitle("Setting up Steam") + .setContentText(stage.step) + .setProgress(0, 0, true) + .setOngoing(true) + .setOnlyAlertOnce(true) + Stage.Done -> builder + .setContentTitle("Steam is ready") + .setContentText("Tap to go back to DroidDeck. You can turn Wireless debugging off now.") + .setStyle(Notification.BigTextStyle().bigText("Tap to go back to DroidDeck. You can turn Wireless debugging off now.")) + .setAutoCancel(true) + is Stage.Failed -> builder + .setContentTitle("Wireless debugging setup stopped") + .setContentText(stage.error) + .setStyle(Notification.BigTextStyle().bigText(stage.error)) + .setAutoCancel(true) + } + return builder.build() + } + + companion object { + private const val CHANNEL_ID = "wireless-adb-pairing" + private const val NOTIFICATION_ID = 3 + private const val RESULT_NOTIFICATION_ID = 4 + private const val PAIRING_TYPE = "_adb-tls-pairing._tcp" + private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE" + private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL" + private const val KEY_CODE = "code" + private const val TIMEOUT_MS = 5 * 60_000L + + private val current = MutableStateFlow(Stage.Idle) + val stage: StateFlow = current + + private fun publish(stage: Stage) { current.value = stage } + + 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) + } + + fun cancel(context: Context) { + if (current.value.let { it is Stage.Done || it is Stage.Failed || it is Stage.Idle }) { + publish(Stage.Idle) + return + } + context.startService(Intent(context, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL)) + } + + 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/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index ee5153f0d..d245f0346 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -157,6 +157,8 @@ class FrontEndActions( val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit = { _, done -> done("Wireless debugging is unavailable") }, val onCopyPhantomCommand: (Boolean) -> Unit = {}, val onDismissPhantomGate: () -> Unit = {}, + val onStartWirelessAdbPairing: () -> Unit = {}, + val onOpenNotificationSettings: () -> Unit = {}, val controller: ControllerActions? = null, ) @@ -469,7 +471,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com status = s.phantomProcessStatus, onDismiss = a.onDismissPhantomGate, onOpenDeveloperOptions = requestDeveloperOptions, - onSetUpWirelessAdb = { requestWirelessAdbFix(false) }, + onFixWithWirelessDebugging = { + a.onStartWirelessAdbPairing() + requestDeveloperOptions() + }, + onEnterAddressManually = { requestWirelessAdbFix(false) }, + onCopyCommand = { a.onCopyPhantomCommand(false) }, + onOpenNotificationSettings = a.onOpenNotificationSettings, ) } } 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 36d880365..781361044 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -1,64 +1,102 @@ package com.droiddeck.launcher.ui +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Build import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator 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.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +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.platform.LocalContext +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.core.PhantomProcessLimit 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, onDismiss: () -> Unit, onOpenDeveloperOptions: () -> Unit, - onSetUpWirelessAdb: () -> Unit, + onFixWithWirelessDebugging: () -> Unit, + onEnterAddressManually: () -> Unit, + onCopyCommand: () -> Unit, + onOpenNotificationSettings: () -> Unit, ) { 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) + kotlinx.coroutines.delay(2_000) + } + } + val hasToggle = PhantomProcessLimit.hasDeveloperToggle() BoxWithConstraints(Modifier.fillMaxWidth()) { val compact = maxWidth < 620.dp && maxHeight < 500.dp SettingsPage( host = rememberMenuHost(), - title = if (compact) "Steam paused" else "Steam cannot start yet", + title = "One Android setting to change", eyebrow = "Steam", - lede = if (compact) compactStatus(status) else "${PhantomProcessLimit.title(status)} · checking again every two seconds", + lede = if (compact) null else "Android stops apps that start lots of background processes, and Steam starts dozens. " + + "Until this is changed, games close with no error.", onBack = onDismiss, - // Scrolls, so the larger text never pushes the ADB command off a short screen. scrollContent = true, 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() - } + val fix: @Composable ColumnScope.() -> Unit = { + FixGroup(hasToggle, stage, environment, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, + onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) }) + } + val side: @Composable ColumnScope.() -> Unit = { + StatusGroup(status, compact) + OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand) + } + if (wide) { + Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) { + Column(Modifier.weight(1.2f), content = fix) + Column(Modifier.weight(1f), content = side) + } + } else { + Column(Modifier.widthIn(max = 600.dp).fillMaxWidth()) { + fix() + side() } } } @@ -66,97 +104,168 @@ fun PhantomProcessGatePage( } } -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) +private data class GateEnvironment(val onWifi: Boolean, val notifications: Boolean) { + companion object { + fun read(context: Context): GateEnvironment { + val connectivity = context.getSystemService(ConnectivityManager::class.java) + val wifi = runCatching { + connectivity?.getNetworkCapabilities(connectivity.activeNetwork) + ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true + }.getOrDefault(true) + return GateEnvironment(wifi, WirelessAdbPairingService.notificationsEnabled(context)) + } } - return "$state · retrying every 2 sec" } @Composable -private fun CompactGateInstructions( - status: PhantomProcessStatus, +private fun FixGroup( + hasToggle: Boolean, + stage: Stage, + environment: GateEnvironment, + compact: Boolean, onOpenDeveloperOptions: () -> Unit, - onSetUpWirelessAdb: () -> Unit, + onFixWithWirelessDebugging: () -> Unit, + onOpenNotificationSettings: () -> Unit, + onCancel: () -> Unit, ) { - SettingsGroup("1 · Developer options", compact = true) { + val pairing = stage is Stage.Waiting || stage is Stage.CodeNeeded || stage is Stage.Working + SettingsGroup(if (hasToggle) "Developer options" else "Fix it for me", compact = compact) { Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp), - verticalArrangement = Arrangement.spacedBy(5.dp), + modifier = Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp), + verticalArrangement = Arrangement.spacedBy(8.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 Wireless debugging", compact = true, onClick = onSetUpWirelessAdb) + when { + pairing -> PairingProgress(stage, onCancel) + hasToggle -> { + Body("Turn off “Disable child process restrictions”, then come back. DroidDeck notices on its own.") + PrimaryButton("Open Developer options", compact = compact, onClick = onOpenDeveloperOptions) + } + else -> { + Body("This Android version has no switch for it, so DroidDeck changes it over Wireless debugging on this device. About a minute, no computer needed.") + (stage as? Stage.Failed)?.let { Body(it.error, error = true) } + PrimaryButton( + if (stage is Stage.Failed) "Try again" else "Fix it for me", + compact = compact, + enabled = environment.onWifi && environment.notifications, + onClick = onFixWithWirelessDebugging, + ) + } + } + if (!hasToggle && !pairing) { + if (!environment.onWifi) { + Body("Wireless debugging needs Wi-Fi. Connect to any network first; it doesn't need internet.", warn = true) + } + if (!environment.notifications) { + Body("The pairing code is entered in a notification. Allow notifications for DroidDeck, or use Other ways.", warn = true) + SecondaryButton("Allow notifications", compact = compact, onClick = onOpenNotificationSettings) + } } } } - 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 = 12.sp), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - PhantomProcessLimit.ADB_COMMAND, - style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) +} + +@Composable +private fun PairingProgress(stage: Stage, onCancel: () -> Unit) { + val steps = listOf( + "Open Settings → Developer options → Wireless debugging and turn it on", + "Tap “Pair device with pairing code”", + "Type the code into the DroidDeck notification", + ) + val active = when (stage) { + Stage.Waiting -> 1 + is Stage.CodeNeeded -> 2 + else -> 3 + } + steps.forEachIndexed { index, step -> + val done = index < active + val current = index == active + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(if (done) "✓" else "${index + 1}", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, + color = if (done) LocalPalette.current.good else MaterialTheme.colorScheme.onSurfaceVariant) + Text(step, style = MaterialTheme.typography.bodySmall, + color = if (current) MaterialTheme.colorScheme.onBackground else MaterialTheme.colorScheme.onSurfaceVariant) + } + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + Text( + when (stage) { + Stage.Waiting -> "Waiting for the pairing pop-up…" + is Stage.CodeNeeded -> stage.error ?: "Pop-up found. Enter its code in the notification." + is Stage.Working -> stage.step + else -> "" + }, + style = MaterialTheme.typography.bodySmall, + color = if (stage is Stage.CodeNeeded && stage.error != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + SecondaryButton("Cancel", compact = true, onClick = onCancel) + } +} + +@Composable +private fun StatusGroup(status: PhantomProcessStatus, compact: Boolean) { + SettingsGroup("Status", compact = compact) { + Column(Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(PhantomProcessLimit.title(status), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground) + Body("Checking every 2 seconds. This page closes when it's off.") } } } @Composable -private fun GateInstructions( - status: PhantomProcessStatus, +private fun OtherWays( + hasToggle: Boolean, + compact: Boolean, onOpenDeveloperOptions: () -> Unit, - onSetUpWirelessAdb: () -> Unit, + onFixWithWirelessDebugging: () -> Unit, + onEnterAddressManually: () -> Unit, + onCopyCommand: () -> Unit, ) { - SettingsGroup("1 · Developer options first") { - Column( - modifier = Modifier.fillMaxWidth().padding(14.dp), + var open by rememberSaveable { mutableStateOf(false) } + SettingsGroup("Other ways", compact = compact) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().clickable { open = !open }.padding(horizontal = 14.dp, vertical = 10.dp), + ) { + Body(if (hasToggle) "Wireless debugging, manual address, computer ADB" else "Manual address, computer ADB, Developer options", modifier = Modifier.weight(1f)) + Text(if (open) "▴" else "▾", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + if (open) Column( + modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { + if (hasToggle) { + SecondaryButton("Use Wireless debugging instead", compact = true, onClick = onFixWithWirelessDebugging) + } else { + Body("Some ROMs add the switch anyway. Look for “child process” in Developer options.") + SecondaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions) + } + Body("If the notification doesn't work, enter the pop-up's address and code yourself.") + SecondaryButton("Enter address manually", compact = true, onClick = onEnterAddressManually) + Body("From a computer with ADB:") Text( - PhantomProcessLimit.gateInstructions(status), + PhantomProcessLimit.ADB_COMMAND, + style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp), color = MaterialTheme.colorScheme.onSurfaceVariant, ) - PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions) - SecondaryButton("Use Wireless debugging", onClick = onSetUpWirelessAdb) + SecondaryButton("Copy command", compact = true, onClick = onCopyCommand) } } } @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, - ) - } - } +private fun Body(text: String, modifier: Modifier = Modifier, error: Boolean = false, warn: Boolean = false) { + Text( + text, + modifier = modifier, + style = MaterialTheme.typography.bodySmall, + color = when { + error -> MaterialTheme.colorScheme.error + warn -> androidx.compose.ui.graphics.Color(0xFFFFB86B) + else -> MaterialTheme.colorScheme.onSurfaceVariant + }, + ) } @Composable