mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f80be06061 | ||
|
|
66c74fdac2 | ||
|
|
63859fa776 | ||
|
|
fb2a1445b1 | ||
|
|
1bb03d3c74 | ||
|
|
d662dca21c | ||
|
|
ce5cd4feae | ||
|
|
0178661374 | ||
|
|
e72b41e2e4 | ||
|
|
a051cd5fa6 | ||
|
|
788920ff89 |
No files matched your search
@@ -34,8 +34,26 @@ jobs:
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
path: out/debs/
|
||||
scrcpy-server:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
- run: |
|
||||
sdkmanager 'platforms;android-36' 'build-tools;35.0.0'
|
||||
tools/ubuntu/build-scrcpy-server.sh out/scrcpy-server.jar
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: droiddeck-scrcpy-server
|
||||
path: out/scrcpy-server.jar
|
||||
rootfs:
|
||||
needs: debs
|
||||
needs: [debs, scrcpy-server]
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
@@ -46,6 +64,10 @@ jobs:
|
||||
with:
|
||||
name: ubuntu-runtime-debs
|
||||
path: out/debs
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: droiddeck-scrcpy-server
|
||||
path: out/server
|
||||
- uses: actions/create-github-app-token@v2
|
||||
id: components-token
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
@@ -68,7 +90,7 @@ jobs:
|
||||
set -euo pipefail
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq zstd gpgv ubuntu-keyring >/dev/null
|
||||
tag='${{ inputs.tag }}'
|
||||
tools/ubuntu/build.sh out/debs out "${tag:-ubuntu-dev}"
|
||||
tools/ubuntu/build.sh out/debs out "${tag:-ubuntu-dev}" out/server/scrcpy-server.jar
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ubuntu-runtime
|
||||
|
||||
@@ -1329,6 +1329,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
setTheme(R.style.AppTheme)
|
||||
super.onCreate(savedInstanceState)
|
||||
drivers.restartBlocked = ::runtimeChangesBlocked
|
||||
drivers.loadTpUbwcMode()
|
||||
|
||||
@@ -879,6 +879,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var runtimeRemovalBlocked = false
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
setTheme(R.style.SessionTheme)
|
||||
super.onCreate(savedInstanceState)
|
||||
com.droiddeck.launcher.session.xr.XrPanels.setMenuHost(this)
|
||||
AgentGuest.readyListener = agentReadyListener
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ActivityInfo
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.LinearGradient
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import android.os.Build
|
||||
import android.text.TextPaint
|
||||
import android.text.TextUtils
|
||||
import android.util.AtomicFile
|
||||
import android.util.Log
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
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 TAG = "AndroidSteamApps"
|
||||
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)
|
||||
|
||||
private data class Artwork(val slot: String, val width: Int, val height: Int, val iconSize: Float = 0f)
|
||||
|
||||
private val artwork = listOf(
|
||||
Artwork("p", 600, 900, 236f),
|
||||
Artwork("header", 460, 215, 104f),
|
||||
Artwork("hero", 1920, 620),
|
||||
)
|
||||
|
||||
private fun iconHue(icon: Bitmap): Float {
|
||||
val bins = FloatArray(12)
|
||||
val hsv = FloatArray(3)
|
||||
for (y in 8 until icon.height step 16) for (x in 8 until icon.width step 16) {
|
||||
val pixel = icon.getPixel(x, y)
|
||||
if (Color.alpha(pixel) < 128) continue
|
||||
Color.colorToHSV(pixel, hsv)
|
||||
if (hsv[1] >= 0.25f && hsv[2] >= 0.3f) {
|
||||
bins[(hsv[0] / 30f).toInt()] += hsv[1] * hsv[1] * hsv[2]
|
||||
}
|
||||
}
|
||||
val strongest = bins.indices.maxByOrNull { bins[it] } ?: return 210f
|
||||
return if (bins[strongest] == 0f) 210f else strongest * 30f + 15f
|
||||
}
|
||||
|
||||
private fun renderArtwork(canvas: Canvas, slot: Artwork, icon: Bitmap, hue: Float, label: String) {
|
||||
val w = slot.width.toFloat()
|
||||
val h = slot.height.toFloat()
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
paint.shader = LinearGradient(0f, h, w, 0f, 0xff111721.toInt(),
|
||||
Color.HSVToColor(floatArrayOf((hue + 335f) % 360f, 0.45f, 0.26f)), Shader.TileMode.CLAMP)
|
||||
canvas.drawPaint(paint)
|
||||
val glow = Color.HSVToColor(floatArrayOf(hue, 0.65f, 0.53f))
|
||||
val wide = w > h
|
||||
paint.shader = RadialGradient(if (wide) w * 0.83f else w * 0.49f, h * 0.36f,
|
||||
if (wide) w * 0.58f else h * 0.62f, glow, glow and 0x00ffffff, Shader.TileMode.CLAMP)
|
||||
canvas.drawPaint(paint)
|
||||
if (slot.iconSize == 0f) return
|
||||
|
||||
paint.shader = null
|
||||
val cx = if (wide) w * 0.19f else w * 0.5f
|
||||
val cy = if (wide) h * 0.5f else h * 0.42f
|
||||
val radius = slot.iconSize * 0.5f
|
||||
canvas.drawBitmap(icon, null, RectF(cx - radius, cy - radius, cx + radius, cy + radius), paint)
|
||||
|
||||
val title = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.WHITE
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
textSize = if (wide) 30f else 46f
|
||||
textAlign = if (wide) Paint.Align.LEFT else Paint.Align.CENTER
|
||||
}
|
||||
val titleWidth = w * if (wide) 0.60f else 0.82f
|
||||
val text = TextUtils.ellipsize(label, title, titleWidth, TextUtils.TruncateAt.END).toString()
|
||||
val baseline = if (wide) cy - (title.ascent() + title.descent()) / 2f else h * 0.66f
|
||||
canvas.drawText(text, if (wide) w * 0.35f else w * 0.5f, baseline, title)
|
||||
}
|
||||
|
||||
private fun savePng(file: File, bitmap: Bitmap) {
|
||||
val atomic = AtomicFile(file)
|
||||
val out = atomic.startWrite()
|
||||
try {
|
||||
check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out))
|
||||
atomic.finishWrite(out)
|
||||
} catch (e: Exception) {
|
||||
atomic.failWrite(out)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun exportArtwork(context: Context, id: Long, activity: ActivityInfo, label: String): JSONObject {
|
||||
val pm = context.packageManager
|
||||
val dir = File(context.filesDir, "session/android-steam-art/$id").apply { mkdirs() }
|
||||
val iconFile = File(dir, "icon.png")
|
||||
val covers = artwork.associateWith { File(dir, "${it.slot}.png") }
|
||||
val art = JSONObject().put("icon", iconFile.absolutePath)
|
||||
covers.forEach { (slot, file) -> art.put(slot.slot, file.absolutePath) }
|
||||
val stamp = File(dir, "version")
|
||||
val version = "2:${pm.getPackageInfo(activity.packageName, 0).lastUpdateTime}:$label"
|
||||
if (stamp.isFile && stamp.readText() == version && iconFile.isFile && covers.values.all(File::isFile)) return art
|
||||
|
||||
val icon = activity.loadIcon(pm).toBitmap(384, 384, Bitmap.Config.ARGB_8888)
|
||||
savePng(iconFile, icon)
|
||||
val hue = iconHue(icon)
|
||||
for ((slot, file) in covers) {
|
||||
val bitmap = Bitmap.createBitmap(slot.width, slot.height, Bitmap.Config.ARGB_8888)
|
||||
try {
|
||||
renderArtwork(Canvas(bitmap), slot, icon, hue, label)
|
||||
savePng(file, bitmap)
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
stamp.writeText(version)
|
||||
return art
|
||||
}
|
||||
|
||||
fun sessionEnvironment(context: Context, sessionDir: File): List<String> {
|
||||
if (Build.VERSION.SDK_INT < MIN_ANDROID) return emptyList()
|
||||
val packages = prefs(context).all.keys.sorted()
|
||||
val apps = JSONArray()
|
||||
val appIds = mutableListOf<Long>()
|
||||
for (pkg in packages) {
|
||||
if (!supports(pkg)) continue
|
||||
val pm = context.packageManager
|
||||
val launch = pm.getLaunchIntentForPackage(pkg) ?: continue
|
||||
val component = launch.component ?: continue
|
||||
val activity = runCatching { pm.getActivityInfo(component, 0) }.getOrNull()
|
||||
val label = runCatching { activity?.loadLabel(pm)?.toString() }.getOrNull().orEmpty().ifBlank { pkg }
|
||||
val id = CRC32().apply { update("droiddeck-android-app:$pkg".toByteArray()) }.value or 0x80000000L
|
||||
appIds.add(id)
|
||||
val entry = JSONObject().put("name", label).put("appid", id)
|
||||
.put("exe", LAUNCHER).put("dir", "/usr/local/bin").put("launch", pkg).put("native", true)
|
||||
if (activity != null) runCatching {
|
||||
entry.put("art", exportArtwork(context, id, activity, label))
|
||||
}.onFailure { Log.w(TAG, "Steam artwork for $pkg", it) }
|
||||
apps.put(entry)
|
||||
}
|
||||
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}",
|
||||
"DD_ANDROID_APP_IDS=${appIds.joinToString(" ")}")
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
|
||||
@@ -1591,6 +1591,10 @@
|
||||
<string name="apps_add_to_folder">Add to folder</string>
|
||||
<string name="apps_new_folder">New folder</string>
|
||||
<string name="apps_remove_from_folder">Remove from folder</string>
|
||||
<string name="apps_add_to_steam">Add to Steam</string>
|
||||
<string name="apps_remove_from_steam">Remove from Steam</string>
|
||||
<string name="apps_steam_restart">Restart Steam in DroidDeck to apply this change.</string>
|
||||
<string name="apps_steam_pairing_required">Pair Wireless debugging in DroidDeck Settings → Diagnostics, then restart Steam.</string>
|
||||
<string name="apps_app_info">App info</string>
|
||||
<string name="apps_uninstall">Uninstall</string>
|
||||
<string name="apps_folder_rename">Rename</string>
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Android apps in Steam
|
||||
|
||||
On Android 15 or newer, open DroidDeck’s **Apps** tab. If it’s hidden, show it using **Arrange tabs**. Then 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 gestures and gamepad input. Android’s system Back stays with the handheld display, so it can open DroidDeck’s menu. Apps with controller support see an Xbox 360 pad. The app plays sound through Android, so use the handheld's media volume.
|
||||
|
||||
- Exiting the Android app returns you to Steam. You can also use **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.
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
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
|
||||
export SCRCPY_SERVER_PATH=/usr/share/droiddeck/scrcpy-server.jar
|
||||
command -v scrcpy >/dev/null && command -v adb >/dev/null && [ -r "$SCRCPY_SERVER_PATH" ] ||
|
||||
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."
|
||||
output=
|
||||
cleanup() {
|
||||
adb kill-server 9>&- >/dev/null 2>&1 || true
|
||||
[ -z "$output" ] || rm -f "$output"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 0' INT TERM HUP
|
||||
connected() {
|
||||
timeout 8 adb connect "$serial" 9>&- >/dev/null 2>&1 || true
|
||||
[ "$(timeout 3 adb -s "$serial" get-state 9>&- 2>/dev/null || true)" = device ]
|
||||
}
|
||||
connected || connected ||
|
||||
fail "Android is disconnected. Turn on Wireless debugging, then restart Steam."
|
||||
|
||||
output=$(mktemp)
|
||||
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 --no-mouse-hover \
|
||||
--mouse-bind=----:---- --gamepad=uhid --no-audio --max-fps=60 9>&- 2>&1 | tee "$output" ||
|
||||
grep -Fq '[server] INFO: DroidDeck Android shortcut ended' "$output" ||
|
||||
fail "The Android app window closed unexpectedly. Try launching it again."
|
||||
@@ -100,6 +100,31 @@ def tools(root):
|
||||
return found
|
||||
|
||||
|
||||
def startable(root, available):
|
||||
c = compat()
|
||||
sources = dict(c["OWN_TOOLS"])
|
||||
return {name: tool for name, tool in available.items()
|
||||
if name not in sources or c["find_source"](root, sources[name], runnable=True)}
|
||||
|
||||
|
||||
def missing_proton(root):
|
||||
c = compat()
|
||||
for library in c["libraries"](root):
|
||||
text = read_text(os.path.join(library, "steamapps", "appmanifest_%s.acf" % c["PROTON_ARM64_APPID"]))
|
||||
if text is None:
|
||||
continue
|
||||
tokens = c["tokenize"](text)
|
||||
sizes = tuple(c["manifest_number"](tokens, key) // 2 ** 20 for key in ("BytesDownloaded", "BytesToDownload", "BytesToStage"))
|
||||
try:
|
||||
st = os.statvfs(library)
|
||||
free = "%d MB" % (st.f_bavail * st.f_frsize // 2 ** 20)
|
||||
except OSError:
|
||||
free = "unknown"
|
||||
return ("%s has not finished downloading in Steam (%d of %d MB downloaded, %d MB to unpack, %s free in %s); "
|
||||
"keep Steam open until it finishes" % ((c["SOURCES"][0],) + sizes + (free, library)))
|
||||
return "no Proton is installed yet; open Steam and keep it open until it has downloaded %s" % c["SOURCES"][0]
|
||||
|
||||
|
||||
def state_default():
|
||||
try:
|
||||
with open(STATE, encoding="utf-8") as f:
|
||||
@@ -130,6 +155,8 @@ def choose_tool(appid, current, available):
|
||||
for name in (default, c["TOOL"], c["TOOL_11"]):
|
||||
if name in available:
|
||||
return name, "the default ARM64 Proton"
|
||||
if newest:
|
||||
return newest, "the newest DroidDeck-Proton"
|
||||
return (sorted(available)[0], "the only one installed") if available else (None, None)
|
||||
|
||||
|
||||
@@ -515,10 +542,10 @@ def main(argv):
|
||||
target = fixed(program, root, prefix, compatdata)
|
||||
else:
|
||||
target = locate(program, root)
|
||||
available = tools(root)
|
||||
available = startable(root, tools(root))
|
||||
name, why = choose_tool(target.appid, mapping(root), available)
|
||||
if name is None:
|
||||
say("no Proton is installed yet; open Steam once and it is downloaded for you")
|
||||
say(missing_proton(root))
|
||||
return 69
|
||||
folder, command = available[name]
|
||||
os.makedirs(target.compatdata, exist_ok=True)
|
||||
|
||||
@@ -1359,6 +1359,12 @@ case $mode in
|
||||
&& echo "== scaling: applied the client's saved scaling filter $filter"
|
||||
return 0
|
||||
}
|
||||
android_touch_mode() {
|
||||
[ -n "$app" ] || return 0
|
||||
case " ${DD_ANDROID_APP_IDS:-} " in
|
||||
*" $app "*) xprop -root -f STEAM_TOUCH_CLICK_MODE 32c -set STEAM_TOUCH_CLICK_MODE 4 ;;
|
||||
esac
|
||||
}
|
||||
tmode= app= prev=
|
||||
while read -r line; do
|
||||
case $line in
|
||||
@@ -1367,12 +1373,14 @@ case $mode in
|
||||
[ "$pv" = "$tmode" ] && continue
|
||||
tmode=$pv
|
||||
echo "== touch mode: $tmode (focused app ${app:-?}) at $(date +%T)"
|
||||
[ "$tmode" = 4 ] || android_touch_mode
|
||||
;;
|
||||
GAMESCOPE_FOCUSED_APP*)
|
||||
prop_value "$line" none
|
||||
if [ "$pv" != "$app" ]; then
|
||||
app=$pv
|
||||
echo "== focused app: $app (touch mode ${tmode:-unset}) at $(date +%T)"
|
||||
[ "$tmode" = 4 ] || android_touch_mode
|
||||
if [ -n "${DD_LAUNCH_DIR:-}" ]; then
|
||||
printf '%s\n' "$app" > "$DD_LAUNCH_DIR/steam-focused-app.tmp" && mv -f "$DD_LAUNCH_DIR/steam-focused-app.tmp" "$DD_LAUNCH_DIR/steam-focused-app"
|
||||
fi
|
||||
|
||||
@@ -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"):
|
||||
|
||||
@@ -1104,14 +1104,19 @@ def app_manifest(steam_root, app):
|
||||
return None
|
||||
|
||||
|
||||
def manifest_flags(tokens):
|
||||
def manifest_number(tokens, key):
|
||||
quoted = '"%s"' % key.lower()
|
||||
for i in range(len(tokens) - 1):
|
||||
if tokens[i].lower() == '"stateflags"':
|
||||
if tokens[i].lower() == quoted:
|
||||
value = tokens[i + 1].strip('"')
|
||||
return int(value) if value.isdigit() else 0
|
||||
return 0
|
||||
|
||||
|
||||
def manifest_flags(tokens):
|
||||
return manifest_number(tokens, "StateFlags")
|
||||
|
||||
|
||||
def installed_manifest(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
|
||||
@@ -106,6 +106,8 @@ class ProtonRunOptionsTest(Temp):
|
||||
self.write("Steam/compatibilitytools.d/droiddeck-proton-arm64/toolmanifest.vdf",
|
||||
'"manifest"\n{\n "commandline" "/droiddeck-proton %verb%"\n}\n')
|
||||
self.write("Steam/compatibilitytools.d/droiddeck-proton-arm64/droiddeck-proton", b"#!/bin/sh\n", 0o755)
|
||||
self.write("Steam/steamapps/common/Proton Experimental (ARM64)/proton", b"#!/bin/sh\n", 0o755)
|
||||
self.write("Steam/steamapps/common/Proton Experimental (ARM64)/files/bin-arm64/wine", b"#!/bin/sh\n", 0o755)
|
||||
self.entry = str(folder / "droiddeck-proton")
|
||||
patcher = mock.patch.dict(RUN, {"EXTRA_LIBRARIES": (), "SYSTEM_TOOLS": (), "STATE": str(self.tmp / "state.json"),
|
||||
"say": lambda message: None})
|
||||
|
||||
@@ -698,7 +698,72 @@ class ProtonRunTest(Temp):
|
||||
self.assertIsNone(OPEN["game_folder"](str(program)))
|
||||
self.assertEqual(ran, [[OPEN["STEAM_LAUNCH"], "desktop", "413150"]])
|
||||
|
||||
def depot(self, name="Proton 11.0 (ARM64)"):
|
||||
self.write("Steam/steamapps/common/%s/proton" % name, b"#!/bin/sh\n", 0o755)
|
||||
self.write("Steam/steamapps/common/%s/files/bin-arm64/wine" % name, b"#!/bin/sh\n", 0o755)
|
||||
|
||||
def own_build(self, version):
|
||||
folder = "compatibilitytools.d/DroidDeck-Proton %s" % version
|
||||
self.write("Steam/%s/compatibilitytool.vdf" % folder, TOOL_VDF % ("DroidDeck-Proton-" + version, version, "windows"))
|
||||
self.write("Steam/%s/toolmanifest.vdf" % folder, '"manifest"\n{\n "commandline" "/proton %verb%"\n}\n')
|
||||
self.write("Steam/%s/proton" % folder, b"#!/bin/sh\n", 0o755)
|
||||
return "DroidDeck-Proton-" + version
|
||||
|
||||
def test_a_wrapper_without_its_depot_gives_way_to_an_installed_proton(self):
|
||||
newest = [self.own_build(v) for v in ("11-12.2", "11-12.3")][-1]
|
||||
available = RUN["startable"](str(self.root), RUN["tools"](str(self.root)))
|
||||
self.assertEqual(sorted(available), ["DroidDeck-Proton-11-12.2", newest])
|
||||
current = RUN["mapping"](str(self.root))
|
||||
self.assertEqual(RUN["choose_tool"]("70", current, available), (newest, "the newest DroidDeck-Proton"))
|
||||
self.assertEqual(RUN["choose_tool"]("413150", current, available), (newest, "the newest DroidDeck-Proton"))
|
||||
self.assertEqual(RUN["choose_tool"]("70", {"0": "DroidDeck-Proton-11-12.2"}, available),
|
||||
("DroidDeck-Proton-11-12.2", "Steam's default"))
|
||||
|
||||
def test_a_wrapper_with_its_depot_is_still_steams_choice(self):
|
||||
self.own_build("11-12.3")
|
||||
self.depot()
|
||||
available = RUN["startable"](str(self.root), RUN["tools"](str(self.root)))
|
||||
self.assertIn("droiddeck-proton-arm64", available)
|
||||
self.assertIn("droiddeck-proton-11-arm64", available)
|
||||
current = RUN["mapping"](str(self.root))
|
||||
self.assertEqual(RUN["choose_tool"]("70", current, available), ("droiddeck-proton-arm64", "Steam's default"))
|
||||
self.assertEqual(RUN["choose_tool"]("413150", current, available), ("droiddeck-proton-11-arm64", "Steam's choice for this title"))
|
||||
|
||||
def test_each_wrapper_needs_its_own_depot(self):
|
||||
self.depot("Proton Experimental (ARM64)")
|
||||
available = RUN["startable"](str(self.root), RUN["tools"](str(self.root)))
|
||||
self.assertEqual(sorted(available), ["droiddeck-proton-arm64"])
|
||||
|
||||
def test_an_unfinished_depot_is_not_started(self):
|
||||
self.write("Steam/steamapps/common/Proton 11.0 (ARM64)/files/bin-arm64/wine", b"#!/bin/sh\n", 0o755)
|
||||
self.assertEqual(RUN["startable"](str(self.root), RUN["tools"](str(self.root))), {})
|
||||
|
||||
def test_with_no_runnable_proton_the_launch_stops_with_the_download_state(self):
|
||||
program = self.game("413150", "Stardew Valley", "Stardew Valley.exe")
|
||||
self.write("Steam/steamapps/appmanifest_4427310.acf", '"AppState"\n{\n "appid" "4427310"\n'
|
||||
' "BytesToDownload" "288773824"\n "BytesDownloaded" "37081024"\n "BytesToStage" "1370855407"\n}\n')
|
||||
said = []
|
||||
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.root)}), \
|
||||
mock.patch.object(RUN["os"], "execve") as execve, mock.patch.dict(RUN, {"say": said.append}):
|
||||
code = RUN["main"]([str(program)])
|
||||
self.assertEqual(code, 69)
|
||||
execve.assert_not_called()
|
||||
self.assertRegex(said[-1], r"^Proton Experimental \(ARM64\) has not finished downloading in Steam "
|
||||
r"\(35 of 275 MB downloaded, 1307 MB to unpack, \d+ MB free in ")
|
||||
self.assertFalse((self.root / "steamapps/compatdata/413150").exists())
|
||||
|
||||
def test_with_no_proton_at_all_the_launch_says_what_to_download(self):
|
||||
program = self.game("413150", "Stardew Valley", "Stardew Valley.exe")
|
||||
said = []
|
||||
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.root)}), \
|
||||
mock.patch.object(RUN["os"], "execve") as execve, mock.patch.dict(RUN, {"say": said.append}):
|
||||
self.assertEqual(RUN["main"]([str(program)]), 69)
|
||||
execve.assert_not_called()
|
||||
self.assertEqual(said[-1], "no Proton is installed yet; open Steam and keep it open until it has downloaded "
|
||||
"Proton Experimental (ARM64)")
|
||||
|
||||
def test_the_tool_is_started_as_steam_starts_it(self):
|
||||
self.depot()
|
||||
program = self.game("413150", "Stardew Valley", "Stardew Valley.exe")
|
||||
calls = []
|
||||
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.root)}), \
|
||||
@@ -713,6 +778,7 @@ class ProtonRunTest(Temp):
|
||||
self.assertTrue((self.root / "steamapps/compatdata/413150").is_dir())
|
||||
|
||||
def run_main(self, argv):
|
||||
self.depot()
|
||||
calls, dirs = [], []
|
||||
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.root)}), \
|
||||
mock.patch.object(RUN["os"], "execve", lambda *a: calls.append(a)), \
|
||||
|
||||
@@ -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,30 @@ 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
|
||||
art = {}
|
||||
for slot in ('icon', 'p', 'header', 'hero'):
|
||||
image = self.root / f'{slot}.png'
|
||||
image.write_bytes(slot.encode())
|
||||
art[slot] = str(image)
|
||||
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, art=art,
|
||||
)]))
|
||||
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(entries[android_id]['icon'], art['icon'])
|
||||
for slot, suffix in (('p', 'p'), ('header', ''), ('hero', '_hero')):
|
||||
target = self.config / 'grid' / f'{android_id}{suffix}.png'
|
||||
self.assertEqual(target.read_bytes(), slot.encode())
|
||||
self.assertEqual(set(self.run_writer(game)), {APPID})
|
||||
self.assertFalse(list((self.config / 'grid').glob(f'{android_id}*.png')))
|
||||
|
||||
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%',
|
||||
|
||||
@@ -50,3 +50,5 @@ At run time:
|
||||
`.github/workflows/build-ubuntu-runtime.yml` builds it and, run with a new tag (`ubuntu-rN`),
|
||||
publishes the runtime and its desktop pack in Droid-Deck/DroidDeck-Components; `linuxfs-ubuntu.json` there names the release the
|
||||
app installs.
|
||||
|
||||
Build the scrcpy server with `tools/ubuntu/build-scrcpy-server.sh out/scrcpy-server.jar`. It requires JDK 17, Android platform 36 and build-tools 35.0.0. Pass the resulting jar as the fourth argument to `tools/ubuntu/build.sh` when building a runtime locally.
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
sdk=${ANDROID_HOME:?Android SDK required}
|
||||
out=$(realpath -m "${1:?output server jar}")
|
||||
tools=$sdk/build-tools/35.0.0
|
||||
platform=$sdk/platforms/android-36
|
||||
version=3.3.4
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
curl -fsSL --retry 3 --proto '=https' -o "$work/source.tar.gz" \
|
||||
"https://codeload.github.com/Genymobile/scrcpy/tar.gz/refs/tags/v$version"
|
||||
echo "03b72d1f71ca7783cff2995ca7cd8c67b9b75038a3cc35e443a1913e951b49dd $work/source.tar.gz" | sha256sum -c -
|
||||
tar xzf "$work/source.tar.gz" -C "$work" --strip-components=1
|
||||
git -C "$work" apply "$here/patches/scrcpy-display-focus.patch"
|
||||
git -C "$work" apply "$here/patches/scrcpy-shortcut-exit.patch"
|
||||
src=$work/server/src/main
|
||||
mkdir -p "$work/generated/com/genymobile/scrcpy" "$work/classes" "$(dirname "$out")"
|
||||
for file in "$src"/aidl/android/*/*.aidl; do
|
||||
"${DROIDDECK_AIDL:-$tools/aidl}" -I"$src/aidl" -p"$platform/framework.aidl" -o"$work/generated" "$file"
|
||||
done
|
||||
cat > "$work/generated/com/genymobile/scrcpy/BuildConfig.java" <<JAVA
|
||||
package com.genymobile.scrcpy;
|
||||
public final class BuildConfig {
|
||||
public static final boolean DEBUG = false;
|
||||
public static final String VERSION_NAME = "$version";
|
||||
}
|
||||
JAVA
|
||||
find "$src/java" "$work/generated" -name '*.java' > "$work/sources"
|
||||
javac --release 8 -classpath "$platform/android.jar" -d "$work/classes" @"$work/sources"
|
||||
jar cf "$work/server.jar" -C "$work/classes" .
|
||||
java -cp "$tools/lib/d8.jar" com.android.tools.r8.D8 --release --min-api 21 \
|
||||
--lib "$platform/android.jar" --output "$out" "$work/server.jar"
|
||||
@@ -4,6 +4,7 @@ here=$(cd "$(dirname "$0")" && pwd)
|
||||
debs=$(realpath "${1:?directory with the DroidDeck-built .deb files}")
|
||||
out=$(realpath -m "${2:?out dir}")
|
||||
runtime_id=${3:?runtime id, e.g. ubuntu-r1}
|
||||
scrcpy_server=$(realpath "${4:?patched scrcpy server jar}")
|
||||
[ "$(uname -m)" = aarch64 ] || { echo 'the Ubuntu runtime needs a native arm64 runner' >&2; exit 1; }
|
||||
source "$here/base.env"
|
||||
fetch() { curl -fsSL --proto '=https' --proto-redir '=https' --retry 6 --retry-delay 5 --retry-all-errors -o "$1" "$2"; }
|
||||
@@ -47,6 +48,11 @@ unseal() {
|
||||
}
|
||||
|
||||
stage runtime
|
||||
case $(sudo chroot "$root" dpkg-query -W -f='${Version}' scrcpy) in
|
||||
3.3.4-*) ;;
|
||||
*) echo "The scrcpy client must match the patched 3.3.4 server" >&2; exit 1 ;;
|
||||
esac
|
||||
sudo install -D -m 644 "$scrcpy_server" "$root/usr/share/droiddeck/scrcpy-server.jar"
|
||||
seal
|
||||
sudo mv "$root/tmp/droiddeck" "$work/src-keep"
|
||||
sudo chroot "$root" dpkg-query -W -f '${Package} ${Version}\n' > "$out/$runtime_id.packages.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
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
--- a/server/src/main/java/com/genymobile/scrcpy/video/NewDisplayCapture.java
|
||||
+++ b/server/src/main/java/com/genymobile/scrcpy/video/NewDisplayCapture.java
|
||||
@@ -38,6 +38,8 @@
|
||||
private static final int VIRTUAL_DISPLAY_FLAG_OWN_FOCUS = 1 << 14;
|
||||
private static final int VIRTUAL_DISPLAY_FLAG_DEVICE_DISPLAY_GROUP = 1 << 15;
|
||||
|
||||
+ private static final int VIRTUAL_DISPLAY_FLAG_STEAL_TOP_FOCUS_DISABLED = 1 << 16;
|
||||
+
|
||||
private final VirtualDisplayListener vdListener;
|
||||
private final NewDisplay newDisplay;
|
||||
|
||||
@@ -187,7 +189,8 @@
|
||||
| VIRTUAL_DISPLAY_FLAG_TOUCH_FEEDBACK_DISABLED;
|
||||
if (Build.VERSION.SDK_INT >= AndroidVersions.API_34_ANDROID_14) {
|
||||
flags |= VIRTUAL_DISPLAY_FLAG_OWN_FOCUS
|
||||
- | VIRTUAL_DISPLAY_FLAG_DEVICE_DISPLAY_GROUP;
|
||||
+ | VIRTUAL_DISPLAY_FLAG_DEVICE_DISPLAY_GROUP
|
||||
+ | VIRTUAL_DISPLAY_FLAG_STEAL_TOP_FOCUS_DISABLED;
|
||||
}
|
||||
}
|
||||
virtualDisplay = ServiceManager.getDisplayManager()
|
||||
@@ -0,0 +1,95 @@
|
||||
--- a/server/src/main/java/com/genymobile/scrcpy/control/Controller.java
|
||||
+++ b/server/src/main/java/com/genymobile/scrcpy/control/Controller.java
|
||||
@@ -691,6 +691,9 @@
|
||||
|
||||
Ln.i("Starting app \"" + app.getName() + "\" [" + app.getPackageName() + "] on display " + startAppDisplayId + "...");
|
||||
Device.startApp(app.getPackageName(), startAppDisplayId, forceStopBeforeStart);
|
||||
+ if (displayId == Device.DISPLAY_ID_NONE && Build.VERSION.SDK_INT >= AndroidVersions.API_35_ANDROID_15) {
|
||||
+ AndroidShortcutMonitor.start(startAppDisplayId);
|
||||
+ }
|
||||
}
|
||||
|
||||
private int getStartAppDisplayId() {
|
||||
--- /dev/null
|
||||
+++ b/server/src/main/java/com/genymobile/scrcpy/control/AndroidShortcutMonitor.java
|
||||
@@ -0,0 +1,80 @@
|
||||
+package com.genymobile.scrcpy.control;
|
||||
+
|
||||
+import com.genymobile.scrcpy.device.Device;
|
||||
+import com.genymobile.scrcpy.util.Ln;
|
||||
+
|
||||
+import android.os.Handler;
|
||||
+import android.os.Looper;
|
||||
+
|
||||
+import java.lang.reflect.Field;
|
||||
+import java.lang.reflect.Method;
|
||||
+import java.util.List;
|
||||
+
|
||||
+final class AndroidShortcutMonitor implements Runnable {
|
||||
+ private static final int ACTIVITY_TYPE_HOME = 2;
|
||||
+ private static final long POLL_MS = 1000;
|
||||
+
|
||||
+ private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
+ private final int displayId;
|
||||
+ private final Object manager;
|
||||
+ private final Method getTasks;
|
||||
+ private final Field topActivity;
|
||||
+ private final Field activityType;
|
||||
+ private final Field visible;
|
||||
+ private boolean opened;
|
||||
+ private int emptyPolls;
|
||||
+
|
||||
+ static void start(int displayId) {
|
||||
+ try {
|
||||
+ AndroidShortcutMonitor monitor = new AndroidShortcutMonitor(displayId);
|
||||
+ monitor.handler.post(monitor);
|
||||
+ } catch (ReflectiveOperationException e) {
|
||||
+ Ln.w("Could not watch Android shortcut tasks", e);
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ private AndroidShortcutMonitor(int displayId) throws ReflectiveOperationException {
|
||||
+ this.displayId = displayId;
|
||||
+ Class<?> taskManager = Class.forName("android.app.ActivityTaskManager");
|
||||
+ Class<?> service = Class.forName("android.app.IActivityTaskManager");
|
||||
+ Class<?> task = Class.forName("android.app.TaskInfo");
|
||||
+ manager = taskManager.getMethod("getService").invoke(null);
|
||||
+ getTasks = service.getMethod("getAllRootTaskInfosOnDisplay", int.class);
|
||||
+ topActivity = task.getField("topActivity");
|
||||
+ activityType = task.getField("topActivityType");
|
||||
+ visible = task.getField("isVisible");
|
||||
+ }
|
||||
+
|
||||
+ private boolean hasVisibleApp() throws ReflectiveOperationException {
|
||||
+ for (Object task : (List<?>) getTasks.invoke(manager, displayId)) {
|
||||
+ if (visible.getBoolean(task) && topActivity.get(task) != null && activityType.getInt(task) != ACTIVITY_TYPE_HOME) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ }
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ @Override
|
||||
+ public void run() {
|
||||
+ try {
|
||||
+ if (!Device.isScreenOn(0)) {
|
||||
+ emptyPolls = 0;
|
||||
+ } else if (hasVisibleApp()) {
|
||||
+ opened = true;
|
||||
+ emptyPolls = 0;
|
||||
+ } else if (++emptyPolls >= (opened ? 3 : 15)) {
|
||||
+ if (opened) {
|
||||
+ Ln.i("DroidDeck Android shortcut ended");
|
||||
+ } else {
|
||||
+ Ln.w("Android shortcut did not open a visible activity");
|
||||
+ }
|
||||
+ handler.getLooper().quitSafely();
|
||||
+ return;
|
||||
+ }
|
||||
+ } catch (ReflectiveOperationException e) {
|
||||
+ Ln.w("Could not watch Android shortcut tasks", e);
|
||||
+ return;
|
||||
+ }
|
||||
+ handler.postDelayed(this, POLL_MS);
|
||||
+ }
|
||||
+}
|
||||
Reference in new issue
Block a user