diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AndroidSteamApps.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AndroidSteamApps.kt new file mode 100644 index 0000000000..2009731e9c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AndroidSteamApps.kt @@ -0,0 +1,59 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context +import android.os.Build +import com.droiddeck.launcher.agent.AgentAdb +import com.droiddeck.launcher.core.WirelessAdbFix +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.util.zip.CRC32 + +internal object AndroidSteamApps { + const val MIN_ANDROID = 35 + private const val LAUNCHER = "/usr/local/bin/droiddeck-android-app" + private val packagePattern = Regex("[a-zA-Z][a-zA-Z0-9_]*(\\.[a-zA-Z][a-zA-Z0-9_]*)+") + + private fun prefs(context: Context) = + context.getSharedPreferences("android-steam-apps", Context.MODE_PRIVATE) + + fun contains(context: Context, pkg: String): Boolean = prefs(context).contains(pkg) + + fun set(context: Context, pkg: String, enabled: Boolean) { + require(packagePattern.matches(pkg)) + val editor = prefs(context).edit() + if (enabled) editor.putBoolean(pkg, true) else editor.remove(pkg) + editor.apply() + } + + fun supports(pkg: String): Boolean = Build.VERSION.SDK_INT >= MIN_ANDROID && packagePattern.matches(pkg) + + fun sessionEnvironment(context: Context, sessionDir: File): List { + if (Build.VERSION.SDK_INT < MIN_ANDROID) return emptyList() + val packages = prefs(context).all.keys.sorted() + val apps = JSONArray() + for (pkg in packages) { + if (!supports(pkg)) continue + val pm = context.packageManager + val launch = pm.getLaunchIntentForPackage(pkg) ?: continue + val component = launch.component ?: continue + val label = runCatching { + pm.getActivityInfo(component, 0).loadLabel(pm).toString() + }.getOrDefault(pkg).ifBlank { pkg } + val id = CRC32().apply { update("droiddeck-android-app:$pkg".toByteArray()) }.value or 0x80000000L + apps.put(JSONObject().put("name", label).put("appid", id) + .put("exe", LAUNCHER).put("dir", "/usr/local/bin").put("launch", pkg).put("native", true)) + } + if (apps.length() == 0) return emptyList() + val listing = File(sessionDir, "android-apps.json").apply { writeText(apps.toString()) } + val env = mutableListOf("DD_ANDROID_APPS=${listing.absolutePath}") + if (WirelessAdbFix.hasSavedPairing(context)) { + val link = AgentAdb.prepare(context) + if (link.paired) { + env.add("DD_ANDROID_ADB_SERIAL=${link.serial}") + env.add("DD_ANDROID_ADB_KEY=${link.vendorKeys}") + } + } + return env + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index 81a84fcdba..dfba56ad50 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -277,9 +277,16 @@ public final class PadBridge { return lower.startsWith("uinput-") || lower.startsWith("uinput_") || lower.equals("ui-input-xiaomi"); } + private static boolean isVirtualInput(InputDevice device) { + // scrcpy's UHID pad is internal and reports the wired Xbox 360 USB identity. + return device.isVirtual() || isSystemVirtualInputName(device.getName()) + || (!device.isExternal() && device.getVendorId() == 0x045e + && device.getProductId() == 0x028e && "Microsoft X-Box 360 Pad".equals(device.getName())); + } + public static boolean isFromController(InputDevice device) { if (device == null) return false; - if (device.isVirtual() || isSystemVirtualInputName(device.getName())) return false; + if (isVirtualInput(device)) return false; int sources = device.getSources(); if ((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) return true; if ((sources & InputDevice.SOURCE_JOYSTICK) != InputDevice.SOURCE_JOYSTICK) return false; @@ -299,7 +306,7 @@ public final class PadBridge { } static boolean isControllerKeyEvent(KeyEvent event, InputDevice device) { - if (device == null || device.isVirtual() || isSystemVirtualInputName(device.getName())) return false; + if (device == null || isVirtualInput(device)) return false; if (KeyEvent.isGamepadButton(event.getKeyCode())) { return device.supportsSource(InputDevice.SOURCE_GAMEPAD) || device.supportsSource(InputDevice.SOURCE_JOYSTICK); @@ -327,8 +334,7 @@ public final class PadBridge { } static boolean isControllerMotionEvent(MotionEvent event, InputDevice device) { - return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual() - && !isSystemVirtualInputName(device.getName()) + return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !isVirtualInput(device) && (device.supportsSource(InputDevice.SOURCE_GAMEPAD) || device.supportsSource(InputDevice.SOURCE_JOYSTICK)); } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index dc708cb51d..61d44b9bc9 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -191,6 +191,7 @@ object SessionFiles { "usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap", "usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim", "usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts", + "usr/local/bin/droiddeck-android-app" to "usr/local/bin/droiddeck-android-app", "usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox", "usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch", "usr/local/bin/droiddeck-gog-maintenance" to "usr/local/bin/droiddeck-gog-maintenance", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index fb6d3503f8..a8588fd390 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -714,6 +714,9 @@ class SessionService : Service() { SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) } } guest.add("DD_ADDED_GAMES=" + listing.path) + if (steamHere) runCatching { + guest.addAll(com.droiddeck.launcher.frontend.AndroidSteamApps.sessionEnvironment(this, sessionDir)) + }.onFailure { Log.w(TAG, "Android Steam shortcuts", it) } if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1") if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1") } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt index 4d4ac7adc0..cc423357d9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt @@ -798,6 +798,17 @@ private fun AppMenu( onDismiss() HomeIcons.clear(ctx, app.key) } + val steamApps = com.droiddeck.launcher.frontend.AndroidSteamApps + if (!app.work && steamApps.supports(app.packageName)) { + val added = steamApps.contains(ctx, app.packageName) + MenuItem(stringResource(if (added) R.string.apps_remove_from_steam else R.string.apps_add_to_steam), checked = false) { + onDismiss() + steamApps.set(ctx, app.packageName, !added) + val message = if (!added && !com.droiddeck.launcher.core.WirelessAdbFix.hasSavedPairing(ctx)) + R.string.apps_steam_pairing_required else R.string.apps_steam_restart + android.widget.Toast.makeText(ctx, message, android.widget.Toast.LENGTH_LONG).show() + } + } MenuItem(stringResource(R.string.apps_app_info), checked = false) { onDismiss() runCatching { HomeApp.openAppInfo(ctx, app) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ae5278bcf8..ca58994b74 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1590,6 +1590,10 @@ Add to folder New folder Remove from folder + Add to Steam + Remove from Steam + Restart Steam in DroidDeck to apply this change. + Pair Wireless debugging in DroidDeck Settings → Diagnostics, then restart Steam. App info Uninstall Rename diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt index 316cf90f90..6776bc914e 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt @@ -84,6 +84,18 @@ class PadBridgeRoutingTest { assertFalse(PadBridge.anyControllerConnected()) } + @Test fun scrcpyGamepadDoesNotHideControlsOrLoopBackIntoSteam() { + fun xbox(external: Boolean) = device( + InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK, InputDevice.KEYBOARD_TYPE_NONE, + name = "Microsoft X-Box 360 Pad", external = external, vendor = 0x045e, product = 0x028e, + ) + val mirrored = xbox(external = false) + assertFalse(PadBridge.anyControllerConnected()) + assertFalse(PadBridge.isControllerKeyEvent(key(mirrored, KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN))) + assertTrue(PadBridge.isFromController(xbox(external = true))) + assertTrue(PadBridge.anyControllerConnected()) + } + @Test fun homeShortcutsIgnoreHomeFromSystemKeys() { val gpio = device(InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, name = "gpio-keys") val pad = device(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC) @@ -171,9 +183,11 @@ class PadBridgeRoutingTest { private var nextId = 10 private fun device(sources: Int, type: Int, keys: IntArray = intArrayOf(KeyEvent.KEYCODE_A, KeyEvent.KEYCODE_DPAD_UP), - rangeSource: Int? = null, axis: Int = MotionEvent.AXIS_X, id: Int = nextId++, name: String = "routing fixture $id"): InputDevice { + rangeSource: Int? = null, axis: Int = MotionEvent.AXIS_X, id: Int = nextId++, name: String = "routing fixture $id", + external: Boolean = true, vendor: Int = 0, product: Int = 0): InputDevice { val builder = InputDeviceBuilder.newBuilder().setId(id).setName(name) - .setDescriptor("routing-$id").setExternal(true).setSources(sources).setKeyboardType(type) + .setDescriptor("routing-$id").setExternal(external).setVendorId(vendor).setProductId(product) + .setSources(sources).setKeyboardType(type) .setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)) if (rangeSource != null) builder.addMotionRange(axis, rangeSource, -1f, 1f, 0f, 0f, 0f) val device = builder.build() diff --git a/docs/android-apps-in-steam.md b/docs/android-apps-in-steam.md new file mode 100644 index 0000000000..c90bd5b72a --- /dev/null +++ b/docs/android-apps-in-steam.md @@ -0,0 +1,10 @@ +# Android apps in Steam + +On Android 15 or newer, set DroidDeck as your Android Home app. In DroidDeck's **Apps** tab, open an app's menu and select **Add to Steam**. Pair Wireless debugging in DroidDeck's **Settings → Diagnostics** and keep Wireless debugging enabled. Restart Steam from DroidDeck. The app appears as a non-Steam shortcut in your library. To remove it, select **Remove from Steam** in the same app menu and restart Steam. + +The app runs on a separate Android display. Steam shows that display and forwards touch and gamepad input. Apps with controller support see an Xbox 360 pad. The app plays sound through Android, so use the handheld's media volume. + +- Use the DroidDeck menu button for session controls and **Exit Game** in Steam to close the shortcut. +- To go back inside the Android app with a keyboard, press **Alt+B**. DroidDeck's Back and the session menu are separate controls. +- You can run one Android shortcut at a time. Work profile apps and apps that block screen capture or refuse secondary displays may be unavailable. +- If the shortcut reports a disconnected device after Wireless debugging has restarted, restart Steam in DroidDeck to refresh the connection. If it asks for an updated Linux runtime, install the runtime update before trying again. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-android-app b/tools/linuxfs/overlay/usr/local/bin/droiddeck-android-app new file mode 100755 index 0000000000..69aca90191 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-android-app @@ -0,0 +1,45 @@ +#!/bin/sh +set -eu + +fail() { + printf 'droiddeck-android-app: %s\n' "$1" >&2 + if [ -n "${DISPLAY:-}" ] && command -v xmessage >/dev/null; then + xmessage -center -buttons 'OK:0' -default OK "$1" || true + fi + exit 1 +} + +case "${1:-}" in + ''|*[!a-zA-Z0-9_.]*) fail "This shortcut has no valid Android app." ;; +esac +package=$1 +command -v scrcpy >/dev/null && command -v adb >/dev/null || + fail "Update the DroidDeck Linux runtime to launch Android apps." + +serial=${DD_ANDROID_ADB_SERIAL:-} +key=${DD_ANDROID_ADB_KEY:-} +case "$serial" in + 127.0.0.1:*) ;; + *) fail "Pair Wireless debugging in DroidDeck Settings → Diagnostics, then restart Steam." ;; +esac +[ -r "$key" ] || fail "Pair Wireless debugging in DroidDeck Settings → Diagnostics, then restart Steam." + +# Keep the pairing and server lifetime independent of DroidDeck's Agent ADB connection. +unset ADB_SERVER_SOCKET ANDROID_ADB_SERVER_ADDRESS ANDROID_ADB_SERVER_PORT +export ADB_VENDOR_KEYS="$key" ADB_SERVER_SOCKET=tcp:5039 +exec 9>"${XDG_RUNTIME_DIR:-/tmp}/droiddeck-android-app.lock" +flock -n 9 || fail "Close the running Android app shortcut first." +# The ADB server must not inherit the lock. +adb start-server 9>&- || fail "Could not start the Android connection." +trap 'adb kill-server 9>&- >/dev/null 2>&1 || true' EXIT +trap 'exit 0' INT TERM HUP +timeout 8 adb connect "$serial" 9>&- || true +[ "$(timeout 5 adb -s "$serial" get-state 9>&- 2>/dev/null || true)" = device ] || + fail "Android is disconnected. Turn on Wireless debugging, then restart Steam." + +export SDL_VIDEODRIVER=x11 +# Android plays audio on the handheld. Capturing it here would feed it back into Android again. +scrcpy --serial "$serial" --new-display=1280x720/240 --start-app="$package" \ + --window-title="Android app" --no-vd-system-decorations --no-clipboard-autosync \ + --mouse-bind=----:---- --gamepad=uhid --no-audio --max-fps=60 9>&- || + fail "The Android app window closed unexpectedly. Check Wireless debugging and try again." diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts index 31d679677c..0d21cfd00e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts @@ -377,6 +377,13 @@ def main(): routing = importlib.util.module_from_spec(spec) loader.exec_module(routing) games, routes = routing.route(steam_root, acct, games) + android_apps = os.environ.get("DD_ANDROID_APPS") + if android_apps: + try: + with open(android_apps, encoding="utf-8") as f: + games.extend(json.load(f)) + except (OSError, ValueError) as e: + print("droiddeck-steam-shortcuts: Android apps unavailable (%s)" % e) wanted, seen = {}, {} for game in games: if game.get("exe") and game.get("name"): diff --git a/tools/tests/test_steam_shortcuts.py b/tools/tests/test_steam_shortcuts.py index 74396e3221..cc2a38726d 100644 --- a/tools/tests/test_steam_shortcuts.py +++ b/tools/tests/test_steam_shortcuts.py @@ -46,10 +46,11 @@ class ShortcutsTest(unittest.TestCase): path = installed(GUEST + '/' + exe) return dict(name=name, exe=path, folder=GUEST, dir=path.rsplit('/', 1)[0], appid=appid, seen=seen) - def run_writer(self, *games): + def run_writer(self, *games, android_apps=None): self.listing.write_text(json.dumps(list(games))) subprocess.run(['python3', str(BIN / 'droiddeck-steam-shortcuts'), str(self.steam), str(self.listing)], - check=True, capture_output=True) + check=True, capture_output=True, + env={**os.environ, 'DD_ANDROID_APPS': str(android_apps or '')}) return self.entries() def entries(self): @@ -89,6 +90,20 @@ class ShortcutsTest(unittest.TestCase): entry, _ = shortcuts.merge(fresh, current, state, 0) return entry + def test_android_app_shortcut_is_added_and_removed_alongside_pc_games(self): + android_apps = self.root / 'android-apps.json' + android_id = APPID + 1 + android_apps.write_text(json.dumps([dict( + name='Settings', exe='/usr/local/bin/droiddeck-android-app', dir='/usr/local/bin', + appid=android_id, launch='com.android.settings', native=True, + )])) + game = self.game() + entries = self.run_writer(game, android_apps=android_apps) + self.assertEqual(set(entries), {APPID, android_id}) + self.assertEqual(entries[android_id]['LaunchOptions'], 'com.android.settings') + self.assertEqual(entries[android_id]['Exe'], '"/usr/local/bin/droiddeck-android-app"') + self.assertEqual(set(self.run_writer(game)), {APPID}) + def test_settings_changed_in_steam_survive_its_restart(self): self.run_writer(self.game()) edits = dict(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s"' % GUEST, LaunchOptions='DXVK_HUD=1 %command%', diff --git a/tools/ubuntu/packages-runtime.txt b/tools/ubuntu/packages-runtime.txt index 95269a035b..c518015e71 100644 --- a/tools/ubuntu/packages-runtime.txt +++ b/tools/ubuntu/packages-runtime.txt @@ -1,4 +1,5 @@ 7zip +adb apt base-files base-passwd @@ -222,6 +223,7 @@ python3 python3-gi python3-ibus-1.0 python3-zstandard +scrcpy sed sensible-utils strace