diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 5d3f283701..16099d458f 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -130,6 +130,17 @@
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation|uiMode"
android:theme="@style/AppTheme" />
+
+
"$inbox/device-code.part" && mv -f "$inbox/device-code.part" "$inbox/device-code" || return 1
+ i=0
+ while [ $i -lt 40 ] && [ -e "$inbox/device-code" ]; do
+ sleep 0.2
+ i=$((i + 1))
+ done
+ if [ -e "$inbox/device-code" ]; then
+ rm -f "$inbox/device-code"
+ return 1
+ fi
+ # DroidDeck writes "ok" or "failed" once it has tried to open the page; no answer counts as failed.
+ i=0
+ while [ $i -lt 50 ] && [ ! -e "$inbox/device-code.result" ]; do
+ sleep 0.2
+ i=$((i + 1))
+ done
+ result=$(cat "$inbox/device-code.result" 2>/dev/null)
+ rm -f "$inbox/device-code.result"
+ [ "$result" = ok ]
+}
+
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
gh_pid=$GH_PID
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
shown=
while IFS= read -r line <&"$ghout"; do
- printf '%s\n' "$line"
code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1)
+ # gh's own prompts would push the code out of the one line the setup card shows.
+ case "$line" in
+ *"one-time code"* | *"Press Enter"* | *"Open this URL"*) ;;
+ *) printf '%s\n' "$line" ;;
+ esac
if [ -n "$code" ] && [ -z "$shown" ]; then
shown=1
echo >&"$ghin"
printf 'GitHub device code: %s · github.com/login/device\n' "$code"
- android-open https://github.com/login/device
+ float_code "$code" || android-open "$url"
fi
done
wait "$gh_pid"
+status=$?
+[ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code"
+exit $status
diff --git a/app/src/main/java/com/droiddeck/launcher/DeviceCodeActivity.kt b/app/src/main/java/com/droiddeck/launcher/DeviceCodeActivity.kt
new file mode 100644
index 0000000000..472521fe20
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/DeviceCodeActivity.kt
@@ -0,0 +1,167 @@
+package com.droiddeck.launcher
+
+import android.app.ActivityOptions
+import android.app.PictureInPictureParams
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.content.Intent
+import android.content.res.Configuration
+import android.net.Uri
+import android.os.Bundle
+import android.util.Rational
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.BackHandler
+import androidx.activity.compose.setContent
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.droiddeck.launcher.core.AppLanguage
+import com.droiddeck.launcher.ui.DroidDeckTheme
+import com.droiddeck.launcher.ui.FitText
+import com.droiddeck.launcher.ui.LocalPalette
+import com.droiddeck.launcher.ui.PrimaryButton
+import com.droiddeck.launcher.ui.SecondaryButton
+import java.lang.ref.WeakReference
+
+/** Floats a sign-in code over the browser page that asks for it. */
+class DeviceCodeActivity : ComponentActivity() {
+ private var code by mutableStateOf("")
+ private var url = ""
+ private var display: Int? = null
+ private var inPip by mutableStateOf(false)
+ private var openPending = false
+
+ override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ current = WeakReference(this)
+ read(intent)
+ openPending = savedInstanceState == null
+ setContent { DroidDeckTheme { Float() } }
+ }
+
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ read(intent)
+ openPending = true
+ }
+
+ override fun onDestroy() {
+ if (current?.get() === this) current = null
+ super.onDestroy()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ if (!openPending) return
+ if (isInPictureInPictureMode) {
+ openPage()
+ return
+ }
+ enterPip()
+ if (!inPip) {
+ openPage()
+ finish()
+ }
+ }
+
+ override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
+ super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
+ inPip = isInPictureInPictureMode
+ if (isInPictureInPictureMode && openPending) openPage()
+ }
+
+ private fun read(intent: Intent) {
+ code = intent.getStringExtra(EXTRA_CODE).orEmpty()
+ url = intent.getStringExtra(EXTRA_URL).orEmpty()
+ display = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it > 0 }
+ copy()
+ }
+
+ private fun copy() {
+ runCatching { getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("GitHub", code)) }
+ }
+
+ private fun enterPip() {
+ inPip = runCatching {
+ enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(16, 9)).build())
+ }.getOrDefault(false)
+ }
+
+ private fun openPage() {
+ openPending = false
+ val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ val at = display
+ val opened = runCatching {
+ if (at == null) startActivity(intent)
+ else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(at).toBundle())
+ }.recoverCatching { startActivity(intent) }.isSuccess
+ com.droiddeck.launcher.agent.AgentHost.deviceCodeOpened(applicationContext, opened)
+ }
+
+ @androidx.compose.runtime.Composable
+ private fun Float() {
+ val colors = MaterialTheme.colorScheme
+ val accent = LocalPalette.current.signal
+ BackHandler(enabled = !inPip) { enterPip() }
+ Box(Modifier.fillMaxSize().background(colors.background), contentAlignment = Alignment.Center) {
+ Column(
+ Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(if (inPip) 8.dp else 24.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(if (inPip) 2.dp else 16.dp),
+ ) {
+ Text(stringResource(R.string.agent_step_github), style = MaterialTheme.typography.labelLarge, color = colors.onSurfaceVariant)
+ FitText(code, maxSize = if (inPip) 40.sp else 56.sp, fontWeight = FontWeight.Bold, color = accent,
+ modifier = Modifier.fillMaxWidth())
+ Text(Uri.parse(url).let { it.host + it.path }, style = MaterialTheme.typography.labelMedium, color = colors.onSurfaceVariant, maxLines = 1)
+ if (!inPip) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ PrimaryButton(stringResource(R.string.fm_copy), onClick = ::copy)
+ SecondaryButton(stringResource(R.string.common_close), onClick = ::finish)
+ }
+ }
+ }
+ }
+
+ companion object {
+ private const val EXTRA_CODE = "code"
+ private const val EXTRA_URL = "url"
+ private const val EXTRA_DISPLAY = "display"
+ private var current: WeakReference? = null
+
+ /** False when this device cannot float a window, so the caller opens the page itself. */
+ fun show(context: Context, code: String, url: String, display: Int): Boolean {
+ if (!PairingGuideActivity.canFloat(context)) return false
+ val intent = Intent(context, DeviceCodeActivity::class.java)
+ .putExtra(EXTRA_CODE, code).putExtra(EXTRA_URL, url).putExtra(EXTRA_DISPLAY, display)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ return runCatching {
+ if (display > 0) context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
+ else context.startActivity(intent)
+ }.isSuccess
+ }
+
+ fun close() {
+ current?.get()?.finish()
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt
index 1f78672f4a..63e60f3d5d 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt
@@ -382,7 +382,7 @@ object AgentHost {
val adb = AgentAdb.prepare(app)
val env = listOf(
"/usr/bin/env", "HOME=/root", "PATH=$GUEST_PATH", "LANG=C.UTF-8",
- "ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}",
+ "ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}", "DROIDDECK_PACKAGE=${app.packageName}",
"DD_AGENT=1", "DD_AGENT_INBOX=${File(app.filesDir, "agent").path}", "BROWSER=/root/.local/bin/android-open", "DD_BROWSER_DISPLAY=${AgentAdb.browserDisplay}",
)
val shell = listOf(
@@ -508,6 +508,7 @@ object AgentHost {
appContext?.let { app ->
claimLabRequest(app)
claimOpenUrl(app)
+ claimDeviceCode(app)
// proot comes from an add-on pack fetched after the app starts, so the runtime can become usable later.
if (!available && state != State.WORKING) available = LinuxRuntime.hasRootfs(app)
lab = LabProgress.read(LinuxRuntime.rootDir(app))
@@ -529,15 +530,43 @@ object AgentHost {
val url = runCatching { claimed.readText().trim() }.getOrNull()
claimed.delete()
if (url == null || !(url.startsWith("https://") || url.startsWith("http://"))) return
+ if (!openUrl(app, url)) runCatching { File(app.filesDir, "$OPEN_URL.failed").writeText("") }
+ }
+
+ /** dd-gh-login leaves " " here to float the code over the page, and an empty file when it ends. */
+ private fun claimDeviceCode(app: Context) {
+ val request = File(app.filesDir, DEVICE_CODE)
+ if (!request.isFile) return
+ val claimed = File(app.filesDir, "$DEVICE_CODE.claimed")
+ if (!request.renameTo(claimed)) return
+ val parts = runCatching { claimed.readText().trim() }.getOrDefault("").split(' ', limit = 2)
+ claimed.delete()
+ val code = parts[0]
+ val url = parts.getOrNull(1)?.takeIf { it.startsWith("https://") }
+ if (code.isEmpty() || url == null) {
+ com.droiddeck.launcher.DeviceCodeActivity.close()
+ return
+ }
+ if (!com.droiddeck.launcher.DeviceCodeActivity.show(app, code, url, AgentAdb.browserDisplay)) deviceCodeOpened(app, openUrl(app, url))
+ }
+
+ /** Tells dd-gh-login whether the device page opened, so it can fall back to android-open. */
+ fun deviceCodeOpened(app: Context, opened: Boolean) {
+ runCatching {
+ val part = File(app.filesDir, "$DEVICE_CODE.result.part")
+ part.writeText(if (opened) "ok" else "failed")
+ part.renameTo(File(app.filesDir, "$DEVICE_CODE.result"))
+ }
+ }
+
+ private fun openUrl(app: Context, url: String): Boolean {
val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(AgentAdb.browserDisplay).toBundle()
- runCatching { app.startActivity(intent, options) }
+ return runCatching { app.startActivity(intent, options) }
.recoverCatching { app.startActivity(intent) }
- .onFailure {
- Log.w(TAG, "could not open a sign-in link: ${it.javaClass.simpleName}")
- runCatching { File(app.filesDir, "$OPEN_URL.failed").writeText("") }
- }
+ .onFailure { Log.w(TAG, "could not open a sign-in link: ${it.javaClass.simpleName}") }
+ .isSuccess
}
/**
@@ -593,6 +622,7 @@ object AgentHost {
private const val RESUME = "agent/resume"
private const val LAB_REQUEST = "agent/lab-request"
private const val OPEN_URL = "agent/open-url"
+ private const val DEVICE_CODE = "agent/device-code"
private const val LAB_CHAT_KEY = "lab_chat"
/** The raw output of the latest turn, for working out what a CLI did when the chat shows nothing. */
private const val TURN_LOG = "agent/turn.log"
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt
index a5f900d6f5..1ff5475b6e 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt
@@ -191,6 +191,14 @@ object AgentSetup {
for (name in HELPERS) copyAsset(app, "agent/$name", File(bin, name))
val ctl = File(root, CTL.removePrefix("/")).apply { mkdirs() }
for (name in app.assets.list("agent/ctl").orEmpty()) copyAsset(app, "agent/ctl/$name", File(ctl, name))
+ unpinAdbSerial(File(root, "root/.bashrc"))
+ }
+
+ /** Older tools/agent/setup pinned the adb port in .bashrc, which overrides the live port DroidDeck passes. */
+ internal fun unpinAdbSerial(bashrc: File) {
+ val text = runCatching { bashrc.readText() }.getOrNull() ?: return
+ val fixed = text.replace("ADB_SERIAL=127.0.0.1:5555 ", "ADB_SERIAL=\"\${ADB_SERIAL:-127.0.0.1:5555}\" ")
+ if (fixed != text) runCatching { bashrc.writeText(fixed) }
}
private fun copyAsset(app: Context, asset: String, target: File) {
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
index d0f4ea80a0..c4d443184d 100644
--- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
@@ -529,6 +529,17 @@ object AddedGames {
}
}
+ class Listed(val appId: Long, val name: String, val launchOptions: String)
+
+ fun listed(context: Context): List? = runCatching {
+ val file = File(context.filesDir, "session/added-games.json")
+ if (!file.isFile) return null
+ val entries = org.json.JSONArray(file.readText())
+ (0 until entries.length()).mapNotNull { i ->
+ entries.optJSONObject(i)?.takeIf { it.has("appid") }?.let { Listed(it.optLong("appid") and 0xFFFFFFFFL, it.optString("name"), it.optString("launch")) }
+ }
+ }.getOrNull()
+
fun writeListing(context: Context, games: List,
extra: List = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
index 4c567fd1b6..cf7b324eac 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
@@ -1281,6 +1281,11 @@ object SessionPrefs {
fun addedGameStoredAppId(context: Context, folderPath: String): Long? =
prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
+ fun addedGameFolders(context: Context): Map = prefs(context).all.mapNotNull { (key, value) ->
+ val id = (value as? Long)?.takeIf { key.startsWith("addedAppId:") && it != 0L } ?: return@mapNotNull null
+ (id and 0xFFFFFFFFL) to key.removePrefix("addedAppId:")
+ }.toMap()
+
fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) {
val p = prefs(context)
val previous = p.getString("storeFolder:$key", null)
diff --git a/app/src/main/java/com/droiddeck/launcher/storage/SteamStorage.kt b/app/src/main/java/com/droiddeck/launcher/storage/SteamStorage.kt
index 2111bfdee1..62ba45fd9c 100644
--- a/app/src/main/java/com/droiddeck/launcher/storage/SteamStorage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/storage/SteamStorage.kt
@@ -155,6 +155,42 @@ object SteamStorage {
fun leftoverId(name: String): Int? = name.toLongOrNull()?.takeIf { it in 1 until (1L shl 31) }?.toInt()
+ fun shortcutId(name: String): Long? = name.toLongOrNull()
+ ?.takeIf { it in Int.MIN_VALUE until 0 || it in (1L shl 31) until (1L shl 32) }?.and(0xFFFFFFFFL)
+
+ private val COMPAT_PATH = Regex("""STEAM_COMPAT_DATA_PATH=(?:"([^"]*)"|'([^']*)'|(\S+))""")
+ private val COMPAT_ID = Regex("""/compatdata/(-?\d+)/*$""")
+
+ fun sharedPrefixId(launchOptions: String): Long? {
+ val path = COMPAT_PATH.find(launchOptions)?.groupValues?.drop(1)?.firstOrNull { it.isNotEmpty() } ?: return null
+ return COMPAT_ID.find(path.trim())?.groupValues?.get(1)?.let(::shortcutId)
+ }
+
+ private val GAME_FOLDER = Regex("""Z:\\\\(?:[^"\\]+\\\\)*?(?:steamapps\\\\common|Games\\\\Stores\\\\[^"\\]+)\\\\([^"\\]+)""")
+
+ fun gameFolderHint(prefix: File): String? = runCatching {
+ listOf("pfx/system.reg", "pfx/user.reg").map { File(prefix, it) }.filter { it.isFile && it.length() < 64L * 1024 * 1024 }
+ .flatMap { f -> f.useLines { lines -> lines.flatMap { GAME_FOLDER.findAll(it).map { m -> m.groupValues[1] } }.toList() } }
+ .groupingBy { it }.eachCount().maxByOrNull { it.value }?.key
+ }.getOrNull()
+
+ class Shortcut(val name: String, val launchOptions: List)
+
+ fun shortcuts(root: File): Map? = runCatching {
+ val userdata = File(root, "userdata")
+ val users = if (userdata.exists()) userdata.listFiles() ?: return null else emptyArray()
+ users.mapNotNull { File(it, "config/shortcuts.vdf").takeIf(File::isFile) }.flatMap { file ->
+ val vdf = com.droiddeck.launcher.frontend.SteamAppInfo.readMap(java.nio.ByteBuffer.wrap(file.readBytes()).order(java.nio.ByteOrder.LITTLE_ENDIAN), null)
+ (vdf["shortcuts"] as? Map<*, *>)?.values?.filterIsInstance