chore: merge main to catch up with 0.5.0

This commit is contained in:
xXJsonDeruloXx committed 2026-10-18 16:52:02 -04:00
commit 5de7af9b41
18 files changed
+496 -149

No files matched your search

+9
View File
@@ -153,6 +153,15 @@
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".ui.SecondScreenActivity"
android:exported="false"
android:excludeFromRecents="true"
android:theme="@style/SessionTheme"
android:screenOrientation="sensorLandscape"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".gpu.SteamVrRestartActivity"
android:exported="false"
@@ -12,6 +12,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableIntStateOf
import com.droiddeck.launcher.gpu.AutoDriverTrial
import com.droiddeck.launcher.gpu.AutoPicks
import com.droiddeck.launcher.gpu.DriverBundle
import com.droiddeck.launcher.gpu.DriverPairs
import com.droiddeck.launcher.gpu.GpuInfo
@@ -179,7 +180,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val lm = LinuxVulkanDriverManager(activity)
val td = TurnipDriver(activity)
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val recommended = if (QuestExperimental.isSupported()) null else DriverPairs.recommendedKey(gpu, pairs)
val recommended = if (QuestExperimental.isSupported()) null else recommendedKey(pairs)
pairRows = pairs.map { p ->
val bundle = p.bundle?.let { installedBundle(it) }
val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) }
@@ -196,6 +197,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}.sortedByDescending { it.recommended }
}
private fun recommendedKey(pairs: List<DriverPairs.DriverPair>) = DriverPairs.recommendedKey(
gpu, pairs, TurnipReleases.autoPicks(activity), AutoDriverTrial.bad(activity),
blob = AutoPicks.blobVersion(com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull()?.get("driver_version")),
)
fun chooseMode(next: String) {
pairModeOpen = next == GPU_MODE_PAIR
setMode(auto = next == GPU_MODE_AUTO, mix = next == GPU_MODE_MIX)
@@ -255,12 +261,13 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
Thread({
val problem = if (force || releasesStale()) runCatching { TurnipReleases.refresh(activity) }.exceptionOrNull()?.message else null
val holdBack = !force && com.droiddeck.launcher.frontend.AutoComponents.constrained(activity)
runCatching { com.droiddeck.launcher.gpu.VulkanInfo.query() }
ui.post {
releaseChecking = false
refreshReleaseRows()
refreshPairs()
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val key = DriverPairs.recommendedKey(gpu, pairs)
val key = recommendedKey(pairs)
val pair = pairs.firstOrNull { it.key == key }
val row = pairRows.firstOrNull { it.key == key }
when {
@@ -109,7 +109,7 @@ import com.droiddeck.launcher.ui.HudText
import com.droiddeck.launcher.ui.LoadingOverlay
import com.droiddeck.launcher.ui.SessionDrawer
import com.droiddeck.launcher.ui.SessionPausedOverlay
import com.droiddeck.launcher.ui.SecondScreenPresentation
import com.droiddeck.launcher.ui.SecondScreenWindow
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -347,7 +347,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay)
private var started = false
private lateinit var displayManager: DisplayManager
private var secondScreenPresentation: SecondScreenPresentation? = null
private var secondScreenPresentation: SecondScreenWindow? = null
private val displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
@@ -2165,7 +2165,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
var presentation = secondScreenPresentation
if (presentation?.display?.displayId != target.displayId) {
presentation?.closeControls()
presentation = SecondScreenPresentation(
presentation = SecondScreenWindow(
this, target,
sendPointer = ::moveSecondScreenPointer,
sendButton = { button, pressed ->
@@ -202,7 +202,8 @@ object DeviceReport {
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
k("Driver mode", SessionPrefs.gpuDriverMode(context) +
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)))?.let { " (recommended pair: $it)" } ?: ""))
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)), com.droiddeck.launcher.gpu.TurnipReleases.autoPicks(context),
com.droiddeck.launcher.gpu.AutoDriverTrial.bad(context))?.let { " (recommended pair: $it)" } ?: ""))
val turnip = TurnipDriver(context)
val androidChoice = SessionPrefs.androidDriver(context)
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice)
@@ -38,6 +38,7 @@ object DownloadSource {
private val CATALOGS = listOf(
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-CI/",
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/",
"https://raw.githubusercontent.com/Droid-Deck/Drivers-CI/",
)
data class Mirror(val host: String, val api: Boolean)
@@ -0,0 +1,64 @@
package com.droiddeck.launcher.gpu
import com.droiddeck.launcher.gpu.GpuInfo.Family
import org.json.JSONArray
import org.json.JSONObject
object AutoPicks {
const val URL = "https://raw.githubusercontent.com/Droid-Deck/Drivers-CI/main/auto-drivers.json"
const val SCHEMA = 1
const val NEWEST_DD_TURNIP = DriverPairs.DD_TURNIP
class Rule(
val families: Set<Family>,
val models: Set<Int> = emptySet(),
val oneUi8Gen2: Boolean? = null,
val minSdk: Int = 0,
val blobMin: Int = 0,
val blobMax: Int = Int.MAX_VALUE,
val prefer: List<String>,
) {
fun matches(gpu: GpuInfo, sdk: Int, blob: Int?): Boolean =
gpu.family in families &&
(models.isEmpty() || gpu.model in models) &&
(oneUi8Gen2 == null || gpu.oneUi8Gen2 == oneUi8Gen2) &&
sdk >= minSdk &&
(blobMin == 0 && blobMax == Int.MAX_VALUE || blob != null && blob in blobMin..blobMax)
}
val BUILT_IN = listOf(
Rule(setOf(Family.A8XX), models = setOf(840), prefer = listOf(NEWEST_DD_TURNIP, DriverPairs.WN_BALANCED)),
Rule(setOf(Family.A8XX), prefer = listOf(DriverPairs.WN_BALANCED)),
Rule(setOf(Family.A7XX_LOW), prefer = listOf(DriverPairs.BANNER_710)),
Rule(setOf(Family.A7XX), oneUi8Gen2 = true, prefer = listOf(DriverPairs.BANNER_ONEUI)),
Rule(setOf(Family.A7XX, Family.A6XX), prefer = listOf(DriverPairs.BANNER)),
Rule(setOf(Family.ADRENO_UNKNOWN), minSdk = 36, prefer = listOf(DriverPairs.WN_BALANCED)),
Rule(setOf(Family.ADRENO_UNKNOWN), prefer = listOf(DriverPairs.BANNER)),
)
fun parse(text: String?): List<Rule>? = runCatching {
val json = JSONObject(text ?: return null)
if (json.optInt("schemaVersion") != SCHEMA) return null
val rules = json.getJSONArray("rules")
(0 until rules.length()).mapNotNull { i -> rule(rules.getJSONObject(i)) }.takeIf { it.isNotEmpty() }
}.getOrNull()
private fun rule(o: JSONObject): Rule? {
val families = strings(o.optJSONArray("families")).mapNotNull { name -> Family.values().firstOrNull { it.name == name } }.toSet()
val prefer = strings(o.optJSONArray("prefer"))
if (families.isEmpty() || prefer.isEmpty()) return null
val models = o.optJSONArray("models")?.let { a -> (0 until a.length()).map { a.getInt(it) }.toSet() } ?: emptySet()
return Rule(
families, models,
if (o.has("oneUi8Gen2")) o.getBoolean("oneUi8Gen2") else null,
o.optInt("minSdk", 0), o.optInt("blobMin", 0), o.optInt("blobMax", Int.MAX_VALUE), prefer,
)
}
private fun strings(a: JSONArray?): List<String> = a?.let { (0 until it.length()).map { i -> it.getString(i) } }.orEmpty()
fun preferences(gpu: GpuInfo, rules: List<Rule>, sdk: Int, blob: Int?): List<String> =
rules.firstOrNull { it.matches(gpu, sdk, blob) }?.prefer.orEmpty()
fun blobVersion(driverVersion: String?): Int? = driverVersion?.split('.')?.getOrNull(1)?.toIntOrNull()
}
@@ -61,13 +61,17 @@ object DriverPairs {
}
}
fun recommendedKey(gpu: GpuInfo, pairs: List<DriverPair>): String? = when (gpu.family) {
Family.NOT_ADRENO -> null
Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED
Family.A7XX_LOW -> BANNER_710
Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER
Family.A6XX -> BANNER
Family.ADRENO_UNKNOWN -> if (android.os.Build.VERSION.SDK_INT >= 36) WN_BALANCED else BANNER
fun recommendedKey(
gpu: GpuInfo, pairs: List<DriverPair>,
rules: List<AutoPicks.Rule> = AutoPicks.BUILT_IN, bad: Set<String> = emptySet(),
sdk: Int = android.os.Build.VERSION.SDK_INT, blob: Int? = null,
): String? {
if (gpu.family == Family.NOT_ADRENO) return null
val keys = AutoPicks.preferences(gpu, rules, sdk, blob)
.ifEmpty { AutoPicks.preferences(gpu, AutoPicks.BUILT_IN, sdk, blob) }
.mapNotNull { if (it == AutoPicks.NEWEST_DD_TURNIP) newestDdTurnip(pairs) else it }
return keys.firstOrNull { key -> pairs.any { it.key == key && it.complete && AutoDriverTrial.release(it) !in bad } }
?: keys.firstOrNull()
}
fun newestDdTurnip(pairs: List<DriverPair>): String? = pairs
@@ -19,6 +19,7 @@ object TurnipReleases {
private const val PREFS = "turnip_releases"
private const val KEY_RELEASE = "latest"
private const val KEY_DOWNLOADS = "downloads"
private const val KEY_PICKS = "autoPicks"
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String,
val sha256: String = "", val pair: String = "", val bundle: Boolean = false)
@@ -57,6 +58,9 @@ object TurnipReleases {
},
)
fun autoPicks(context: Context): List<AutoPicks.Rule> =
AutoPicks.parse(prefs(context).getString(KEY_PICKS, null)) ?: AutoPicks.BUILT_IN
fun cached(context: Context): Check? {
val raw = prefs(context).getString(KEY_RELEASE, null) ?: return null
return runCatching { parse(JSONObject(raw)) }.getOrNull()
@@ -100,6 +104,10 @@ object TurnipReleases {
}
}
if (failed.size == SOURCES.size) throw lastError ?: IOException("no source answered")
runCatching { get(context, AutoPicks.URL, AutoPicks.URL) }
.onFailure { Log.i(TAG, "auto picks: ${it.message}") }
.getOrNull()?.takeIf { AutoPicks.parse(it) != null }
?.let { prefs(context).edit().putString(KEY_PICKS, it).apply() }
val stored = JSONObject().put("assets", assets).put("latest", latest)
.put("failed", JSONArray(failed)).put("checkedAt", System.currentTimeMillis())
prefs(context).edit().putString(KEY_RELEASE, stored.toString()).apply()
@@ -18,7 +18,7 @@ import org.json.JSONObject
object DeckyManager {
private const val TAG = "DeckyManager"
const val REPOSITORY = "Droid-Deck/decky-loader"
const val REPOSITORY = "SteamDeckHomebrew/decky-loader"
private const val RELEASES = "https://api.github.com/repos/$REPOSITORY/releases?per_page=30"
private const val PATH = "root/homebrew/services/PluginLoader"
private const val VERSION = "root/homebrew/services/.droiddeck-decky-version"
@@ -1480,6 +1480,7 @@ class SessionService : Service() {
}
override fun onTaskRemoved(rootIntent: Intent?) {
if (rootIntent?.component?.className == com.droiddeck.launcher.ui.SecondScreenActivity::class.java.name) return
if (pipTask || xrActivityVisible) {
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
activityVisible = false
@@ -1,21 +1,17 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import android.app.Presentation
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.Display
import android.view.Gravity
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewConfiguration
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.FrameLayout
@@ -37,9 +33,9 @@ import com.termux.terminal.TerminalSessionClient
import com.termux.view.TerminalView
import com.termux.view.TerminalViewClient
class SecondScreenPresentation(
internal class SecondScreenControls(
context: Context,
private val sessionActivity: SessionActivity,
display: Display,
private val sendPointer: (x: Float, y: Float, width: Float, height: Float) -> Unit,
private val sendButton: (button: Int, pressed: Boolean) -> Unit,
private val sendWheel: (steps: Int) -> Unit,
@@ -47,12 +43,8 @@ class SecondScreenPresentation(
private val onQam: () -> Unit,
private val onClose: () -> Unit,
private val pad: PadBridge? = null,
) : Presentation(sessionActivity, display) {
private val root = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.rgb(15, 18, 22))
isFocusableInTouchMode = true
}
) : LinearLayout(context) {
private val root get() = this
private var currentMode = SecondScreenMode.NONE
private var keyboardHost: KeyboardHost? = null
private var terminalSession: TerminalSession? = null
@@ -60,35 +52,22 @@ class SecondScreenPresentation(
private var terminalPid = -1
private var ctrlActive = false
private var altActive = false
private var created = false
init {
setCancelable(false)
setCanceledOnTouchOutside(false)
setOnDismissListener { closeTerminal() }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
created = true
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
setContentView(root)
applyImmersiveMode()
renderMode()
orientation = VERTICAL
setBackgroundColor(Color.rgb(15, 18, 22))
isFocusableInTouchMode = true
}
fun showMode(mode: SecondScreenMode) {
if (currentMode == mode && isShowing) return
if (currentMode == mode) return
currentMode = mode
if (created) renderMode()
renderMode()
}
fun closeControls() {
closeTerminal()
keyboardHost?.hide()
keyboardHost = null
dismiss()
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
@@ -98,14 +77,6 @@ class SecondScreenPresentation(
return super.dispatchKeyEvent(event)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
applyImmersiveMode()
sessionActivity.refreshClipboard()
}
}
private fun renderMode() {
keyboardHost?.hide()
keyboardHost = null
@@ -291,16 +262,6 @@ class SecondScreenPresentation(
private fun weightParams() = LinearLayout.LayoutParams(-1, 0, 1f)
private fun applyImmersiveMode() {
@Suppress("DEPRECATION")
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
}
private inner class TrackpadView(context: Context) : View(context) {
private val gestures = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(),
object : PointerGestures.Listener {
@@ -0,0 +1,139 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.view.Display
import android.view.View
import android.view.WindowManager
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.session.SessionState
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.AtomicLong
class SecondScreenWindow(
private val sessionActivity: SessionActivity,
val display: Display,
private val sendPointer: (Float, Float, Float, Float) -> Unit,
private val sendButton: (Int, Boolean) -> Unit,
private val sendWheel: (Int) -> Unit,
private val onSteamMenu: () -> Unit,
private val onQam: () -> Unit,
private val onClose: () -> Unit,
private val pad: PadBridge? = null,
) {
private val token = tokens.incrementAndGet()
private var activity = WeakReference<SecondScreenActivity>(null)
private var controls: SecondScreenControls? = null
private var mode = SecondScreenMode.NONE
private var launching = false
private var closed = false
val window get() = activity.get()?.window
val isShowing get() = !closed && (launching || activity.get()?.isFinishing == false)
fun show() {
if (isShowing || closed) return
owners[token] = WeakReference(this)
launching = true
try {
val intent = Intent(sessionActivity, SecondScreenActivity::class.java)
.putExtra(OWNER, token)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
sessionActivity.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display.displayId).toBundle())
} catch (error: Exception) {
launching = false
owners.remove(token)
throw error
}
}
fun showMode(mode: SecondScreenMode) {
this.mode = mode
controls?.showMode(mode)
}
fun closeControls() {
closed = true
launching = false
owners.remove(token)
controls?.closeControls()
controls = null
activity.get()?.finishAndRemoveTask()
activity.clear()
}
internal fun attach(host: SecondScreenActivity): View {
controls?.closeControls()
activity = WeakReference(host)
launching = false
return SecondScreenControls(host, sessionActivity, sendPointer, sendButton, sendWheel,
onSteamMenu, onQam, onClose, pad).also {
controls = it
it.showMode(mode)
}
}
internal fun detach(host: SecondScreenActivity) {
if (activity.get() !== host) return
controls?.closeControls()
controls = null
activity.clear()
if (host.isFinishing && !closed) onClose()
}
internal fun refreshClipboard() = sessionActivity.refreshClipboard()
companion object {
private const val OWNER = "secondScreenOwner"
private val tokens = AtomicLong()
private val owners = mutableMapOf<Long, WeakReference<SecondScreenWindow>>()
internal fun find(intent: Intent): SecondScreenWindow? =
owners[intent.getLongExtra(OWNER, 0)]?.get()?.takeUnless { it.closed }
}
}
class SecondScreenActivity : Activity() {
private var owner: SecondScreenWindow? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val host = SecondScreenWindow.find(intent)
if (host == null || !SessionState.running) {
finishAndRemoveTask()
return
}
owner = host
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
setContentView(host.attach(this))
applyImmersiveMode()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
applyImmersiveMode()
owner?.refreshClipboard()
}
}
@Deprecated("Back is handled by the session controls")
override fun onBackPressed() = Unit
override fun onDestroy() {
owner?.detach(this)
owner = null
super.onDestroy()
}
private fun applyImmersiveMode() {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
}
}
@@ -0,0 +1,67 @@
package com.droiddeck.launcher.gpu
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class AutoPicksTest {
private fun gpu(model: Int) = GpuInfo("Adreno $model", model, GpuInfo.familyOf(true, model), "", false)
private fun bundle(tag: String) = TurnipReleases.Asset("DroidDeck", tag, "$tag.zip", "https://example/$tag", 6_000_000,
false, "Android + Linux", "0".repeat(64), DriverPairs.ddTurnip(tag), bundle = true)
private fun half(name: String, tag: String, linux: Boolean, pair: String) =
TurnipReleases.Asset("src", tag, name, "https://example/$name", 3_000_000, linux, "label", "0".repeat(64), pair)
private val pairs = DriverPairs.from(TurnipReleases.Check(
listOf(
bundle("DD-Turnip-v0.3.0"),
half("Turnip-r6.zip", "r6", false, DriverPairs.BANNER),
half("Turnip-r6-Linux.zip", "r6", true, DriverPairs.BANNER),
),
emptyList(), emptyList(), 0L,
))
private val manifest = """
{"schemaVersion": 1, "rules": [
{"families": ["A7XX"], "models": [740], "blobMin": 700, "prefer": ["banner"]},
{"families": ["A7XX", "A6XX"], "prefer": ["dd-turnip", "banner"]},
{"families": ["A9XX"], "prefer": ["banner"]}
]}
""".trimIndent()
@Test fun theManifestOrdersPreferencesAndTheNewestDdTurnipResolves() {
val rules = AutoPicks.parse(manifest)!!
assertEquals(2, rules.size)
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v0.3.0"), DriverPairs.recommendedKey(gpu(650), pairs, rules))
}
@Test fun aReleaseMarkedBadFallsThroughToTheNextPreference() {
val rules = AutoPicks.parse(manifest)!!
val dd = pairs.first { it.key.startsWith(DriverPairs.DD_TURNIP) }
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650), pairs, rules, bad = setOf(AutoDriverTrial.release(dd))))
}
@Test fun systemDriverRulesOnlyMatchAKnownBlob() {
val rules = AutoPicks.parse(manifest)!!
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), pairs, rules, blob = 744))
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v0.3.0"), DriverPairs.recommendedKey(gpu(740), pairs, rules, blob = 676))
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v0.3.0"), DriverPairs.recommendedKey(gpu(740), pairs, rules, blob = null))
assertEquals(744, AutoPicks.blobVersion("512.744.0"))
}
@Test fun aGpuTheManifestDoesNotCoverUsesTheBuiltInTable() {
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), pairs, AutoPicks.parse(manifest)!!))
}
@Test fun anotherSchemaOrNoUsableRulesIsIgnored() {
assertNull(AutoPicks.parse("""{"schemaVersion": 2, "rules": [{"families": ["A7XX"], "prefer": ["banner"]}]}"""))
assertNull(AutoPicks.parse("""{"schemaVersion": 1, "rules": [{"families": ["A9XX"], "prefer": ["banner"]}]}"""))
assertNull(AutoPicks.parse("not json"))
}
}
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.ui
import android.app.Application
import android.content.Intent
import android.hardware.display.DisplayManager
import android.view.Display
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@Config(application = Application::class, manifest = Config.NONE, sdk = [28, 33])
@LooperMode(LooperMode.Mode.PAUSED)
class SecondScreenActivityTest {
@Before fun setUp() {
SessionState.running = true
SessionState.stopRequested = false
}
@After fun tearDown() {
SessionState.running = false
SessionState.stopRequested = false
}
@Test fun removingControlsTaskDoesNotStopTheRunningSession() {
val service = Robolectric.buildService(SessionService::class.java).get()
service.onTaskRemoved(Intent(service, SecondScreenActivity::class.java))
assertTrue(SessionState.running)
assertFalse(SessionState.stopRequested)
}
@Test fun activityRestoredWithoutItsSessionOwnerFinishes() {
val activity = Robolectric.buildActivity(SecondScreenActivity::class.java).create().get()
assertTrue(activity.isFinishing)
assertTrue(SessionState.running)
}
@Test fun closingBeforeTheSecondaryActivityStartsRejectsTheLateLaunch() {
val session = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = session.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val controls = SecondScreenWindow(session, display, { _, _, _, _ -> }, { _, _ -> }, {}, {}, {}, {})
controls.show()
val intent = shadowOf(session).nextStartedActivity
controls.closeControls()
val activity = Robolectric.buildActivity(SecondScreenActivity::class.java, intent).create().get()
assertTrue(activity.isFinishing)
assertFalse(controls.isShowing)
assertTrue(SessionState.running)
}
}
@@ -593,41 +593,37 @@ case $mode in
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
) &
steam_hold_launch() {
_bl_launch_ready=
local game=$1 shortcut= waited=0 status=0
_bl_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; }
_bl_hand_off() {
printf '%s\n' "$game" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game"
}
_bl_end=$((SECONDS + 120))
until [ "$(xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p')" = 769 ] || [ "$SECONDS" -ge "$_bl_end" ]; do
until [ "$(_bl_focused)" = 769 ] || [ "$SECONDS" -ge "$_bl_end" ]; do
sleep 1
done
# With a large library the overview can stay missing for 30+ minutes while Steam already takes the launch URL.
_bl_overview_status=1
_bl_overview_tries=0
while [ "$_bl_overview_tries" -lt 2 ]; do
if /usr/local/bin/droiddeck-agent --wait-steam-shortcut-overview "$1" 45; then
_bl_overview_status=0
else
_bl_overview_status=$?
fi
if [ "$_bl_overview_status" -ne 1 ]; then
break
fi
_bl_overview_tries=$((_bl_overview_tries + 1))
echo "== steam: shortcut overview not ready yet (attempt $_bl_overview_tries of 2)"
sleep 2
# Shortcut CGameIDs are 64-bit; Steam app ids fit in 32 bits and keep the old short delay.
[ "${#game}" -gt 10 ] && shortcut=1
[ -n "$shortcut" ] || sleep 4
echo "== steam: interface up; launching the requested game $game"
_bl_hand_off
[ -n "$shortcut" ] || return 0
# Steam can drop a shortcut launch it gets before the shortcut's overview exists (large libraries).
# Hand it over again only if the game never took focus, so a launch that worked is not started twice.
while [ "$(_bl_focused)" = 769 ] && [ "$waited" -lt 20 ]; do
sleep 1
waited=$((waited + 1))
done
if [ "$_bl_overview_status" -eq 0 ]; then
echo "== steam: shortcut overview ready; launching the requested game $1"
_bl_launch_ready=1
elif [ "$_bl_overview_status" -eq 3 ]; then
echo "== steam: not a shortcut CGameID; keeping the existing launch path"
sleep 4
_bl_launch_ready=1
[ "$(_bl_focused)" = 769 ] || return 0
echo "== steam: the game is not in front after about 20 s; waiting for the shortcut overview"
/usr/local/bin/droiddeck-agent --wait-steam-shortcut-overview "$game" 45 || status=$?
if [ "$status" -eq 3 ]; then
echo "== steam: not a shortcut CGameID; not launching again"
elif [ "$(_bl_focused)" = 769 ]; then
echo "== steam: launching the requested game again $game (overview status $status)"
_bl_hand_off
else
echo "== steam: shortcut overview not ready after about 90 s; launching the requested game anyway $1"
_bl_launch_ready=1
fi
if [ "$_bl_launch_ready" = 1 ]; then
echo "== steam: interface up; launching the requested game $1"
printf '%s\n' "$1" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game"
echo "== steam: the game took focus while waiting; not launching again"
fi
}
if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then
@@ -244,6 +244,10 @@ bl_vacdiag() {
BL_DIRECTAUDIO_SETUP = """
bl_directaudio() {
case "${verb:-}" in
run|waitforexitandrun|runinprefix) ;;
*) return 0 ;;
esac
base=$1
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
[ -d "$BL_DIRECTAUDIO" ] || return 0
+24 -3
View File
@@ -964,12 +964,12 @@ class DirectAudioPrefixTest(unittest.TestCase):
(self.windows / folder).mkdir(parents=True)
self.reg = self.compat / "pfx/user.reg"
def run_setup(self):
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nbl_directaudio "$1"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
def run_setup(self, verb="waitforexitandrun"):
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat))
env.pop("WINEDLLPATH", None)
env.pop("WINE_AUDIO_DRIVER", None)
return subprocess.run(["bash", "-c", script, "bash", str(self.tool)], env=env, capture_output=True, text=True, check=True)
return subprocess.run(["bash", "-c", script, "bash", str(self.tool), verb], env=env, capture_output=True, text=True, check=True)
def audio_values(self):
found, current = [], None
@@ -984,6 +984,27 @@ class DirectAudioPrefixTest(unittest.TestCase):
path = self.windows / folder / "winedirectaudio.drv"
return os.readlink(path) if path.is_symlink() else None
def test_non_launch_verbs_preserve_audio_configuration(self):
for verb in ("getcompatpath", "getnativepath", "destroyprefix"):
with self.subTest(verb=verb):
self.reg.write_text('WINE REGISTRY Version 2\n\n[Software\\\\Wine\\\\Drivers] 1\n"Audio"="pulse"\n')
before = self.reg.read_bytes()
result = self.run_setup(verb)
self.assertEqual(self.reg.read_bytes(), before)
self.assertIsNone(self.link("system32"))
self.assertIsNone(self.link("syswow64"))
self.assertIn("WINEDLLPATH=\n", result.stdout)
self.assertIn("WINE_AUDIO_DRIVER=\n", result.stdout)
def test_other_windows_launch_verbs_still_set_up_audio(self):
self.reg.write_text("WINE REGISTRY Version 2\n")
for verb in ("run", "runinprefix"):
with self.subTest(verb=verb):
result = self.run_setup(verb)
self.assertIn("DirectAudio ready", result.stderr)
self.assertIn("WINE_AUDIO_DRIVER=directaudio,pulse\n", result.stdout)
self.assertEqual(self.link("system32"), str(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv"))
def test_the_driver_is_placed_and_selected_the_way_wine_reads_it(self):
self.reg.write_text("WINE REGISTRY Version 2\n;; All keys relative to \\\\User\\\\S-1-5-21-0-0-0-1000\n\n#arch=win64\n")
result = self.run_setup()
+57 -54
View File
@@ -1,4 +1,4 @@
"""Cold shortcut launches wait for Steam's CGameID-to-app overview mapping."""
"""Requested Steam games are handed over as soon as the interface is up; a shortcut is handed over again only if it never took focus."""
import os
from pathlib import Path
import subprocess
@@ -12,6 +12,7 @@ START = SOURCE.index(" steam_hold_launch() {")
END = SOURCE.index(' if [ -s "$HOME/.bl-autolaunch" ]; then', START)
assert START >= 0
LAUNCH_BLOCK = textwrap.dedent(SOURCE[START:END])
SHORTCUT = str((3551182975 << 32) | 0x02000000)
class SteamColdLaunchTest(unittest.TestCase):
@@ -26,93 +27,95 @@ class SteamColdLaunchTest(unittest.TestCase):
self.agent_args = self.root / "agent-args"
self.sleep_args = self.root / "sleep-args"
self.agent_count = self.root / "agent-count"
self.focus_count = self.root / "focus-count"
# FOCUS lists the focused app per xprop call; the last value repeats.
xprop = self.bin / "xprop"
xprop.write_text("#!/bin/sh\necho 'GAMESCOPE_FOCUSED_APP(CARDINAL) = 769'\n")
xprop.write_text(
"#!/bin/sh\n"
"n=$(cat \"$FOCUS_COUNT\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$FOCUS_COUNT\"\n"
"i=0; last=769\n"
"for f in $FOCUS; do i=$((i + 1)); last=$f; [ \"$i\" -eq \"$n\" ] && break; done\n"
"echo \"GAMESCOPE_FOCUSED_APP(CARDINAL) = $last\"\n")
xprop.chmod(0o755)
agent = self.bin / "droiddeck-agent"
agent.write_text(
"#!/bin/sh\n"
"printf '%s\\n' \"$@\" > \"$AGENT_ARGS\"\n"
"printf '%s\n' \"$@\" > \"$AGENT_ARGS\"\n"
"n=$(cat \"$AGENT_COUNT\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$AGENT_COUNT\"\n"
"i=0; last=1\n"
"for s in $AGENT_STATUS; do i=$((i + 1)); last=$s; [ \"$i\" -eq \"$n\" ] && exit \"$s\"; done\n"
"exit \"$last\"\n")
"exit \"$AGENT_STATUS\"\n")
agent.chmod(0o755)
sleep = self.bin / "sleep"
sleep.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$SLEEP_ARGS\"\n")
sleep.write_text("#!/bin/sh\nprintf '%s\n' \"$@\" >> \"$SLEEP_ARGS\"\n")
sleep.chmod(0o755)
self.block = LAUNCH_BLOCK.replace("/usr/local/bin/droiddeck-agent", str(agent))
def run_launch(self, target, helper_status):
def run_launch(self, target, focus="769", helper_status=0):
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir),
PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args),
AGENT_COUNT=str(self.agent_count), AGENT_STATUS=str(helper_status))
script = self.block + "\nprintf 'ARG:%s\\n' \"$@\"\nwait\n"
AGENT_COUNT=str(self.agent_count), AGENT_STATUS=str(helper_status),
FOCUS=focus, FOCUS_COUNT=str(self.focus_count))
script = self.block + "\nprintf 'ARG:%s\n' \"$@\"\nwait\n"
url = target if target.startswith("steam://") else "steam://rungameid/" + target
result = subprocess.run(["bash", "-c", script, "cold-launch", url],
env=env, text=True, capture_output=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
return result
def test_shortcut_overview_gate_releases_original_64_bit_cgameid_without_fixed_sleep(self):
game_id = str((3551182975 << 32) | 0x02000000)
result = self.run_launch(game_id, 0)
self.assertEqual("steam-game", (self.launch_dir / "steam-game").name)
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip())
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
self.assertFalse(self.sleep_args.exists(), result.stdout)
def hand_offs(self, result):
return [l for l in result.stdout.splitlines() if "launching the requested game" in l]
def test_native_app_id_keeps_legacy_bounded_launch_path(self):
game_id = "413150"
self.run_launch(game_id, 3)
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip())
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
def test_a_shortcut_that_takes_focus_is_handed_over_once_without_waiting_for_the_overview(self):
result = self.run_launch(SHORTCUT, focus="769 769 4242")
self.assertEqual(SHORTCUT, (self.launch_dir / "steam-game").read_text().strip())
self.assertEqual(1, len(self.hand_offs(result)), result.stdout)
self.assertFalse(self.agent_args.exists(), result.stdout)
self.assertEqual(["1"], self.sleep_args.read_text().split())
def test_a_shortcut_that_never_takes_focus_is_handed_over_again_after_the_overview_wait(self):
result = self.run_launch(SHORTCUT, focus="769", helper_status=0)
self.assertEqual(2, len(self.hand_offs(result)), result.stdout)
self.assertIn("launching the requested game again", result.stdout)
self.assertEqual(["--wait-steam-shortcut-overview", SHORTCUT, "45"], self.agent_args.read_text().splitlines())
self.assertEqual(["1"] * 20, self.sleep_args.read_text().split())
def test_a_timed_out_overview_still_gets_one_more_hand_off(self):
result = self.run_launch(SHORTCUT, focus="769", helper_status=1)
self.assertEqual(2, len(self.hand_offs(result)), result.stdout)
self.assertIn("overview status 1", result.stdout)
def test_a_game_that_takes_focus_during_the_overview_wait_is_not_started_twice(self):
focus = " ".join(["769"] * 23) + " 4242"
result = self.run_launch(SHORTCUT, focus=focus, helper_status=0)
self.assertEqual(1, len(self.hand_offs(result)), result.stdout)
self.assertIn("took focus while waiting", result.stdout)
self.assertNotIn("launching the requested game again", result.stdout)
def test_native_app_id_keeps_the_short_delay_and_is_handed_over_once(self):
result = self.run_launch("413150")
self.assertEqual("413150", (self.launch_dir / "steam-game").read_text().strip())
self.assertEqual(1, len(self.hand_offs(result)), result.stdout)
self.assertEqual("4", self.sleep_args.read_text().strip())
self.assertFalse(self.agent_args.exists())
def test_a_shortcut_whose_overview_never_appears_is_launched_after_a_bounded_wait(self):
game_id = str((3551182975 << 32) | 0x02000000)
result = self.run_launch(game_id, 1)
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
self.assertEqual("2", self.agent_count.read_text().strip())
self.assertEqual(["2", "2"], self.sleep_args.read_text().split())
self.assertIn("launching the requested game anyway", result.stdout)
def test_a_late_overview_is_still_waited_for_once_more(self):
game_id = str((3551182975 << 32) | 0x02000000)
result = self.run_launch(game_id, "1 0")
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual("2", self.agent_count.read_text().strip())
self.assertEqual(["2"], self.sleep_args.read_text().split())
self.assertIn("attempt 1 of 2", result.stdout)
self.assertNotIn("anyway", result.stdout)
def test_an_agent_failure_other_than_a_timeout_launches_without_retrying(self):
game_id = str((3551182975 << 32) | 0x02000000)
result = self.run_launch(game_id, 2)
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual("1", self.agent_count.read_text().strip())
self.assertFalse(self.sleep_args.exists())
def test_a_restart_for_a_game_waits_for_its_overview_too(self):
game_id = str((3551182975 << 32) | 0x02000000)
def test_a_restart_for_a_game_uses_the_same_hand_off(self):
loop = SOURCE[SOURCE.index(' if [ -s "$HOME/.bl-restart-game" ]; then'):SOURCE.index(' if [ -f "$HOME/.bl-restart-once" ]; then')]
self.assertIn('steam_hold_launch "$_bl_again" &', loop)
self.assertNotIn("set -- \"steam://rungameid/", loop)
script = self.block + '\nsteam_hold_launch "%s"\n' % game_id
script = self.block + '\nsteam_hold_launch "%s"\n' % SHORTCUT
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir),
PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args),
AGENT_COUNT=str(self.agent_count), AGENT_STATUS="1 0")
AGENT_COUNT=str(self.agent_count), AGENT_STATUS="1",
FOCUS="769", FOCUS_COUNT=str(self.focus_count))
result = subprocess.run(["bash", "-c", script, "restart"], env=env, text=True, capture_output=True, timeout=10, check=True)
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
self.assertEqual(SHORTCUT, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual(2, len(self.hand_offs(result)), result.stdout)
def test_non_game_steam_urls_remain_on_the_original_startup_arguments(self):
url = "steam://open/library"
result = self.run_launch(url, 0)
result = self.run_launch(url)
self.assertIn("ARG:" + url, result.stdout)
self.assertFalse((self.launch_dir / "steam-game").exists())
self.assertFalse(self.agent_args.exists())