Merge org main into feat/components-manager

Keeps both onResume additions: the phantom status refresh from main and the queued component swaps.
This commit is contained in:
The412Banner committed 2026-09-26 04:36:02 -04:00
commit 408fbff7da
21 files changed
+2536 -62

No files matched your search

@@ -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<String?>(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var clientDirectAudio by mutableStateOf(false)
private var forceFullscreen by mutableStateOf(true)
@@ -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
@@ -5,7 +5,6 @@ import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.provider.Settings
import android.util.Log
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
@@ -162,21 +161,7 @@ object DeviceReport {
})
h("Android process limits")
// Android 12 kills "phantom" processes - the children an app forks itself rather than
// starting through the framework - once there are more than a handful of them. A session is
// nothing but those: proot, gamescope, Xwayland, the client, its helpers, Wine, FEX. Where
// this is left on, the OS kills the session and nothing in our logs says why, because
// nothing in the session did it. Some ROMs expose it in Developer options as a
// "restrict child processes" switch; otherwise it is
// adb shell settings put global settings_enable_monitor_phantom_procs false
val phantom = runCatching {
Settings.Global.getString(context.contentResolver, "settings_enable_monitor_phantom_procs")
}.getOrNull()
k("Phantom proc monitor", when (phantom?.lowercase()) {
"false", "0" -> "disabled (good - the OS will not kill the session's children)"
null, "" -> "not set (ROM default, usually ENABLED - see the note below)"
else -> "ENABLED (the OS may kill the session with no log; turn off \"restrict child processes\")"
})
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context.contentResolver)))
h("Device switch files in Download")
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
@@ -0,0 +1,71 @@
package com.droiddeck.launcher.core
import android.content.ContentResolver
import android.os.Build
import android.provider.Settings
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */
enum class PhantomProcessStatus {
NOT_APPLICABLE,
DISABLED,
ENABLED,
UNSET,
UNREADABLE,
}
object PhantomProcessLimit {
const val ADB_COMMAND = "adb shell settings put global settings_enable_monitor_phantom_procs false"
const val SHELL_COMMAND = "settings put global settings_enable_monitor_phantom_procs false"
private const val SETTING = "settings_enable_monitor_phantom_procs"
fun adbCommand(enabled: Boolean): String =
"adb shell settings put global $SETTING ${if (enabled) "true" else "false"}"
fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
val value = try {
Settings.Global.getString(resolver, SETTING)
} catch (_: Exception) {
return PhantomProcessStatus.UNREADABLE
}
return when (value?.trim()?.lowercase()) {
"false", "0" -> PhantomProcessStatus.DISABLED
null, "" -> PhantomProcessStatus.UNSET
else -> PhantomProcessStatus.ENABLED
}
}
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
fun title(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
PhantomProcessStatus.UNREADABLE -> "Child-process limit could not be checked"
PhantomProcessStatus.DISABLED -> "Child-process limit is off"
PhantomProcessStatus.NOT_APPLICABLE -> "Child-process limit not required"
}
fun instructions(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.UNSET -> "This setting is unset, so the ROM default applies and may enforce the limit. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not read the setting. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.DISABLED -> "Steam sessions can start."
PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit."
}
fun gateInstructions(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options."
PhantomProcessStatus.UNSET -> "The ROM default may enforce this limit. Explicitly turn off “Restrict child processes” in Developer options."
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not check this setting. Turn off “Restrict child processes” in Developer options."
else -> instructions(status)
}
fun reportValue(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
}
}
@@ -0,0 +1,185 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import com.flyfishxu.kadb.Kadb
import com.flyfishxu.kadb.cert.KadbCert
import java.io.File
import java.net.InetAddress
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.ArrayDeque
/** A narrowly scoped Wireless debugging client for the child-process setting repair. */
object WirelessAdbFix {
private const val CERT_FILE = "wireless-adb-cert.pem"
private const val KEY_FILE = "wireless-adb-key.pem"
private const val HOST_FILE = "wireless-adb-host.txt"
private const val CONNECTION_FILE = "wireless-adb-connection.txt"
private data class SavedConnection(val host: String, val port: Int?)
@Synchronized
private fun loadOrCreateIdentity(context: Context) {
val directory = context.noBackupFilesDir
val cert = File(directory, CERT_FILE)
val key = File(directory, KEY_FILE)
if (cert.isFile && key.isFile) {
KadbCert.set(cert.readBytes(), key.readBytes())
return
}
val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650))
KadbCert.set(identity.first, identity.second)
writeAtomically(cert, identity.first)
writeAtomically(key, identity.second)
}
private fun writeAtomically(destination: File, contents: ByteArray) {
val temporary = File(destination.parentFile, "${destination.name}.tmp")
temporary.writeBytes(contents)
check(temporary.renameTo(destination)) { "Could not save Wireless debugging identity" }
}
suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) {
loadOrCreateIdentity(context.applicationContext)
Kadb.pair(host, port, pairingCode, "DroidDeck")
writeAtomically(File(context.noBackupFilesDir, HOST_FILE), host.toByteArray())
writeAtomically(File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
}
private fun savedConnection(context: Context): SavedConnection? {
val directory = context.applicationContext.noBackupFilesDir
if (!File(directory, CERT_FILE).isFile || !File(directory, KEY_FILE).isFile) return null
val host = File(directory, HOST_FILE).takeIf(File::isFile)?.readText()?.trim()
?.takeIf(String::isNotEmpty) ?: return null
val lines = File(directory, CONNECTION_FILE).takeIf(File::isFile)?.readLines()
val port = lines?.takeIf { it.size == 2 && it[0] == host }
?.get(1)?.toIntOrNull()?.takeIf { it in 1..65535 }
return SavedConnection(host, port)
}
/** A saved pairing skips the PIN; an unknown connection port can be filled in from Settings. */
fun savedConnectionAddress(context: Context): String? = savedConnection(context)?.let { saved ->
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
"$host:${saved.port ?: ""}"
}
private fun saveConnection(context: Context, host: String, port: Int) {
writeAtomically(
File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE),
"$host\n$port".toByteArray(),
)
}
/** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */
fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12): Int? {
val manager = context.applicationContext.getSystemService(Context.NSD_SERVICE) as NsdManager
val expectedAddress = runCatching { InetAddress.getByName(pairedHost).address }.getOrNull() ?: return null
val resolvedPort = AtomicInteger(-1)
val finished = AtomicBoolean(false)
val latch = CountDownLatch(1)
val queue = ArrayDeque<NsdServiceInfo>()
val seen = mutableSetOf<String>()
var resolving = false
val lock = Any()
lateinit var resolveNext: () -> Unit
resolveNext = {
val next = synchronized(lock) {
if (finished.get() || resolving || queue.isEmpty()) null
else queue.removeFirst().also { resolving = true }
}
if (next != null) {
val listener = object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
synchronized(lock) { resolving = false }
resolveNext()
}
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
val address = serviceInfo.host?.address
if (address != null && address.contentEquals(expectedAddress) && finished.compareAndSet(false, true)) {
resolvedPort.set(serviceInfo.port)
latch.countDown()
} else {
synchronized(lock) { resolving = false }
resolveNext()
}
}
}
runCatching { manager.resolveService(next, listener) }.onFailure {
synchronized(lock) { resolving = false }
resolveNext()
}
}
}
val discoveryListener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = Unit
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
if (serviceInfo.serviceType?.contains("_adb-tls-connect._tcp") == true) {
synchronized(lock) {
if (seen.add(serviceInfo.serviceName)) queue.addLast(serviceInfo)
}
resolveNext()
}
}
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
override fun onDiscoveryStopped(serviceType: String) { latch.countDown() }
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
}
try {
manager.discoverServices("_adb-tls-connect._tcp.", NsdManager.PROTOCOL_DNS_SD, discoveryListener)
latch.await(timeoutSeconds, TimeUnit.SECONDS)
} catch (_: Exception) {
return null
} finally {
runCatching { manager.stopServiceDiscovery(discoveryListener) }
}
return resolvedPort.get().takeIf { it in 1..65535 }
}
fun setChildProcessLimit(context: Context, host: String, port: Int, enabled: Boolean) {
loadOrCreateIdentity(context.applicationContext)
Kadb.create(host, port).use { adb ->
val value = if (enabled) "true" else "false"
val change = adb.shell("settings put global settings_enable_monitor_phantom_procs $value")
check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
val result = adb.shell("settings get global settings_enable_monitor_phantom_procs")
check(result.exitCode == 0 && result.output.trim() == value) {
"Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}"
}
}
saveConnection(context, host, port)
}
/** Tries the app's saved pairing without asking for a new pairing code. */
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
val appContext = context.applicationContext
val saved = savedConnection(appContext)
?: error("No Wireless debugging pairing is saved")
val cachedPort = saved.port
if (cachedPort != null) {
val cachedResult = runCatching {
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
}
if (cachedResult.isSuccess) return
val discoveredPort = findConnectPort(appContext, saved.host)
if (discoveredPort != null && discoveredPort != cachedPort) {
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
} else {
cachedResult.getOrThrow()
}
} else {
val discoveredPort = findConnectPort(appContext, saved.host)
?: error("Enter the current Wireless debugging IP address & Port")
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
}
}
}
@@ -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
@@ -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<HomeApp.LaunchableApp?>(null) }
val colors = MaterialTheme.colorScheme
val ctx = LocalContext.current
BackHandler(enabled = s.pageKey != null && page != null) { a.onPageBack() }
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
val requestDeveloperOptions = {
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
else showDeveloperDisplayChoice = true
}
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
wirelessAdbDesiredEnabled = enabled
showWirelessAdbFix = true
}
LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) {
if (phantomGateVisible) {
while (true) {
kotlinx.coroutines.delay(2_000)
a.onRefreshPhantomStatus()
}
}
}
BackHandler(enabled = !processSettingsPageVisible && s.pageKey != null && page != null) { a.onPageBack() }
// Back (and B) from a game or an emulator steps out one level, as its "‹" link does, instead
// of leaving the app: a game -> its emulator (or Steam), an emulator -> Desktop.
BackHandler(
enabled = (s.pageKey == null || page == null) &&
enabled = !processSettingsPageVisible && (s.pageKey == null || page == null) &&
(selected.startsWith("app:") || selected.startsWith("emu:") || selected.startsWith("rom:")),
) {
selected = when {
@@ -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<File?, Float> = 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<Library.Emulator, L
private fun Content(
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
@@ -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<String?>(null) }
val setProcessLimit: (Boolean) -> Unit = { enabled ->
processLimitBusy = true
processLimitMessage = null
a.onSetPhantomProcessLimit(enabled) { error ->
processLimitBusy = false
if (error == null) {
a.onRefreshPhantomStatus()
} else {
processLimitMessage = "Check the Wireless debugging IP address & Port, or pair again if Android removed this device."
onRequestWirelessAdb(enabled)
}
}
}
val runtime = when {
s.busy -> "Working…"
!s.ready -> "Install"
@@ -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
@@ -0,0 +1,182 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
@Composable
fun PhantomProcessGatePage(
status: PhantomProcessStatus,
onDismiss: () -> Unit,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
BackHandler(onBack = onDismiss)
BoxWithConstraints(Modifier.fillMaxWidth()) {
val compact = maxWidth < 620.dp && maxHeight < 500.dp
SettingsPage(
host = rememberMenuHost(),
title = if (compact) "Steam paused" else "Steam cannot start yet",
eyebrow = "Steam",
lede = if (compact) compactStatus(status) else "${PhantomProcessLimit.title(status)} · checking again every two seconds",
onBack = onDismiss,
scrollContent = false,
compactLayout = compact,
) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 620.dp
Column(
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
when {
compact -> CompactGateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
wide -> Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) {
Column(Modifier.weight(1f)) {
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
}
Column(Modifier.weight(1f)) { AdbFallback() }
}
else -> {
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
AdbFallback()
}
}
}
}
}
}
}
private fun compactStatus(status: PhantomProcessStatus): String {
val state = when (status) {
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
PhantomProcessStatus.UNREADABLE -> "Child-process limit is unreadable"
else -> PhantomProcessLimit.title(status)
}
return "$state · retrying every 2 sec"
}
@Composable
private fun CompactGateInstructions(
status: PhantomProcessStatus,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
SettingsGroup("1 · Developer options", compact = true) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp),
verticalArrangement = Arrangement.spacedBy(5.dp),
) {
Text(
PhantomProcessLimit.gateInstructions(status),
style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
SecondaryButton("Use on-device ADB", compact = true, onClick = onSetUpWirelessAdb)
}
}
}
SettingsGroup("3 · Computer ADB last resort", compact = true) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp),
verticalArrangement = Arrangement.spacedBy(3.dp),
) {
Text(
"If the setting is missing and Wireless debugging is unavailable, run this from a computer:",
style = MaterialTheme.typography.bodySmall.copy(fontSize = 11.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
PhantomProcessLimit.ADB_COMMAND,
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace, fontSize = 9.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
private fun GateInstructions(
status: PhantomProcessStatus,
onOpenDeveloperOptions: () -> Unit,
onSetUpWirelessAdb: () -> Unit,
) {
SettingsGroup("1 · Developer options first") {
Column(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
PhantomProcessLimit.gateInstructions(status),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
SecondaryButton("Use on-device ADB", onClick = onSetUpWirelessAdb)
}
}
}
@Composable
private fun AdbFallback() {
SettingsGroup("3 · Computer ADB last resort") {
Column(
modifier = Modifier.fillMaxWidth().padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
"Use this only if Developer options has no setting and Wireless debugging is unavailable. Connect this device to a computer with ADB and run:",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
Text(
PhantomProcessLimit.ADB_COMMAND,
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
fun DeveloperDisplayChoiceDialog(
displays: List<Pair<Int, String>>,
onMainScreen: () -> Unit,
onSecondaryScreen: (Int) -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Open Developer options") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
Text("Choose which display to open Android Settings on.")
TextButton(modifier = Modifier.fillMaxWidth(), onClick = onMainScreen) { Text("Main screen") }
displays.forEach { (id, label) ->
TextButton(modifier = Modifier.fillMaxWidth(), onClick = { onSecondaryScreen(id) }) { Text(label) }
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@@ -235,10 +235,14 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
}
@Composable
fun SettingsGroup(title: String, content: @Composable ColumnScope.() -> Unit) {
fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 6.dp)) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 10.dp),
modifier = Modifier.fillMaxWidth().padding(top = if (compact) 4.dp else 16.dp, bottom = if (compact) 3.dp else 6.dp),
) {
Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant)
Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line))
}
@@ -332,24 +336,32 @@ fun SettingsPage(
action: (@Composable () -> Unit)? = null,
/** Pass one held above the page to keep its scroll position across a page opened over it. */
scroll: androidx.compose.foundation.ScrollState? = null,
scrollContent: Boolean = true,
compactLayout: Boolean = false,
content: @Composable ColumnScope.() -> Unit,
) {
val scrollState = scroll ?: rememberScrollState()
val colors = MaterialTheme.colorScheme
val dim by animateFloatAsState(if (host.open != null) 0.6f else 1f, Motion.tw(220), label = "pageDim")
Column(modifier = Modifier.fillMaxSize().padding(horizontal = 22.dp, vertical = 18.dp)) {
Column(
modifier = Modifier.fillMaxSize().padding(
horizontal = if (compactLayout) 14.dp else 22.dp,
vertical = if (compactLayout) 6.dp else 18.dp,
),
verticalArrangement = Arrangement.spacedBy(if (compactLayout) 2.dp else 0.dp),
) {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically) {
// Outlined when a controller's focus is on it, like every other control here.
val backSrc = remember { MutableInteractionSource() }
val backHot = backSrc.collectIsFocusedAsState().value || backSrc.collectIsHoveredAsState().value
Text(
"‹ Back", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
"‹ Back", fontSize = if (compactLayout) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold,
color = if (backHot) LocalPalette.current.signal else colors.onSurfaceVariant,
modifier = Modifier.clip(RoundedCornerShape(8.dp))
.border(2.dp, if (backHot) LocalPalette.current.signal else Color.Transparent, RoundedCornerShape(8.dp))
.hoverable(backSrc).clickable(interactionSource = backSrc, indication = null, onClick = onBack)
.padding(horizontal = 6.dp, vertical = 4.dp),
.padding(horizontal = 6.dp, vertical = if (compactLayout) 2.dp else 4.dp),
)
if (eyebrow != null) {
Spacer(Modifier.width(10.dp))
@@ -359,13 +371,44 @@ fun SettingsPage(
}
Rise(1) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.weight(1f)) { Title(title) }
Box(Modifier.weight(1f)) {
if (compactLayout) {
Text(
title,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
color = colors.onBackground,
modifier = Modifier.padding(vertical = 2.dp),
)
} else {
Title(title)
}
}
if (action != null) action()
}
}
if (lede != null) Rise(2) { Lede(lede) }
if (lede != null) Rise(2) {
if (compactLayout) {
Text(
lede,
fontSize = 11.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(bottom = 3.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
} else {
Lede(lede)
}
}
Rise(3, Modifier.weight(1f).fillMaxWidth()) {
Column(modifier = Modifier.fillMaxSize().graphicsLayer { alpha = dim }.verticalScroll(scrollState).padding(bottom = 24.dp)) { content() }
Column(
modifier = Modifier
.fillMaxSize()
.graphicsLayer { alpha = dim }
.then(if (scrollContent) Modifier.verticalScroll(scrollState) else Modifier)
.padding(bottom = if (compactLayout) 0.dp else 24.dp),
) { content() }
}
}
}
@@ -0,0 +1,538 @@
package com.droiddeck.launcher.ui
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.WirelessAdbFix
import kotlin.math.min
import kotlin.math.roundToInt
@Composable
fun WirelessAdbFixPage(
onBack: () -> Unit,
desiredEnabled: Boolean,
onOpenDeveloperOptions: () -> Unit,
onPair: (String, Int, String, (String?) -> Unit) -> Unit,
onFindConnectPort: (String, (Int?) -> Unit) -> Unit,
onApply: (String, Int, Boolean, (String?) -> Unit) -> Unit,
) {
val context = LocalContext.current
val savedAddress = remember { WirelessAdbFix.savedConnectionAddress(context) }
var step by rememberSaveable { mutableStateOf(if (savedAddress == null) 0 else 1) }
var pairingAddress by rememberSaveable { mutableStateOf("") }
var connectionAddress by rememberSaveable { mutableStateOf(savedAddress.orEmpty()) }
var pairingCode by rememberSaveable { mutableStateOf("") }
var busy by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
var messageIsError by remember { mutableStateOf(false) }
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
val pairingEndpoint = parseAdbAddress(pairingAddress)
val pairNow: () -> Unit = {
parseAdbAddress(pairingAddress)?.let { endpoint ->
keyboardController?.hide()
focusManager.clearFocus()
busy = true
editing = false
message = null
messageIsError = false
onPair(endpoint.host, endpoint.port, pairingCode) { error ->
pairingCode = ""
if (error != null) {
busy = false
message = error
messageIsError = true
} else {
step = 1
busy = true
message = "Paired. Finding the Wireless debugging port…"
onFindConnectPort(endpoint.host) { discoveredPort ->
if (discoveredPort == null) {
connectionAddress = formatAddressHost(endpoint.host) + ":"
busy = false
message = "Paired. Enter the port from Settings."
} else {
connectionAddress = formatAdbAddress(endpoint.host, discoveredPort)
message = "Device found. Applying the setting…"
onApply(endpoint.host, discoveredPort, desiredEnabled) { applyError ->
busy = false
if (applyError == null) {
step = 2
message = null
} else {
message = "Could not apply automatically. Check the address below and retry. $applyError"
messageIsError = true
}
}
}
}
}
}
}
}
val applyAddress: () -> Unit = {
parseAdbAddress(connectionAddress)?.let { endpoint ->
keyboardController?.hide()
focusManager.clearFocus()
busy = true
editing = false
message = null
messageIsError = false
onApply(endpoint.host, endpoint.port, desiredEnabled) { error ->
busy = false
if (error == null) {
step = 2
message = null
} else {
message = error
messageIsError = true
}
}
}
}
val pairAgain: () -> Unit = {
step = 0
pairingAddress = ""
pairingCode = ""
message = null
messageIsError = false
}
BackHandler { if (!busy) onBack() }
BoxWithConstraints(Modifier.fillMaxSize()) {
val compactSplit = maxWidth < 620.dp && maxHeight < 500.dp
val form: @Composable () -> Unit = {
WirelessStepForm(
step = step,
pairingAddress = pairingAddress,
onPairingAddressChange = { pairingAddress = it },
pairingCode = pairingCode,
onPairingCodeChange = { pairingCode = it.filter(Char::isDigit).take(6) },
connectionAddress = connectionAddress,
onConnectionAddressChange = { connectionAddress = it },
busy = busy,
message = message,
messageIsError = messageIsError,
compact = compactSplit,
editing = editing,
onEditingChanged = { editing = it },
focusManager = focusManager,
desiredEnabled = desiredEnabled,
canPair = pairingEndpoint != null && pairingCode.length == 6,
onPair = pairNow,
onApply = applyAddress,
onPairAgain = pairAgain,
)
}
SettingsPage(
host = rememberMenuHost(),
title = when {
compactSplit && step < 2 -> "Wireless ADB"
step == 2 -> "Wireless ADB ready"
else -> "Set up on-device ADB"
},
eyebrow = "Setup",
lede = when {
compactSplit && step == 0 -> "If the option is missing, pair over Wireless debugging."
compactSplit && step == 1 -> "Paired. Check IP address & Port in Wireless debugging."
compactSplit -> "The child-process limit was updated."
step == 0 -> "Use step 2 if Developer options has no child-process setting. In Android Settings, open Developer options → Wireless debugging → Pair device with pairing code."
step == 1 -> "Paired. Use the address below; update it from Wireless debugging → IP address & Port if needed."
else -> "The child-process limit was updated over Wireless debugging."
},
onBack = { if (!busy) onBack() },
action = if (compactSplit && step < 2) {
{ SecondaryButton("Developer options", compact = true, enabled = !busy, onClick = onOpenDeveloperOptions) }
} else null,
scrollContent = !compactSplit,
compactLayout = compactSplit,
) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 620.dp
if (step == 2) {
Column(
modifier = Modifier.widthIn(max = 680.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
SettingsGroup("Child-process limit", compact = compactSplit) {
Text(
"Android confirmed the limit is ${if (desiredEnabled) "enabled" else "disabled"}.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(14.dp),
)
}
PrimaryButton("Done", enabled = !busy, onClick = onBack)
}
} else if (compactSplit) {
Column(
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
form()
if (!editing) CompactComputerFallback(desiredEnabled)
}
} else {
val routes: @Composable () -> Unit = {
FallbackOrder(desiredEnabled, busy, onOpenDeveloperOptions)
}
if (wide) {
Row(
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalAlignment = Alignment.Top,
) {
Column(Modifier.weight(1f)) { routes() }
Column(Modifier.weight(1f)) { form() }
}
} else {
Column(
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
routes()
form()
}
}
}
}
}
}
}
@Composable
private fun WirelessStepForm(
step: Int,
pairingAddress: String,
onPairingAddressChange: (String) -> Unit,
pairingCode: String,
onPairingCodeChange: (String) -> Unit,
connectionAddress: String,
onConnectionAddressChange: (String) -> Unit,
busy: Boolean,
message: String?,
messageIsError: Boolean,
compact: Boolean,
editing: Boolean,
onEditingChanged: (Boolean) -> Unit,
focusManager: FocusManager,
desiredEnabled: Boolean,
canPair: Boolean,
onPair: () -> Unit,
onApply: () -> Unit,
onPairAgain: () -> Unit,
) {
if (step == 0) {
SettingsGroup("2 · Pair Wireless debugging", compact = compact) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
) {
AdbTextField(
value = pairingAddress,
onValueChange = onPairingAddressChange,
label = "Pairing pop-up IP address & Port",
placeholder = "192.168.1.42:37123",
keyboardType = KeyboardType.Ascii,
imeAction = ImeAction.Next,
compact = compact,
onFocusChange = onEditingChanged,
onNext = { focusManager.moveFocus(FocusDirection.Next) },
)
Row(
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth(),
) {
AdbTextField(
value = pairingCode,
onValueChange = onPairingCodeChange,
label = "Pairing code (PIN)",
placeholder = "6 digits",
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done,
compact = compact,
onFocusChange = onEditingChanged,
onDone = {
focusManager.clearFocus()
},
modifier = Modifier.weight(1f),
)
PrimaryButton("Pair", compact = compact, enabled = !busy && canPair, onClick = onPair)
}
StatusMessage(busy, message, isError = messageIsError)
}
}
} else {
SettingsGroup("2 · Apply over Wireless debugging", compact = compact) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
) {
AdbTextField(
value = connectionAddress,
onValueChange = onConnectionAddressChange,
label = "Connection IP address & Port",
placeholder = "192.168.1.42:45678",
keyboardType = KeyboardType.Ascii,
imeAction = ImeAction.Done,
compact = compact,
onFocusChange = onEditingChanged,
onDone = { focusManager.clearFocus() },
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth(),
) {
StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError)
SecondaryButton("Pair again", compact = compact, enabled = !busy, onClick = onPairAgain)
PrimaryButton(
if (desiredEnabled) "Enable limit" else "Disable limit",
compact = compact,
enabled = !busy && parseAdbAddress(connectionAddress) != null,
onClick = onApply,
)
}
}
}
}
}
@Composable
private fun AdbTextField(
value: String,
onValueChange: (String) -> Unit,
label: String,
keyboardType: KeyboardType,
imeAction: ImeAction,
modifier: Modifier = Modifier,
placeholder: String? = null,
compact: Boolean = false,
onFocusChange: (Boolean) -> Unit = {},
onNext: (() -> Unit)? = null,
onDone: (() -> Unit)? = null,
) {
val context = LocalContext.current
val palette = LocalPalette.current
val onValueChangeLatest = rememberUpdatedState(onValueChange)
val onNextLatest = rememberUpdatedState(onNext)
val onDoneLatest = rememberUpdatedState(onDone)
val onFocusChangeLatest = rememberUpdatedState(onFocusChange)
var focused by remember { mutableStateOf(false) }
val shape = RoundedCornerShape(8.dp)
val inputHeight = if (compact) 44.dp else 52.dp
val colors = MaterialTheme.colorScheme
Column(modifier = modifier.fillMaxWidth()) {
Text(
label,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Medium,
color = colors.onSurfaceVariant,
maxLines = 1,
)
Box(
modifier = Modifier
.fillMaxWidth()
.height(inputHeight)
.background(colors.surfaceVariant, shape)
.border(1.dp, if (focused) palette.signal else palette.line2, shape)
.padding(horizontal = 10.dp),
contentAlignment = Alignment.CenterStart,
) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { viewContext ->
EditText(viewContext).apply {
isSingleLine = true
setHorizontallyScrolling(true)
background = null
setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0)
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f)
setTextColor(colors.onBackground.toArgb())
setHintTextColor(colors.onSurfaceVariant.toArgb())
contentDescription = label
inputType = if (keyboardType == KeyboardType.Number) {
InputType.TYPE_CLASS_NUMBER
} else {
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
}
imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
hint = placeholder
setOnEditorActionListener { _, actionId, event ->
val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER
when {
imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> {
onNextLatest.value?.invoke()
true
}
imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> {
onDoneLatest.value?.invoke()
true
}
else -> false
}
}
setOnFocusChangeListener { _, hasFocus ->
focused = hasFocus
onFocusChangeLatest.value(hasFocus)
}
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable?) {
onValueChangeLatest.value(s?.toString().orEmpty())
}
})
}
},
update = { editText ->
editText.setTextColor(colors.onBackground.toArgb())
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
editText.hint = placeholder
editText.contentDescription = label
if (editText.text.toString() != value) {
val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length
editText.setText(value)
editText.setSelection(min(cursor, value.length))
}
},
)
}
}
}
@Composable
private fun FallbackOrder(
desiredEnabled: Boolean,
busy: Boolean,
onOpenDeveloperOptions: () -> Unit,
) {
SettingsGroup("Other ways to change it") {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text("1 · Developer options (try first)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
Text("Set “Restrict child processes” ${if (desiredEnabled) "on" else "off"}.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
SecondaryButton("Open Developer options", enabled = !busy, onClick = onOpenDeveloperOptions)
Text("3 · Computer ADB (last resort)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
Text("Only if Wireless debugging is unavailable.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
PhantomProcessLimit.adbCommand(desiredEnabled),
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
private fun CompactComputerFallback(desiredEnabled: Boolean) {
SettingsGroup("3 · Computer ADB last resort", compact = true) {
Text(
PhantomProcessLimit.adbCommand(desiredEnabled),
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace),
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp),
)
}
}
@Composable
private fun StatusMessage(busy: Boolean, message: String?, modifier: Modifier = Modifier, isError: Boolean = false) {
if (busy) {
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
Text(message ?: "Working…", style = MaterialTheme.typography.bodySmall)
}
} else {
message?.let {
Text(
it,
modifier = modifier,
style = MaterialTheme.typography.bodySmall,
color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
private data class AdbEndpoint(val host: String, val port: Int)
private fun parseAdbAddress(value: String): AdbEndpoint? {
val address = value.trim()
val host: String
val portText: String
if (address.startsWith("[")) {
val closingBracket = address.indexOf(']')
if (closingBracket <= 1 || address.getOrNull(closingBracket + 1) != ':') return null
host = address.substring(1, closingBracket)
if (':' !in host) return null
portText = address.substring(closingBracket + 2)
} else {
val colon = address.lastIndexOf(':')
if (colon <= 0 || address.indexOf(':') != colon) return null
host = address.substring(0, colon)
portText = address.substring(colon + 1)
}
if (host.isBlank() || host.any(Char::isWhitespace)) return null
val port = portText.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null
return AdbEndpoint(host, port)
}
private fun formatAddressHost(host: String): String = if (':' in host) "[$host]" else host
private fun formatAdbAddress(host: String, port: Int): String = "${formatAddressHost(host)}:$port"
private fun imeActionFlag(action: ImeAction): Int = when (action) {
ImeAction.Next -> EditorInfo.IME_ACTION_NEXT
ImeAction.Done -> EditorInfo.IME_ACTION_DONE
ImeAction.Go -> EditorInfo.IME_ACTION_GO
ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH
else -> EditorInfo.IME_ACTION_UNSPECIFIED
}