Merge latest upstream main before Controller UI integration

# Conflicts:
#	app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
#	app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt
#	app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
#	app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt
#	app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt
This commit is contained in:
Delete228 committed 2026-11-06 14:37:50 +03:00
commit ba5876bf6d
360 files changed
+34610 -1088

No files matched your search

@@ -3,6 +3,7 @@ package com.droiddeck.launcher
import android.app.Application
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.session.CrashHandler
import com.droiddeck.launcher.session.EnhancedSessionLogShare
import com.droiddeck.launcher.session.GpuClockPin
class App : Application() {
@@ -16,6 +17,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
HomeApp.trackRecents(this)
@@ -14,10 +14,12 @@ 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.core.DeviceSupport
import com.droiddeck.launcher.gpu.DriverPairs
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.session.SessionService
@@ -42,7 +44,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
var canRestoreBundled by mutableStateOf(false)
private val releaseProgress = HashMap<String, Int>()
var linuxSelected by mutableStateOf("")
val gpu: GpuInfo = GpuInfo.detect()
var gpu: GpuInfo = GpuInfo.detect()
private set
var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO)
var pairRows by mutableStateOf<List<PairRow>>(emptyList())
var pairBusy by mutableStateOf<String?>(null)
@@ -65,13 +68,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
fun state() = GpuDriversState(
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)),
gpuName = gpu.displayName(activity), gpuFamily = if (gpu.name.contains("Xclipse", ignoreCase = true)) gpu.family.label(gpu.name) else gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)),
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
autoStatus = autoStatus, releaseStatus = releaseStatus.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking,
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
activeBundle = activeBundle,
activeBundle = activeBundle, powerVr = gpu.family == GpuInfo.Family.POWERVR,
systemPowerVr = SystemVulkanDriver.usesDefault(linuxSelected),
mode = uiMode, display = displaySlot(), runtime = runtimeSlot(),
canRestart = !sessionRunning,
checkedAt = TurnipReleases.cached(activity)?.checkedAt ?: 0L,
@@ -142,7 +146,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
DriverRow(id, it.label, activity.getString(if (linux) R.string.drivers_bundle_sets_display else R.string.drivers_bundle_sets_runtime), true, DriverRow.BUNDLE)
}
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
if (id.isEmpty()) DriverRow("", activity.getString(if (gpu.family == GpuInfo.Family.POWERVR) R.string.gpu_system_powervr else R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
else bundleRow(id, linux = true) ?: DriverRow(
id, lm.getDriverName(id),
listOfNotNull(
@@ -177,6 +181,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
fun summary(): String {
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
?: if (SystemVulkanDriver.usesDefault(linuxSelected) && androidSelected == TurnipDriver.AUTO) activity.getString(R.string.gpu_system_powervr) else null
val display = displaySlot().name
val base = when {
uiMode == GPU_MODE_AUTO -> activity.getString(R.string.drivers_summary, activity.getString(R.string.common_auto), active ?: display)
@@ -193,17 +198,28 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val recommended = if (QuestExperimental.isSupported()) null else recommendedKey(pairs)
pairRows = pairs.map { p ->
val bundle = p.bundle?.let { installedBundle(it) }
val nad = DriverPairs.isNonAdreno(p.key)
val bundle = p.bundle?.let { if (nad) installedBundleAnyBuild(it) else installedBundle(it) }
val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) }
val linuxId = if (p.bundle != null) bundle?.linuxId else p.linux?.let { TurnipReleases.installedId(activity, it, lm::isInstalled) }
val mb = p.assets.sumOf { it.size } / 1_048_576.0
val update = nad && bundle != null && p.bundle?.let { TurnipReleases.updateAvailable(activity, it) } == true
val builtOn = if (nad) p.bundle?.builtOn.orEmpty() else ""
val version = when {
!nad -> p.version
bundle != null -> bundle.version.ifEmpty { p.version }
builtOn.isNotEmpty() -> activity.getString(R.string.drivers_built_on, builtOn)
else -> p.version
}
PairRow(
key = p.key, name = p.name, version = p.version,
key = p.key, name = p.name, version = version, update = if (update) builtOn.takeIf { it.isNotEmpty() }?.let { activity.getString(R.string.drivers_built_on, it) } ?: p.version else null,
detail = if (!p.complete) activity.getString(R.string.drivers_half_published) else activity.getString(R.string.drivers_pair_size, mb),
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
installed = displayId != null && linuxId != null,
active = displayId != null && linuxId != null &&
SessionPrefs.androidDriver(activity) == displayId && SessionPrefs.linuxDriver(activity) == linuxId,
active = displayId != null && linuxId != null && SessionPrefs.linuxDriver(activity) == linuxId &&
(SessionPrefs.androidDriver(activity) == displayId ||
// A Mali pair under Auto: the display is the phone's own driver.
(gpu.family.mali && DriverPairs.isNonAdreno(p.key) && SessionPrefs.androidDriver(activity) == TurnipDriver.AUTO)),
)
}.sortedByDescending { it.recommended }
}
@@ -237,7 +253,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private fun releasesStale(): Boolean {
val cached = TurnipReleases.cached(activity)
return cached == null || System.currentTimeMillis() - cached.checkedAt > RELEASE_CHECK_INTERVAL_MS ||
cached.assets.none { it.pair.isNotEmpty() }
cached.assets.none { it.pair.isNotEmpty() } ||
// A list checked before this device's open non-Adreno drivers were offered has none of them.
(!DeviceSupport.adreno() && cached.assets.none { DriverPairs.isNonAdreno(it.pair) })
}
fun ensureAuto(force: Boolean) {
@@ -247,9 +265,33 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
if (force) autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
return
}
if (gpu.family == GpuInfo.Family.POWERVR && !SystemVulkanDriver.isXclipse()) {
// Auto owns both choices. Manual imports remain available when Manual is selected.
SessionPrefs.ensurePowerVrAutoDrivers(activity)
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
refreshDrivers()
return
}
// A Mali pair set by an earlier build put its PanVK Android half on the display, which fails
// on Mali gralloc. Under Auto the display is the phone's own driver (Android's loader).
if (gpu.family.mali) {
// Builds before 0.5.0-nad1 turned the bridge on under Auto without recording it, and
// left it on for good (it wins over the pair). Under Auto that switch is taken as Auto's.
if (!SessionPrefs.maliFallbackKnown(activity))
SessionPrefs.setMaliFallbackByAuto(activity, if (SessionPrefs.vkBridge(activity)) "bridge" else "")
// A lone imported PanVK Android driver set by hand stalls the display the same way
// ("black screen with the start-up logo"), so under Auto any imported display goes.
val display = SessionPrefs.androidDriver(activity)
if (display != TurnipDriver.AUTO) {
SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
Log.i(TAG, "auto: Mali display back on the phone's own driver (was $display)")
}
}
AutoDriverTrial.rollbackDue(activity)?.let { trial ->
AutoDriverTrial.rollBack(activity, trial)
autoStatus = activity.getString(R.string.drivers_rolled_back, trial.name)
// The drivers before the trial on a Mali are the runtime's Turnip, which finds no GPU there.
if (gpu.family.mali && maliHasNoRoute()) useMaliFallback(trial.name)
refreshDrivers()
return
}
@@ -263,6 +305,29 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers()
return
}
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
releaseChecking = true
autoStatus = activity.getString(R.string.drivers_checking_latest)
Thread({
com.droiddeck.launcher.gpu.VulkanInfo.query()
ui.post {
releaseChecking = false
gpu = GpuInfo.detect()
Log.i(TAG, "auto: Mali named by its driver: ${gpu.name} -> ${gpu.family}")
lastAutoCheck = 0L
ensureAuto(force)
}
}, "gpu-name").start()
return
}
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair"))
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) {
// No PanVK build covers this Mali (e.g. the G1 series, arch v14): the phone's own driver.
autoStatus = useMaliFallback(null)
refreshDrivers()
return
}
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return
@@ -275,6 +340,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
runCatching { com.droiddeck.launcher.gpu.VulkanInfo.query() }
ui.post {
releaseChecking = false
if (gpu.family == GpuInfo.Family.POWERVR) gpu = GpuInfo.detect()
refreshReleaseRows()
refreshPairs()
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
@@ -284,10 +350,37 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
when {
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
?: activity.getString(R.string.upd_current_status)
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
// RADV is not published right now: the Xclipse falls back to the system route.
SessionPrefs.ensurePowerVrAutoDrivers(activity)
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
refreshDrivers()
}
gpu.family.mali && (pair == null || !pair.complete) &&
(problem != null || TurnipReleases.cached(activity)?.failed?.contains(TurnipReleases.NON_ADRENO_LABEL) == true) -> {
// The list could not be read: nothing is known to be missing, so a working route stays.
// With no open driver, Venus or bridge the session would run the runtime's Turnip,
// which finds no GPU on a Mali, so the stand-in goes on anyway.
autoStatus = activity.getString(R.string.upd_couldnt_check, problem ?: TurnipReleases.NON_ADRENO_LABEL)
if (maliHasNoRoute()) {
useMaliFallback(null)
refreshDrivers()
}
}
gpu.family.mali && (pair == null || !pair.complete) -> {
// No open driver for this Mali published yet: the phone's own driver until it is.
autoStatus = useMaliFallback(key?.let { DriverPairs.nonAdrenoName(it) } ?: gpu.name)
refreshDrivers()
}
pair == null || !pair.complete ->
autoStatus = problem?.let { activity.getString(R.string.upd_couldnt_check, it) } ?: activity.getString(R.string.drivers_recommended_unpublished)
AutoDriverTrial.release(pair) in AutoDriverTrial.bad(activity) ->
AutoDriverTrial.release(pair) in AutoDriverTrial.bad(activity) -> {
autoStatus = activity.getString(R.string.drivers_skipping_bad, pair.name, pair.version)
if (gpu.family.mali && maliHasNoRoute()) {
useMaliFallback(pair.name)
refreshDrivers()
}
}
SessionState.running -> autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
holdBack && row?.installed != true -> autoStatus = activity.getString(R.string.drivers_auto_waits_for_network, pair.name, pair.version)
else -> installPair(pair, auto = true)
@@ -296,6 +389,53 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-driver-auto").start()
}
/**
* A Mali with no open driver pair to install ([missing] names the unpublished pair, or null when
* no PanVK build covers this GPU) runs through the phone's own driver: Mali (Venus) where this
* apk carries it (Steam runs on it from the G57 to the G1 series), the Mali bridge otherwise.
* Venus needs Vulkan 1.2 from the phone's driver; the bridge raises a Vulkan 1.1 driver
* (r32p1 on the G77, G78 and G610) for gamescope itself, so there the bridge stands in.
* The Linux driver choice is left alone (it is the bridge's fallback), and Auto
* switches only its own choice off again once a pair is installed ([endMaliFallback]).
*/
private fun useMaliFallback(missing: String?): String {
val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
if (venus && !SessionPrefs.venus(activity)) {
SessionPrefs.setVenus(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, "venus")
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
SessionPrefs.setVkBridge(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, "bridge")
}
val route = activity.getString(if (venus) R.string.drivers_route_venus else R.string.drivers_route_bridge)
Log.i(TAG, "auto: Mali stand-in route $route (missing pair: ${missing ?: "none covers ${gpu.name}"})")
if (oldVulkan != null) return activity.getString(R.string.drivers_mali_old_vulkan_bridge, missing ?: gpu.name, oldVulkan)
return if (missing == null) activity.getString(R.string.drivers_mali_no_pair_auto, route)
else activity.getString(R.string.drivers_mali_unpublished_auto, missing, route)
}
/** Neither an installed open Linux driver nor Venus or the bridge: the runtime's Turnip would run. */
private fun maliHasNoRoute(): Boolean {
if (SessionPrefs.vkBridge(activity)) return false
// Venus on a Vulkan 1.1 driver does not start (VenusComponent.wanted), so it is no route.
if (SessionPrefs.venus(activity) && com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity) == null) return false
val linux = SessionPrefs.linuxDriver(activity)
return linux.isEmpty() || !LinuxVulkanDriverManager(activity).isInstalled(linux)
}
/** A pair is installed for this Mali: the route Auto switched on in its place goes off again. */
private fun endMaliFallback() {
when (SessionPrefs.maliFallbackByAuto(activity)) {
"venus" -> SessionPrefs.setVenus(activity, false)
"bridge" -> SessionPrefs.setVkBridge(activity, false)
else -> return
}
Log.i(TAG, "auto: pair installed; ${SessionPrefs.maliFallbackByAuto(activity)} (Auto's stand-in) off")
SessionPrefs.setMaliFallbackByAuto(activity, "")
}
fun selectPair(key: String) {
if (pairBusy != null) return
val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
@@ -304,7 +444,15 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
installPair(pair, auto = false)
}
private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean) {
/** A newer build of an installed open non-Adreno pair: replaced in place, still selected if it was. */
fun updatePair(key: String) {
if (pairBusy != null) return
val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
val wasActive = pairRows.firstOrNull { it.key == key }?.active == true
installPair(pair, auto = wasActive && mode == SessionPrefs.GPU_DRIVERS_AUTO, force = true, select = wasActive)
}
private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean, force: Boolean = false, select: Boolean = true) {
if (!pair.complete) return
pairBusy = pair.key
pairPercent = 0
@@ -314,7 +462,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val result = runCatching {
val zips = pair.assets
val ids = zips.mapIndexed { i, asset ->
installedIdOf(asset)
(if (force) null else installedIdOf(asset))
?: installAsset(asset) { pct -> ui.post { pairPercent = (i * 100 + pct) / zips.size } }.also { downloaded = true }
}
if (pair.bundle != null) DriverBundle.get(activity, ids[0])!!.let { listOf(it.androidId, it.linuxId) } else ids
@@ -322,23 +470,39 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
ui.post {
pairBusy = null
pairPercent = -1
result.onSuccess { (displayId, linuxId) ->
result.onSuccess { (pairDisplayId, linuxId) ->
if (!select) {
android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_pair_updated, pair.name), android.widget.Toast.LENGTH_LONG).show()
return@onSuccess
}
if (auto && SessionState.running) {
lastAutoCheck = 0L
autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
return@onSuccess
}
// A Mali pair under Auto: the compositor draws on the phone's own Mali driver
// (dma-buf, modifiers and AHB all work there) and the guest runs the pair's
// PanVK. Its Android half stays installed for a manual pick.
// The same when the pair is picked by hand: a PanVK Android half on the display
// stalls Mali gralloc ("Waiting for Steam's first frame"); it stays a manual pick
// under "Runtime and display drivers separately".
val displayId = if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) TurnipDriver.AUTO else pairDisplayId
val previousDisplay = SessionPrefs.androidDriver(activity)
val previousLinux = SessionPrefs.linuxDriver(activity)
val displayChanged = previousDisplay != displayId
SessionPrefs.setAndroidDriver(activity, displayId)
SessionPrefs.setLinuxDriver(activity, linuxId)
// A route Auto switched on in place of a missing pair goes off now that one is
// here. A Mali bridge or Venus switch the user set stays: it wins for the session
// (DeviceSupport.vkBridge, VenusComponent.wanted) and the pair waits.
if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) endMaliFallback()
val restart = displayChanged && CompositorHost.isStarted
if (auto) {
val trial = AutoDriverTrial.current(activity)
val lastGood = trial?.let { setOf(it.previousDisplay, it.previousLinux) } ?: setOf(previousDisplay, previousLinux)
val changed = previousDisplay != displayId || previousLinux != linuxId
SessionPrefs.setGpuAutoInstalled(activity, SessionPrefs.gpuAutoInstalled(activity) + setOf(displayId, linuxId))
// A Mali pair's display is the phone's own driver (AUTO): not a download to own or prune.
SessionPrefs.setGpuAutoInstalled(activity, SessionPrefs.gpuAutoInstalled(activity) + setOf(displayId, linuxId).filter { it.isNotEmpty() && it != TurnipDriver.AUTO })
if (changed) AutoDriverTrial.begin(
activity, AutoDriverTrial.release(pair), "${pair.name} ${pair.version}", displayId, linuxId,
trial?.previousDisplay ?: previousDisplay, trial?.previousLinux ?: previousLinux,
@@ -366,6 +530,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private fun installedBundle(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
TurnipReleases.installedId(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
private fun installedBundleAnyBuild(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
TurnipReleases.installedIdAnyBuild(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
private fun installedIdOf(asset: TurnipReleases.Asset): String? = when {
asset.bundle -> installedBundle(asset)?.id
asset.linux -> TurnipReleases.installedId(activity, asset, LinuxVulkanDriverManager(activity)::isInstalled)
@@ -163,6 +163,8 @@ class FrontEndActivity : ComponentActivity() {
private var tuSysmem by mutableStateOf(false)
private var zinkLazy by mutableStateOf(false)
private var vkBridge by mutableStateOf(false)
private var venus by mutableStateOf(false)
private var venusHostVulkan by mutableStateOf<String?>(null)
private var vkBridgeSafe by mutableStateOf(true)
private var bridgeProtonDxvk by mutableStateOf(false)
private val adrenoGpu by lazy { com.droiddeck.launcher.core.DeviceSupport.adreno() }
@@ -197,6 +199,7 @@ class FrontEndActivity : ComponentActivity() {
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf<String?>(null)
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
@@ -208,6 +211,7 @@ class FrontEndActivity : ComponentActivity() {
private var wifiDiscoveryBlocked by mutableStateOf(false)
private var integrationState by mutableStateOf(SteamIntegration.State())
private var integrationFocus by mutableStateOf<SteamIntegration.Feature?>(null)
private var pendingSessionLogExport: File? = null
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
refreshWifiDiscovery()
@@ -266,6 +270,26 @@ class FrontEndActivity : ComponentActivity() {
val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
}
private val pickSessionLogExport = registerForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri ->
val folder = pendingSessionLogExport.also { pendingSessionLogExport = null } ?: return@registerForActivityResult
if (uri != null) {
SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) {
android.widget.Toast.makeText(this, R.string.setup_log_export_failed, android.widget.Toast.LENGTH_LONG).show()
} else Thread({
val saved = runCatching {
contentResolver.openOutputStream(uri)?.use { output -> zip.inputStream().buffered().use { it.copyTo(output) } }
?: error("Could not open destination")
}.isSuccess
ui.post {
android.widget.Toast.makeText(this,
if (saved) R.string.setup_log_export_saved else R.string.setup_log_export_failed,
android.widget.Toast.LENGTH_LONG).show()
}
}, "save-session-logs").start()
}
}
}
private fun refreshWifiDiscovery() {
wifiDiscoveryPermission = WifiDiscovery.permissionGranted(this)
@@ -410,6 +434,27 @@ class FrontEndActivity : ComponentActivity() {
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_saves_pick_zip, name), GameSaves.savesDir().parentFile?.parentFile?.path))
}
private fun importAddons(name: String, target: com.droiddeck.launcher.runtime.WowAddons.Target) {
if (SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_addons_close_session, android.widget.Toast.LENGTH_LONG).show()
return
}
onSavePicked = { zip ->
saveAction(getString(R.string.main_addons_importing, name)) {
if (SessionState.running) return@saveAction getString(R.string.main_addons_close_session)
val imported = try {
com.droiddeck.launcher.runtime.WowAddons.import(zip, target)
} catch (_: com.droiddeck.launcher.runtime.WowAddons.TooLarge) {
return@saveAction getString(R.string.main_addons_too_large, zip.name)
}
if (imported.isEmpty()) getString(R.string.main_addons_none, zip.name)
else resources.getQuantityString(R.plurals.main_addons_imported, imported.size, imported.size, target.flavor)
}
}
val downloads = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_addons_pick_zip, name), downloads))
}
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
onSavePicked = { dir ->
saveAction(getString(R.string.main_saves_exporting, name)) {
@@ -533,10 +578,15 @@ class FrontEndActivity : ComponentActivity() {
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
private var runningLabel by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true)
private var enhancedDiagnosticsArmed by mutableStateOf(false)
private var gameDebugLogsEnabled by mutableStateOf(false)
private var gameDebugLogsNeedsRestart by mutableStateOf(false)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
private var graphicsLogs by mutableStateOf(false)
private var steamGpuDrawing by mutableStateOf(false)
private var bridgeFellBack by mutableStateOf(false)
private var bridgeFellBackMemory by mutableStateOf(false)
private var clearCachedApps by mutableStateOf(false)
private var adbPaired by mutableStateOf(false)
private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF)
@@ -1026,6 +1076,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
if (savedInstanceState == null) readIntegrationIntent(intent)
@@ -1083,7 +1134,7 @@ class FrontEndActivity : ComponentActivity() {
FrontEndScreen(
FrontEndState(
installed = installed, ready = ready, available = available?.version, removalPending = removalPending, runtimeActionsBlocked = runtimeChangesBlocked(),
vkBridge = vkBridge, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
vkBridge = vkBridge, venus = venus, venusHostVulkan = venusHostVulkan, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
shortcutPicker = shortcutPicker,
shortcutLibraryScanning = shortcutLibraryScanning,
gameSyncFolder = gameSyncFolder,
@@ -1091,8 +1142,10 @@ class FrontEndActivity : ComponentActivity() {
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
graphicsLogs = graphicsLogs, steamGpuDrawing = steamGpuDrawing, bridgeFellBack = bridgeFellBack, bridgeFellBackMemory = bridgeFellBackMemory,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this),
@@ -1162,8 +1215,13 @@ class FrontEndActivity : ComponentActivity() {
onSteamGame = { g ->
if (shortcutPicker) chooseGameShortcut(g)
else {
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
val request = gameLaunchRequest.incrementAndGet()
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g) {
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) return@beforeLaunch
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
}
}
}
},
onEpicLauncher = { openEpicLauncher() },
@@ -1233,9 +1291,18 @@ class FrontEndActivity : ComponentActivity() {
onRemovePackage = { id -> removePackage(id) },
onRuntime = { onRuntimeButton() },
onVkBridge = { on ->
SessionPrefs.setVkBridge(this, on); vkBridge = on
SessionPrefs.setVkBridge(this, on); SessionPrefs.setMaliFallbackByAuto(this, ""); vkBridge = on
if (!on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
},
onVenus = { on ->
SessionPrefs.setVenus(this, on)
SessionPrefs.setMaliFallbackByAuto(this, "")
venus = on
if (on && !com.droiddeck.launcher.core.DeviceSupport.adreno()) Thread({
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
runOnUiThread { venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this) }
}, "venus-host-vulkan").start()
},
onVkBridgeSafe = { on -> SessionPrefs.setVkBridgeSafe(this, on); vkBridgeSafe = on },
onBridgeProtonDxvk = { on ->
SessionPrefs.setBridgeProtonDxvk(this, on); bridgeProtonDxvk = on
@@ -1253,6 +1320,13 @@ class FrontEndActivity : ComponentActivity() {
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onAddonImport = { sg, target -> importAddons(sg.name, target) },
onAddonDelete = { target, name ->
saveAction(getString(R.string.main_addons_deleting, name)) {
com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
getString(R.string.main_addons_deleted, name)
}
},
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
onRoms = { showRoms = true },
@@ -1270,6 +1344,15 @@ class FrontEndActivity : ComponentActivity() {
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onEnhancedDiagnostics = {
val requested = !com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
if (!com.droiddeck.launcher.session.EnhancedDiagnostics.setArmed(this, requested)) {
android.widget.Toast.makeText(
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
).show()
}
enhancedDiagnosticsArmed = com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
},
onGameDebugLogs = {
val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this))
if (!changed) android.widget.Toast.makeText(
@@ -1278,6 +1361,14 @@ class FrontEndActivity : ComponentActivity() {
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onSteamGpuDrawing = {
SessionPrefs.setSteamGpuCompositing(this, !SessionPrefs.steamGpuCompositing(this))
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
},
onGraphicsLogs = {
SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this))
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
},
onVacDiagnostics = {
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
@@ -1293,11 +1384,40 @@ class FrontEndActivity : ComponentActivity() {
if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
},
onShareLogs = {
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
val folder = SessionLogShare.latest(this)
if (folder == null) {
android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
} else if (com.droiddeck.launcher.session.EnhancedDiagnostics.isActive(this, folder)) {
SessionLogShare.prepareEnhanced(this, { folder }) { zips ->
if (zips.isEmpty()) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else shareEnhancedArchives(zips)
}
} else {
SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else startActivity(SessionLogShare.shareIntent(this, zip))
}
}
},
onShareSessionLog = { folder ->
SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else startActivity(SessionLogShare.shareIntent(this, zip))
}
},
onSaveSessionLog = { folder ->
pendingSessionLogExport = folder
pickSessionLogExport.launch("DroidDeck-${folder.name}.zip")
},
onDeleteSessionLog = { folder, done ->
Thread({
val deleted = runCatching { SessionLogShare.deleteSession(this, folder) }.getOrDefault(false)
ui.post {
if (!deleted) android.widget.Toast.makeText(this, R.string.setup_log_delete_failed, android.widget.Toast.LENGTH_SHORT).show()
done()
}
}, "delete-session-logs").start()
},
onClearLogs = {
Thread({
val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0)
@@ -1468,6 +1588,7 @@ class FrontEndActivity : ComponentActivity() {
onStickClick = { on -> ControllerPrefs.setStickClick(this, on); refreshController() },
onAdaptiveSticks = { on -> ControllerPrefs.setAdaptiveSticks(this, on); refreshController() },
onRumble = { on -> ControllerPrefs.setRumble(this, on); refreshController() },
onDeadZone = { v -> ControllerPrefs.setDeadZone(this, v); refreshController() },
onSteamButton = { on -> ControllerPrefs.setSteamButton(this, on); refreshController() },
onQamButton = { on -> ControllerPrefs.setQamButton(this, on); refreshController() },
onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() },
@@ -1585,6 +1706,9 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.frontend.GamesFolderMigration.run(this)
SessionLogShare.clear(this)
SessionArtifacts.finishAbandoned(this)
if (SessionPrefs.takeMemoryKillNotice(this)) runOnUiThread {
android.widget.Toast.makeText(this, R.string.session_killed_for_memory, android.widget.Toast.LENGTH_LONG).show()
}
SessionArtifacts.scrubOlder(this)
SessionArtifacts.prune(this)
}, "finish-abandoned").start()
@@ -1802,6 +1926,7 @@ class FrontEndActivity : ComponentActivity() {
super.onSaveInstanceState(outState)
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
@@ -1816,6 +1941,7 @@ class FrontEndActivity : ComponentActivity() {
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
super.onDestroy()
@@ -2030,6 +2156,7 @@ class FrontEndActivity : ComponentActivity() {
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
onAuto = { on -> drivers.setMode(on) },
onPair = { key -> drivers.selectPair(key) },
onPairUpdate = { key -> drivers.updatePair(key) },
onRefresh = { if (drivers.mode == SessionPrefs.GPU_DRIVERS_AUTO) drivers.ensureAuto(force = true) else drivers.checkLatestTurnip() },
onSelectLinux = { id -> drivers.selectDriver(id, linux = true) },
onSelectAndroid = { id -> drivers.selectDriver(id, linux = false) },
@@ -2580,6 +2707,8 @@ class FrontEndActivity : ComponentActivity() {
tuSysmem = SessionPrefs.tuSysmem(this)
zinkLazy = SessionPrefs.zinkLazy(this)
vkBridge = SessionPrefs.vkBridge(this)
venus = SessionPrefs.venus(this)
venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
noXalia = SessionPrefs.noXalia(this)
@@ -2602,6 +2731,32 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) &&
!SessionPaths.currentSessionLogsRetained(this)
private fun shareEnhancedArchives(zips: List<java.io.File>) {
if (isFinishing || isDestroyed) return
val choices = zips.map { zip ->
val label = when {
zip.name.endsWith("-session.zip") -> getString(R.string.diagnostics_share_session)
zip.name.endsWith("-graphics.zip") -> getString(R.string.diagnostics_share_graphics)
else -> getString(R.string.diagnostics_share_games)
}
label to listOf(zip)
} + (getString(R.string.diagnostics_share_all) to zips)
android.app.AlertDialog.Builder(this)
.setTitle(R.string.diagnostics_share_title)
.setItems(choices.map { it.first }.toTypedArray()) { _, which ->
val selected = choices[which].second
runCatching {
startActivity(if (selected.size == 1) SessionLogShare.shareIntent(this, selected.single())
else SessionLogShare.shareEnhancedIntent(this, selected))
}.onFailure {
android.util.Log.w("SessionLogShare", "could not share latest session logs", it)
android.widget.Toast.makeText(this, R.string.session_logs_share_failed, android.widget.Toast.LENGTH_LONG).show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun refresh() {
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
if (listX64 != steamGamesX64) {
@@ -2626,10 +2781,15 @@ class FrontEndActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
enhancedDiagnosticsArmed = com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
bridgeFellBack = SessionPrefs.bridgeFellBack(this)
bridgeFellBackMemory = SessionPrefs.bridgeFellBackForMemory(this)
clearCachedApps = SessionPrefs.clearCachedApps(this)
adbPaired = WirelessAdbFix.hasSavedPairing(this)
memoryHud = SessionPrefs.memoryHud(this)
@@ -2867,6 +3027,7 @@ class FrontEndActivity : ComponentActivity() {
companion object {
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
private const val KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export"
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
@@ -96,6 +96,7 @@ import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold
import com.droiddeck.launcher.input.GestureTouchStreamGate
import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.PointerSpace
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
import com.droiddeck.launcher.input.SecondScreenMode
@@ -207,6 +208,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private val guestKeysDown = mutableSetOf<Int>()
private val guestButtonsDown = mutableMapOf<Int, Boolean>()
private lateinit var surfaceView: SurfaceView
private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState
@@ -374,6 +376,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onCancel = { padBridge?.cancelBackQam() },
holds = { backHold },
)
private val mouseBackInput = com.droiddeck.launcher.input.MouseBackInput(
sendRight = { down -> heldButtons.set(32, PointerGestures.BTN_RIGHT, down) },
mouseAttached = ::mouseAttached,
)
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
private var drawerDirectionDownTime = 0L
private var drawerDirectionDeviceId = -1
@@ -628,6 +634,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "input device $deviceId disconnected")
dropMouseCursor()
backQamInput.onDeviceRemoved(deviceId)
mouseBackInput.onDeviceRemoved(deviceId)
joyConVr?.refresh()
physicalInputBindings?.disconnected(deviceId)
padBridge?.onDeviceRemoved(deviceId)
@@ -708,7 +715,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchPointerCaptureChanged(hasCapture: Boolean) {
super.dispatchPointerCaptureChanged(hasCapture)
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
if (!hasCapture) uiHandler.postDelayed(::updatePointerCapture, 250)
if (!hasCapture) {
releaseHeldGuestInput()
uiHandler.postDelayed(::updatePointerCapture, 250)
}
}
}
sessionRoot = root
@@ -720,6 +730,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
bridge.setStickDeadZone(ControllerPrefs.deadZone(this))
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
padBridge = bridge
inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it) }
@@ -775,6 +786,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
.also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener, directTouchSink)
touchSlop = PointerGestures.slop(this)
threeFingerTap = com.droiddeck.launcher.input.ThreeFingerTap(PointerGestures.slop(this) * 2)
twoFingerGestures = com.droiddeck.launcher.input.TwoFingerGestures(PointerGestures.slop(this) * 2,
object : com.droiddeck.launcher.input.TwoFingerGestures.Listener {
@@ -1248,6 +1260,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionDrawer(drawerOpen || (docked && drawerPinned), drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, docked = docked,
backRequest = drawerBackRequests, onLayerChange = { drawerLayerOpen = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM,
systemPowerVr = com.droiddeck.launcher.gpu.SystemVulkanDriver.usesDefault(
SessionPrefs.linuxDriver(this@SessionActivity)),
direct = noSteamSession(),
title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
@@ -1918,7 +1932,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Toast.makeText(this, R.string.session_no_logs, Toast.LENGTH_LONG).show()
return
}
SessionLogShare.prepare(this, { folder }) { zip ->
if (com.droiddeck.launcher.session.EnhancedDiagnostics.isActive(this, folder)) {
SessionLogShare.prepareEnhanced(this, { folder }) { zips ->
if (zips.isEmpty()) {
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
} else runCatching { shareEnhancedArchives(zips) }
.onFailure {
Log.w(TAG, "could not share current session logs", it)
Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show()
}
}
} else SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) {
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
} else {
@@ -1931,6 +1955,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private fun shareEnhancedArchives(zips: List<File>) {
val choices = zips.map { zip ->
val label = when {
zip.name.endsWith("-session.zip") -> getString(R.string.diagnostics_share_session)
zip.name.endsWith("-graphics.zip") -> getString(R.string.diagnostics_share_graphics)
else -> getString(R.string.diagnostics_share_games)
}
label to listOf(zip)
} + (getString(R.string.diagnostics_share_all) to zips)
android.app.AlertDialog.Builder(this)
.setTitle(R.string.diagnostics_share_title)
.setItems(choices.map { it.first }.toTypedArray()) { _, which ->
val selected = choices[which].second
runCatching {
startActivity(if (selected.size == 1) SessionLogShare.shareIntent(this, selected.single())
else SessionLogShare.shareEnhancedIntent(this, selected))
}.onFailure {
Log.w(TAG, "could not share current session logs", it)
Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -2260,7 +2309,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
if (width <= 0 || height <= 0) return null
if (isInPictureInPictureMode) return com.droiddeck.launcher.session.PipPolicy.outputSize(
width, height, SessionState.outputSize.first, SessionState.outputSize.second)
if (bottomGame != null) return when {
SessionState.followScreen ->
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, false, SessionState.followScale)
@@ -2466,10 +2517,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = true)
updateGlassesScreen()
updateHeadTracker()
if (status == 0) {
Thread({
val hint = sessionExitHint(status)
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
SessionState.relaunch?.let { next ->
if (status == 0) SessionState.relaunch?.let { next ->
SessionState.relaunch = null
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
@@ -2477,14 +2529,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
recreate()
return@runOnUiThread
}
finish()
}
return
}
Thread({
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
showEnded(status, hint)
}
}, "session-end-hint").start()
@@ -2549,13 +2593,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true)
}
private fun presentationFault(): String? {
runCatching { com.droiddeck.launcher.wayland.WaylandCompositor.compositorFault() }.getOrNull()
?.takeIf { it.isNotEmpty() }?.let { return it }
val waylandLog = SessionState.logDirectory?.let { File(it, "wayland.log") }?.takeIf { it.isFile } ?: return null
return try {
java.io.RandomAccessFile(waylandLog, "r").use { f ->
val start = maxOf(0L, waylandLog.length() - 256L * 1024)
f.seek(start)
val bytes = ByteArray((waylandLog.length() - start).toInt())
f.readFully(bytes)
var fault: String? = null
String(bytes, Charsets.ISO_8859_1).lineSequence().forEach { line ->
val i = line.indexOf("DD_PRESENT_FAULT: ")
if (i >= 0) fault = line.substring(i + 18).trim().ifEmpty { null }
else if (line.contains("presentation recovered: fault cleared")) fault = null
}
fault
}
} catch (_: Exception) {
null
}
}
private fun prootFailureHint(): EndHint? {
if (SessionState.failureCode != "PROOT_MISSING") return null
val message = SessionState.failureMessage ?: return null
return EndHint(message)
}
private fun presentationFaultHint(): EndHint? = presentationFault()?.let {
EndHint(getString(R.string.session_end_present_fault, it), evenOnSuccess = true)
}
private fun sessionExitHint(status: Int): EndHint? = if (status == 0) presentationFaultHint()
else runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
private fun sessionEndHint(log: File?): EndHint? {
presentationFaultHint()?.let { return it }
if (log == null || !log.isFile) return null
return try {
var enosys = 0
@@ -2582,8 +2657,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val fallback = if (SessionState.steamClientArch == "arm64") getString(R.string.session_end_steam_try_x64) else null
EndHint(listOfNotNull(message, fallback).joinToString("\n"))
} else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.VULKAN_DEVICE_MISSING) {
val adreno = com.droiddeck.launcher.gpu.GpuInfo.detect().family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO
EndHint(getString(if (adreno) R.string.session_end_vulkan_device else R.string.session_end_gpu_unsupported))
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
val family = gpu.family
val adreno = family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO &&
family != com.droiddeck.launcher.gpu.GpuInfo.Family.POWERVR && !family.mali
val message = getString(R.string.session_end_vulkan_device)
EndHint(if (adreno) message else "${gpu.name} (${family.label(gpu.name)})\n$message")
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
@@ -2638,6 +2717,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}) return true
}
if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
Log.i(TAG, String.format(java.util.Locale.ROOT, "back key device=%d (%s) source=0x%x flags=0x%x",
event.deviceId, event.device?.name, event.source, event.flags))
}
val mouseToGuest = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen &&
!SessionState.suspended && !(::loading.isInitialized && (loading.visible || loading.ended))
if (mouseBackInput.onKeyEvent(event, mouseToGuest)) return true
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
@@ -2985,7 +3071,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val gestureOutput = object : TouchscreenGestures.Output {
override fun moveTo(x: Float, y: Float) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
if (pointerLocked) {
if (gesturePointerReady) moveBy(x - gesturePointerX, y - gesturePointerY, true)
} else movePointer(x, y)
@@ -2995,7 +3081,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cursorVisible = false
}
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {
val rect = drawnRect() ?: return
val rect = (if (pointerLocked) drawnRect() else pointerSurfaceRect()) ?: return
if (relative || pointerLocked) {
val scale = sceneScale(rect)
sendSceneDelta(dx * scale, dy * scale)
@@ -3006,7 +3092,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun prepareRelativePan() {
if (pointerLocked) return
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
moveTo(rect.centerX(), rect.centerY())
}
override fun key(code: Int, down: Boolean) {
@@ -3050,7 +3136,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val scrollListener = object : ScrollTouchGestures.Listener {
override fun onMove(x: Float, y: Float) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
@@ -3060,7 +3146,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
heldButtons.set(1, button, pressed)
}
override fun onScroll(dx: Float, dy: Float) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val out = SessionState.outputSize
scrollRestX += dx * out.first / rect.width()
scrollRestY += dy * out.second / rect.height()
@@ -3079,7 +3165,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onScrollStart() {
scrollRestX = 0f
scrollRestY = 0f
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val x = rect.left + rect.width() * PAD_SCROLL_POINTER_X
WaylandCompositor.nativeSendPointer(1, InputSpace.x(x, outputView().width), InputSpace.y(rect.centerY(), outputView().height))
cursorVisible = false
@@ -3092,7 +3178,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onNavigate() {
cursorVisible = false
}
override fun scrollSpeed(): Float = (drawnRect()?.height() ?: 0f) * PAD_SCROLL_HEIGHTS_PER_S
override fun scrollSpeed(): Float = (pointerSurfaceRect()?.height() ?: 0f) * PAD_SCROLL_HEIGHTS_PER_S
}
private fun padMouseMode(): Boolean {
@@ -3115,7 +3201,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
(routedTouchMode == SessionPrefs.TOUCH_AUTO || routedTouchMode == SessionPrefs.TOUCH_DIRECT) && padMouseMode()
private fun fingerScroll(dx: Float, dy: Float) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val out = SessionState.outputSize
scrollRestX += dx * out.first / rect.width() * AXIS_UNITS_PER_PIXEL
scrollRestY += dy * out.second / rect.height() * AXIS_UNITS_PER_PIXEL
@@ -3138,7 +3224,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * outputView().width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * outputView().height
if (rect.contains(x, y)) touchpad.place(x, y)
touchpad.place(x.coerceIn(rect.left, rect.right), y.coerceIn(rect.top, rect.bottom))
}
private fun moveLockedPointer(x: Float, y: Float) {
@@ -3150,7 +3236,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun movePointer(x: Float, y: Float, fromMouse: Boolean = false) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
@@ -3555,7 +3641,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (width <= 0f || height <= 0f) return
val nx = (x / width).coerceIn(0f, 1f)
val ny = (y / height).coerceIn(0f, 1f)
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val px = rect.left + nx * rect.width()
val py = rect.top + ny * rect.height()
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, outputView().width), InputSpace.y(py, outputView().height))
@@ -3703,7 +3789,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun sendSceneButton(code: Int, down: Boolean) {
val writer = if (evdevMouseActive) mouseWriter else null
val raw = if (down) evdevMouseActive.also { guestButtonsDown[code] = it }
else guestButtonsDown.remove(code) ?: evdevMouseActive
val writer = if (raw) mouseWriter else null
if (writer != null) writer.writeMouseButton(code.toShort(), down)
else WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0)
}
@@ -3741,10 +3829,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return android.graphics.RectF(left, top, left + drawnW, top + drawnH)
}
/**
* Where the pointer can travel on this view. With the glasses owning the output the view is
* not showing the picture, so the whole view is the touchpad; using the letterboxed picture
* rect there would leave the pointer unable to reach the scene edges.
*/
private fun pointerSurfaceRect(): android.graphics.RectF? {
val view = outputView()
return PointerSpace.area(view.width, view.height, glassesOutputActive, drawnRect())
}
private var ignoreGameTouch = false
private var lockedTouchTurns = false
private var touchEditorOpen by mutableStateOf(false)
private var lockedSwipeUsed = false
private var touchSlop = 0f
private var lockedSwipeX = 0f
private var lockedSwipeY = 0f
private var dismissTouch = false
@@ -3789,15 +3887,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
com.droiddeck.launcher.input.TouchRouter.Route.SCROLL -> scrollTouch.onTouch(event)
else -> {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
val inPicture = drawnRect()?.let { !topPictureMapped || it.contains(event.x, event.y) } ?: false
lockedTouchTurns = programLocksPointer() && inPicture && route != com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD
}
if (com.droiddeck.launcher.input.TouchRouter.steamKeyboardZone(snapshot)) {
val wasActive = threeFingerTap.active
if (threeFingerTap.onTouch(event)) padBridge?.triggerSteamKeyboard()
if (threeFingerTap.active && !wasActive) {
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD || lockedTouchTurns) touchpad.cancel()
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD) touchpad.cancel()
else {
directTouchHold.cancel()
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
@@ -3805,8 +3899,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
if (threeFingerTap.active || wasActive) return true
}
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD || lockedTouchTurns) {
val rect = drawnRect() ?: return false
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD) {
val rect = (if (pointerLocked) drawnRect() else pointerSurfaceRect()) ?: return false
if (touchpad.bounds != rect) {
val fresh = touchpad.bounds.width() <= 1f
touchpad.bounds = rect
@@ -3859,8 +3953,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun forwardTouch(event: MotionEvent, rect: android.graphics.RectF): Boolean {
val swipeX = lockedSwipeX
val swipeY = lockedSwipeY
lockedSwipeX = event.x
lockedSwipeY = event.y
if (programLocksPointer() && event.actionMasked == MotionEvent.ACTION_MOVE && !lockedSwipeUsed &&
abs(event.x - swipeX) <= touchSlop && abs(event.y - swipeY) <= touchSlop) return true
val anchor = if (event.actionMasked == MotionEvent.ACTION_POINTER_UP && event.actionIndex == 0 && event.pointerCount > 1) 1 else 0
lockedSwipeX = event.getX(anchor)
lockedSwipeY = event.getY(anchor)
if ((event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) && lockedSwipeUsed) {
lockedSwipeUsed = false
directTouchHold.cancel()
@@ -3892,14 +3989,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y, fromMouse = true)
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y, fromMouse = true)
val button = when (event.actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
MotionEvent.BUTTON_BACK -> BTN_SIDE
MotionEvent.BUTTON_FORWARD -> BTN_EXTRA
else -> PointerGestures.BTN_LEFT
}
heldButtons.set(8, button, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS)
guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
@@ -3914,7 +4004,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun isHardwareMouse(d: InputDevice?): Boolean =
d != null && !d.isVirtual && (d.supportsSource(InputDevice.SOURCE_MOUSE) || d.supportsSource(InputDevice.SOURCE_MOUSE_RELATIVE))
private fun mouseAttached(): Boolean = InputDevice.getDeviceIds().any { isHardwareMouse(InputDevice.getDevice(it)) }
/** Android also sends the Back and Forward buttons as key events, so they are handled as keys. */
private fun guestMouseButton(actionButton: Int): Int? = when (actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
MotionEvent.BUTTON_BACK, MotionEvent.BUTTON_FORWARD -> null
else -> PointerGestures.BTN_LEFT
}
private fun mouseAttached(): Boolean = InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
isHardwareMouse(d) && d?.supportsSource(InputDevice.SOURCE_TOUCHPAD) != true
}
private fun relativeMouseAttached(): Boolean = !isInMultiWindowMode && !glassesOutputActive && InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
@@ -4012,14 +4113,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
moveCapturedMouse(dx, dy)
}
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
val button = when (event.actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
else -> PointerGestures.BTN_LEFT
}
heldButtons.set(8, button, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS)
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE ->
guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) sendSceneWheel(-Math.round(v))
@@ -4205,6 +4300,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun keyboardCoversPad() =
SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard
private fun releaseHeldGuestInput() {
mouseBackInput.cancel()
heldButtons.release(1 or 2 or 8 or 16)
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
heldKeys.release(8)
}
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
@@ -4426,6 +4528,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this))
refreshSecondScreenDisplays()
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
joyConVr?.refresh()
@@ -4460,6 +4563,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (runtimeRemovalBlocked) { super.onPause(); return }
physicalShortcuts.clear()
backQamInput.cancel()
mouseBackInput.cancel()
capturePausedFrame()
padBridge?.setInputEnabled(false)
sessionClipboard.stop()
@@ -5033,11 +5137,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
if (!hasFocus) backQamInput.cancel()
if (!hasFocus) mouseBackInput.cancel()
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
if (runtimeRemovalBlocked) return
if (!hasFocus) {
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
releaseHeldGuestInput()
}
if (hasFocus && !pipUi) {
goFullscreen()
@@ -18,12 +18,15 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.nio.file.Files
import java.util.UUID
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@@ -93,6 +96,7 @@ class AgentBridgeProvider : ContentProvider() {
}
"prefs" -> prefs(context, request)
"glasses" -> glasses(context, request)
"logs" -> logs(context)
"access" -> JSONObject().put("ok", true).put("commands", AgentAccess.commandsAllowed(context))
.put("debugBuild", BuildConfig.DEBUG).put("inbox", AgentEnv.inbox(context).absolutePath)
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
@@ -197,9 +201,46 @@ class AgentBridgeProvider : ContentProvider() {
private fun hex(text: String, max: Int): Int? =
text.removePrefix("0x").removePrefix("0X").takeIf { it.isNotEmpty() }?.toIntOrNull(16)?.takeIf { it in 0..max }
private fun logDir(context: Context): File? =
SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
private fun cleanupExpiredLogExports(exports: File) {
val now = System.currentTimeMillis()
val canonicalRoot = exports.canonicalFile
exports.listFiles()?.forEach { candidate ->
val isUuid = runCatching { UUID.fromString(candidate.name).toString() == candidate.name }.getOrDefault(false)
if (!isUuid || !candidate.isDirectory || Files.isSymbolicLink(candidate.toPath())) return@forEach
if (candidate.canonicalFile.parentFile != canonicalRoot) return@forEach
if (now - candidate.lastModified() >= LOG_EXPORT_RETENTION_MS) candidate.deleteRecursively()
}
}
// The session folder is app-private, so adb pulls this copy from external files instead.
private fun logs(context: Context): JSONObject {
val dir = logDir(context)?.takeIf { it.isDirectory }
?: return error("NO_SESSION_LOGS", "No session artifact directory is available")
val externalFiles = context.getExternalFilesDir(null)
?: return error("NO_SESSION_LOGS", "External app storage is unavailable")
val exports = File(externalFiles, "agent-logs")
if ((!exports.exists() && !exports.mkdirs()) || !exports.isDirectory) {
return error("NO_SESSION_LOGS", "Could not create the session export directory")
}
cleanupExpiredLogExports(exports)
val output = File(exports, UUID.randomUUID().toString())
val zip = try {
SessionLogShare.zipFolder(context, dir, output)
} catch (error: Exception) {
output.deleteRecursively()
throw error
}
?: return error("NO_SESSION_LOGS", "The session artifact directory is empty")
return JSONObject().put("ok", true).put("command", "logs").put("sessionId", dir.name)
.put("zip", zip.absolutePath).put("cleanupDir", output.absolutePath)
}
private fun state(context: Context): JSONObject {
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
val dir = logDir(context)
val session = JSONObject()
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
.put("phase", SessionState.phase.name)
@@ -351,6 +392,7 @@ class AgentBridgeProvider : ContentProvider() {
const val RESULT_JSON = "json"
const val EXTRA_REQUEST = "request"
const val SCHEMA = 2
private const val LOG_EXPORT_RETENTION_MS = 24 * 60 * 60 * 1000L
private val recoveryComplete = CountDownLatch(1)
fun awaitRecovery() {
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.agent
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -143,9 +144,10 @@ object AgentInput {
val right = request.optString("stick", "left") == "right"
val x = request.optDouble("x", 0.0).toFloat().coerceIn(-1f, 1f)
val y = request.optDouble("y", 0.0).toFloat().coerceIn(-1f, 1f)
bridge.applyTouch { if (right) { it.rightX = x; it.rightY = y } else { it.leftX = x; it.leftY = y } }
val stickWrite = if (right) PadBridge.RIGHT_STICK else PadBridge.LEFT_STICK
bridge.applyTouch(stickWrite) { if (right) { it.rightX = x; it.rightY = y } else { it.leftX = x; it.leftY = y } }
hold(request, 300)
bridge.applyTouch { if (right) { it.rightX = 0f; it.rightY = 0f } else { it.leftX = 0f; it.leftY = 0f } }
bridge.applyTouch(stickWrite) { if (right) { it.rightX = 0f; it.rightY = 0f } else { it.leftX = 0f; it.leftY = 0f } }
return JSONObject().put("stick", if (right) "right" else "left")
}
@@ -130,22 +130,46 @@ public class PulseAudioComponent extends SessionPart {
private void ensureClientSink(java.io.PrintWriter out) {
try {
long deadline = System.currentTimeMillis() + 15000L;
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
// fallbacks are loaded here, after it is up, each pactl call bounded by its timeout.
long started = System.currentTimeMillis();
long deadline = started + 30000L;
String sinks = null;
boolean socketSeen = false;
while (System.currentTimeMillis() < deadline && pid > 1) {
if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
socketSeen |= socket().exists();
if (socketSeen && (sinks = pactl("list", "short", "sinks")) != null) break;
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
}
note(out, "client sink: daemon " + (sinks != null ? "answered" : "did not answer") + " after "
+ (System.currentTimeMillis() - started) + " ms (socket " + (socketSeen ? "present" : "never appeared") + ", pactl "
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + pid + ")");
String line;
if (sinks == null) {
line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
} else {
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "AAudioSink") != null;
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
// AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
// try DirectAudio again, then the plain sink, a few times over ten seconds.
String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && pid > 1; attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
if (pactl("load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "DirectAudio") != null) {
loadedAs = "DirectAudio on attempt " + attempt;
} else if (pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "AAudioSink") != null) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
}
}
line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
Log.w(TAG, line);
}
Log.i(TAG, line);
@@ -155,6 +179,14 @@ public class PulseAudioComponent extends SessionPart {
}
}
/** A timestamped line in the session's audio log. */
private void note(java.io.PrintWriter out, String what) {
String line = "== " + new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(new java.util.Date()) + " " + what;
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
}
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
private String pactl(String... args) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || pid <= 1) return null;
@@ -149,5 +149,8 @@ internal class AddonPack(
listOf("version", "comet"))
val BUTLER = AddonPack("butler", BuildConfig.PACK_BUTLER_SHA256, BuildConfig.PACK_BUTLER_SIZE,
listOf("version", "butler", "7z.so", "libc7zip.so"))
@JvmField
val POWERVR = AddonPack("powervr", BuildConfig.PACK_POWERVR_SHA256, BuildConfig.PACK_POWERVR_SIZE,
listOf("runtime.tzst", "version.txt"))
}
}
@@ -10,6 +10,8 @@ import android.os.PowerManager
import android.os.StatFs
import android.provider.Settings
import android.util.Log
import com.droiddeck.launcher.gpu.DeviceInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import android.view.Display
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
@@ -110,6 +112,7 @@ object DeviceReport {
runCatching {
val info = context.packageManager.getPackageInfo(context.packageName, 0)
k("Version", "${info.versionName} (${info.longVersionCode})")
k("App build", "${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
}
k("Package", context.packageName)
k("targetSdk", context.applicationInfo.targetSdkVersion)
@@ -186,7 +189,11 @@ object DeviceReport {
h("GPU")
k("KGSL gpu_model", readSys("/sys/class/kgsl/kgsl-3d0/gpu_model"))
k("KGSL chip id", readSys("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))
k("System Vulkan ICD", if (File("/vendor/lib64/hw/vulkan.adreno.so").exists()) "/vendor/lib64/hw/vulkan.adreno.so" else "not at the usual path")
k("System Vulkan ICD", when {
SystemVulkanDriver.isPowerVr() -> SystemVulkanDriver.hal()
File("/vendor/lib64/hw/vulkan.adreno.so").exists() -> "/vendor/lib64/hw/vulkan.adreno.so"
else -> "not at the usual path"
})
h("Display")
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
@@ -208,7 +215,7 @@ object DeviceReport {
h("Drivers")
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText(SessionPrefs.vkBridge(context))}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
k("GPU", "${gpu.name} · ${gpu.family.label(gpu.name)} · ${gpu.supportText(SessionPrefs.vkBridge(context))}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
if (gpu.model == 740) {
val hint = com.droiddeck.launcher.gpu.TpUbwcHint
k("TP UBWC hint", hint.forThisDevice(context) ?: "driver default")
@@ -221,19 +228,25 @@ object DeviceReport {
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)
k(" name / version", "${turnip.displayName(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)} ${turnip.driverVersion(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)}".trim())
val displayId = androidChoice.ifEmpty { turnip.autoId() }
val displayLabel = if (displayId == "system") DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = false)
else "${turnip.displayName(displayId)} ${turnip.driverVersion(displayId)}".trim()
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> $displayLabel" else androidChoice)
k(" name / version", displayLabel)
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
val lm = LinuxVulkanDriverManager(context)
run {
val id = SessionPrefs.linuxDriver(context)
val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
val label = if (id.isEmpty()) DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = true)
else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() +
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]"
if (lm.isInstalled(id)) "" else if (SystemVulkanDriver.isPowerVr()) " [MISSING - select an installed driver or Auto]"
else " [MISSING - falls back to the runtime's own]"
k("Linux driver", label)
}
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
else if (com.droiddeck.launcher.session.VenusComponent.available(context)) "available, off" else "not in this build")
h("Runtime")
k("Installed version", LinuxRuntimeInstaller.installedVersion(context))
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.core
import android.content.Context
import android.os.Build
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import java.io.File
object DeviceSupport {
@@ -10,16 +11,35 @@ object DeviceSupport {
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
}
private val maliGpu by lazy { !adrenoGpu && File("/dev/mali0").exists() }
fun adreno(): Boolean = adrenoGpu
fun mali(): Boolean = maliGpu
fun graphicsAvailable(): Boolean = graphicsAvailable(adreno(), SystemVulkanDriver.isAvailable())
internal fun graphicsAvailable(adreno: Boolean, powerVrReady: Boolean): Boolean = adreno || powerVrReady
fun vkBridge(context: Context): Boolean =
!adreno() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
bridgeUsable() && !com.droiddeck.launcher.session.VenusComponent.wanted(context) &&
com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
fun canDraw(context: Context): Boolean = adreno() || vkBridge(context)
fun mali(): Boolean = isMali
private val isMali by lazy {
!adreno() && (File("/dev/mali0").exists() ||
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
}
fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
fun openDriverActive(context: Context): Boolean {
if (adreno()) return false
if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) return false
if (bridgeUsable() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)) return false
val linux = com.droiddeck.launcher.session.SessionPrefs.linuxDriver(context).ifEmpty { return false }
return com.droiddeck.launcher.gpu.DriverPairs.isNonAdreno(com.droiddeck.launcher.gpu.DriverBundle.containing(context, linux, true)?.id)
}
fun canDraw(context: Context): Boolean = graphicsAvailable() || openDriverActive(context) || vkBridge(context) ||
com.droiddeck.launcher.session.VenusComponent.wanted(context)
fun gpuName(context: Context): String {
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
@@ -30,8 +30,6 @@ object GameEnvironment {
fun defaults(preset: String, forceSsbs: Boolean = false): Map<String, String?> = linkedMapOf<String, String?>(
"MESA_SHADER_CACHE_DISABLE" to "false",
"DROIDDECK_ANTICHEAT_OFFLINE" to "1",
"VKD3D_FEATURE_LEVEL" to "12_2",
"VKD3D_SHADER_MODEL" to "6_9",
"DOTNET_GCRegionRange" to "800000000",
"DOTNET_EnableWriteXorExecute" to "0",
).apply {
@@ -131,42 +131,81 @@ object LogRedactor {
@Volatile
private var accounts: List<Learned> = emptyList()
fun learnAccounts(vararg loginUsers: java.io.File) {
internal const val MAX_LEARN_INPUT_BYTES = 2 * 1024 * 1024
private const val MAX_LEARNED_ACCOUNTS = 2048
private const val MAX_LEARNED_ADDRESSES = 1024
private const val MAX_ACCOUNT_LENGTH = 256
private fun boundedText(file: java.io.File): String? = try {
file.inputStream().buffered().use { input ->
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(16 * 1024)
var remaining = MAX_LEARN_INPUT_BYTES
while (remaining > 0) {
val read = input.read(buffer, 0, minOf(buffer.size, remaining))
if (read < 0) return out.toString(Charsets.UTF_8.name())
if (read == 0) continue
out.write(buffer, 0, read)
remaining -= read
}
if (input.read() != -1) null else out.toString(Charsets.UTF_8.name())
}
} catch (_: Exception) {
null
}
fun learnAccounts(vararg loginUsers: java.io.File): Boolean {
val names = LinkedHashSet<String>()
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
var unread = false
for (file in loginUsers) {
if (!file.isFile) continue
val text = try { file.readText() } catch (e: Exception) { unread = true; continue }
kv.findAll(text).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.forEach { names += it }
val text = boundedText(file)
if (text == null) {
unread = true
continue
}
for (match in kv.findAll(text)) {
val name = match.groupValues[2].trim()
if (name.length < 3) continue
if (name.length > MAX_ACCOUNT_LENGTH || names.size >= MAX_LEARNED_ACCOUNTS) {
unread = true
break
}
names += name
}
}
val learned = names.map { name ->
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
}
accounts = if (unread) (accounts + learned).distinctBy { it.regex.pattern } else learned
accounts = if (unread) (learned + accounts).distinctBy { it.regex.pattern }.take(MAX_LEARNED_ACCOUNTS) else learned
return !unread
}
fun learnFromRuntime(root: java.io.File) {
learnOwnAddresses(java.io.File(root, "etc/droiddeck-net"))
learnAccounts(
fun learnFromRuntime(root: java.io.File): Boolean {
val addressesComplete = learnOwnAddresses(java.io.File(root, "etc/droiddeck-net"))
val accountsComplete = learnAccounts(
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
)
matchers.remove()
return addressesComplete && accountsComplete
}
@Volatile
private var own: List<Learned> = emptyList()
fun learnOwnAddresses(linkFile: java.io.File) {
fun learnOwnAddresses(linkFile: java.io.File): Boolean {
val found = ArrayList<Learned>()
try {
if (linkFile.isFile) linkFile.forEachLine { line ->
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
val text = if (linkFile.isFile) boundedText(linkFile) ?: return false else ""
text.lineSequence().forEach { line ->
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEach
if (found.size >= MAX_LEARNED_ADDRESSES) return false
when (kind(addr)) {
"public IPv6" -> {
val groups = expand6(addr)?.take(4) ?: return@forEachLine
val groups = expand6(addr)?.take(4) ?: return@forEach
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
found += Learned(
Regex("(?i)(?<![0-9A-Fa-f:])$prefix(?::[0-9A-Fa-f]{0,4}){1,4}(?:%[A-Za-z0-9_.]+)?"),
@@ -177,9 +216,10 @@ object LogRedactor {
}
}
} catch (e: Exception) {
return
return false
}
own = found
return true
}
fun kind(address: String): String? {
@@ -99,10 +99,11 @@ object AddedGames {
fun candidates(folder: File): List<File> = rank(folder).exes
fun rank(folder: File): GameExePicker.Ranking {
fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
val key = "${folder.path}|${folder.lastModified()}"
val now = System.currentTimeMillis()
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
if (reuse) kept?.rank(folder)?.let { return it }
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) }
val declared = declaredExes(folder)
val preferred = declared.map { it.path }.toSet()
@@ -114,23 +115,27 @@ object AddedGames {
)
if (ranked.size > 256) ranked.clear()
ranked[key] = now to result
kept?.keepRank(folder, result)
return result
}
private val ranked = java.util.concurrent.ConcurrentHashMap<String, Pair<Long, GameExePicker.Ranking>>()
private const val RANK_FRESH_MS = 60_000L
@Volatile private var kept: AddedGamesCache? = null
private val identified = java.util.concurrent.ConcurrentHashMap<String, String>()
internal fun identifiedName(folder: File, exe: File): String? {
val key = "${exe.path}|${exe.length()}|${exe.lastModified()}|${folder.lastModified()}"
identified[key]?.let { return it.ifEmpty { null } }
kept?.name(key)?.let { identified[key] = it; return it.ifEmpty { null } }
val id = runCatching { GameIdentifier.identify(exe) }.getOrNull()
val found = id?.name?.takeIf {
id.nameSource in setOf(GameIdentifier.Source.STEAM_MANIFEST_ACF, GameIdentifier.Source.GOG_INFO, GameIdentifier.Source.PE_VERSION)
}
val name = found?.let { if (id?.nameSource == GameIdentifier.Source.PE_VERSION) betterSpelling(underscoresToSpaces(it), folder.name) else it }
identified[key] = name.orEmpty()
kept?.keepName(key, name.orEmpty())
return name
}
@@ -172,17 +177,17 @@ object AddedGames {
"launcher", "game", "engine", "system", "data", "app",
)
internal fun groupGames(folder: File): List<File>? {
internal fun groupGames(folder: File, reuse: Boolean = false): List<File>? {
val files = folder.listFiles() ?: return null
if (files.any { it.isFile && it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) }) return null
if (declaredExes(folder).isNotEmpty()) return null
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") && !isSteamLibraryFolder(it.name) }.sortedBy { it.name.lowercase() }
if (dirs.any { it.name.lowercase() in GAME_PARTS || GameExePicker.auxiliaryDir(it) }) return null
return dirs.filter { rank(it).exes.isNotEmpty() }.takeIf { it.size >= 2 }
return dirs.filter { rank(it, reuse).exes.isNotEmpty() }.takeIf { it.size >= 2 }
}
private fun expand(folder: File, entries: Set<String>): List<File> =
if (folder.path in entries) listOf(folder) else groupGames(folder) ?: listOf(folder)
private fun expand(folder: File, entries: Set<String>, reuse: Boolean = false): List<File> =
if (folder.path in entries) listOf(folder) else groupGames(folder, reuse) ?: listOf(folder)
private fun entryFolders(context: Context): Set<String> = AddedExes.list(context).map { it.folder }.toSet()
@@ -192,7 +197,19 @@ object AddedGames {
internal fun isSteamLibraryFolder(name: String): Boolean =
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
fun scan(context: Context): List<Game> {
private val scanning = Any()
fun scan(context: Context): List<Game> = synchronized(scanning) {
val file = File(context.filesDir, AddedGamesCache.FILE)
val cache = kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
try {
scanAll(context)
} finally {
cache.save()
}
}
private fun scanAll(context: Context): List<Game> {
val out = ArrayList<Game>()
GamesFolderMigration.run(context)
val folders = listOfNotNull(
@@ -208,16 +225,16 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
for (game in expand(folder, entries)) if (game.path !in removed) scanGame(context, game, out)
for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
}
}
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
scanGame(context, folder, out, single = entry)
scanGame(context, folder, out, single = entry, reuse = true)
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
}
@@ -398,11 +415,11 @@ object AddedGames {
private val INSTALL_DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null) {
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null, reuse: Boolean = false) {
run {
val sidecar = StoreGameSidecar.read(folder)
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
val ranking = rank(folder)
val ranking = rank(folder, reuse)
val candidates = ranking.exes
val picked = SessionPrefs.addedGameExe(context, folder.path)
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
@@ -0,0 +1,87 @@
package com.droiddeck.launcher.frontend
import android.util.AtomicFile
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ConcurrentHashMap
internal class AddedGamesCache(val file: File) {
private class Rank(val modified: Long, val at: Long, val ranking: GameExePicker.Ranking)
private class Name(val name: String, val at: Long)
private val ranks = ConcurrentHashMap<String, Rank>()
private val names = ConcurrentHashMap<String, Name>()
@Volatile private var changed = false
init {
val json = runCatching { JSONObject(AtomicFile(file).readFully().toString(Charsets.UTF_8)) }.getOrNull()
json?.optJSONObject("ranks")?.let { all ->
for (path in all.keys()) runCatching {
val o = all.getJSONObject(path)
val exes = o.getJSONArray("exes")
val scores = o.getJSONArray("scores")
require(exes.length() > 0 && exes.length() == scores.length())
ranks[path] = Rank(o.getLong("modified"), o.getLong("at"), GameExePicker.Ranking(
List(exes.length()) { File(exes.getString(it)) }, List(scores.length()) { scores.getInt(it) }, o.optBoolean("uncertain"),
))
}
}
json?.optJSONObject("names")?.let { all ->
for (key in all.keys()) runCatching { all.getJSONObject(key).let { names[key] = Name(it.getString("name"), it.getLong("at")) } }
}
}
fun rank(folder: File): GameExePicker.Ranking? {
val kept = ranks[folder.path] ?: return null
val age = System.currentTimeMillis() - kept.at
val top = kept.ranking.exes.first()
return kept.ranking.takeIf { kept.modified == folder.lastModified() && age in 0 until KEEP_MS && top.isFile }
}
fun keepRank(folder: File, ranking: GameExePicker.Ranking) {
if (ranking.exes.isEmpty()) {
if (ranks.remove(folder.path) != null) changed = true
return
}
ranks[folder.path] = Rank(folder.lastModified(), System.currentTimeMillis(), ranking)
changed = true
}
fun name(key: String): String? = names[key]?.takeIf { System.currentTimeMillis() - it.at in 0 until KEEP_MS }?.name
fun keepName(key: String, name: String) {
names[key] = Name(name, System.currentTimeMillis())
changed = true
}
@Synchronized
fun save() {
if (!changed) return
changed = false
val oldest = System.currentTimeMillis() - KEEP_MS
val keptRanks = JSONObject()
ranks.forEach { (path, r) ->
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("at", r.at)
.put("exes", JSONArray(r.ranking.exes.map { it.path })).put("scores", JSONArray(r.ranking.scores))
.put("uncertain", r.ranking.uncertain))
}
val keptNames = JSONObject()
names.forEach { (key, n) -> if (n.at >= oldest) keptNames.put(key, JSONObject().put("name", n.name).put("at", n.at)) }
val atomic = AtomicFile(file)
var out: java.io.FileOutputStream? = null
try {
out = atomic.startWrite()
out.write(JSONObject().put("ranks", keptRanks).put("names", keptNames).toString().toByteArray())
atomic.finishWrite(out)
} catch (e: Exception) {
out?.let(atomic::failWrite)
changed = true
}
}
companion object {
const val FILE = "added-games-scan.json"
const val KEEP_MS = 7L * 24 * 3600 * 1000
}
}
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.frontend
import android.content.Context
import android.net.ConnectivityManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.util.AtomicFile
import android.util.Log
@@ -20,7 +22,11 @@ object AutoComponents {
private const val TAG = "AutoComponents"
fun appKey(game: Library.SteamGame): String? =
if (game.library == Library.ADDED) Integer.toUnsignedString(game.appId) else game.appId.takeIf { it > 0 }?.toString()
when {
game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> game.profileKey
game.library == Library.ADDED -> Integer.toUnsignedString(game.appId)
else -> game.appId.takeIf { it > 0 }?.toString()
}
fun autoPicks(findings: List<WinCompSources.Finding>, catalog: Map<String, WinComponents.Component>): Map<String, WinComponents.AutoReason> {
val out = LinkedHashMap<String, WinComponents.AutoReason>()
@@ -48,6 +54,8 @@ object AutoComponents {
val downloading = MutableStateFlow<Map<String, WinComponents.Progress>>(emptyMap())
val repairFailures = MutableStateFlow<Map<String, String>>(emptyMap())
val pendingGames = MutableStateFlow<Set<String>>(emptySet())
val pendingComponents = MutableStateFlow<Set<String>>(emptySet())
@@ -56,12 +64,12 @@ object AutoComponents {
if (job.pics != null) return
val flow = if (job.component != null) pendingComponents else pendingGames
val id = job.component ?: job.game?.let { appKey(it) } ?: return
flow.value = if (on) flow.value + id else flow.value - id
flow.value = if (on || job.component != null && job.key in queuedKeys) flow.value + id else flow.value - id
}
internal class Job(
val game: Library.SteamGame?, val component: String?, val asked: Boolean, val seq: Long, val pics: List<Int>? = null,
val inSession: Boolean = false,
val inSession: Boolean = false, val revision: Int? = null,
) {
val key get() = when {
pics != null -> "pics"
@@ -79,29 +87,45 @@ object AutoComponents {
@Volatile private var worker: Thread? = null
private const val PAUSE_MS = 15_000L
private fun waitFor(game: Library.SteamGame, id: String) {
val key = appKey(game) ?: return
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
}
fun queueGame(context: Context, game: Library.SteamGame, asked: Boolean) {
if (appKey(game) == null) return
enqueue(context, Job(game, null, asked, seq.incrementAndGet()))
}
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false) =
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession))
fun queueRepair(context: Context, id: String, gameKey: String?, revision: Int) {
if (!WinComponents.validId(id)) return
gameKey?.let { Pending.add(context, it, listOf(id), mapOf(id to revision)) }
queueDownload(context, id, asked = true, inSession = gameKey != null,
revision = maxOf(revision, Pending.revision(context, id) ?: 0))
}
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false, revision: Int? = null) =
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession, revision = revision))
private fun enqueue(context: Context, job: Job) {
if (!queuedKeys.add(job.key)) {
synchronized(jobs) {
val added = synchronized(jobs) {
if (!queuedKeys.add(job.key)) {
val old = jobs.firstOrNull { it.key == job.key }
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession)) && jobs.remove(old)) {
val revision = listOfNotNull(old?.revision, job.revision).maxOrNull()
val pics = listOfNotNull(old?.pics, job.pics).flatten().distinct().takeIf { old?.pics != null || job.pics != null }
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession) || revision != old.revision || pics != old.pics) && jobs.remove(old)) {
jobs.add(Job(old.game ?: job.game, old.component, old.asked || job.asked,
if (job.asked && !old.asked) job.seq else old.seq, old.pics ?: job.pics, old.inSession || job.inSession))
if (job.asked && !old.asked) job.seq else old.seq, pics,
old.inSession || job.inSession, revision))
}
}
if (runNow && !draining) drain(context)
return
false
} else {
jobs.add(job)
mark(job, true)
true
}.also { (jobs as java.lang.Object).notifyAll() }
}
if (job.component != null) Log.i(TAG, "wincomp: queued ${job.component}")
mark(job, true)
jobs.add(job)
if (added && job.component != null) Log.i(TAG, "wincomp: queued ${job.component}")
if (runNow) { if (!draining) drain(context) } else ensureWorker(context.applicationContext)
}
@@ -113,8 +137,15 @@ object AutoComponents {
private fun gameProcessRunning(): Boolean = com.droiddeck.launcher.session.SteamGameProcess.running()
private fun queuePending(context: Context, key: String) {
Pending.ids(context, key).forEach { id ->
queueDownload(context, id, asked = true, inSession = true, revision = Pending.revision(context, id))
}
}
fun queueInSession(context: Context, game: Library.SteamGame) {
if (appKey(game) == null) return
val key = appKey(game) ?: return
queuePending(context, key)
enqueue(context, Job(game, null, true, seq.incrementAndGet(), inSession = true))
}
@@ -124,7 +155,6 @@ object AutoComponents {
try {
while (true) {
val job = next(context) ?: return
queuedKeys.remove(job.key)
run(context, job)
}
} finally {
@@ -135,6 +165,7 @@ object AutoComponents {
private fun next(context: Context): Job? = synchronized(jobs) {
val job = jobs.sortedWith(order).firstOrNull { !mustWait(context, it) } ?: return null
jobs.remove(job)
queuedKeys.remove(job.key)
job
}
@@ -148,13 +179,17 @@ object AutoComponents {
worker = Thread({
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
while (true) {
try { jobs.put(jobs.take()) } catch (e: InterruptedException) { return@Thread }
val job = next(app)
if (job == null) {
try { Thread.sleep(PAUSE_MS) } catch (e: InterruptedException) { return@Thread }
continue
val job = try {
synchronized(jobs) {
next(app) ?: run {
(jobs as java.lang.Object).wait(PAUSE_MS)
next(app)
}
}
} catch (e: InterruptedException) {
return@Thread
}
queuedKeys.remove(job.key)
if (job == null) continue
WinComponents.background { run(app, job) }
}
}, "auto-components").apply { isDaemon = true; start() }
@@ -164,18 +199,23 @@ object AutoComponents {
try {
when {
job.pics != null -> SteamAppInfo.lookup(context, job.pics)
job.component != null -> download(context, job.component, job.asked, job.inSession)
job.component != null -> download(context, job.component, job.asked, job.inSession, job.revision)
else -> job.game?.let { apply(context, it, job.asked, job.inSession) }
}
} catch (e: Exception) {
Log.w(TAG, "wincomp: ${job.key}: ${e.javaClass.simpleName}: ${e.message}")
job.component?.let {
repairFailures.value = repairFailures.value + (it to (e.message ?: "Install failed"))
Pending.drop(context, it, job.revision)
}
} finally {
mark(job, false)
changes.value = changes.value + 1
}
}
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false) {
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false,
knownCatalog: Map<String, WinComponents.Component>? = null) {
val key = appKey(game) ?: return
val folder = game.gameFiles
if (game.library == Library.ADDED && game.source == Library.ADDED && folder != null && SteamMatch.get(context, folder.path) == null) {
@@ -183,9 +223,10 @@ object AutoComponents {
}
val store = com.droiddeck.launcher.stores.Store.byId(game.source)
if (folder != null && (store == com.droiddeck.launcher.stores.Store.GOG || store == com.droiddeck.launcher.stores.Store.EPIC)) StoreListBackfill.fill(context, folder)
if (asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
if (knownCatalog == null && asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
val findings = findings(context, game)
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val refreshed = if (knownCatalog == null && asked && online(context)) catalogOf(context, true) else null
val catalog = knownCatalog ?: (refreshed ?: catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val wanted = autoPicks(findings, catalog)
val user = WinComponents.selection(context, key).user
val before = WinComponents.selection(context, key).auto
@@ -196,22 +237,37 @@ object AutoComponents {
if (user[id] == false) { kept[id] = reason; continue }
if (id in installed) { kept[id] = reason; continue }
if (id in before) kept[id] = reason
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
queueDownload(context, id, asked, inSession)
waitFor(game, id)
missing.add(id)
}
if (inSession) Pending.set(context, key, (Pending.ids(context, key).filter { it !in installed && it !in wanted } + missing).distinct())
if (before.keys != kept.keys) {
WinComponents.setAuto(context, key, kept)
Log.i(TAG, "${game.name}: on by itself ${kept.keys.joinToString().ifEmpty { "(none)" }}")
}
Pending.update(context, key, catalog.mapValues { it.value.revision }) { ids ->
ids.filter { id -> user[id] != false && (id !in installed && id !in wanted || (Pending.revision(context, id) ?: 0) > (catalog[id]?.revision ?: 0)) } + missing
}
missing.forEach { id -> queueDownload(context, id, asked, inSession, catalog[id]?.revision) }
changes.value = changes.value + 1
}
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false) {
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run { Pending.drop(context, id); return }
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false, requestedRevision: Int? = null) {
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run {
repairFailures.value = repairFailures.value + (id to "Could not load the component catalog")
return
}
val catalogComponent = catalog[id]
val requiredRevision = maxOf(requestedRevision ?: 0, Pending.revision(context, id) ?: 0)
if (catalogComponent != null && catalogComponent.revision < requiredRevision) {
repairFailures.value = repairFailures.value + (id to "The component catalog is older than the requested revision")
return
}
if (id !in installedOf(context)) {
val c = catalog[id] ?: run { Pending.drop(context, id); return }
val c = catalogComponent ?: run {
repairFailures.value = repairFailures.value + (id to "Component is no longer available")
Pending.drop(context, id, requestedRevision)
return
}
val started = System.currentTimeMillis()
downloading.value = downloading.value + (id to WinComponents.Progress(id, "", WinComponents.Phase.DOWNLOAD, -1))
val problem = try {
@@ -219,12 +275,28 @@ object AutoComponents {
} finally {
downloading.value = downloading.value - id
}
if (problem != null) { Log.w(TAG, "wincomp: $id did not install: $problem"); Pending.drop(context, id); return }
if (problem != null) {
repairFailures.value = repairFailures.value + (id to problem)
Log.w(TAG, "wincomp: $id did not install: $problem")
Pending.drop(context, id, maxOf(requestedRevision ?: 0, c.revision))
return
}
Log.i(TAG, "wincomp: $id installed in ${System.currentTimeMillis() - started}ms")
}
val games = synchronized(waiting) { waiting.remove(id).orEmpty() }
games.forEach { apply(context, it, asked, inSession) }
Pending.drop(context, id)
var applied = true
games.forEach { game ->
try {
apply(context, game, asked, inSession, knownCatalog = catalog)
} catch (e: Exception) {
applied = false
appKey(game)?.let { key -> Pending.add(context, key, listOf(id), mapOf(id to (catalog[id]?.revision ?: requestedRevision ?: 0))) }
waitFor(game, id)
Log.w(TAG, "wincomp: $id installed, but ${game.name} was not updated: ${e.javaClass.simpleName}: ${e.message}")
}
}
if (applied) Pending.drop(context, id, maxOf(requestedRevision ?: 0, catalog[id]?.revision ?: 0))
repairFailures.value = repairFailures.value - id
}
internal object Pending {
@@ -233,24 +305,37 @@ object AutoComponents {
@Synchronized fun read(context: Context): JSONObject =
runCatching { JSONObject(file(context).readText()) }.getOrDefault(JSONObject()).let { it.optJSONObject("games") ?: JSONObject() }
@Synchronized fun set(context: Context, key: String, ids: List<String>) {
@Synchronized fun set(context: Context, key: String, ids: List<String>, revisions: Map<String, Int> = emptyMap()) {
val games = read(context)
if (ids.isEmpty()) games.remove(key) else games.put(key, JSONArray(ids))
write(context, games)
write(context, games, revisions)
}
@Synchronized fun ids(context: Context, key: String): List<String> =
read(context).optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
@Synchronized fun add(context: Context, key: String, ids: List<String>) {
@Synchronized fun update(context: Context, key: String, revisions: Map<String, Int>, transform: (List<String>) -> List<String>): Boolean {
val games = read(context)
val current = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
val ids = transform(current).distinct()
if (ids.isEmpty()) games.remove(key) else games.put(key, JSONArray(ids))
return write(context, games, revisions)
}
@Synchronized fun revision(context: Context, id: String): Int? =
runCatching { JSONObject(file(context).readText()).optJSONObject("revisions")?.optInt(id) }.getOrNull()
@Synchronized fun add(context: Context, key: String, ids: List<String>, revisions: Map<String, Int> = emptyMap()) {
val games = read(context)
val have = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
games.put(key, JSONArray((have + ids).distinct()))
write(context, games)
write(context, games, revisions)
}
@Synchronized fun drop(context: Context, id: String) {
@Synchronized fun drop(context: Context, id: String, throughRevision: Int? = null) {
val games = read(context)
val required = runCatching { JSONObject(file(context).readText()).optJSONObject("revisions")?.optInt(id, 0) ?: 0 }.getOrDefault(0)
if (throughRevision != null && required > throughRevision) return
for (k in games.keys().asSequence().toList()) {
val left = games.optJSONArray(k)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty() - id
if (left.isEmpty()) games.remove(k) else games.put(k, JSONArray(left))
@@ -258,13 +343,29 @@ object AutoComponents {
write(context, games)
}
private fun write(context: Context, games: JSONObject) {
private fun write(context: Context, games: JSONObject, required: Map<String, Int> = emptyMap()): Boolean {
val f = file(context)
runCatching {
return runCatching {
f.parentFile?.mkdirs()
val tmp = File(f.path + ".tmp")
tmp.writeText(JSONObject().put("games", games).toString())
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
val before = runCatching { JSONObject(f.readText()).optJSONObject("revisions") }.getOrNull()
val revisions = JSONObject()
for (key in games.keys()) {
val ids = games.getJSONArray(key)
for (i in 0 until ids.length()) {
val id = ids.getString(i)
revisions.put(id, maxOf(before?.optInt(id, 0) ?: 0, required[id] ?: 0))
}
}
tmp.writeText(JSONObject().put("games", games).put("revisions", revisions).toString())
if (!tmp.renameTo(f)) {
f.delete()
if (!tmp.renameTo(f)) throw java.io.IOException("Could not replace pending repair file")
}
true
}.getOrElse {
Log.w(TAG, "wincomp: could not save pending repairs: ${it.javaClass.simpleName}: ${it.message}")
false
}
}
}
@@ -329,21 +430,76 @@ object AutoComponents {
}
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
internal fun prepareLaunch(context: Context, game: Library.SteamGame): Boolean {
val key = appKey(game) ?: return false
val findings = findings(context, game)
val cached = catalogOf(context, false)
val current = if (online(context)) catalogOf(context, true) else null
val catalog = (current ?: cached)?.associateBy { it.name } ?: run {
val missing = WinComponents.selection(context, key).effective
.filter { WinComponents.validId(it) && it !in installedOf(context) }
val pendingSaved = missing.isEmpty() || Pending.update(context, key, emptyMap()) { ids -> (ids + missing).distinct() }
val pending = Pending.ids(context, key)
pending.forEach { waitFor(game, it) }
queuePending(context, key)
if (!pendingSaved) {
missing.forEach { id ->
waitFor(game, id)
queueDownload(context, id, asked = true, inSession = true, revision = Pending.revision(context, id))
repairFailures.value = repairFailures.value + (id to "Could not save pending repairs")
}
}
return pendingSaved && pending.isEmpty()
}
val wanted = autoPicks(findings, catalog)
val selection = WinComponents.selection(context, key)
val user = selection.user
val installed = installedOf(context)
val roots = selection.effective + wanted.keys.filter { user[it] != false }
val required = withParts(roots.filter { WinComponents.validId(it) }, catalog)
val missing = required.filter { user[it] != false && it !in installed }
val pendingSaved = Pending.update(context, key, catalog.mapValues { it.value.revision }) { ids ->
ids.filter { id -> user[id] != false && (id !in installed && id !in wanted || (Pending.revision(context, id) ?: 0) > (catalog[id]?.revision ?: 0)) } + missing
}
missing.forEach { id ->
waitFor(game, id)
queueDownload(context, id, asked = true, inSession = true,
revision = maxOf(catalog[id]?.revision ?: 0, Pending.revision(context, id) ?: 0))
}
Pending.ids(context, key).forEach { waitFor(game, it) }
queuePending(context, key)
if (!pendingSaved && missing.isNotEmpty()) {
missing.forEach { id -> repairFailures.value = repairFailures.value + (id to "Could not save pending repairs") }
return false
}
return true
}
fun beforeLaunch(context: Context, game: Library.SteamGame, onReady: () -> Unit) {
val app = context.applicationContext
Thread({
val ready = runCatching { prepareLaunch(app, game) }.getOrElse {
Log.w(TAG, "${game.name}: launch repair discovery failed: ${it.javaClass.simpleName}: ${it.message}")
false
}
queueGame(app, game, asked = false)
if (ready) Handler(Looper.getMainLooper()).post(onReady)
}, "auto-components-launch").apply { isDaemon = true; start() }
}
fun restoreMissing(context: Context): List<String> {
val selections = WinComponents.selections(context)
if (selections.isEmpty()) return emptyList()
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return emptyList()
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name }
val installed = installedOf(context)
val lostFor = selections.mapValues { (_, selection) ->
val lostFor = if (catalog == null) emptyMap() else selections.mapValues { (_, selection) ->
withParts(selection.effective.filter { WinComponents.validId(it) }, catalog).filter { it !in installed && it in catalog }
}.filterValues { it.isNotEmpty() }
if (lostFor.isEmpty()) return emptyList()
val lost = lostFor.values.flatten().distinct()
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids) }
lost.forEach { queueDownload(context, it, asked = true, inSession = true) }
if (lost.isNotEmpty()) {
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids, catalog!!.mapValues { it.value.revision }) }
}
Pending.read(context).keys().asSequence().toList().forEach { queuePending(context, it) }
return lost
}
@@ -360,6 +516,7 @@ object AutoComponents {
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
fun sweep(context: Context, games: List<Library.SteamGame>) {
if (online(context) && !unfavourable(context)) catalogOf(context, true)
val apps = games.mapNotNull { steamAppOf(context, it) }.distinct()
if (apps.isNotEmpty() && SteamAppInfo.needLookup(context, apps).isNotEmpty()) enqueue(context, Job(null, null, false, seq.incrementAndGet(), pics = apps))
games.forEach { queueGame(context, it, asked = false) }
@@ -14,6 +14,8 @@ object SteamRedists {
"228988" to ("vcredist2019_dll" to "VC++ 2019"),
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
"228990" to ("d3dx9" to "DirectX (June 2010)"),
// OpenAL 2.0.7.0 (Hotline Miami lists it; without it HotlineGL.exe fails to load, c0000135).
"229020" to ("oalinst_dll" to "OpenAL"),
)
val SCRIPTED = mapOf(
72850 to listOf("xact" to "DirectX XACT audio"),
@@ -1,6 +1,9 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import android.util.Log
@@ -13,14 +16,17 @@ import java.util.Locale
class ClockLogComponent(private val logFile: File) : SessionPart() {
@Volatile private var running = false
private var stopped = false
private var thread: Thread? = null
override fun start() {
@Synchronized override fun start() {
if (stopped || running) return
running = true
thread = Thread({ run() }, "clock-log").apply { isDaemon = true; start() }
}
override fun stop() {
@Synchronized override fun stop() {
stopped = true
running = false
thread?.interrupt()
thread = null
@@ -65,6 +71,7 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
if (!h.isNaN()) line.append(String.format(Locale.US, " headroom %.2f", h))
}
}
batteryTenths()?.let { line.append(String.format(Locale.US, " | battery %.1f C", it / 10.0)) }
w.write(line.append('\n').toString())
w.flush()
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
@@ -75,6 +82,10 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
}
}
private fun batteryTenths(): Int? =
app().registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
?.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, Int.MIN_VALUE)?.takeIf { it != Int.MIN_VALUE }
companion object {
private const val TAG = "SessionService"
private const val PERIOD_MS = 2000L
@@ -85,8 +96,13 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
"/sys/kernel/ged/hal/current_freqency", "/sys/kernel/ged/hal/current_frequency",
"/proc/gpufreqv2/gpufreq_status", "/proc/gpufreq/gpufreq_var_dump",
"/sys/kernel/gpu/gpu_clock", "/sys/class/misc/mali0/device/cur_freq",
"/sys/class/misc/mali0/device/clock",
"/sys/class/misc/mali0/device/clock", "/sys/class/kgsl/kgsl-3d0/clock_mhz",
"/sys/class/kgsl/kgsl-3d0/gpu_clock", "/sys/class/kgsl/kgsl-3d0/gpuclk",
"/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq", "/sys/kernel/gpu/gpu_clock",
"/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq",
)
listOf("kgsl-3d0", "3d00000.qcom,kgsl-3d0", "2c00000.qcom,kgsl-3d0", "5000000.qcom,kgsl-3d0", "5900000.qcom,kgsl-3d0")
.forEach { list.add("/sys/class/devfreq/$it/cur_freq") }
File("/sys/class/devfreq").list()?.sorted()?.forEach { node ->
if (node.contains("mali", true) || node.contains("gpu", true)) list.add("/sys/class/devfreq/$node/cur_freq")
}
@@ -53,7 +53,7 @@ object DeviceInfo {
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
add("GPU", gpu.name)
add("Family", gpu.family.label)
add("Family", gpu.family.label(gpu.name))
add("Model found from", when (gpu.modelSource) {
"kernel" -> "the kernel's GPU name"
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
@@ -146,10 +146,20 @@ object DeviceInfo {
add("Driver mode", SessionPrefs.gpuDriverMode(context))
val turnip = TurnipDriver(context)
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val powerVr = gpu.family == GpuInfo.Family.POWERVR
add("Display driver", if (choice == "system") builtinDriverLabel(powerVr, runtime = false)
else "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val linux = LinuxVulkanDriverManager(context)
val id = SessionPrefs.linuxDriver(context)
add("Game driver", if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
add("Game driver", if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
})
/** Shared by the device card and the session report, which are written in English. */
internal fun builtinDriverLabel(powerVr: Boolean, runtime: Boolean): String = when {
powerVr -> "System PowerVR"
runtime -> "the runtime's own Turnip"
else -> "System Vulkan"
}
}
@@ -75,8 +75,8 @@ object DriverBundle {
val linuxStage = lm.newStagingDir()
val linuxId = try {
val library = linuxDir.listFiles()?.firstOrNull { it.isFile && it.name.startsWith("libvulkan_freedreno") && it.name.endsWith(".so") }
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.LIB_NAME))
val library = linuxDir.listFiles()?.firstOrNull { it.isFile && LinuxVulkanDriverManager.isDriverLibrary(it.name) }
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.storedName(library.name)))
val meta = File(linuxDir, LinuxVulkanDriverManager.META_NAME).takeIf { it.isFile }
?.let { runCatching { JSONObject(FileUtils.readString(it)) }.getOrNull() }
lm.adopt(linuxStage, library?.name, meta, manifest.name)
@@ -86,6 +86,10 @@ object DriverBundle {
}
val base = LinuxVulkanDriverManager.sanitizeId(manifest.tag.ifEmpty { "${manifest.name}-${manifest.version}" })
get(context, base)?.takeIf { DriverPairs.isNonAdreno(it.id) }?.let { old ->
Log.i(TAG, "replacing bundle ${old.id} (display ${old.androidId}, runtime ${old.linuxId})")
remove(context, old)
}
val saved = registry(context)
var id = base
var n = 2
@@ -12,6 +12,48 @@ object DriverPairs {
const val DD_TURNIP = "dd-turnip"
fun ddTurnip(tag: String) = "$DD_TURNIP:$tag"
/** The open non-Adreno drivers (The412Banner/droiddeck-nonadreno-drivers), one pair per driver. */
const val NON_ADRENO = "nad"
const val NAD_RADV_XCLIPSE = "nad:radv-xclipse"
/** RADV-Xclipse rebased on JimVulkan's upstream: a manual choice, never Auto. */
const val NAD_RADV_XCLIPSE_UPSTREAM = "nad:radv-xclipse-upstream"
private val XCLIPSE_MODEL = Regex("""(?i)xclipse\s*(\d{3})\b""")
const val NAD_MALI_JM = "nad:panvk-mali-jm"
const val NAD_MALI_G710 = "nad:panvk-mali-g710"
const val NAD_MALI_G615 = "nad:panvk-mali-g615"
const val NAD_MALI_G720 = "nad:panvk-mali-g720"
/** One PanVK kbase binary for Mali v9-v13; its display half needs Android 15. */
const val NAD_MALI_KBASE = "nad:panvk-mali-kbase"
const val MALI_KBASE_MIN_SDK = 35
/** faux123's PanVK builds for three handhelds: manual choices, never Auto. */
const val NAD_FAUX_RP4PRO = "nad:panvk-faux123-rp4pro"
const val NAD_FAUX_ACE = "nad:panvk-faux123-ace"
const val NAD_FAUX_RG556 = "nad:panvk-faux123-rg556"
/** The one Mali a device-specific build is for, by the number in the GPU's name. */
private val DEVICE_BUILDS = mapOf(NAD_FAUX_RP4PRO to 77, NAD_FAUX_ACE to 610, NAD_FAUX_RG556 to 57)
/** "PanVK-Mali-G720" (the release asset's id) to its pair key, "nad:panvk-mali-g720". */
fun nonAdreno(id: String) = "$NON_ADRENO:" + id.lowercase()
/** True for a non-Adreno pair's key, or a bundle installed from one ("PanVK-Mali-G720"). */
fun isNonAdreno(keyOrBundleId: String?): Boolean = keyOrBundleId != null &&
(keyOrBundleId.startsWith("$NON_ADRENO:") || Regex("""^(?i)(RADV-Xclipse|PanVK-[A-Za-z0-9]+)(-[A-Za-z0-9]+)*$""").matches(keyOrBundleId))
fun nonAdrenoName(key: String): String = describeNonAdreno(key).first
private fun describeNonAdreno(key: String): Pair<String, Set<Family>> = when (key) {
NAD_RADV_XCLIPSE -> "RADV · Samsung Xclipse" to setOf(Family.POWERVR)
NAD_RADV_XCLIPSE_UPSTREAM -> "RADV upstream · Samsung Xclipse" to setOf(Family.POWERVR)
NAD_MALI_JM -> "PanVK · Mali G52-G78" to setOf(Family.MALI_JM)
NAD_MALI_G710 -> "PanVK · Mali-G610/G710" to setOf(Family.MALI_G610_G710)
NAD_MALI_G615 -> "PanVK · Mali-G615" to setOf(Family.MALI_G615)
NAD_MALI_G720 -> "PanVK · Mali-G720" to setOf(Family.MALI_G720)
NAD_FAUX_RP4PRO -> "PanVK faux123 · Retroid Pocket 4 Pro (Mali-G77)" to setOf(Family.MALI_JM)
NAD_FAUX_ACE -> "PanVK faux123 · GameForce Ace (Mali-G610)" to setOf(Family.MALI_G610_G710)
NAD_FAUX_RG556 -> "PanVK faux123 · Anbernic RG556 (Mali-G57)" to setOf(Family.MALI_JM)
NAD_MALI_KBASE -> "PanVK kbase · Mali G57-G925" to
setOf(Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST)
else -> key.removePrefix("$NON_ADRENO:") to emptySet<Family>()
}
class DriverPair(
val key: String,
val name: String,
@@ -24,14 +66,23 @@ object DriverPairs {
val assets: List<TurnipReleases.Asset> get() = listOfNotNull(bundle ?: display, if (bundle == null) linux else null)
val version: String
get() = listOfNotNull(bundle?.tag, display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-").removePrefix("DD-Turnip-") }
fun suits(gpu: GpuInfo) = gpu.family in families ||
(gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families))
fun suits(gpu: GpuInfo) = when {
// The system-driver family covers PowerVR and Xclipse; RADV is only for the Xclipse.
key == NAD_RADV_XCLIPSE || key == NAD_RADV_XCLIPSE_UPSTREAM ->
gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true)
// One binary for Mali v9-v13, not the older G52/G76 in the Job Manager family.
key == NAD_MALI_KBASE -> gpu.family.mali && GpuInfo.maliKbaseCovered(gpu.name)
key in DEVICE_BUILDS -> gpu.family.mali && GpuInfo.maliNumber(gpu.name) == DEVICE_BUILDS[key]
else -> gpu.family in families ||
(gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families))
}
}
private val ALL_ADRENO = setOf(Family.A6XX, Family.A7XX, Family.A7XX_LOW, Family.A8XX, Family.ADRENO_UNKNOWN)
private fun describe(key: String): Pair<String, Set<Family>> = when {
key.startsWith(DD_TURNIP) -> "DroidDeck · DD-Turnip" to ALL_ADRENO
key.startsWith("$NON_ADRENO:") -> describeNonAdreno(key)
else -> describeFixed(key)
}
@@ -47,7 +98,7 @@ object DriverPairs {
fun from(check: TurnipReleases.Check?): List<DriverPair> {
val assets = check?.assets.orEmpty().filter { it.pair.isNotEmpty() }
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE)
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE, NON_ADRENO)
return assets.map { it.pair }.distinct()
.sortedBy { key -> order.indexOf(key.substringBefore(':')).let { i -> if (i < 0) order.size else i } }
.map { key ->
@@ -61,12 +112,26 @@ object DriverPairs {
}
}
/** 950 and 960 panic on the older build; a name without a model number is treated the same way. */
private fun xclipseNeedsUpstream(name: String): Boolean =
XCLIPSE_MODEL.find(name)?.groupValues?.get(1).let { it == null || it == "950" || it == "960" }
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
when (gpu.family) {
Family.POWERVR -> return when {
!gpu.name.contains("Xclipse", ignoreCase = true) -> null
xclipseNeedsUpstream(gpu.name) && pairs.any { it.key == NAD_RADV_XCLIPSE_UPSTREAM } -> NAD_RADV_XCLIPSE_UPSTREAM
else -> NAD_RADV_XCLIPSE
}
Family.MALI_OTHER, Family.NOT_ADRENO -> return null
Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST ->
return maliKey(gpu, pairs, sdk)
else -> Unit
}
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 }
@@ -74,6 +139,20 @@ object DriverPairs {
?: keys.firstOrNull()
}
private fun maliKey(gpu: GpuInfo, pairs: List<DriverPair>, sdk: Int): String? {
val family = when (gpu.family) {
Family.MALI_JM -> NAD_MALI_JM
Family.MALI_G610_G710 -> NAD_MALI_G710
Family.MALI_G615 -> NAD_MALI_G615
Family.MALI_G720 -> NAD_MALI_G720
else -> null
}
val kbase = NAD_MALI_KBASE.takeIf { sdk >= MALI_KBASE_MIN_SDK && GpuInfo.maliKbaseCovered(gpu.name) }
if (pairs.isEmpty()) return kbase ?: family
fun listed(key: String?) = key?.takeIf { k -> pairs.any { it.key == k && it.complete } }
return listed(kbase) ?: listed(family) ?: kbase ?: family
}
fun newestDdTurnip(pairs: List<DriverPair>): String? = pairs
.filter { it.key.startsWith("$DD_TURNIP:") && it.complete }
.maxByOrNull { p ->
@@ -24,8 +24,22 @@ data class GpuInfo(
A7XX("Adreno 7xx"),
A6XX("Adreno 6xx"),
ADRENO_UNKNOWN("Adreno"),
POWERVR("PowerVR"),
/** Mali on Arm's kbase driver, by the open PanVK build each generation needs. */
MALI_JM("Mali (G52-G78)"),
MALI_G610_G710("Mali-G610/G710"),
MALI_G615("Mali-G615"),
MALI_G720("Mali-G720"),
/** Mali-G715/G725/G925: only the one-binary PanVK kbase build covers them (Android 15+). */
MALI_LATEST("Mali-G715/G725/G925"),
/** A Mali no open driver build covers: the Vulkan bridge is its only path. */
MALI_OTHER("Mali"),
NOT_ADRENO("Not an Adreno GPU");
val mali: Boolean get() = name.startsWith("MALI_")
fun label(gpuName: String): String = if (this == POWERVR && gpuName.contains("Xclipse", ignoreCase = true)) "Samsung Xclipse" else label
fun label(context: Context): String = if (this == NOT_ADRENO) context.getString(R.string.gpuinfo_not_adreno) else label
}
@@ -47,10 +61,16 @@ data class GpuInfo(
val supportText: String
get() = when (support) {
Support.TESTED -> "Supported"
Support.UNTESTED -> if (isA850) "Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device"
else if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
Support.UNTESTED -> when {
family == Family.POWERVR -> if (name.contains("Xclipse", ignoreCase = true)) "Experimental: RADV or the system Xclipse driver"
else "System PowerVR driver: compatibility varies by device"
family == Family.MALI_OTHER -> "Experimental: Mali through the phone's own driver (Venus)"
family.mali -> "Experimental: open Mali driver (test builds)"
isA850 -> "Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device"
family == Family.A7XX_LOW -> "Experimental: its drivers are test builds"
else -> "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
}
Support.UNSUPPORTED -> "Not supported: no compatible graphics backend is available for this GPU"
}
fun supportText(bridge: Boolean): String = when {
@@ -68,8 +88,9 @@ data class GpuInfo(
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
Support.UNTESTED -> when {
family == Family.POWERVR -> if (name.contains("Xclipse", ignoreCase = true)) R.string.gpuinfo_xclipse else R.string.gpuinfo_powervr
isA850 -> R.string.gpuinfo_a850_experimental
family == Family.A7XX_LOW -> R.string.gpuinfo_experimental
family == Family.A7XX_LOW || family.mali -> R.string.gpuinfo_experimental
else -> R.string.gpuinfo_below_tested
}
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
@@ -91,10 +112,20 @@ data class GpuInfo(
{ VulkanInfo.cachedOrNull()?.get("device") },
{ platformGpuModel },
) else 0 to ""
val family = familyOf(adreno, model)
// Mali, named by the vendor's Vulkan driver ("Mali-G720-Immortalis MC12") or by kbase.
val mali = if (adreno || !File("/dev/mali0").exists()) null else maliName()
val family = familyOf(adreno, model, SystemVulkanDriver.isPowerVr(), mali)
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
name = when {
family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
}
mali != null && mali.isNotEmpty() -> mali
!adreno -> Build.HARDWARE.ifBlank { UNNAMED }
model > 0 -> "Adreno $model"
else -> "Adreno"
},
model = model, family = family, soc = soc,
oneUi8Gen2 = samsung && model == 740,
kgslName = raw.orEmpty(), modelSource = source, kgslChipId = chipId,
@@ -136,7 +167,68 @@ data class GpuInfo(
""
}
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
/**
* The Mali's name, "" when nothing names it: the vendor Vulkan driver's own name when this
* process has asked it, kbase's gpuinfo where SELinux lets the app read it (most phones do
* not), else the GPU the chip is known to carry ([MALI_SOCS]).
*/
private fun maliName(): String =
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains("Mali", ignoreCase = true) }
?: FileUtils.readString(File("/sys/class/misc/mali0/device/gpuinfo"))?.trim()?.takeIf { it.contains("Mali", ignoreCase = true) }
?.substringBefore(" ")
?: maliOfSoc(socIds())
?: ""
/** The chip's names as the platform gives them: "mt6989", "MT6989", "gs201". */
private fun socIds(): List<String> = listOfNotNull(
if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL else null,
systemProperty("ro.board.platform"), systemProperty("ro.soc.model"), Build.HARDWARE, Build.BOARD,
).filter { it.isNotBlank() }
/** Chips whose Mali is known for certain (MediaTek Dimensity / Helio / Kompanio, Google Tensor). */
private val MALI_SOCS = mapOf(
"mt6993" to "Mali-G1-Ultra", "mt6991" to "Mali-G925", "mt6989" to "Mali-G720", "mt6899" to "Mali-G720", "mt6985" to "Mali-G715",
"mt6983" to "Mali-G710", "mt6897" to "Mali-G615", "mt6878" to "Mali-G615", "mt6895" to "Mali-G610",
"mt6896" to "Mali-G610", "mt6886" to "Mali-G610", "mt6893" to "Mali-G77", "mt6891" to "Mali-G77",
"mt6889" to "Mali-G77", "mt6885" to "Mali-G77", "mt6877" to "Mali-G68", "mt6853" to "Mali-G57",
"mt6833" to "Mali-G57", "mt6835" to "Mali-G57", "mt6789" to "Mali-G57", "mt6785" to "Mali-G76",
"mt6781" to "Mali-G52", "mt6769" to "Mali-G52", "mt8192" to "Mali-G57", "mt8195" to "Mali-G57",
"gs101" to "Mali-G78", "gs201" to "Mali-G710", "zuma" to "Mali-G715", "zumapro" to "Mali-G715",
"s5e8835" to "Mali-G68", "s5e8825" to "Mali-G68",
)
/** The Mali [ids] name a chip of, "Mali-G720 (by chip mt6989)", or null for an unknown chip. */
internal fun maliOfSoc(ids: List<String>): String? = ids.firstNotNullOfOrNull { id ->
MALI_SOCS[id.trim().lowercase()]?.let { "$it (by chip ${id.trim().lowercase()})" }
}
/** The number in a Mali's name: 720 for "Mali-G720-Immortalis MC12". */
fun maliNumber(name: String): Int? =
Regex("""G(\d{2,3})""", RegexOption.IGNORE_CASE).find(name)?.groupValues?.get(1)?.toIntOrNull()
/**
* The Malis the one-binary PanVK kbase build covers (arch v9-v13): G57/G68/G77/G78,
* G610/G710, G615/G715, G720/G725 and G925. Not the older Bifrost G52/G76.
*/
fun maliKbaseCovered(name: String): Boolean =
maliNumber(name) in setOf(57, 68, 77, 78, 610, 710, 615, 715, 720, 725, 925)
/** The PanVK generation a Mali name belongs to; MALI_OTHER when none of the builds covers it. */
internal fun maliFamily(name: String): Family {
val number = maliNumber(name) ?: return Family.MALI_OTHER
return when (number) {
31, 51, 52, 57, 68, 71, 72, 76, 77, 78 -> Family.MALI_JM
610, 710 -> Family.MALI_G610_G710
615 -> Family.MALI_G615
720 -> Family.MALI_G720
715, 725, 925 -> Family.MALI_LATEST
else -> Family.MALI_OTHER
}
}
internal fun familyOf(adreno: Boolean, model: Int, powerVr: Boolean = false, mali: String? = null): Family = when {
!adreno && powerVr -> Family.POWERVR
!adreno && mali != null -> maliFamily(mali)
!adreno -> Family.NOT_ADRENO
model == 0 -> Family.ADRENO_UNKNOWN
model >= 800 -> Family.A8XX
@@ -3,8 +3,12 @@ package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.R;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public final class LinuxVulkanDriver {
private static final String TAG = "LinuxVulkanDriver";
@@ -25,15 +29,36 @@ public final class LinuxVulkanDriver {
return values;
}
public static String resolveIcdPath(Context context, String value) {
if (value == null || value.isEmpty()) return null;
public static String optionLabel(Context context, String value) {
if (value == null || value.isEmpty()) return SystemVulkanDriver.isPowerVr()
? context.getString(R.string.gpu_system_powervr) : "Runtime default (built into the runtime)";
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
String icd = m.getIcdPath(value);
if (icd == null) {
Log.w(TAG, "imported Linux driver \"" + value + "\" is gone; using the runtime's own driver");
return null;
}
Log.i(TAG, "Linux session draws with imported driver " + value + " (" + icd + ")");
if (!m.isInstalled(value)) return value + (SystemVulkanDriver.isPowerVr()
? " (imported, missing)" : " (imported, missing - uses the runtime default)");
String ver = m.getDriverVersion(value);
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
}
public static String resolveIcdPath(Context context, String value) {
boolean powerVr = SystemVulkanDriver.isPowerVr();
return resolveIcdPath(value, powerVr,
() -> SystemVulkanDriver.icdPath(context), id -> {
String icd = new LinuxVulkanDriverManager(context).getIcdPath(id);
if (icd == null) Log.w(TAG, "imported Linux driver \"" + id + "\" is gone"
+ (powerVr ? "" : "; using the runtime's own driver"));
else Log.i(TAG, "Linux session draws with imported driver " + id + " (" + icd + ")");
return icd;
});
}
/** Resolve the selected backend before looking up an imported driver. */
static String resolveIcdPath(String value, boolean powerVr, Supplier<String> systemIcd,
Function<String, String> importedIcd) {
if (SystemVulkanDriver.usesDefault(powerVr, value)) return systemIcd.get();
if (value == null || value.isEmpty()) return null;
String icd = importedIcd.apply(value);
if (powerVr && icd == null) throw new IllegalStateException(
"Selected Linux Vulkan driver \"" + value + "\" is unavailable. Select an installed driver or use Auto.");
return icd;
}
}
@@ -45,7 +45,9 @@ public class LinuxVulkanDriverManager {
public boolean isInstalled(String id) {
if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return false;
File dir = getDriverDir(id);
return new File(dir, LIB_NAME).isFile() && new File(dir, ICD_NAME).isFile();
if (!new File(dir, ICD_NAME).isFile()) return false;
for (String name : STORED_NAMES) if (new File(dir, name).isFile()) return true;
return false;
}
public String getIcdPath(String id) {
@@ -107,10 +109,10 @@ public class LinuxVulkanDriverManager {
if (entry.isDirectory()) continue;
String base = new File(entry.getName()).getName();
if (base.isEmpty()) continue;
if (base.startsWith("libvulkan_freedreno") && base.endsWith(".so")) {
if (soName != null) Log.w(TAG, "zip has several libvulkan_freedreno*.so; using the first (" + soName + ")");
if (isDriverLibrary(base)) {
if (soName != null) Log.w(TAG, "zip has several driver libraries; using the first (" + soName + ")");
else {
Files.copy(zis, new File(tmpDir, LIB_NAME).toPath(), StandardCopyOption.REPLACE_EXISTING);
Files.copy(zis, new File(tmpDir, storedName(base)).toPath(), StandardCopyOption.REPLACE_EXISTING);
soName = base;
}
} else if (base.equals(META_NAME)) {
@@ -142,7 +144,8 @@ public class LinuxVulkanDriverManager {
if (soName == null) {
throw new IllegalArgumentException(context.getString(R.string.lvd_no_library));
}
File so = new File(tmpDir, LIB_NAME);
String stored = storedName(soName);
File so = new File(tmpDir, stored);
if (!isAarch64Elf(so)) {
throw new IllegalArgumentException(context.getString(R.string.lvd_not_aarch64, soName));
}
@@ -167,7 +170,7 @@ public class LinuxVulkanDriverManager {
JSONObject icd = new JSONObject();
icd.put("file_format_version", "1.0.0");
JSONObject icdBody = new JSONObject();
icdBody.put("library_path", new File(dir, LIB_NAME).getAbsolutePath());
icdBody.put("library_path", new File(dir, stored).getAbsolutePath());
icdBody.put("api_version", "1.1.274");
icd.put("ICD", icdBody);
if (!FileUtils.writeString(new File(tmpDir, ICD_NAME), icd.toString(2))) throw new IOException("cannot write icd.json");
@@ -180,6 +183,7 @@ public class LinuxVulkanDriverManager {
meta.put("libc", "glibc");
meta.put("minGlibc", minGlibc);
meta.put("sourceLibraryName", soName);
meta.put("libraryName", stored);
meta.put("importedAt", System.currentTimeMillis());
if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json");
@@ -198,6 +202,24 @@ public class LinuxVulkanDriverManager {
return id;
}
/** The names an installed driver's library is kept under; Turnip keeps {@link #LIB_NAME}. */
private static final String[] STORED_NAMES = {LIB_NAME, "libvulkan_panfrost.so", "libvulkan_radeon.so"};
/**
* The name a driver library is installed under: its own driver's (PanVK, RADV), so the session
* log and the graphics report say which driver it is; a Turnip build keeps {@link #LIB_NAME}.
*/
public static String storedName(String soName) {
if (soName != null && soName.startsWith("libvulkan_panfrost")) return "libvulkan_panfrost.so";
if (soName != null && soName.startsWith("libvulkan_radeon")) return "libvulkan_radeon.so";
return LIB_NAME;
}
public static boolean isDriverLibrary(String base) {
return base.endsWith(".so") && (base.startsWith("libvulkan_freedreno")
|| base.startsWith("libvulkan_panfrost") || base.startsWith("libvulkan_radeon"));
}
static String sanitizeId(String name) {
String s = name.trim().replaceAll("[^A-Za-z0-9._-]+", "_").replaceAll("^[._]+", "");
if (s.length() > 64) s = s.substring(0, 64);
@@ -0,0 +1,267 @@
package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.os.Build;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import com.droiddeck.launcher.core.AddonPack;
import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.TarZst;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.TreeSet;
import java.util.UUID;
import java.util.function.Predicate;
import org.json.JSONObject;
/** Isolated glibc-to-Android Vulkan bridge. It does not replace the rootfs's Mesa libraries. */
public final class SystemVulkanDriver {
/** Vendor HALs the bridge loads. Samsung Xclipse (Exynos, sgpu) is experimental. */
private static final String[] HALS = {
"/vendor/lib64/hw/vulkan.powervr.so",
"/vendor/lib64/hw/vulkan.samsung.so"
};
private static final String[] REQUIRED = {
"lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1",
"lib/libhybris/linker/q.so", "lib/libVkLayer_hybris_compat.so",
"run-proton.py", "wsi/libVkLayer_window_system_integration.so",
"wsi/VkLayer_window_system_integration.json",
"dxvk/x32/d3d8.dll", "dxvk/x32/d3d9.dll", "dxvk/x32/d3d10core.dll",
"dxvk/x32/d3d11.dll", "dxvk/x32/dxgi.dll",
"dxvk/x64/d3d8.dll", "dxvk/x64/d3d9.dll", "dxvk/x64/d3d10core.dll",
"dxvk/x64/d3d11.dll", "dxvk/x64/dxgi.dll"
};
/** Rootfs directory of the Xclipse layer the apk stages (SessionFiles). */
private static final String XCLIPSE_LAYER_DIR = "/usr/local/lib/droiddeck-xclipse";
private SystemVulkanDriver() {}
/**
* The first vendor HAL present, or null. An Exynos with a Mali (Exynos 1280/1380: /dev/mali0)
* may name its HAL vulkan.samsung.so too; that is a Mali, not an Xclipse, and is not taken.
*/
public static String hal() {
for (String path : HALS) {
if (!new File(path).isFile()) continue;
if (path.endsWith("/vulkan.samsung.so") && new File("/dev/mali0").exists()) continue;
return path;
}
return null;
}
/** Samsung's Xclipse (Exynos, sgpu) rather than PowerVR. */
public static boolean isXclipse() {
String hal = hal();
return hal != null && hal.endsWith("/vulkan.samsung.so");
}
/** The system-driver GPU family, for labels. */
public static String gpuName() { return isXclipse() ? "Xclipse" : "PowerVR"; }
/** Whether a system-driver GPU (PowerVR or Xclipse) is present; the name predates Xclipse. */
public static boolean isPowerVr() { return hal() != null; }
/** HAL detection names the GPU; launching also needs the real DRM render node. */
public static boolean isAvailable() { return isPowerVr() && renderNodeAvailable(); }
public static boolean renderNodeAvailable() {
return renderNodePath() != null;
}
/** Select the actual PowerVR node, including devices where another GPU owns renderD128. */
public static String renderNodePath() {
String[] nodes = new File("/dev/dri").list();
if (nodes == null) nodes = new File("/sys/class/drm").list();
return findRenderNode(nodes, SystemVulkanDriver::renderNodeAvailable);
}
static String findRenderNode(String[] nodes, Predicate<String> available) {
TreeSet<String> candidates = new TreeSet<>();
// Android can deny directory listing while allowing direct access. Probe the kernel's
// reserved render range too; directory entries also cover dynamically allocated minors.
for (int minor = 128; minor < 192; minor++) candidates.add("renderD" + minor);
if (nodes != null) for (String node : nodes)
if (node.matches("renderD[0-9]+")) candidates.add(node);
for (String node : candidates) {
String path = "/dev/dri/" + node;
if (available.test(path)) return path;
}
return null;
}
private static boolean renderNodeAvailable(String node) {
try {
if (!renderNodeAvailable(OsConstants.S_ISCHR(Os.stat(node).st_mode),
Os.access(node, OsConstants.R_OK), Os.access(node, OsConstants.W_OK))) return false;
return powerVrDevice(new File("/sys/class/drm/" + new File(node).getName() + "/device"));
} catch (ErrnoException error) {
return false;
}
}
static boolean powerVrDriver(String driver) {
return "pvrsrvkm".equals(driver) || "pvr".equals(driver) || "powervr".equals(driver)
|| "sgpu".equals(driver);
}
static boolean powerVrDevice(File device) {
try {
return powerVrDriver(Files.readSymbolicLink(new File(device, "driver").toPath())
.getFileName().toString());
} catch (IOException error) {
// Some Android policies expose uevent but deny reading the driver symlink.
try (BufferedReader input = Files.newBufferedReader(
new File(device, "uevent").toPath(), StandardCharsets.US_ASCII)) {
String line;
while ((line = input.readLine()) != null)
if (line.startsWith("DRIVER=")) return powerVrDriver(line.substring(7));
} catch (IOException ignored) { }
return false;
}
}
static boolean renderNodeAvailable(boolean characterDevice, boolean readable, boolean writable) {
return characterDevice && readable && writable;
}
public static boolean usesDefault(String choice) {
return usesDefault(isPowerVr(), choice);
}
static boolean usesDefault(boolean powerVr, String choice) {
return powerVr && (choice == null || choice.isEmpty());
}
/** APK-versioned directories stay intact while an older session still has libraries mapped. */
public static synchronized File prepare(Context context) throws IOException {
if (!isPowerVr()) throw new IOException("System PowerVR Vulkan driver is unavailable");
if (!renderNodeAvailable()) throw new IOException(
"System PowerVR requires an identifiable, readable and writable DRM render node");
if (!AddonPack.POWERVR.await(context)) throw new IOException(
"Couldn't download the PowerVR graphics runtime. Check your connection and try again.");
File target = runtimeDirectory(context);
File base = target.getParentFile();
if (complete(target)) return target;
if (!base.isDirectory() && !base.mkdirs()) throw new IOException("Cannot create system Vulkan directory");
File staged = new File(base, ".stage-" + UUID.randomUUID());
try {
try (FileInputStream archive = new FileInputStream(AddonPack.POWERVR.file(context, "runtime.tzst"))) {
if (!TarZst.extract(archive, staged)) throw new IOException("Cannot unpack system Vulkan runtime");
}
for (String name : REQUIRED)
if (!present(staged, name)) throw new IOException("Missing system Vulkan component: " + name);
if (!new File(staged, "run-proton.py").canExecute())
throw new IOException("System Vulkan Proton wrapper is not executable");
JSONObject library = new JSONObject();
library.put("library_path", new File(target, REQUIRED[0]).getPath());
library.put("api_version", "1.3.0");
JSONObject manifest = new JSONObject();
manifest.put("file_format_version", "1.0.0");
manifest.put("ICD", library);
Files.write(new File(staged, "icd.json").toPath(), manifest.toString().getBytes(StandardCharsets.UTF_8));
if (target.exists()) throw new IOException("Incomplete system Vulkan runtime directory: " + target.getName());
if (!staged.renameTo(target)) throw new IOException("Cannot publish system Vulkan runtime");
return target;
} catch (org.json.JSONException error) {
throw new IOException("Cannot write system Vulkan manifest", error);
} finally {
if (staged.exists()) FileUtils.delete(staged);
}
}
/** The current APK's versioned runtime path, without extracting or modifying it. */
public static File runtimeDirectory(Context context) throws IOException {
String version;
if (!AddonPack.POWERVR.installed(context)) throw new IOException("PowerVR graphics runtime is not installed");
try (BufferedReader input = new BufferedReader(new InputStreamReader(
new FileInputStream(AddonPack.POWERVR.file(context, "version.txt")), StandardCharsets.US_ASCII))) {
version = input.readLine();
}
if (version == null || !version.matches("[0-9a-f]{64}")) throw new IOException("Invalid system Vulkan runtime version");
return new File(new File(context.getFilesDir(), "system_vulkan"), version);
}
/** Collect abandoned stages, and obsolete versions once older guests can no longer load them. */
public static synchronized void pruneUnused(Context context, boolean guestsStopped) throws IOException {
pruneUnused(runtimeDirectory(context), guestsStopped);
}
static synchronized void pruneUnused(File current, boolean guestsStopped) {
File base = current.getParentFile();
if (base == null || Files.isSymbolicLink(base.toPath()) || Files.isSymbolicLink(current.toPath())) return;
File[] entries = base.listFiles();
if (entries == null) return;
// Retain the previous good version if publishing the replacement failed.
boolean pruneVersions = guestsStopped && complete(current);
for (File entry : entries) {
if (entry.equals(current)) continue;
String name = entry.getName();
boolean oldVersion = pruneVersions && name.matches("[0-9a-f]{64}");
boolean abandonedStage = name.matches("\\.stage-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
// The prepare monitor excludes any extraction still writing a .stage directory.
if (oldVersion || abandonedStage) FileUtils.delete(entry);
}
}
private static boolean complete(File directory) {
if (!new File(directory, "icd.json").isFile()) return false;
for (String name : REQUIRED) if (!present(directory, name)) return false;
return new File(directory, "run-proton.py").canExecute();
}
private static boolean present(File directory, String name) {
File file = new File(directory, name);
return file.isFile() && file.length() > 0;
}
public static String icdPath(Context context) {
try {
return new File(prepare(context), "icd.json").getPath();
} catch (IOException error) {
throw new IllegalStateException("System Vulkan runtime is unavailable", error);
}
}
public static void addEnvironment(Context context, List<String> environment) {
File directory;
try { directory = prepare(context); }
catch (IOException error) { throw new IllegalStateException("System Vulkan runtime is unavailable", error); }
String node = renderNodePath();
if (node == null) throw new IllegalStateException("System PowerVR render node is unavailable");
environment.add("HYBRIS_ANDROID_SDK_VERSION=" + Build.VERSION.SDK_INT);
environment.add("HYBRIS_VULKAN_HAL=" + hal());
environment.add("HYBRIS_LINKER_DIR=" + new File(directory, "lib/libhybris/linker").getPath());
// Prefer framework dependencies for the system Vulkan loader, including libbase.so.
environment.add("HYBRIS_LD_LIBRARY_PATH=/system/lib64:/system_ext/lib64:/vendor/lib64/egl:/vendor/lib64/hw:/vendor/lib64");
boolean xclipse = isXclipse();
// Xclipse gets its own layer (tools/linuxfs/xclipse-layer) in front of everything: it sets
// bionic's environ for the driver's shader compiler, among other driver workarounds. The
// session's own clients need nothing else; games keep the compat layer's BC emulation.
String layers = xclipse ? "VK_LAYER_DROIDDECK_xclipse" : "VK_LAYER_HYBRIS_compat";
environment.add("VK_LAYER_PATH=" + new File(directory, "lib").getPath() + (xclipse ? ":" + XCLIPSE_LAYER_DIR : ""));
environment.add("VK_INSTANCE_LAYERS=" + layers);
// Proton game launches add their WSI layer in front of these (droiddeck-game-env).
environment.add("DROIDDECK_HYBRIS_LAYERS=" + (xclipse ? layers + ":VK_LAYER_HYBRIS_compat" : layers));
if (xclipse) environment.add("DROIDDECK_HYBRIS_LAYER_PATH=" + XCLIPSE_LAYER_DIR);
// DXVK 3 needs 256 bytes of push constants; this driver has 128.
if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2");
// The Android driver has a render node, but no KMS primary node. SDL presents
// through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path.
environment.add("BL_GAMESCOPE_BACKEND=sdl");
// The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles.
environment.add("BL_POWERVR_DRM_HANDLES=1");
environment.add("BL_POWERVR_RENDER_NODE=" + node);
// Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols.
environment.add("BL_STEAM_GL_PRESENT=1");
// Only actual Proton game launches use the bundled DXVK and X11 WSI layer.
environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath());
}
}
@@ -263,7 +263,24 @@ public final class TurnipDriver {
}
private String choose() {
SessionPrefs.ensurePowerVrAutoDrivers(context);
String chosen = SessionPrefs.androidDriver(context);
// Mali (Venus): the phone's own driver draws the screen, as Venus replays on it.
if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) {
Log.i(TAG, "Mali (Venus): display on the system Vulkan loader");
return null;
}
// A Mali under Auto draws its display on Android's own Vulkan loader, whatever an earlier
// build set: a PanVK Android half fails on Mali gralloc. A manual pick is respected.
if (chosen != null && !chosen.isEmpty() && new File("/dev/mali0").exists()
&& !com.droiddeck.launcher.core.DeviceSupport.INSTANCE.adreno()
&& SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))) {
DriverBundle.Bundle bundle = DriverBundle.INSTANCE.containing(context, chosen, false);
if (bundle != null && DriverPairs.INSTANCE.isNonAdreno(bundle.getId())) {
Log.i(TAG, "Mali under Auto: display on the system Vulkan loader, not " + chosen);
return null;
}
}
if (chosen != null && !chosen.isEmpty()) {
if (BUNDLED.contains(chosen)) {
Log.i(TAG, "driver pinned by the user: " + chosen);
@@ -289,6 +306,7 @@ public final class TurnipDriver {
if (forced.startsWith("a7")) return DRIVER_A7XX;
if (forced.startsWith("a6")) return DRIVER_A6XX;
}
if (SystemVulkanDriver.isPowerVr()) return null;
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
if (quest != null) return quest;
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) {
@@ -296,7 +314,7 @@ public final class TurnipDriver {
return null;
}
GpuInfo gpu = gpuDetector.get();
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) {
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO || gpu.getFamily().getMali()) {
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
return null;
}
@@ -22,12 +22,17 @@ object TurnipReleases {
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)
val sha256: String = "", val pair: String = "", val bundle: Boolean = false,
val assetId: Long = 0, val updatedAt: String = "") {
/** "2026-10-15" from GitHub's updated_at; empty when the check did not record it. */
val builtOn: String get() = updatedAt.take(10)
}
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
private class Kind(val linux: Boolean, val label: String, val pair: String, val bundle: Boolean = false)
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Kind?)
/** [prerelease]: a source whose bundles are all test builds offers them from pre-releases too. */
private class Source(val label: String, val repo: String, val prerelease: Boolean = false, val classify: (name: String, tag: String) -> Kind?)
private val SOURCES = listOf(
Source("Banners-Turnip", "The412Banner/Banners-Turnip") { name, tag ->
@@ -56,8 +61,22 @@ object TurnipReleases {
if (!Regex("""^DD-Turnip-v\d+\.\d+\.\d+\.zip$""").matches(name)) return@Source null
Kind(false, "Android + Linux · all Adreno", DriverPairs.ddTurnip(tag), bundle = true)
},
// <Id>-Pair.zip: open drivers for GPUs that are not Adreno (PanVK for Mali, RADV for
// Xclipse), both halves in one zip. One release per driver, replaced in place on each
// rebuild; every one is a test build, published as a pre-release.
Source(NON_ADRENO_LABEL, NON_ADRENO_REPO, prerelease = true) { name, _ ->
val m = Regex("""^(RADV-Xclipse(?:-[A-Za-z0-9]+)*?|PanVK-[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*?)-Pair\.zip$""").find(name) ?: return@Source null
val key = DriverPairs.nonAdreno(m.groupValues[1])
Kind(false, "Android + Linux · " + DriverPairs.nonAdrenoName(key), key, bundle = true)
},
)
private const val NON_ADRENO_REPO = "The412Banner/droiddeck-nonadreno-drivers"
const val NON_ADRENO_LABEL = "Non-Adreno"
private fun sources(): List<Source> =
if (com.droiddeck.launcher.core.DeviceSupport.adreno()) SOURCES.filter { it.repo != NON_ADRENO_REPO } else SOURCES
fun autoPicks(context: Context): List<AutoPicks.Rule> =
AutoPicks.parse(prefs(context).getString(KEY_PICKS, null)) ?: AutoPicks.BUILT_IN
@@ -71,9 +90,13 @@ object TurnipReleases {
val latest = JSONArray()
val failed = ArrayList<String>()
var lastError: Exception? = null
for (src in SOURCES) {
val sources = sources()
for (src in sources) {
try {
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=15"))
// The non-Adreno repo keeps one release per driver plus many component builds (gamescope,
// Venus): its driver pairs fall past the first 15, so it is read in one full page.
val perPage = if (src.repo == NON_ADRENO_REPO) 100 else 15
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=$perPage"))
val seen = HashSet<String>()
var newest: String? = null
for (i in 0 until releases.length()) {
@@ -86,7 +109,7 @@ object TurnipReleases {
val a = list.getJSONObject(j)
val name = a.getString("name")
val kind = src.classify(name, tag) ?: continue
if (kind.bundle && r.optBoolean("prerelease")) continue
if (kind.bundle && r.optBoolean("prerelease") && !src.prerelease) continue
val linux = kind.linux
val label = kind.label
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
@@ -94,7 +117,7 @@ object TurnipReleases {
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
.put("linux", linux).put("label", label).put("sha256", sha).put("pair", kind.pair)
.put("bundle", kind.bundle))
.put("bundle", kind.bundle).put("id", a.optLong("id")).put("updated_at", a.optString("updated_at")))
}
}
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
@@ -103,7 +126,7 @@ object TurnipReleases {
lastError = e
}
}
if (failed.size == SOURCES.size) throw lastError ?: IOException("no source answered")
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 }
@@ -154,7 +177,7 @@ object TurnipReleases {
val a = list.getJSONObject(i)
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", ""), a.optString("pair", ""),
a.optBoolean("bundle", false)))
a.optBoolean("bundle", false), a.optLong("id"), a.optString("updated_at", "")))
}
val latest = ArrayList<Pair<String, String>>()
val l = json.optJSONArray("latest") ?: JSONArray()
@@ -165,16 +188,53 @@ object TurnipReleases {
return Check(out, latest, failed, json.optLong("checkedAt"))
}
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? {
val d = downloads(context)
if (DriverPairs.isNonAdreno(asset.pair) && asset.sha256.isNotEmpty() &&
!asset.sha256.equals(d.optString(SHA_PREFIX + asset.name, asset.sha256), ignoreCase = true)) return null
return d.optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
}
private const val SHA_PREFIX = "sha256:"
private const val ASSET_ID_PREFIX = "asset:"
private const val UPDATED_PREFIX = "updated:"
/** The id an open non-Adreno pair's asset was installed as, whichever build of it that was. */
fun installedIdAnyBuild(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
downloads(context).optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
/**
* An open non-Adreno pair is rebuilt in place under the same tag: a different digest, asset id
* or upload time than the one installed means a newer build.
*/
fun updateAvailable(context: Context, asset: Asset): Boolean {
if (!DriverPairs.isNonAdreno(asset.pair)) return false
val d = downloads(context)
if (d.optString(asset.name, "").isEmpty()) return false
val sha = d.optString(SHA_PREFIX + asset.name, "")
val id = d.optLong(ASSET_ID_PREFIX + asset.name, 0)
val updated = d.optString(UPDATED_PREFIX + asset.name, "")
return (sha.isNotEmpty() && asset.sha256.isNotEmpty() && !sha.equals(asset.sha256, ignoreCase = true)) ||
(id != 0L && asset.assetId != 0L && id != asset.assetId) ||
(updated.isNotEmpty() && asset.updatedAt.isNotEmpty() && updated != asset.updatedAt)
}
/** When the installed build of [asset] was uploaded, as recorded at download ("" if unknown). */
fun installedBuiltOn(context: Context, asset: Asset): String = downloads(context).optString(UPDATED_PREFIX + asset.name, "").take(10)
fun isDownloaded(context: Context, id: String): Boolean {
val d = downloads(context)
return d.keys().asSequence().any { d.optString(it) == id }
}
fun recordDownload(context: Context, asset: Asset, id: String) {
prefs(context).edit().putString(KEY_DOWNLOADS, downloads(context).put(asset.name, id).toString()).apply()
val d = downloads(context).put(asset.name, id)
if (DriverPairs.isNonAdreno(asset.pair)) {
if (asset.sha256.isNotEmpty()) d.put(SHA_PREFIX + asset.name, asset.sha256)
if (asset.assetId != 0L) d.put(ASSET_ID_PREFIX + asset.name, asset.assetId)
if (asset.updatedAt.isNotEmpty()) d.put(UPDATED_PREFIX + asset.name, asset.updatedAt)
}
prefs(context).edit().putString(KEY_DOWNLOADS, d.toString()).apply()
}
fun forget(context: Context, id: String) {
@@ -9,7 +9,7 @@ internal object DroidDeckHudConfig {
"hudOutline" to "40", "hudOutlineAccent" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
@@ -37,11 +37,11 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
fun from(token: String?): DroidDeckHudSize =
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "0.01% low", "FPS .1", "Engine", "Clock")
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "1% low", "0.1% low", "0.01% low", "FPS .1", "Engine", "Clock")
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
val STANDARD_CHIPS = setOf(
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
"Battery", "GPU model", "Engine", "0.01% low", "FPS .1", "Clock",
"Battery", "GPU model", "Engine", "1% low", "0.1% low", "0.01% low", "FPS .1", "Clock",
)
val MEGA_ONLY = setOf(
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
@@ -90,6 +90,8 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showPower = true
private var showBatteryTemp = false
private var showGraph = false
private var showLow1 = true
private var showLow01 = true
private var showLow001 = true
private var fpsDecimal = true
private var showClockTime = true
@@ -299,6 +301,8 @@ class DroidDeckHudView(context: Context) : View(context) {
showPower = cfg.get("showPower", "1") == "1"
showBatteryTemp = cfg.get("showBatteryTemp", "0") == "1"
showGraph = cfg.get("showFPSGraph", "0") == "1"
showLow1 = cfg.get("showLow1", "1") == "1"
showLow01 = cfg.get("showLow01", "1") == "1"
showLow001 = cfg.get("showLow001", "1") == "1"
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
showClockTime = cfg.get("showClock", "1") == "1"
@@ -750,8 +754,10 @@ class DroidDeckHudView(context: Context) : View(context) {
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow1)
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
if (showLow01)
rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow001)
rows.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
@@ -799,7 +805,7 @@ class DroidDeckHudView(context: Context) : View(context) {
val tiles = ArrayList<Tile>()
if (showFPS) tiles.add(Tile("FPS", colFps, listOf(Span(fpsText(fpsNow), colValue, valPx, glow = true)),
"${fmt1(fpsAvg)} avg · ${lowText(lows.low1Fps) ?: "—"} 1%", false))
"${fmt1(fpsAvg)} avg" + (if (showLow1) " · ${lowText(lows.low1Fps) ?: "—"} 1%" else ""), false))
if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx),
"${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false))
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
@@ -963,11 +969,14 @@ class DroidDeckHudView(context: Context) : View(context) {
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx))
val sub = ArrayList<Span>()
sub += Span("1% ", colDim, subPx); sub += Span(lowText(lows.low1Fps) ?: "—", colFps, subPx)
sub += Span(" · 0.1% ", colDim, subPx); sub += Span(lowText(lows.low01Fps) ?: "—", colFps, subPx)
if (showLow001) {
sub += Span(" · 0.01% ", colDim, subPx); sub += Span(lowText(lows.low001Fps) ?: "—", colFps, subPx)
fun low(label: String, value: Float) {
if (sub.isNotEmpty()) sub += Span(" · ", colDim, subPx)
sub += Span("$label ", colDim, subPx)
sub += Span(lowText(value) ?: "—", colFps, subPx)
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer)
.filter { it.isNotBlank() }.joinToString(" · ")
val hdr = if (hdrState != DroidDeckHudHdr.NONE) hdrLine(footPx) else emptyList()
@@ -979,11 +988,13 @@ class DroidDeckHudView(context: Context) : View(context) {
max(measure(footerLabel, footPx), runWidth(hdr)), if (showGraph) sp(120f) else 0f)
val bigBase = headerBottom + sp(8f) + capHeight(big[0].sizePx)
placeRun(left - inkLeft(big[0].text, big[0].sizePx), bigBase, big, glow = true)
val subBase = bigBase + sp(10f) + capHeight(subPx)
placeRun(left - inkLeft(sub[0].text, subPx), subBase, sub)
var last = subBase
var last = bigBase
if (sub.isNotEmpty()) {
last += sp(10f) + capHeight(subPx)
placeRun(left - inkLeft(sub[0].text, subPx), last, sub)
}
if (showGraph) {
val top = subBase + sp(9f)
val top = last + sp(9f)
graphRect = RectF(left, top, left + colW, top + sp(24f))
last = top + sp(24f)
}
@@ -1042,10 +1053,15 @@ class DroidDeckHudView(context: Context) : View(context) {
val groups = ArrayList<List<Span>>()
run {
val l = ArrayList<Span>()
l += Span("1% ", colDim, rowPx); l += Span(lowText(lows.low1Fps) ?: "—", colFps, rowPx)
l += Span(" 0.1% ", colDim, rowPx); l += Span(lowText(lows.low01Fps) ?: "—", colFps, rowPx)
if (showLow001) { l += Span(" 0.01% ", colDim, rowPx); l += Span(lowText(lows.low001Fps) ?: "—", colFps, rowPx) }
groups += l
fun low(label: String, value: Float) {
if (l.isNotEmpty()) l += Span(" ", colDim, rowPx)
l += Span("$label ", colDim, rowPx)
l += Span(lowText(value) ?: "—", colFps, rowPx)
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
if (l.isNotEmpty()) groups += l
}
if (showGPU || showGpuTemp) {
val l = arrayListOf(Span("GPU", colGpu, rowPx))
@@ -1208,8 +1224,10 @@ class DroidDeckHudView(context: Context) : View(context) {
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
right.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow1)
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
if (showLow01)
right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow001)
right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
@@ -22,6 +22,9 @@ object ControllerPrefs {
val sizes = listOf(80, 90, 100, 110, 125)
val deadZones = listOf(0, 5, 8, 12, 15, 20, 25)
const val DEFAULT_DEAD_ZONE_PERCENT = 12
val mappable = listOf(
"a" to R.string.ctrl_button_a, "b" to R.string.ctrl_button_b, "x" to R.string.ctrl_button_x, "y" to R.string.ctrl_button_y,
"lb" to R.string.ctrl_button_lb, "rb" to R.string.ctrl_button_rb, "lt" to R.string.ctrl_button_lt, "rt" to R.string.ctrl_button_rt,
@@ -51,6 +54,7 @@ object ControllerPrefs {
val snap: Boolean,
val customLayout: Boolean,
val mapping: Map<String, String>,
val deadZone: Int,
)
internal fun prefs(context: Context) = context.getSharedPreferences("controller", Context.MODE_PRIVATE)
@@ -72,6 +76,7 @@ object ControllerPrefs {
snap = p.getBoolean("snap", true),
customLayout = p.all.keys.any { it.startsWith("layout.") },
mapping = mappable.associate { (id, _) -> id to target(context, id) },
deadZone = deadZone(context),
)
}
@@ -109,6 +114,13 @@ object ControllerPrefs {
fun rumbleEnabled(context: Context): Boolean = prefs(context).getBoolean("rumble", true)
fun deadZone(context: Context): Int =
prefs(context).getInt("deadZone", DEFAULT_DEAD_ZONE_PERCENT).takeIf { it in deadZones } ?: DEFAULT_DEAD_ZONE_PERCENT
fun setDeadZone(context: Context, percent: Int) {
prefs(context).edit().putInt("deadZone", percent).apply()
}
fun setRumble(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("rumble", on).apply()
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.input
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
/**
* Some firmware turns a mouse's right button into Back. Most report it from the mouse itself; REDMAGIC's
* cast mode injects it from no device and without the virtual-hard-key flag that the navigation bar and
* back gesture set, so that form only counts while a mouse is connected.
*/
class MouseBackInput(private val sendRight: (Boolean) -> Unit, private val mouseAttached: () -> Boolean) {
private val held = mutableSetOf<Int>()
fun onKeyEvent(event: KeyEvent, toGuest: Boolean): Boolean {
if (event.keyCode != KeyEvent.KEYCODE_BACK) return false
val device = event.deviceId
val fromMouse = isFromMouse(event)
val injected = isInjectedBack(event)
if (device in held && (fromMouse || injected)) {
if (event.action == KeyEvent.ACTION_UP) {
held.remove(device)
if (held.isEmpty()) sendRight(false)
}
return true
}
if (event.action != KeyEvent.ACTION_DOWN || event.repeatCount > 0 || !toGuest) return false
if (!fromMouse && !(injected && mouseAttached())) return false
if (held.isEmpty()) sendRight(true)
held.add(device)
return true
}
fun cancel() {
if (held.isEmpty()) return
held.clear()
sendRight(false)
}
fun onDeviceRemoved(deviceId: Int) {
if (held.isEmpty()) return
held.remove(deviceId)
if (!mouseAttached()) held.remove(KeyCharacterMap.VIRTUAL_KEYBOARD)
if (held.isEmpty()) sendRight(false)
}
companion object {
fun isFromMouse(event: KeyEvent): Boolean =
event.isFromSource(InputDevice.SOURCE_MOUSE) || event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)
fun isInjectedBack(event: KeyEvent): Boolean =
event.deviceId == KeyCharacterMap.VIRTUAL_KEYBOARD && (event.flags and KeyEvent.FLAG_VIRTUAL_HARD_KEY) == 0
}
}
@@ -550,6 +550,7 @@ class OnScreenControls(
control.ax = if (adaptive) event.getX(index) else control.cx
control.ay = if (adaptive) event.getY(index) else control.cy
control.drag(event.getX(index), event.getY(index))
control.dirty = true
}
if (SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
apply()
@@ -694,15 +695,18 @@ class OnScreenControls(
private fun adaptiveStickAt(x: Float, y: Float): Control? {
if (!settings.adaptiveSticks || editing || buttonsOnly || quickHidden) return null
if (x < safe.left || x >= width - safe.right || y < safe.top || y >= height - safe.bottom) return null
if (controls.any { it.stick < 0 && isVisible(it) && it.contains(x, y, it.radius, 5f) }) return null
return controls.filter {
val dx = x - it.cx
val dy = y - it.cy
val reach = it.radius * 1.4f * sqrt(1.5f)
it.stick >= 0 && isVisible(it) && it.pressedBy == -1 && dx * dx + dy * dy <= reach * reach
}.minByOrNull {
val dx = x - it.cx
val dy = y - it.cy
if (controls.any { control ->
control.stick < 0 && isVisible(control) && control.contains(x, y, control.radius, 5f)
}) return null
return controls.filter { control ->
val dx = if (control.stick == 0) max(0f, x - control.cx) else x - control.cx
val dy = y - control.cy
val reach = control.radius * 1.4f * sqrt(1.5f)
control.stick >= 0 && isVisible(control) && control.pressedBy == -1 &&
dx * dx + dy * dy <= reach * reach
}.minByOrNull { control ->
val dx = x - control.cx
val dy = y - control.cy
dx * dx + dy * dy
}
}
@@ -737,7 +741,10 @@ class OnScreenControls(
bridge.setSystemButtons(controls.any { it.id == "guide" && it.pressedBy != -1 }, qamHeld)
} else {
bridge.setSystemButtons(false, qamHeld)
bridge.applyTouch(this, InputRole.PRIMARY) { state ->
val stickWrites = controls.filter { it.stick >= 0 && it.dirty }.fold(0) { mask, control ->
mask or if (control.stick == 0) PadBridge.LEFT_STICK else PadBridge.RIGHT_STICK
}
bridge.applyTouch(this, InputRole.PRIMARY, stickWrites) { state ->
val used = HashSet<String>()
val held = HashSet<String>()
for (control in controls) {
@@ -17,7 +17,10 @@ import java.util.concurrent.atomic.AtomicIntegerArray;
public final class PadBridge {
private static final String TAG = "PadBridge";
public static final int SLOTS = 4;
public static final int LEFT_STICK = 1;
public static final int RIGHT_STICK = 2;
private static final float DEAD_ZONE = 0.12f;
private float stickDeadZone = DEAD_ZONE;
private static final int[] JOYSTICK_AXES = {
MotionEvent.AXIS_X, MotionEvent.AXIS_Y, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ,
MotionEvent.AXIS_RX, MotionEvent.AXIS_RY,
@@ -52,6 +55,8 @@ public final class PadBridge {
private volatile java.util.function.IntPredicate excluded = id -> false;
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
private final float[][] rawSticks = new float[SLOTS][4];
private final int[] retainedSticks = new int[SLOTS];
private final PadState effectiveState = new PadState();
private final PadState homeGuideReport = new PadState();
private final PadState combinedState = new PadState();
@@ -203,7 +208,7 @@ public final class PadBridge {
chordButtonPressed = false;
qamChordGeneration++;
chordHandler.removeCallbacksAndMessages(null);
state.clear();
clearPlayerState(0);
publish();
}
@@ -240,7 +245,7 @@ public final class PadBridge {
playerWriters[slot].destroy();
playerWriters[slot] = null;
}
if (playerStates[slot] != null) playerStates[slot].clear();
clearPlayerState(slot);
}
systemGuidePressed = false;
systemQamPressed = false;
@@ -250,7 +255,7 @@ public final class PadBridge {
qamTapPressed = false;
qamChordGeneration++;
if (open) {
state.clear();
clearPlayerState(0);
writer.writePad(state);
writer.close();
open = false;
@@ -415,6 +420,65 @@ public final class PadBridge {
return true;
}
public synchronized void setStickDeadZone(int percent) {
float value = Math.max(0, Math.min(25, percent)) / 100f;
if (stickDeadZone == value) return;
stickDeadZone = value;
for (int slot = 0; slot < SLOTS; slot++) {
if (retainedSticks[slot] == 0) continue;
int owner = owners[slot], partner = partners[slot];
if (owner != NO_CONTROLLER && (InputDevice.getDevice(owner) == null || excluded.test(owner))) leave(slot, owner);
if (partner != NO_CONTROLLER && (InputDevice.getDevice(partner) == null || excluded.test(partner))) leave(slot, partner);
if (retainedSticks[slot] == 0) continue;
projectSticks(slot);
publish(slot);
}
}
private void retainStick(int slot, int side, float x, float y) {
rawSticks[slot][side * 2] = x;
rawSticks[slot][side * 2 + 1] = y;
retainedSticks[slot] |= 1 << side;
}
private void projectSticks(int slot) {
PadState pad = stateFor(slot);
for (int side = 0; side < 2; side++) {
if ((retainedSticks[slot] & (1 << side)) == 0) continue;
float x = rawSticks[slot][side * 2];
float y = rawSticks[slot][side * 2 + 1];
boolean centred = inStickDeadZone(x, y, stickDeadZone);
if (side == JoyCon.LEFT) {
pad.leftX = centred ? 0f : x;
pad.leftY = centred ? 0f : y;
} else {
pad.rightX = centred ? 0f : x;
pad.rightY = centred ? 0f : y;
}
}
}
private void clearPlayerState(int slot) {
stateFor(slot).clear();
retainedSticks[slot] = 0;
Arrays.fill(rawSticks[slot], 0f);
}
private void mutateState(java.util.function.Consumer<PadState> mutation) {
float lx = state.leftX, ly = state.leftY, rx = state.rightX, ry = state.rightY;
mutation.accept(state);
if (state.leftX != lx || state.leftY != ly) retainedSticks[0] &= ~1;
if (state.rightX != rx || state.rightY != ry) retainedSticks[0] &= ~2;
}
static boolean inStickDeadZone(float x, float y, float deadZone) {
return x * x + y * y < deadZone * deadZone;
}
private static boolean hasChordStickInput(float x, float y) {
return Math.max(Math.abs(x), Math.abs(y)) >= DEAD_ZONE;
}
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isControllerMotionEvent(event) || excluded.test(event.getDeviceId())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
@@ -429,26 +493,25 @@ public final class PadBridge {
int side = JoyCon.side(device);
if (side >= 0) {
int[] stick = JoyCon.stickAxes(side, device, event.getSource());
float x = axis(event, stick[0]);
float y = axis(event, stick[1]);
if (side == JoyCon.LEFT) {
pad.leftX = x;
pad.leftY = y;
} else {
pad.rightX = x;
pad.rightY = y;
}
if (x != 0f || y != 0f) noteChordInput(slot);
float x = event.getAxisValue(stick[0]);
float y = event.getAxisValue(stick[1]);
boolean chordStickInput = hasChordStickInput(x, y);
retainStick(slot, side, x, y);
projectSticks(slot);
if (chordStickInput) noteChordInput(slot);
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
publish(slot);
InputTiming.end(timing);
return true;
}
pad.leftX = axis(event, MotionEvent.AXIS_X);
pad.leftY = axis(event, MotionEvent.AXIS_Y);
float lx = event.getAxisValue(MotionEvent.AXIS_X);
float ly = event.getAxisValue(MotionEvent.AXIS_Y);
boolean wired = wiredXboxLayout(event);
pad.rightX = rightX(event, wired);
pad.rightY = rightY(event, wired);
float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
retainStick(slot, JoyCon.LEFT, lx, ly);
retainStick(slot, JoyCon.RIGHT, rx, ry);
projectSticks(slot);
int source = event.getSource();
float lt = 0f;
float rt = 0f;
@@ -470,7 +533,7 @@ public final class PadBridge {
pad.up = hatY < -0.5f;
pad.down = hatY > 0.5f;
}
if (pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
if (hasChordStickInput(lx, ly) || hasChordStickInput(rx, ry)
|| lt > 0f || rt > 0f || pad.up || pad.right || pad.down || pad.left) noteChordInput(slot);
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
@@ -500,10 +563,18 @@ public final class PadBridge {
}
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
applyTouch(defaultTouchSource, InputRole.PRIMARY, mutation);
applyTouch(defaultTouchSource, InputRole.PRIMARY, 0, mutation);
}
public synchronized void applyTouch(int stickWrites, java.util.function.Consumer<PadState> mutation) {
applyTouch(defaultTouchSource, InputRole.PRIMARY, stickWrites, mutation);
}
public synchronized void applyTouch(Object owner, InputRole role, java.util.function.Consumer<PadState> mutation) {
applyTouch(owner, role, 0, mutation);
}
public synchronized void applyTouch(Object owner, InputRole role, int stickWrites, java.util.function.Consumer<PadState> mutation) {
if (!builtinPad) return;
long timing = InputTiming.begin();
TouchSource source = touchSources.get(owner);
@@ -512,7 +583,18 @@ public final class PadBridge {
if (inputRouter != null) source.route = inputRouter.pad(role);
touchSources.put(owner, source);
}
float lx = source.raw.leftX, ly = source.raw.leftY, rx = source.raw.rightX, ry = source.raw.rightY;
mutation.accept(source.raw);
if (inputRouter == null && (touchRoute == null || !touchRoute.active())) {
if ((stickWrites & LEFT_STICK) != 0 || source.raw.leftX != lx || source.raw.leftY != ly) {
retainedSticks[0] &= ~LEFT_STICK;
state.leftX = state.leftY = 0f;
}
if ((stickWrites & RIGHT_STICK) != 0 || source.raw.rightX != rx || source.raw.rightY != ry) {
retainedSticks[0] &= ~RIGHT_STICK;
state.rightX = state.rightY = 0f;
}
}
activeControllerId = NO_CONTROLLER;
slotControllers.set(0, NO_CONTROLLER);
notePlayerInput();
@@ -530,7 +612,7 @@ public final class PadBridge {
}
public synchronized void applyExternal(java.util.function.Consumer<PadState> mutation, boolean changed) {
mutation.accept(state);
mutateState(mutation);
if (changed) {
activeControllerId = NO_CONTROLLER;
notePlayerInput();
@@ -566,7 +648,7 @@ public final class PadBridge {
if (inputRouter == null) for (TouchSource source : touchSources.values()) source.raw.clear();
routedTouch.clear();
DeckControls.INSTANCE.suspend();
if (inputRouter == null) state.clear();
if (inputRouter == null) clearPlayerState(0);
homeGuidePressed = false;
homeGuideSlot = -1;
clearBackQamWrites();
@@ -574,8 +656,8 @@ public final class PadBridge {
if (inputRouter == null) releaseBackPaddles();
publish();
for (int slot = 1; slot < SLOTS; slot++) {
if (inputRouter == null) clearPlayerState(slot);
if (playerWriters[slot] == null) continue;
if (inputRouter == null) playerStates[slot].clear();
publish(slot);
}
}
@@ -615,7 +697,7 @@ public final class PadBridge {
if (!homeGuidePressed) return;
clearBackQamWrites();
homeGuidePressed = false;
if (inputRouter == null) state.clear();
if (inputRouter == null) clearPlayerState(0);
else {
inputRouter.releaseAll();
DeckControls.INSTANCE.suspend();
@@ -642,7 +724,7 @@ public final class PadBridge {
writeBackQamReport(modifier, modifierAt);
}
if (!pressed && !backQamPressed && !homeGuidePressed) {
backQamAxesBlocked = hasAxes(liveReport);
backQamAxesBlocked = hasQamAxes();
if (!backQamWrites.isEmpty()) {
PadState neutral = new PadState();
neutral.copyFrom(lastWrittenReport);
@@ -658,7 +740,7 @@ public final class PadBridge {
if (!backQamPressed && backQamWrites.isEmpty()) return;
clearBackQamWrites();
backQamPressed = false;
if (inputRouter == null) state.clear();
if (inputRouter == null) clearPlayerState(0);
else {
inputRouter.releaseAll();
DeckControls.INSTANCE.suspend();
@@ -699,15 +781,18 @@ public final class PadBridge {
private void writePad(PadState report) {
liveReport.copyFrom(report);
if (backQamAxesBlocked && !hasAxes(liveReport)) backQamAxesBlocked = false;
if (backQamAxesBlocked && !hasQamAxes()) backQamAxesBlocked = false;
long at = android.os.SystemClock.uptimeMillis();
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
writeBackQamReport(report, at);
}
private static boolean hasAxes(PadState pad) {
return pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|| pad.leftTrigger != 0f || pad.rightTrigger != 0f;
private boolean hasQamAxes() {
boolean left = (retainedSticks[0] & 1) != 0 && liveReport.leftX == state.leftX && liveReport.leftY == state.leftY
? hasChordStickInput(rawSticks[0][0], rawSticks[0][1]) : liveReport.leftX != 0f || liveReport.leftY != 0f;
boolean right = (retainedSticks[0] & 2) != 0 && liveReport.rightX == state.rightX && liveReport.rightY == state.rightY
? hasChordStickInput(rawSticks[0][2], rawSticks[0][3]) : liveReport.rightX != 0f || liveReport.rightY != 0f;
return left || right || liveReport.leftTrigger != 0f || liveReport.rightTrigger != 0f;
}
private static void clearAxes(PadState pad) {
@@ -845,7 +930,7 @@ public final class PadBridge {
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
if (slot == firstPlayerSlot()) releaseBackPaddles();
if (slot == 0) clearBackQamWrites();
stateFor(slot).clear();
clearPlayerState(slot);
if (slot == 0) publish();
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
return slot;
@@ -893,7 +978,7 @@ public final class PadBridge {
if (slotControllers.get(slot) == id) slotControllers.set(slot, owners[slot]);
if (activeControllerId == id) activeControllerId = owners[slot];
if (slot == firstPlayerSlot()) releaseBackPaddles();
stateFor(slot).clear();
clearPlayerState(slot);
publish(slot);
}
@@ -912,11 +997,11 @@ public final class PadBridge {
if (slot == homeGuideSlot) homeGuideSlot = -1;
if (slot == firstPlayerSlot()) releaseBackPaddles();
if (slot == 0) {
state.clear();
clearPlayerState(0);
publish();
return;
}
playerStates[slot].clear();
clearPlayerState(slot);
if (playerWriters[slot] != null) {
playerWriters[slot].destroy();
playerWriters[slot] = null;
@@ -1035,14 +1120,6 @@ public final class PadBridge {
&& device.getMotionRange(MotionEvent.AXIS_RZ, event.getSource()) != null;
}
public static float rightX(MotionEvent event, boolean wired) {
return axis(event, wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
}
public static float rightY(MotionEvent event, boolean wired) {
return axis(event, wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
}
public static float leftTrigger(MotionEvent event, boolean wired) {
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f));
float value = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
@@ -1055,8 +1132,4 @@ public final class PadBridge {
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_GAS);
}
private static float axis(MotionEvent event, int axis) {
float value = event.getAxisValue(axis);
return Math.abs(value) < DEAD_ZONE ? 0f : value;
}
}
@@ -90,8 +90,8 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }
sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X)
sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y)
sticks.rightX = PadBridge.rightX(event, wired)
sticks.rightY = PadBridge.rightY(event, wired)
sticks.rightX = scrollAxis(event, if (wired) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z)
sticks.rightY = scrollAxis(event, if (wired) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ)
if (hasTriggerAxes(event)) {
sticks.leftTrigger = PadBridge.leftTrigger(event, wired)
sticks.rightTrigger = PadBridge.rightTrigger(event, wired)
@@ -295,6 +295,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
}
companion object {
private const val SCROLL_AXIS_DEAD_ZONE = 0.12f
private const val DEAD_ZONE = 0.15f
private const val STICK_NAVIGATE = 0.5f
private const val REPEAT_FIRST_MS = 300L
@@ -348,6 +349,9 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
return scaled * scaled / length
}
private fun scrollAxis(event: MotionEvent, axis: Int): Float =
event.getAxisValue(axis).let { if (abs(it) < SCROLL_AXIS_DEAD_ZONE) 0f else it }
private fun source(deviceId: Int, kind: Int): Int = deviceId * 2 + kind
@@ -0,0 +1,20 @@
package com.droiddeck.launcher.input
import android.graphics.RectF
/**
* The area of the session view that drives the guest pointer.
*
* The view is also the compositor output only while it shows the picture: the phone, or the
* bottom screen. With the glasses owning the output the view is a touchpad for a scene drawn
* elsewhere, so the whole view has to drive the pointer. Using the picture rect there would
* confine it to the letterboxed band the scene would occupy on the phone, and the pointer could
* not reach the scene edges.
*/
object PointerSpace {
fun area(viewWidth: Int, viewHeight: Int, glassesOwnOutput: Boolean, picture: RectF?): RectF? {
if (viewWidth <= 0 || viewHeight <= 0) return null
if (glassesOwnOutput) return RectF(0f, 0f, viewWidth.toFloat(), viewHeight.toFloat())
return picture
}
}
@@ -61,6 +61,9 @@ object BattleNet {
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
fun notInstalled(title: Title, installedIds: Collection<String?>) =
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
@@ -164,8 +167,10 @@ object BattleNet {
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
CN_UIDS[id]?.let { alias -> TITLES.firstOrNull { it.uid == alias }?.let { return it } }
val base = id.substringBeforeLast('_', "")
return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null
if (base.isEmpty() || id.substringAfterLast('_') !in LOCALES) return null
return TITLES.firstOrNull { it.uid == base } ?: CN_UIDS[base]?.let { alias -> TITLES.firstOrNull { it.uid == alias } }
}
internal fun titleForProduct(product: String): Title? {
@@ -9,6 +9,7 @@ import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.net.RouteInfo
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
@@ -23,6 +24,7 @@ import java.io.File
import java.io.IOException
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.InetAddress
import org.json.JSONArray
import org.json.JSONObject
@@ -156,7 +158,7 @@ class LinuxNetworkLinkComponent(
try {
file.parentFile?.mkdirs()
val staged = File(file.path + ".staged")
staged.writeText(describe(properties))
staged.writeText(describe(properties, capabilities))
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network link", e)
@@ -210,11 +212,7 @@ class LinuxNetworkLinkComponent(
}
})
put("gateways", JSONArray().apply {
properties?.routes.orEmpty().filter { it.isDefaultRoute }.forEach {
it.gateway?.takeUnless { address -> address.isAnyLocalAddress }?.let { address ->
put(address.hostAddress?.substringBefore('%'))
}
}
gateways(properties, capabilities).forEach { put(it.hostAddress?.substringBefore('%')) }
})
put("dns", JSONArray().apply {
properties?.dnsServers.orEmpty().filter { !it.isLinkLocalAddress }.forEach {
@@ -301,7 +299,7 @@ class LinuxNetworkLinkComponent(
}
}
private fun describe(properties: LinkProperties?): String {
internal fun describe(properties: LinkProperties?, capabilities: NetworkCapabilities?): String {
val addresses = properties?.linkAddresses.orEmpty()
.filter { it.address is Inet4Address || it.address is Inet6Address }
val name = properties?.interfaceName?.takeIf { addresses.isNotEmpty() } ?: OFFLINE_NAME
@@ -316,10 +314,7 @@ class LinuxNetworkLinkComponent(
for (address in addresses) {
append("addr ${address.address.hostAddress?.substringBefore('%')} ${address.prefixLength}\n")
}
for (family in listOf(Inet4Address::class.java, Inet6Address::class.java)) {
val gateway = properties?.routes.orEmpty()
.firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress }
?.gateway ?: continue
for (gateway in gateways(properties, capabilities)) {
append("gw ${gateway.hostAddress?.substringBefore('%')}\n")
}
}
@@ -329,6 +324,27 @@ class LinuxNetworkLinkComponent(
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
companion object {
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
properties?.routes.orEmpty()
.firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress }
?.gateway
?: if (family == Inet4Address::class.java &&
capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
properties?.interfaceName != null &&
properties.routes.any {
it.destination.address is Inet4Address &&
(Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || it.type == RouteInfo.RTN_UNICAST)
}
) {
properties.linkAddresses.firstOrNull {
it.address is Inet4Address && !it.address.isAnyLocalAddress &&
!it.address.isLoopbackAddress && !it.address.isLinkLocalAddress
}?.address
} else null
}
internal fun seededMac(readId: () -> String?): String {
val id = runCatching(readId).getOrNull() ?: "bannerlator"
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
@@ -7,6 +7,7 @@ import android.system.ErrnoException;
import android.system.Os;
import android.system.StructStat;
import android.system.StructUtsname;
import com.droiddeck.launcher.gpu.SystemVulkanDriver;
import com.droiddeck.launcher.session.SessionPrefs;
@@ -191,6 +192,13 @@ public final class LinuxRuntime {
bind(cmd, "/dev");
bind(cmd, "/proc");
bind(cmd, "/sys");
if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
// The glibc bridge loads the device's existing Android HAL and its dependencies.
// These read-only Android partitions remain subject to the app's normal permissions.
for (String path : new String[]{"/system", "/vendor", "/apex", "/system_ext", "/product", "/odm"})
if (new File(path).isDirectory()) bind(cmd, path);
if (new File("/linkerconfig/ld.config.txt").isFile()) bind(cmd, "/linkerconfig/ld.config.txt");
}
bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight");
bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
@@ -198,6 +206,10 @@ public final class LinuxRuntime {
bind(cmd, "/proc/self/fd/1:/dev/stdout");
bind(cmd, "/proc/self/fd/2:/dev/stderr");
bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/fs/selinux");
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
bind(cmd, liveDir(context).getPath());
@@ -259,7 +271,11 @@ public final class LinuxRuntime {
if (unreadablePciDevice()) {
bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/bus/pci/devices");
}
bindGpuNode(context, cmd);
if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
bindPowerVrGpuNode(context, cmd);
} else {
bindGpuNode(context, cmd);
}
bindAdrenoStats(cmd, extraBinds);
bindCpuTemps(cmd, root);
if (extraBinds != null) {
@@ -270,6 +286,24 @@ public final class LinuxRuntime {
return specs;
}
private static void bindPowerVrGpuNode(Context context, List<String> cmd) {
if (new File("/dev/dri").list() != null) return;
String node = SystemVulkanDriver.renderNodePath();
if (node == null) return;
String name = new File(node).getName();
File dri = new File(context.getCacheDir(), "powervr-drm/" + name + "/dri");
try {
if (!dri.isDirectory() && !dri.mkdirs()) return;
new File(dri, name).createNewFile();
} catch (IOException e) {
android.util.Log.w("LinuxRuntime", "Cannot expose the PowerVR render node", e);
return;
}
bind(cmd, dri.getPath() + ":/dev/dri");
bind(cmd, node + ":" + node);
android.util.Log.i("LinuxRuntime", "PowerVR: exposing real " + name + " through a listable directory");
}
private static boolean unreadablePciDevice() {
File[] devices = new File("/sys/bus/pci/devices").listFiles();
if (devices == null) return false;
@@ -279,7 +313,7 @@ public final class LinuxRuntime {
return false;
}
static final String MALI_DEVICE = "/dev/mali0";
public static final String MALI_DEVICE = "/dev/mali0";
static final String[] DRM_RENDER_NODES = {
"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/renderD130", "/dev/dri/renderD131",
@@ -287,6 +321,7 @@ public final class LinuxRuntime {
public static String gpuStandIn(Context context) {
if (new File(KGSL_DEVICE).exists()) return KGSL_DEVICE;
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.openDriverActive(context) && new File(MALI_DEVICE).exists()) return MALI_DEVICE;
if (!com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) return null;
return bridgeStandIn(path -> new File(path).exists());
}
@@ -0,0 +1,164 @@
package com.droiddeck.launcher.runtime
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstalls
import org.apache.commons.compress.archivers.zip.ZipFile
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.LinkOption
object WowAddons {
var imports by mutableIntStateOf(0)
private set
class TooLarge : IOException()
class Target(val flavor: String, val addOns: File)
class Addon(val name: String, val root: String)
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE)
fun targets(game: Library.SteamGame): List<Target> {
if (game.source != Store.BATTLENET.id) return emptyList()
val title = game.storeId?.let(BattleNet::title) ?: return emptyList()
if (title.flavor == null) return emptyList()
val folder = game.gameFiles ?: return emptyList()
return targets(title, folder)
}
internal fun targets(title: BattleNet.Title, folder: File): List<Target> {
val flavors = BattleNet.TITLES.filter { it.code == title.code }.mapNotNull { it.flavor }
.flatMap { listOf(it, it.dropLast(1) + "_beta_") }.distinct()
val root = if (folder.name in flavors) folder.parentFile ?: return emptyList() else folder
return flavors.map { File(root, it) }.filter { it.isDirectory }.map { Target(it.name, addOnsFolder(it)) }
}
fun installed(target: Target): List<String> =
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
.map { it.name }.sortedBy { it.lowercase() }
fun delete(target: Target, name: String) {
val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") }
?: throw IOException("Cannot find $name")
StoreInstalls.deleteTree(folder)
if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name")
imports++
}
fun import(zipFile: File, target: Target): List<String> {
ZipFile.builder().setFile(zipFile).get().use { zip ->
val all = zip.entries.toList()
if (all.any { it.isUnixSymlink }) return emptyList()
val entries = all.filter { clean(it.name) != null }
val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) })
if (addons.isEmpty()) return emptyList()
val addOns = target.addOns
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
try {
val fresh = File(stage, "new")
val buffer = ByteArray(64 * 1024)
var written = 0L
for (entry in entries) {
if (entry.isDirectory) continue
val path = clean(entry.name) ?: continue
val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue
val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue
out.parentFile?.mkdirs()
zip.getInputStream(entry).use { input ->
out.outputStream().use { output ->
while (true) {
val read = input.read(buffer)
if (read < 0) break
written += read
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
output.write(buffer, 0, read)
}
}
}
}
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
} finally {
StoreInstalls.deleteTree(stage)
}
imports++
return addons.map { it.name }
}
}
internal fun addons(files: List<String>): List<Addon> {
val tocs = files.filter { it.endsWith(".toc", ignoreCase = true) }
val folders = tocs.map { it.substringBeforeLast('/', "") }.distinct().sortedBy { it.length }
val roots = ArrayList<String>()
for (folder in folders) {
if (roots.none { it.isEmpty() || folder.startsWith("$it/") }) roots.add(folder)
}
return roots.mapNotNull { root ->
val inFolder = tocs.filter { it.substringBeforeLast('/', "") == root }
.map { it.substringAfterLast('/').dropLast(4) }
val name = addonName(root.substringAfterLast('/'), inFolder)
name.takeIf { it.isNotEmpty() && !it.startsWith(".") }?.let { Addon(it, if (root.isEmpty()) "" else "$root/") }
}.distinctBy { it.name.lowercase() }
}
private fun addonName(folder: String, tocs: List<String>): String {
val match = tocs.firstOrNull { it.equals(folder, ignoreCase = true) }
?: tocs.firstOrNull { it.replace(SUFFIX, "").equals(folder, ignoreCase = true) }
if (match != null) return folder
return tocs.map { it.replace(SUFFIX, "") }.minByOrNull { it.length }.orEmpty()
}
private fun clean(name: String): String? {
val parts = name.replace('\\', '/').trim('/').split('/')
if (name.startsWith("/") || name.startsWith("\\") || parts.any { it.isEmpty() || it == "." || it == ".." || it.endsWith(":") }) return null
if (parts.first() == "__MACOSX" || parts.last().startsWith("._")) return null
return parts.joinToString("/")
}
private fun inside(root: File, path: String): File? {
val out = File(root, path)
return out.takeIf { it.canonicalPath.startsWith(root.canonicalPath + File.separator) }
}
private fun addOnsFolder(flavor: File): File = child(child(flavor, "Interface"), "AddOns")
private fun child(parent: File, name: String): File =
parent.listFiles()?.firstOrNull { it.name.equals(name, ignoreCase = true) } ?: File(parent, name)
internal fun swap(fresh: List<Pair<File, String>>, addOns: File, old: File) {
val done = ArrayList<Replaced>()
try {
for ((folder, name) in fresh) done.add(replace(folder, addOns, name, old))
} catch (e: IOException) {
done.asReversed().forEach { undo(it) }
throw e
}
}
private class Replaced(val installed: File, val previous: File?, val kept: File?)
private fun undo(replaced: Replaced) {
StoreInstalls.deleteTree(replaced.installed)
if (replaced.previous != null) replaced.kept?.renameTo(replaced.previous)
}
private fun replace(fresh: File, addOns: File, name: String, old: File): Replaced {
val current = addOns.listFiles()?.firstOrNull { it.name.equals(name, ignoreCase = true) }
val kept = current?.let { File(old, it.name) }
if (current != null && !current.renameTo(kept!!)) throw IOException("Cannot replace ${current.path}")
val installed = File(addOns, name)
if (!fresh.renameTo(installed)) {
kept?.renameTo(current)
throw IOException("Cannot install $name")
}
return Replaced(installed, current, kept)
}
}
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.gpu.AppVulkan
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
import com.github.luben.zstd.ZstdOutputStream
@@ -199,9 +200,13 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
require(comp in COMPONENTS)
if (file != null) requireSelectable(context, comp, managed)
val state = loadState(context)
val profiles = state.sub("profiles")
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
@@ -638,11 +643,21 @@ object ComponentsManager {
return PreparedLaunchState(lines.toString(), keep)
}
internal fun runtimeManaged(comp: String, systemPowerVr: Boolean): Boolean = comp == "dxvk" && systemPowerVr
private fun runtimeManaged(context: Context, comp: String): Boolean =
runtimeManaged(comp, SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)))
private fun requireSelectable(context: Context, comp: String, managed: (String) -> Boolean = { runtimeManaged(context, it) }) {
check(!managed(comp)) { context.getString(R.string.cmgr_powervr_dxvk_managed) }
}
fun swap(context: Context, protonId: String, file: String, auto: Boolean = false): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
requireSelectable(context, info.comp)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
@@ -668,6 +683,7 @@ object ComponentsManager {
}
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
requireSelectable(context, comp)
val p = proton(context, protonId)
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(wcp.isFile) { context.getString(R.string.cmgr_original_missing) }
@@ -693,7 +709,10 @@ object ComponentsManager {
.put("protonVersion", p.version).put("files", JSONObject(fingerprint(p.dir, comp) as Map<*, *>)).put("at", System.currentTimeMillis() / 1000))
}
fun applyQueued(context: Context): List<String> = synchronized(lock) {
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
fun applyQueued(context: Context): List<String> = applyQueued(context) { runtimeManaged(context, it) }
internal fun applyQueued(context: Context, managed: (String) -> Boolean): List<String> = synchronized(lock) {
val state = loadState(context)
val queued = state.sub("queued")
if (queued.length() == 0) return emptyList()
@@ -705,6 +724,7 @@ object ComponentsManager {
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val q = comps.optJSONObject(comp) ?: continue
if (managed(comp)) continue
runCatching {
if (q.optString("kind") == "original") {
val v = q.optString("protonVersion")
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.AtomicFile
import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object EnhancedDiagnostics {
const val MANIFEST_FILE = "enhanced-diagnostics.json"
private const val TAG = "EnhancedDiagnostics"
private const val PREFS = "session"
private const val ARMED = "enhancedDiagnosticsNext"
private const val ACTIVE_RECORDS = "enhancedDiagnosticsActiveSessions"
private const val SCHEMA = 1
fun isArmed(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(ARMED, false)
fun setArmed(context: Context, armed: Boolean): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(ARMED, armed).commit()
fun isActive(context: Context, folder: File?): Boolean = activeAt(context, folder) != null
internal fun isCurrentSessionActive(context: Context): Boolean = isActive(context, SessionPaths.current())
fun manifest(context: Context, folder: File?): JSONObject? {
val activeAt = activeAt(context, folder) ?: return null
return buildManifest(folder!!, activeAt)
}
@Synchronized
internal fun consumeInto(context: Context, folder: File): Boolean {
if (!isArmed(context)) return isActive(context, folder)
if (!folder.isDirectory) return false
val activatedAt = System.currentTimeMillis()
if (!activateAndConsume(context, folder, activatedAt)) return false
val marker = AtomicFile(File(folder, MANIFEST_FILE))
val manifest = buildManifest(folder, activatedAt)
val output = try {
marker.startWrite()
} catch (error: Exception) {
Log.w(TAG, "could not start the informational enhanced diagnostics manifest", error)
return true
}
try {
output.write((manifest.toString() + "\n").toByteArray(Charsets.UTF_8))
marker.finishWrite(output)
} catch (error: Exception) {
marker.failWrite(output)
Log.w(TAG, "could not write the informational enhanced diagnostics manifest", error)
}
return true
}
@Synchronized
internal fun clearRecordFor(context: Context, folder: File) {
removeRecord(context, folder)
}
private fun buildManifest(folder: File, activatedAt: Long) = JSONObject()
.put("schema", SCHEMA)
.put("profile", "enhanced")
.put("sessionId", folder.name)
.put("activatedAtEpochMs", activatedAt)
.put("exportBundlesBounded", true)
.put("rawCaptureByteBounded", false)
.put("rawCaptureLimitation", "Game and component diagnostics may grow until the session ends")
.put("collectorsRequested", JSONArray(listOf(
"session", "graphics", "games", "processes", "audio", "network", "components",
)))
private fun activeAt(context: Context, folder: File?): Long? {
val path = trustedPath(context, folder) ?: return null
return records(context).optLong(path, Long.MIN_VALUE).takeIf { it != Long.MIN_VALUE }
}
private fun activateAndConsume(context: Context, folder: File, activatedAt: Long): Boolean {
val path = trustedPath(context, folder) ?: return false
val records = records(context)
records.keys().asSequence().toList().forEach { known ->
if (!File(known).isDirectory) records.remove(known)
}
records.put(path, activatedAt)
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(ACTIVE_RECORDS, records.toString())
.putBoolean(ARMED, false)
.commit()
}
private fun removeRecord(context: Context, folder: File) {
val path = runCatching { folder.canonicalPath }.getOrNull() ?: return
val records = records(context)
if (records.has(path)) {
records.remove(path)
saveRecords(context, records)
}
}
private fun trustedPath(context: Context, folder: File?): String? {
if (folder == null || !SessionPaths.isSessionFolder(folder)) return null
return runCatching {
val canonical = folder.canonicalFile
if (canonical.parentFile != SessionFiles.logDirectory(context).canonicalFile) null else canonical.path
}.getOrNull()
}
private fun records(context: Context): JSONObject {
val text = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(ACTIVE_RECORDS, null)
return runCatching { JSONObject(text ?: "{}") }.getOrDefault(JSONObject())
}
private fun saveRecords(context: Context, records: JSONObject): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(ACTIVE_RECORDS, records.toString()).commit()
}
@@ -0,0 +1,975 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.ParcelFileDescriptor
import android.system.Os
import android.system.OsConstants
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.Closeable
import java.io.File
import java.io.FileOutputStream
import java.io.FileInputStream
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.channels.Channels
import java.nio.channels.FileChannel
import java.nio.channels.FileLock
import java.nio.channels.OverlappingFileLockException
import java.nio.channels.SeekableByteChannel
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.StandardOpenOption
import java.nio.file.attribute.BasicFileAttributes
import java.security.MessageDigest
import java.util.Locale
import java.util.UUID
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
internal data class EnhancedShareLimits(
val maxFilesPerArchive: Int = 256,
val maxDiscoveredFiles: Int = 768,
val maxBytesPerFile: Long = 8L * 1024 * 1024,
val maxBytesTotal: Long = 64L * 1024 * 1024,
)
internal interface SecureSourceOpener {
fun <T> withChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T?
}
internal object EnhancedSessionLogShare {
private enum class Category(val suffix: String) { SESSION("session"), GRAPHICS("graphics"), GAMES("games") }
internal class DiagnosticStageLease internal constructor(
val directory: File,
private val canonicalPath: String,
private val channel: FileChannel,
private val lock: FileLock,
) : Closeable {
override fun close() {
synchronized(stageLifecycleMonitor) {
activeStagePaths.remove(canonicalPath)
try {
lock.release()
} finally {
try {
channel.close()
} finally {
directory.deleteRecursively()
}
}
}
}
}
private data class Candidate(
val file: File,
val anchor: File,
val entry: String,
val origin: String,
val category: Category,
val linePrefix: String? = null,
)
private data class Record(
val entry: String,
val origin: String,
val status: String,
val sourceBytes: Long = 0,
val capturedBytes: Long = 0,
val reason: String? = null,
)
private data class Snapshot(val file: File, val sourceBytes: Long, val truncated: Boolean)
private class StageUnavailableException(cause: Throwable) : IOException("Diagnostic staging directory is unavailable", cause)
private class SourceReadException(cause: Throwable) : IOException("Could not read diagnostic source", cause)
private data class CollectionResult(
val candidates: List<Candidate>,
val truncated: Boolean,
val partial: Boolean,
)
private data class ScanResult(
val files: List<File>,
val truncated: Boolean,
val partial: Boolean = false,
)
private data class LegacySource(val file: File, val root: File, val entry: String)
private data class LegacyDiscovery(
val sources: List<LegacySource>,
val truncated: Boolean,
val partial: Boolean,
)
private class Budget(val limit: Long, var remaining: Long = limit)
private val sourceOpenerOverride = object : ThreadLocal<SecureSourceOpener?>() {
override fun initialValue(): SecureSourceOpener? = null
}
private val stageLifecycleMonitor = Any()
private val activeStagePaths = mutableSetOf<String>()
internal fun acquireDiagnosticStage(context: Context, outputName: String): DiagnosticStageLease {
val cache = context.cacheDir
require(outputName.isNotBlank() && File(outputName).name == outputName)
return withStageLifecycleLock(cache) {
val stage = File(cache, "$outputName-${UUID.randomUUID()}.diagnostic-stage")
if (!stage.mkdir()) throw IOException("Could not create the diagnostic staging directory")
val channel = try {
FileChannel.open(File(stage, ".active").toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)
} catch (error: Exception) {
stage.deleteRecursively()
throw IOException("Could not create the diagnostic staging lock", error)
}
try {
val lock = channel.tryLock()
?: throw IOException("Could not lock the diagnostic staging directory")
val canonicalPath = stage.canonicalPath
activeStagePaths += canonicalPath
DiagnosticStageLease(stage, canonicalPath, channel, lock)
} catch (error: Exception) {
channel.close()
stage.deleteRecursively()
throw IOException("Could not lock the diagnostic staging directory", error)
}
}
}
internal fun cleanupAbandonedStages(context: Context) {
val cache = context.cacheDir
val canonicalCache = cache.canonicalFile
withStageLifecycleLock(cache) {
cache.listFiles()?.forEach { stage ->
if (!stage.isDirectory || Files.isSymbolicLink(stage.toPath()) ||
stage.canonicalFile.parentFile != canonicalCache || !isDiagnosticStage(stage.name)) return@forEach
if (stage.canonicalPath in activeStagePaths) return@forEach
val active = File(stage, ".active")
if (Files.isSymbolicLink(active.toPath())) return@forEach
val channel = runCatching {
FileChannel.open(active.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
}.getOrNull() ?: return@forEach
val abandoned = try {
channel.tryLock()?.let { lock -> lock.release(); true } ?: false
} catch (_: OverlappingFileLockException) {
false
} finally {
channel.close()
}
if (abandoned) stage.deleteRecursively()
}
}
}
private fun isDiagnosticStage(name: String): Boolean {
val suffix = ".diagnostic-stage"
if (!name.endsWith(suffix)) return false
val base = name.removeSuffix(suffix)
val uuidStart = base.length - 36
if (uuidStart < 2 || base[uuidStart - 1] != '-') return false
return runCatching { UUID.fromString(base.substring(uuidStart)).toString() == base.substring(uuidStart) }
.getOrDefault(false)
}
private fun <T> withStageLifecycleLock(cache: File, block: () -> T): T = synchronized(stageLifecycleMonitor) {
FileChannel.open(File(cache, ".diagnostic-stages.lock").toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
.use { channel -> channel.lock().use { block() } }
}
internal fun setSourceOpenerForTest(opener: SecureSourceOpener?) {
if (opener == null) sourceOpenerOverride.remove() else sourceOpenerOverride.set(opener)
}
internal fun hasSourceOpenerForTest(): Boolean = sourceOpenerOverride.get() != null
fun create(
context: Context,
folder: File,
onProgress: ((Float) -> Unit)? = null,
limits: EnhancedShareLimits = EnhancedShareLimits(),
): List<File> {
if (!folder.isDirectory || Files.isSymbolicLink(folder.toPath()) ||
limits.maxFilesPerArchive < 1 || limits.maxBytesPerFile < 1 || limits.maxBytesTotal < 1) {
return emptyList()
}
val out = SessionLogShare.shareDir(context).apply { deleteRecursively(); mkdirs() }
val stageLease = acquireDiagnosticStage(context, out.name)
val stage = stageLease.directory
return try {
val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = false)
val candidates = discovery.candidates
val totalCandidates = candidates.size.coerceAtLeast(1)
val share = limits.maxBytesTotal / Category.values().size
val budgets = Category.values().associateWith { category ->
Budget(if (category == Category.GAMES) limits.maxBytesTotal - share * 2 else share)
}
var completed = 0
Category.values().map { category ->
val budget = budgets.getValue(category)
val records = ArrayList<Record>()
val selected = candidates.filter { it.category == category }
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
selected.forEachIndexed { index, candidate ->
val safeEntry = safeEntry(candidate.entry)
val record = when {
index >= limits.maxFilesPerArchive -> Record(
safeEntry ?: "<invalid>", candidate.origin, "omitted", reason = "file-count-limit",
)
safeEntry == null -> Record("<invalid>", candidate.origin, "omitted", reason = "unsafe-entry-name")
!names.add(safeEntry) -> Record(safeEntry, candidate.origin, "omitted", reason = "duplicate-entry")
else -> addCandidate(archive, candidate.copy(entry = safeEntry), stage, budget, limits)
}
records += record
completed++
onProgress?.invoke((completed.toFloat() / totalCandidates).coerceIn(0f, 1f))
}
if (category == Category.SESSION) addTrustedActivation(context, folder, archive)?.let(records::add)
if (selected.isEmpty()) records += Record("", category.suffix, "unavailable", reason = "no-matching-artifacts")
if (discovery.truncated) records += Record("", "discovery", "truncated", reason = "candidate-limit")
if (discovery.partial) records += Record("", "discovery", "truncated", reason = "filesystem-error")
addManifest(
archive, folder.name, category.suffix, records, limits, budget.limit, redactionLearningComplete,
)
}
zip
}
} finally {
stageLease.close()
}
}
fun createLegacy(
context: Context,
folder: File,
onProgress: ((Float) -> Unit)? = null,
outputDirectory: File = SessionLogShare.shareDir(context),
limits: EnhancedShareLimits = EnhancedShareLimits(maxFilesPerArchive = 512),
): File? {
if (!folder.isDirectory || Files.isSymbolicLink(folder.toPath()) ||
limits.maxFilesPerArchive < 1 || limits.maxBytesPerFile < 1 || limits.maxBytesTotal < 1) {
return null
}
val out = outputDirectory.apply { deleteRecursively(); mkdirs() }
val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = true)
val candidates = discovery.candidates.filter { it.linePrefix == null }
if (candidates.isEmpty()) {
out.deleteRecursively()
return null
}
val stageLease = acquireDiagnosticStage(context, out.name)
val stage = stageLease.directory
val records = ArrayList<Record>()
val budget = Budget(limits.maxBytesTotal)
val zip = File(out, "DroidDeck-${folder.name}.zip")
return try {
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
candidates.forEachIndexed { index, candidate ->
val safeEntry = safeEntry(candidate.entry)
records += when {
index >= limits.maxFilesPerArchive -> Record(
safeEntry ?: "<invalid>", candidate.origin, "omitted", reason = "file-count-limit",
)
safeEntry == null -> Record("<invalid>", candidate.origin, "omitted", reason = "unsafe-entry-name")
!names.add(safeEntry) -> Record(safeEntry, candidate.origin, "omitted", reason = "duplicate-entry")
else -> addCandidate(archive, candidate.copy(entry = safeEntry), stage, budget, limits)
}
onProgress?.invoke((index + 1f) / candidates.size)
}
addTrustedActivation(context, folder, archive)?.let(records::add)
if (discovery.truncated) records += Record("", "discovery", "truncated", reason = "candidate-limit")
if (discovery.partial) records += Record("", "discovery", "truncated", reason = "filesystem-error")
addManifest(archive, folder.name, "all", records, limits, budget.limit, redactionLearningComplete)
}
zip
} finally {
stageLease.close()
}
}
private fun addTrustedActivation(
context: Context,
folder: File,
archive: ZipOutputStream,
): Record? {
val manifest = EnhancedDiagnostics.manifest(context, folder) ?: return null
val bytes = (manifest.toString(2) + "\n").toByteArray()
val entry = "${folder.name}/${EnhancedDiagnostics.MANIFEST_FILE}"
archive.putNextEntry(ZipEntry(entry))
archive.write(bytes)
archive.closeEntry()
return Record(entry, "app-private-activation-state", "captured", bytes.size.toLong(), bytes.size.toLong())
}
private fun addCandidate(
archive: ZipOutputStream,
candidate: Candidate,
stage: File,
budget: Budget,
limits: EnhancedShareLimits,
): Record {
if (budget.remaining <= 0) {
return Record(candidate.entry, candidate.origin, "omitted", reason = "bundle-byte-limit")
}
if (!stage.isDirectory || !stage.canWrite()) throw StageUnavailableException(IOException("staging path is not writable"))
val snapshot = try {
snapshot(candidate, stage, minOf(limits.maxBytesPerFile, budget.remaining))
} catch (error: StageUnavailableException) {
throw error
} catch (error: Exception) {
if (!stage.isDirectory || !stage.canWrite()) throw StageUnavailableException(error)
val reportedError = (error as? SourceReadException)?.cause ?: error
return Record(candidate.entry, candidate.origin, "error", reason = reportedError.javaClass.simpleName)
} ?: return Record(candidate.entry, candidate.origin, "omitted", reason = "unsafe-or-unavailable-source")
if (snapshot.file.length() == 0L && candidate.linePrefix != null) {
snapshot.file.delete()
return Record(
candidate.entry,
candidate.origin,
if (snapshot.truncated) "truncated" else "unavailable",
snapshot.sourceBytes,
reason = if (snapshot.truncated) "no-matching-lines-in-bounded-scan" else "no-matching-lines",
)
}
return try {
budget.remaining -= snapshot.file.length()
archive.putNextEntry(ZipEntry(candidate.entry))
val writer = archive.bufferedWriter()
LogRedactor.scrubForShare(snapshot.file, writer)
writer.flush()
archive.closeEntry()
Record(
candidate.entry,
candidate.origin,
if (snapshot.truncated) "truncated" else "captured",
snapshot.sourceBytes,
snapshot.file.length(),
if (snapshot.truncated) "per-file-or-bundle-byte-limit" else null,
)
} finally {
snapshot.file.delete()
}
}
private fun snapshot(candidate: Candidate, stage: File, limit: Long): Snapshot? {
val rootPath = candidate.anchor.toPath().toAbsolutePath().normalize()
val sourcePath = candidate.file.toPath().toAbsolutePath().normalize()
if (!sourcePath.startsWith(rootPath) || sourcePath == rootPath || limit < 1) return null
val target = try {
File.createTempFile("diagnostic-", ".log", stage)
} catch (error: Exception) {
throw StageUnavailableException(error)
}
try {
val relative = rootPath.relativize(sourcePath)
return withSecureChannel(rootPath, relative) { input ->
val size = readSource { input.size() }
candidate.linePrefix?.let { prefix ->
val truncated = filterChannel(input, target, prefix, size, TRACE_SCAN_BYTES, limit)
return@withSecureChannel Snapshot(target, size, truncated)
}
writeStage {
FileOutputStream(target).channel.use { output ->
if (size <= limit) {
copy(input, output, 0, size)
} else {
val marker = "\n<diagnostic file truncated: beginning and tail retained>\n".toByteArray()
val content = (limit - marker.size).coerceAtLeast(0)
copyCompleteHead(input, output, content / 2)
val markerBytes = minOf(marker.size.toLong(), limit - output.position()).toInt()
output.write(ByteBuffer.wrap(marker, 0, markerBytes))
copyCompleteTail(input, output, size, (limit - output.position()).coerceAtLeast(0))
}
output.force(false)
}
}
Snapshot(target, size, size > limit)
} ?: target.delete().let { null }
} catch (e: Exception) {
if (e is StageUnavailableException) {
target.delete()
throw e
}
val targetWasPresent = target.exists()
target.delete()
if (!stage.isDirectory || !stage.canWrite() || !targetWasPresent) throw StageUnavailableException(e)
throw e
}
}
private fun filterChannel(
channel: SeekableByteChannel,
target: File,
prefix: String,
sourceSize: Long,
scanLimit: Long,
outputLimit: Long,
): Boolean {
val wanted = prefix.toByteArray()
var written = 0L
var truncated = sourceSize > scanLimit
writeStage {
target.outputStream().buffered().use { output ->
fun scan(start: Long, count: Long, discardPartialFirstLine: Boolean) {
readSource { channel.position(start) }
val input = BufferedInputStream(Channels.newInputStream(channel), COPY_BUFFER_BYTES)
val line = ByteArrayOutputStream(1024)
var oversized = false
var scanned = 0L
var discard = discardPartialFirstLine
fun emit() {
val bytes = line.toByteArray()
if (!discard && !oversized && bytes.size >= wanted.size && wanted.indices.all { bytes[it] == wanted[it] }) {
if (written + bytes.size + 1 <= outputLimit) {
output.write(bytes)
output.write('\n'.code)
written += bytes.size + 1
} else truncated = true
}
line.reset()
oversized = false
discard = false
}
while (scanned < count) {
val value = readSource { input.read() }
if (value < 0) break
scanned++
if (value == '\n'.code) emit()
else if (!oversized && !discard) {
if (line.size() >= LogRedactor.MAX_LINE_LENGTH) {
oversized = true
line.reset()
} else line.write(value)
}
}
if (start + scanned >= sourceSize && (line.size() > 0 || oversized)) emit()
}
if (sourceSize <= scanLimit) {
scan(0, sourceSize, false)
} else {
val head = scanLimit / 2
val tail = scanLimit - head
scan(0, head, false)
scan((sourceSize - tail).coerceAtLeast(0), tail, true)
}
}
}
return truncated
}
private fun <T> withSecureChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T? {
sourceOpenerOverride.get()?.let { return it.withChannel(root, relative, block) }
return withAndroidSecureChannel(root, relative, block)
}
private fun <T> withAndroidSecureChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T? {
val opened = ArrayList<ParcelFileDescriptor>()
var invokingBlock = false
return try {
val parts = relative.map { it.toString() }
if (parts.isEmpty()) return null
opened += openDirectoryDescriptor(root.toString()) ?: return null
for (part in parts.dropLast(1)) {
opened += openDirectoryDescriptor(procChild(opened.last(), part)) ?: return null
}
val leafFd = openDescriptor(procChild(opened.last(), parts.last())) ?: return null
try {
val stat = Os.fstat(leafFd)
if (!OsConstants.S_ISREG(stat.st_mode) || stat.st_nlink != 1L) return null
// Android's FileInputStream(FileDescriptor) is deliberately not the descriptor owner.
FileInputStream(leafFd).use { stream ->
invokingBlock = true
block(stream.channel)
}
} finally {
runCatching { Os.close(leafFd) }
}
} catch (error: Exception) {
if (invokingBlock) throw error
null
} finally {
opened.asReversed().forEach { runCatching { it.close() } }
}
}
private fun openDescriptor(path: String): java.io.FileDescriptor? = runCatching {
Os.open(
path,
OsConstants.O_RDONLY or OsConstants.O_CLOEXEC or OsConstants.O_NOFOLLOW or OsConstants.O_NONBLOCK,
0,
)
}.getOrNull()
private fun openDirectoryDescriptor(path: String): ParcelFileDescriptor? {
val fd = openDescriptor(path) ?: return null
return try {
if (!OsConstants.S_ISDIR(Os.fstat(fd).st_mode)) return null
ParcelFileDescriptor.dup(fd)
} finally {
runCatching { Os.close(fd) }
}
}
private fun procChild(directory: ParcelFileDescriptor, name: String): String =
"/proc/self/fd/${directory.fd}/$name"
private fun copy(input: SeekableByteChannel, output: FileChannel, start: Long, count: Long) {
readSource { input.position(start) }
var left = count
val buffer = ByteBuffer.allocate(64 * 1024)
while (left > 0) {
buffer.clear()
buffer.limit(minOf(buffer.capacity().toLong(), left).toInt())
val read = readSource { input.read(buffer) }
if (read < 0) break
buffer.flip()
while (buffer.hasRemaining()) writeStage { output.write(buffer) }
left -= read
}
}
private fun copyCompleteHead(input: SeekableByteChannel, output: FileChannel, limit: Long) {
if (limit <= 0) return
copy(input, output, 0, limit)
val copied = output.position()
readSource { input.position(0) }
val buffer = ByteBuffer.allocate(64 * 1024)
var scanned = 0L
var lastComplete = 0L
while (scanned < copied) {
buffer.clear()
buffer.limit(minOf(buffer.capacity().toLong(), copied - scanned).toInt())
val read = readSource { input.read(buffer) }
if (read < 0) break
buffer.flip()
repeat(read) { index ->
if (buffer.get(index) == '\n'.code.toByte()) lastComplete = scanned + index + 1
}
scanned += read
}
writeStage { output.truncate(lastComplete) }
writeStage { output.position(lastComplete) }
}
private fun copyCompleteTail(
input: SeekableByteChannel,
output: FileChannel,
sourceSize: Long,
limit: Long,
) {
if (limit <= 0 || sourceSize <= 0) return
var start = (sourceSize - limit).coerceAtLeast(0)
if (start > 0) {
readSource { input.position(start) }
val buffered = BufferedInputStream(Channels.newInputStream(input), COPY_BUFFER_BYTES)
while (start < sourceSize) {
val value = readSource { buffered.read() }
if (value < 0) return
start++
if (value == '\n'.code) break
}
}
copy(input, output, start, (sourceSize - start).coerceAtMost(limit))
}
private inline fun <T> readSource(block: () -> T): T = try {
block()
} catch (error: Exception) {
throw SourceReadException(error)
}
private inline fun <T> writeStage(block: () -> T): T = try {
block()
} catch (error: SourceReadException) {
throw error
} catch (error: StageUnavailableException) {
throw error
} catch (error: Exception) {
throw StageUnavailableException(error)
}
private fun addManifest(
archive: ZipOutputStream,
sessionId: String,
category: String,
records: List<Record>,
limits: EnhancedShareLimits,
categoryBudget: Long,
redactionLearningComplete: Boolean,
) {
val entries = JSONArray()
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
entries.put(JSONObject().apply {
put("entry", record.entry)
put("origin", record.origin)
put("status", record.status)
put("sourceBytes", record.sourceBytes)
put("capturedBytes", record.capturedBytes)
record.reason?.let { put("reason", it) }
})
}
if (records.size > MAX_MANIFEST_RECORDS) {
entries.put(JSONObject().apply {
put("entry", "")
put("origin", "manifest")
put("status", "omitted")
put("reason", "${records.size - MAX_MANIFEST_RECORDS} additional records")
})
}
val manifest = JSONObject().apply {
put("schema", 1)
put("sessionId", sessionId)
put("category", category)
put("generatedAtMillis", System.currentTimeMillis())
put("redactionLearning", if (redactionLearningComplete) "complete" else "incomplete")
put("limits", JSONObject().apply {
put("maxFilesPerArchive", limits.maxFilesPerArchive)
put("maxDiscoveredFiles", limits.maxDiscoveredFiles)
put("maxBytesPerFile", limits.maxBytesPerFile)
put("budgetBasis", "raw-input-snapshot-bytes")
put("maxRawInputBytesTotal", limits.maxBytesTotal)
put("categoryRawInputBudgetBytes", categoryBudget)
})
put("entries", entries)
}.toString(2) + "\n"
archive.putNextEntry(ZipEntry("diagnostics-manifest.json"))
archive.write(manifest.toByteArray())
archive.closeEntry()
}
private fun collect(context: Context, folder: File, maxFiles: Int, legacy: Boolean): CollectionResult {
val out = LinkedHashMap<String, Candidate>()
val categoryCounts = HashMap<Category, Int>()
val perCategory = (maxFiles / Category.values().size).coerceAtLeast(1)
var truncated = false
var partial = false
fun add(
file: File,
root: File,
entry: String,
origin: String,
forcedCategory: Category? = null,
linePrefix: String? = null,
) {
val safe = safeEntry(entry) ?: return
val category = forcedCategory ?: category(entry.removePrefix("${folder.name}/"))
if (out.size >= maxFiles || (categoryCounts[category] ?: 0) >= perCategory) {
truncated = true
return
}
val anchor = anchorFor(context, root)
if (out.putIfAbsent(safe, Candidate(file, anchor, safe, origin, category, linePrefix)) == null) {
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
}
}
CRITICAL_SESSION_FILES.forEach { name ->
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
}
File(folder, "session.log").takeIf { it.exists() }?.let { file ->
add(
file, folder, "${folder.name}/graphics/frame-trace.log", "guest-frame-trace",
Category.GRAPHICS, "DROIDDECK_FRAME_TRACE ",
)
add(
file, folder, "${folder.name}/graphics/process-trace.log", "guest-process-trace",
Category.GRAPHICS, "DROIDDECK_PROCESS_TRACE ",
)
add(
file, folder, "${folder.name}/games/game-lifecycle.log", "guest-game-lifecycle",
Category.GAMES, "DROIDDECK_DIAGNOSTICS event=game_",
)
}
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
val scan = directFiles(steam, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.forEach {
add(it, steam, "${folder.name}/steam/${it.name}", "live-steam")
}
}
val logs = LinuxRuntime.logDir(context)
for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) {
val scan = directFiles(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) }
.forEach { add(it, root, "$name/${it.name}", name) }
}
if (legacy) {
val scan = legacyBattleNet(context)
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.sources.forEach { source ->
add(source.file, source.root, source.entry, "battlenet")
}
} else {
battleNetRoots(context).forEach { (prefix, root) ->
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
.forEach { file ->
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
add(file, root, "battlenet/$prefix/$relative", "battlenet")
}
}
}
val sessionScan = walk(folder, remaining(maxFiles, out.size))
truncated = truncated || sessionScan.truncated
partial = partial || sessionScan.partial
sessionScan.files.forEach { file ->
val relative = file.toPath().toAbsolutePath().normalize()
.let { folder.toPath().toAbsolutePath().normalize().relativize(it).joinToString("/") }
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
add(file, folder, "${folder.name}/$relative", "session")
}
return CollectionResult(out.values.toList(), truncated, partial)
}
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
private fun walk(root: File, limit: Int): ScanResult {
if (limit <= 0 || !root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
val files = ArrayList<File>(limit)
var truncated = false
var partial = false
var visited = 0
val rootPath = root.toPath()
val visitLimit = (limit * 4).coerceAtLeast(limit).coerceAtMost(MAX_DISCOVERY_VISITS)
try {
Files.walkFileTree(rootPath, object : SimpleFileVisitor<Path>() {
private fun countVisit(): FileVisitResult {
visited++
return if (visited > visitLimit) {
truncated = true
FileVisitResult.TERMINATE
} else FileVisitResult.CONTINUE
}
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult =
if (dir == rootPath) FileVisitResult.CONTINUE else countVisit()
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (countVisit() == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE
if (files.size >= limit) {
truncated = true
return FileVisitResult.TERMINATE
}
if (attrs.isRegularFile || Files.isSymbolicLink(file)) files += file.toFile()
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, exc: IOException): FileVisitResult {
partial = true
return countVisit()
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
if (exc != null) partial = true
return FileVisitResult.CONTINUE
}
})
} catch (_: Exception) {
partial = true
}
return ScanResult(files, truncated, partial)
}
private fun directFiles(root: File, limit: Int): ScanResult {
if (limit <= 0 || !root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
val files = ArrayList<File>(limit)
var truncated = false
var partial = false
try {
Files.newDirectoryStream(root.toPath()).use { entries ->
val iterator = entries.iterator()
while (iterator.hasNext() && files.size < limit) {
val path = iterator.next()
if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(path)) {
files += path.toFile()
}
}
truncated = iterator.hasNext()
}
} catch (_: Exception) {
partial = true
}
return ScanResult(files, truncated, partial)
}
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
return listOf(
"droiddeck" to File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet"),
"client" to File(drive, "users/steamuser/AppData/Local/Battle.net/Logs"),
"agent" to File(data, "Agent"),
"setup" to File(data, "Setup"),
)
}
private fun legacyBattleNet(context: Context): LegacyDiscovery {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
val agent = File(data, "Agent")
val setup = File(data, "Setup")
val agentChildren = childDirectories(agent, "Agent.")
val setupChildren = childDirectories(setup, "")
val scans = listOf(
legacyNewest(
"droiddeck",
listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")),
2,
setOf("battlenet.log", "spawned.log"),
),
legacyNewest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6),
legacyNewest(
"agent", listOf(File(agent, "Logs")) + agentChildren.files.map { File(it, "Logs") }, 10,
byDir = true,
),
legacyNewest("setup", setupChildren.files.map { File(it, "Logs") }, 3, byDir = true),
)
return LegacyDiscovery(
scans.flatMap { it.sources },
scans.any { it.truncated } || agentChildren.truncated || setupChildren.truncated,
scans.any { it.partial } || agentChildren.partial || setupChildren.partial,
)
}
private fun legacyNewest(
folder: String,
roots: List<File>,
count: Int,
names: Set<String>? = null,
byDir: Boolean = false,
): LegacyDiscovery {
val found = ArrayList<Pair<File, File>>()
var truncated = false
var partial = false
roots.forEach { root ->
val scan = directFiles(root, MAX_BATTLENET_SCAN)
truncated = truncated || scan.truncated
partial = partial || scan.partial
found += scan.files.asSequence()
.filter { recent(it) && it.name.endsWith(".log") && it.length() <= LEGACY_LOG_MAX_BYTES }
.filter { names == null || it.name in names }
.map { it to root }
.toList()
}
val ordered = found.sortedByDescending { it.first.lastModified() }
return LegacyDiscovery(
ordered.take(count).map { (file, root) ->
val relative = if (byDir) "$folder/${file.parentFile?.parentFile?.name}/${file.name}" else "$folder/${file.name}"
LegacySource(file, root, "battlenet/$relative")
},
truncated || ordered.size > count,
partial,
)
}
private fun childDirectories(root: File, prefix: String): ScanResult {
if (!root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
val found = ArrayList<File>()
var truncated = false
var partial = false
try {
Files.newDirectoryStream(root.toPath()).use { entries ->
val iterator = entries.iterator()
while (iterator.hasNext() && found.size < MAX_BATTLENET_DIRECTORIES) {
val path = iterator.next()
if (path.fileName.toString().startsWith(prefix) &&
Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) found += path.toFile()
}
truncated = iterator.hasNext()
}
} catch (_: Exception) {
partial = true
}
return ScanResult(found, truncated, partial)
}
private fun recent(file: File): Boolean = file.lastModified() >= System.currentTimeMillis() - RECENT_MILLIS
private fun anchorFor(context: Context, root: File): File {
val path = root.toPath().toAbsolutePath().normalize()
for (anchor in listOf(context.filesDir, context.cacheDir)) {
if (path.startsWith(anchor.toPath().toAbsolutePath().normalize())) return anchor
}
return root.parentFile ?: root
}
private fun safeEntry(name: String): String? {
if (name.any { it.code < 0x20 || it.code == 0x7f }) return null
val normalized = name.replace('\\', '/').trimStart('/')
val parts = normalized.split('/')
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
return parts.joinToString("/") { safeComponent(it) }
}
private fun safeComponent(value: String): String {
if (value in KNOWN_COMPONENTS || KNOWN_COMPONENT_PATTERNS.any { it.matches(value) }) return value
val suffix = SAFE_SUFFIX.find(value)?.value.orEmpty().lowercase(Locale.US)
val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())
.take(8).joinToString("") { "%02x".format(Locale.US, it.toInt() and 0xff) }
return "entry-$digest$suffix"
}
private fun category(entry: String): Category {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
return Category.SESSION
}
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
private val KNOWN_COMPONENTS = setOf(
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
)
private val KNOWN_COMPONENT_PATTERNS = listOf(
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
Regex("steam-[0-9]+\\.(?:log|txt)"),
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
)
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
private val CRITICAL_SESSION_FILES = listOf(
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
"events.jsonl", "memory.csv", "capture.json", "crash.log",
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val COPY_BUFFER_BYTES = 64 * 1024
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
private const val MAX_BATTLENET_SCAN = 64
private const val MAX_BATTLENET_DIRECTORIES = 64
private const val MAX_MANIFEST_RECORDS = 512
private const val MAX_DISCOVERY_VISITS = 4096
}
@@ -117,8 +117,7 @@ object GameEnvironmentStore {
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
json.put(
GAME_DEBUG_LOGS,
gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) &&
SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)),
gameDebugLogsOverride ?: SessionPrefs.gameDebugLogsEffective(context),
)
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
}
@@ -48,7 +48,33 @@ object GameStorage {
return when {
pref == SessionPrefs.GAME_STORAGE_OFF -> null
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) }
else -> Option(SessionPrefs.gameStorageLabel(context), pref)
else -> Option(SessionPrefs.gameStorageLabel(context), pref).takeIf { attached(File(pref)) }
}
}
fun disconnected(context: Context): Boolean {
val pref = SessionPrefs.gameStorage(context)
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(pref))
}
internal fun attached(path: File): Boolean =
attached(path, runCatching { Environment.getExternalStorageState(path) }.getOrNull())
internal fun attached(
path: File,
state: String?,
externalStoragePath: Boolean = isExternalStoragePath(path),
): Boolean = when {
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY -> true
externalStoragePath -> false
state == Environment.MEDIA_UNKNOWN || state == null -> path.isDirectory || path.parentFile?.isDirectory == true
else -> false
}
private fun isExternalStoragePath(path: File): Boolean {
val absolute = path.absoluteFile.toPath().normalize()
return listOf(File("/storage"), File("/mnt/media_rw")).any {
absolute.startsWith(it.absoluteFile.toPath().normalize())
}
}
@@ -0,0 +1,250 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Build
import android.system.Os
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.gpu.DriverBundle
import com.droiddeck.launcher.gpu.DriverPairs
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.gpu.VulkanInfo
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* graphics-report.txt in each session's folder: which graphics path the session drew with and why,
* the GPU and its device nodes, the environment the guest got, and at the end what the compositor
* said about its driver. Written for a non-Adreno test report, where a black screen otherwise comes
* with nothing to read; the Share logs zip takes the whole folder, so it travels with the logs.
* Read-only: nothing here opens a GPU node or changes a setting.
*/
object GraphicsReport {
const val FILE = "graphics-report.txt"
const val GAMES_DIR = "games"
/** One file in games/ past this is cut to its first part at the session's end. */
private const val GAME_FILE_MAX = 20L * 1024 * 1024
/** All of games/ past this loses its oldest launches. */
private const val GAMES_TOTAL_MAX = 120L * 1024 * 1024
/** The guest keys the report repeats: everything that decides which Vulkan driver loads. */
private val ENV_PREFIXES = listOf(
"VK_", "BL_VK", "BL_DRM", "BL_VKBRIDGE", "VKBRIDGE", "MESA_", "GALLIUM_", "ZINK", "TU_", "PANVK",
"DROIDDECK_POWERVR", "DROIDDECK_HYBRIS", "BL_GAME_LOGS", "LIBGL_", "GAMESCOPE_DISABLE", "XWAYLAND",
)
/** Per-game graphics logs and the guest's Vulkan summary: on for a non-Adreno GPU, or by Setup's switch. */
fun detailed(context: Context): Boolean = !DeviceSupport.adreno() || SessionPrefs.detailedGraphicsLogs(context)
/** For finish(), which runs from the session's end without a context of its own. */
@Volatile private var appContext: Context? = null
/** Writes the start of the report; never throws. */
fun begin(context: Context, dir: File, guest: List<String>) {
appContext = context.applicationContext
runCatching { File(dir, FILE).writeText(start(context, guest)) }
.onFailure { android.util.Log.w("GraphicsReport", "could not write $FILE", it) }
}
private fun start(context: Context, guest: List<String>): String = buildString {
val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
appendLine("== graphics report, session start $time")
appendLine("build: ${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
appendLine()
val gpu = runCatching { GpuInfo.detect() }.getOrNull()
appendLine("-- path")
appendLine("path: " + path(context))
appendLine("driver mode: " + SessionPrefs.gpuDriverMode(context))
appendLine("display driver (compositor): " + SessionPrefs.androidDriver(context).ifEmpty {
if (DeviceSupport.adreno()) "(auto: bundled Turnip)" else "(auto: the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"})"
})
val display = SessionPrefs.androidDriver(context)
appendLine("display driver chosen by: " + when {
display.isEmpty() -> "auto (or a pair on a non-Adreno GPU: the phone's own driver)"
DriverBundle.containing(context, display, false) != null -> "pair (its display half)"
else -> "user (picked on its own)"
})
val linux = SessionPrefs.linuxDriver(context)
appendLine("runtime driver: " + linux.ifEmpty { "(runtime default)" })
if (linux.isNotEmpty()) {
val dir = com.droiddeck.launcher.gpu.LinuxVulkanDriverManager(context).getDriverDir(linux)
appendLine("runtime driver dir: ${dir.path} (" + (dir.listFiles()?.filter { it.name.endsWith(".so") }?.joinToString { it.name } ?: "missing") + ")")
}
val prefs = context.getSharedPreferences("graphics_report", Context.MODE_PRIVATE)
val previous = prefs.getString("lastDrivers", null)
val now = "display ${SessionPrefs.androidDriver(context).ifEmpty { "(auto)" }}, runtime ${linux.ifEmpty { "(default)" }}, bridge ${DeviceSupport.vkBridge(context)}, venus ${VenusComponent.wanted(context)}"
appendLine("previous session's drivers: " + (previous ?: "(none recorded)") + if (previous != null && previous != now) " << CHANGED" else "")
prefs.edit().putString("lastDrivers", now).apply()
DriverBundle.active(context)?.let { b ->
appendLine("pair: ${b.name} ${b.version} (bundle ${b.id})")
release(context, b.id)?.let { appendLine("pair release: $it") }
}
if (gpu != null) {
val pairs = DriverPairs.from(TurnipReleases.cached(context))
appendLine("auto would pick: " + (DriverPairs.recommendedKey(gpu, pairs) ?: "(no pair: system driver or bridge)"))
}
appendLine("frame generation: " + runCatching { com.droiddeck.launcher.gpu.FrameGen.mode(context).toString() }.getOrDefault("?") +
" (engine=off means it is switched off in Play settings; a driver that fails LSFG's gates logs \"device gates\" below)")
appendLine("mali bridge setting: " + SessionPrefs.vkBridge(context) + ", in use: " + DeviceSupport.vkBridge(context))
val standIn = runCatching { com.droiddeck.launcher.runtime.LinuxRuntime.gpuStandIn(context) }.getOrNull()
appendLine("render node for the guest: " + (standIn?.let { node ->
com.droiddeck.launcher.runtime.LinuxRuntime.deviceNumbers(node)?.let { n -> "/dev/dri/renderD${n.substringAfter(':')} -> $node ($n)" } ?: node
} ?: if (SystemVulkanDriver.isPowerVr()) "the system GPU's own /dev/dri node (#570)" else "none"))
appendLine()
appendLine("-- gpu")
if (gpu != null) {
appendLine("family: ${gpu.family} (${gpu.supportText})")
appendLine("name: ${gpu.name}" + if (gpu.model > 0) ", model ${gpu.model} (${gpu.modelSource})" else "")
}
appendLine("vulkan device (app): " + (VulkanInfo.cachedOrNull()?.get("device") ?: "(not probed)"))
appendLine("system vulkan hal: " + (SystemVulkanDriver.hal() ?: "none"))
read("/sys/class/misc/mali0/device/gpuinfo")?.let { appendLine("mali gpuinfo: $it") }
appendLine("android: ${Build.VERSION.RELEASE} (sdk ${Build.VERSION.SDK_INT}), ${Build.MANUFACTURER} ${Build.MODEL}")
val soc = if (Build.VERSION.SDK_INT >= 31) "${Build.SOC_MANUFACTURER} ${Build.SOC_MODEL}" else Build.HARDWARE
appendLine("soc: $soc, board ${Build.BOARD}, hardware ${Build.HARDWARE}")
appendLine("kernel: " + (System.getProperty("os.version") ?: "?"))
appendLine()
appendLine("-- gpu nodes (from the app; not opened)")
val dri = File("/dev/dri").list()?.sorted()?.map { "/dev/dri/$it" }.orEmpty()
for (path in listOf("/dev/kgsl-3d0", "/dev/mali0") + dri) appendLine(node(path))
if (dri.isEmpty()) appendLine("/dev/dri: " + if (File("/dev/dri").exists()) "not listable" else "absent")
appendLine()
appendLine("-- guest environment (graphics)")
guest.filter { e -> ENV_PREFIXES.any { e.startsWith(it) } }.sorted().forEach { appendLine(it) }
appendLine()
}
/** Which backend this session's Vulkan goes through, as the session decides it. */
private fun path(context: Context): String = when {
DeviceSupport.adreno() -> "Turnip (Adreno, KGSL)"
VenusComponent.wanted(context) -> "Mali (Venus): Mesa Venus over vtest to the phone's own Vulkan driver, with the Mali compatibility layer"
DeviceSupport.vkBridge(context) -> "Mali bridge (#517): the phone's own Vulkan driver through the bridge"
DeviceSupport.openDriverActive(context) -> "open driver pair (PanVK / RADV)"
SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)) && SystemVulkanDriver.isAvailable() ->
"system Vulkan (#570): ${SystemVulkanDriver.gpuName()} driver through libhybris"
SessionPrefs.linuxDriver(context).isNotEmpty() -> "imported runtime driver ${SessionPrefs.linuxDriver(context)}"
else -> "none for this GPU (no Adreno, no system HAL, no pair, bridge off)"
}
/** The release tag and download a pair bundle came from, when the last release check knows it. */
private fun release(context: Context, bundleId: String): String? {
val bundles = TurnipReleases.cached(context)?.assets?.filter { it.bundle }.orEmpty()
val asset = bundles.firstOrNull { it.name.removeSuffix("-Pair.zip") == bundleId }
?: bundles.firstOrNull { bundleId.startsWith(it.name.removeSuffix("-Pair.zip") + "-") }
?: return null
val installed = TurnipReleases.installedBuiltOn(context, asset)
return "${asset.tag} ${asset.url}" +
(if (installed.isNotEmpty()) ", installed build uploaded $installed" else "") +
(if (asset.builtOn.isNotEmpty()) ", listed build uploaded ${asset.builtOn}" else "") +
(if (TurnipReleases.updateAvailable(context, asset)) " << NEWER BUILD AVAILABLE" else "")
}
private fun node(path: String): String {
val f = File(path)
if (!f.exists()) return "$path: absent"
val access = (if (f.canRead()) "r" else "-") + (if (f.canWrite()) "w" else "-")
val rdev = runCatching { Os.stat(path).st_rdev }.getOrNull()
val numbers = rdev?.let { " ${major(it)}:${minor(it)}" }.orEmpty()
val label = runCatching { String(Os.getxattr(path, "security.selinux")).trimEnd('\u0000') }.getOrNull()
return "$path: $access$numbers" + (label?.let { " $it" } ?: "")
}
/** Linux's dev_t split (glibc's gnu_dev_major / gnu_dev_minor). */
internal fun major(dev: Long): Long = ((dev ushr 8) and 0xfff) or ((dev ushr 32) and 0xfffff000L)
internal fun minor(dev: Long): Long = (dev and 0xff) or ((dev ushr 12) and 0xffffff00L)
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.takeIf { it.isNotEmpty() }
/** The compositor's driver lines from the app's own log. */
private val COMPOSITOR = Regex(
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|TurnipDriver|""" +
"""graphics driver|display driver|DD_PRESENT_FAULT|SystemVulkan|vkbridge|VkBridge|mali_gralloc|panvk|PanVK|radv|MESA|native buffer|first frame|present|""" +
"""lsfg|FrameGen|device gates|AAudio|directaudio|pulse|gralloc|dma.?buf|modifier|import""",
RegexOption.IGNORE_CASE,
)
/** The session script's driver lines: what it exported, the bridge's self-test, vulkaninfo, gamescope's Vulkan errors. */
private val GUEST = Regex("""== vulkan driver|== vkbridge|== vulkaninfo|vulkan:|panvk|PanVK|radv|primary node|No compatible|DRM format|kbase|AAUDIO|client sink|Xwayland|\(EE\)|glamor|XWAYLAND_NO_GLAMOR""", RegexOption.IGNORE_CASE)
/**
* The end of the report, from the finished folder: the compositor's driver lines out of
* app.log, and games/ held to its size limits. Never throws.
*/
fun finish(dir: File) {
runCatching {
val report = File(dir, FILE)
if (!report.isFile) return
val lines = File(dir, "app.log").takeIf { it.isFile }?.useLines { seq -> seq.filter { COMPOSITOR.containsMatchIn(it) }.take(400).toList() }.orEmpty()
val games = File(dir, GAMES_DIR).listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty()
val guestLines = File(dir, "session.log").takeIf { it.isFile }?.useLines { seq ->
seq.filter { GUEST.containsMatchIn(it) }.take(200).toList()
}.orEmpty()
val fallbackLines = File(dir, "vkbridge-fallback").takeIf { it.isFile }?.readLines()?.map { it.trim() }?.filter { it.isNotEmpty() }
val fellBack = fallbackLines?.firstOrNull()
val fallbackReason = fallbackLines?.getOrNull(1).orEmpty()
runCatching { SessionPrefs.setBridgeFellBack(appContext ?: return@runCatching, fellBack != null, fallbackReason) }
val limits = File(dir, "limits.txt").takeIf { it.isFile }?.readText()?.trim()
val audio = File(dir, "audio.log").takeIf { it.isFile }?.readText().orEmpty()
report.appendText(buildString {
limits?.let { appendLine("open files limit: $it") }
fellBack?.let {
if (fallbackReason == "memory") appendLine("!! MALI BRIDGE FELL BACK: memory sharing = none (no method passed the server's self-test); the session ran on $it")
else appendLine("!! MALI BRIDGE FELL BACK: the self-test failed images or draws; the session ran on $it")
}
com.droiddeck.launcher.wayland.WaylandCompositor.compositorFault().takeIf { it.isNotEmpty() }?.let {
appendLine("!! DISPLAY FAILED: $it")
}
com.droiddeck.launcher.wayland.WaylandCompositor.displayDriver().takeIf { it.isNotEmpty() }?.let {
appendLine("display driver (as loaded): $it")
}
appContext?.let { ctx ->
if (SessionPrefs.venus(ctx)) VenusComponent.hostVulkanTooOld(ctx)?.let {
appendLine("!! VENUS OFF: the phone's driver reports Vulkan $it; gamescope needs 1.2 or newer, so the session did not use Venus")
}
}
if (audio.contains("AAUDIO_ERROR_DISCONNECTED")) {
appendLine("!! SOUND: Android refused the audio output (AAUDIO_ERROR_DISCONNECTED) - rebooting the phone usually fixes this")
}
if (guestLines.any { it.contains("vkbridge", ignoreCase = true) && it.contains("FAIL") }) {
appendLine("!! MALI BRIDGE SELF-TEST FAILED: this GPU's driver did not pass the bridge's checks (see below)")
}
if (guestLines.any { it.contains("MEM_EXEC_INIT") }) {
appendLine("note: kbase refused KBASE_IOCTL_MEM_EXEC_INIT with EPERM. That answer comes from the kbase driver")
appendLine(" itself (proot does not filter ioctls; Android's seccomp would kill or return ENOSYS; SELinux")
appendLine(" would return EACCES), so it is the kernel's policy for this context, not the session's.")
}
appendLine("-- driver lines from the session log (${guestLines.size})")
guestLines.forEach { appendLine(it) }
appendLine()
appendLine("-- compositor and driver lines from app.log (${lines.size})")
lines.forEach { appendLine(it) }
appendLine()
appendLine("-- game launches with detailed logs: ${games.size}")
games.forEach { appendLine(it.name) }
appendLine("== session end " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date()))
})
capGames(File(dir, GAMES_DIR))
}.onFailure { android.util.Log.w("GraphicsReport", "could not finish $FILE", it) }
}
/** Cuts each file in [games] to [GAME_FILE_MAX] and drops the oldest launches past [GAMES_TOTAL_MAX]. */
internal fun capGames(games: File, fileMax: Long = GAME_FILE_MAX, totalMax: Long = GAMES_TOTAL_MAX) {
if (!games.isDirectory) return
games.walkTopDown().filter { it.isFile && it.length() > fileMax }.forEach { f ->
runCatching { java.io.RandomAccessFile(f, "rw").use { it.setLength(fileMax) } }
}
val launches = games.listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty().toMutableList()
fun size(d: File) = d.walkTopDown().filter { it.isFile }.sumOf { it.length() }
var total = launches.sumOf { size(it) }
while (total > totalMax && launches.size > 1) {
val oldest = launches.removeAt(0)
total -= size(oldest)
FileUtils.delete(oldest)
}
}
}
@@ -77,6 +77,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
var stepText: String? = null
var downloadAt = -1
var downloadPercent = -1
var applyingAt = -1
var clientDownloadAt = -1
var clientDownload: String? = null
var clientPercent = -1
@@ -99,10 +100,16 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
val done = m.groupValues[1].toLong()
val total = maxOf(1L, m.groupValues[2].toLong())
downloadPercent = (done * 100 / total).toInt()
} else if (steam && UPDATE_APPLYING.matches(line)) {
applyingAt = at
}
}
}
return when {
applyingAt > stepAt && applyingAt > downloadAt -> Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1,
Topic.STEAM, readable = true,
)
downloadAt > stepAt && downloadPercent >= 0 -> Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
Topic.STEAM, readable = true,
@@ -151,6 +158,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""")
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
}
@@ -11,6 +11,22 @@ object OrphanReaper {
fun release(pid: Int) { kept.remove(pid) }
fun hasOtherProcesses(): Boolean = hasOtherProcesses(
File("/proc").list()?.mapNotNull { it.toIntOrNull() }, android.os.Process.myPid(),
) { pid ->
try {
android.system.Os.kill(pid, 0)
true
} catch (error: android.system.ErrnoException) {
error.errno != android.system.OsConstants.ESRCH && error.errno != android.system.OsConstants.EPERM
} catch (error: SecurityException) {
true
}
}
internal fun hasOtherProcesses(pids: List<Int>?, ownPid: Int, signalable: (Int) -> Boolean): Boolean =
pids == null || pids.any { it > 1 && it != ownPid && signalable(it) }
fun reap(reason: String, matching: (String) -> Boolean = { true }): Int {
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
@@ -11,4 +11,12 @@ object PipPolicy {
height.toDouble() / width > 2.39 -> 100 to 239
else -> width to height
}
fun outputSize(width: Int, height: Int, outputWidth: Int, outputHeight: Int): Pair<Int, Int>? {
if (width <= 0 || height <= 0 || outputWidth <= 0 || outputHeight <= 0) return null
val scale = minOf(width.toFloat() / outputWidth, height.toFloat() / outputHeight)
val fittedWidth = ((outputWidth * scale).toInt() and 1.inv()).coerceAtLeast(2)
val fittedHeight = ((outputHeight * scale).toInt() and 1.inv()).coerceAtLeast(2)
return fittedWidth to fittedHeight
}
}
@@ -502,14 +502,20 @@ object SessionArtifacts {
return true
}
/**
* Finishes the folders of sessions whose process died without its teardown. Returns true when
* the newest of them ended because Android killed the app for memory, so the app can say so
* (a game "crashing" on a phone with little free RAM is usually this, not a driver fault).
*/
@Synchronized
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) {
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false): Boolean {
val stopWhenSessionStarts = !beforeGuestStart
val parent = LinuxRuntime.logDir(context)
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f)
}?.sortedWith(SessionPaths.chronological) ?: return
if (abandoned.isEmpty()) return
}?.sortedWith(SessionPaths.chronological) ?: return false
if (abandoned.isEmpty()) return false
var killedForMemory = false
val current = SessionPaths.current()
val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current }
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
@@ -534,8 +540,10 @@ object SessionArtifacts {
"audio.log, device.txt) were on disk already and are as they were left.\n" +
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
"session died of a crash, the entry is in there unless the device rebooted.\n" +
(if (newest) exitReasons(context) else "")
)
if (newest && lastExitForMemory(context)) killedForMemory = true
}
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
(runtimeExpired.exists() || !beforeGuestStart) &&
@@ -593,7 +601,7 @@ object SessionArtifacts {
break
}
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
if (beforeGuestStart) return
if (beforeGuestStart) break
val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running }
val marked = markScrubbed(scrubbed)
if (scrubbed.deferred) break
@@ -604,6 +612,54 @@ object SessionArtifacts {
Log.w(TAG, "could not finish $dir", e)
}
}
// Whoever finishes the folder first (the agent provider starts before the activity) leaves
// the notice for the launcher to show.
if (killedForMemory) SessionPrefs.setMemoryKillNotice(context, true)
return killedForMemory
}
/** Android's newest record for this app's main process says it was killed for memory. */
private fun lastExitForMemory(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < 30) return false
return runCatching {
val am = context.getSystemService(android.app.ActivityManager::class.java) ?: return false
am.getHistoricalProcessExitReasons(context.packageName, 0, 3)
.firstOrNull { it.processName == context.packageName }
?.reason == android.app.ApplicationExitInfo.REASON_LOW_MEMORY
}.getOrDefault(false)
}
private fun exitReasons(context: Context): String {
if (android.os.Build.VERSION.SDK_INT < 30) return ""
return runCatching {
val am = context.getSystemService(android.app.ActivityManager::class.java) ?: return ""
val reasons = am.getHistoricalProcessExitReasons(context.packageName, 0, 3)
if (reasons.isEmpty()) return ""
val fmt = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US)
buildString {
append("\nAndroid's record of how this app's recent processes ended (newest first):\n")
reasons.forEach { r ->
append(" ${fmt.format(java.util.Date(r.timestamp))} ${r.processName} pid ${r.pid}: reason ${reasonName(r.reason)}, " +
"status ${r.status}, importance ${r.importance}, pss ${r.pss / 1024} MB, rss ${r.rss / 1024} MB" +
(r.description?.let { " - $it" } ?: "") + "\n")
}
}
}.getOrDefault("")
}
private fun reasonName(reason: Int): String = when (reason) {
android.app.ApplicationExitInfo.REASON_LOW_MEMORY -> "LOW_MEMORY (killed for memory)"
android.app.ApplicationExitInfo.REASON_SIGNALED -> "SIGNALED"
android.app.ApplicationExitInfo.REASON_CRASH -> "CRASH"
android.app.ApplicationExitInfo.REASON_CRASH_NATIVE -> "CRASH_NATIVE"
android.app.ApplicationExitInfo.REASON_ANR -> "ANR"
android.app.ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE -> "EXCESSIVE_RESOURCE_USAGE"
android.app.ApplicationExitInfo.REASON_USER_REQUESTED -> "USER_REQUESTED"
android.app.ApplicationExitInfo.REASON_USER_STOPPED -> "USER_STOPPED"
android.app.ApplicationExitInfo.REASON_EXIT_SELF -> "EXIT_SELF"
android.app.ApplicationExitInfo.REASON_DEPENDENCY_DIED -> "DEPENDENCY_DIED"
android.app.ApplicationExitInfo.REASON_OTHER -> "OTHER"
else -> reason.toString()
}
@Synchronized
@@ -40,10 +40,12 @@ object SessionFiles {
WinComponents.publish(context)
val files = arrayOf(
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
"usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory",
"usr/local/bin/droiddeck-wincomponents" to "usr/local/bin/droiddeck-wincomponents",
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
"usr/local/bin/droiddeck-esync" to "usr/local/bin/droiddeck-esync",
"usr/local/bin/droiddeck-steam-compat" to "usr/local/bin/droiddeck-steam-compat",
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
"usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex",
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
@@ -71,6 +73,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
@@ -141,6 +144,8 @@ object SessionFiles {
"usr/local/lib/mangoapp/libtraceevent.so.1",
"usr/local/lib/mangoapp/libtracefs.so.1",
).map { it to it }
val xclipse = listOf("libVkLayer_droiddeck_xclipse.so", "VkLayer_droiddeck_xclipse.json")
.map { "usr/local/lib/droiddeck-xclipse/$it" }
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
.map { "usr/local/lib/droiddeck-msitools/$it" } +
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
@@ -164,12 +169,22 @@ object SessionFiles {
val gpuLoad = listOf(
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_vram_cap.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json",
)
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
// The Mali compatibility layer (tools/venus/layer, David Cimo): an implicit Vulkan layer that
// fills in the features DXVK requires and Mali lacks. Idle outside Wine and on GPUs that have them.
// Never staged on an Adreno: an implicit layer is loaded into every Vulkan program there.
val maliCompat = if (com.droiddeck.launcher.core.DeviceSupport.adreno()) emptyList() else listOf(
"usr/local/lib/droiddeck-mali/libVkLayer_droiddeck_mali_compat.so",
"usr/local/share/vulkan/implicit_layer.d/VkLayer_droiddeck_mali_compat.json",
).map { it to it }
val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
"usr/local/bin/droiddeck-glprobe" to "usr/local/bin/droiddeck-glprobe",
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
"usr/local/lib/vkbridge/libvulkan_droidbridge.so" to "usr/local/lib/vkbridge/libvulkan_droidbridge.so",
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
@@ -178,7 +193,7 @@ object SessionFiles {
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
) + mangoapp + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
}
@@ -11,14 +11,12 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.FileProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import java.util.ArrayList
object SessionLogShare {
data class Details(val sizeBytes: Long, val modifiedAt: Long)
private val main = Handler(Looper.getMainLooper())
var progress by mutableStateOf<Float?>(null)
@@ -35,86 +33,55 @@ object SessionLogShare {
}, "share-logs").start()
}
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
fun latest(context: Context): File? = sessions(context).lastOrNull()
fun sessions(context: Context): List<File> {
val current = SessionPaths.current()?.takeIf { it.isDirectory && SessionPaths.isSessionFolder(it) }
return (SessionPaths.sessionFolders(context) + listOfNotNull(current))
.distinctBy { it.absoluteFile.toPath().normalize().toString() }
.sortedWith(SessionPaths.chronological)
}
fun zipFolder(context: Context, folder: File, onProgress: ((Float) -> Unit)? = null): File? {
if (!folder.isDirectory) return null
val files = folder.walkTopDown().filter { it.isFile }
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
if (files.isEmpty()) return null
val out = shareDir(context).apply { deleteRecursively(); mkdirs() }
val zip = File(out, "DroidDeck-${folder.name}.zip")
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val live = liveSteamLogs(context, folder)
val logs = LinuxRuntime.logDir(context)
val stores = recent(File(logs, STORES_DIR))
val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
val battleNet = battleNetLogs(context)
val total = (files + live + stores + tools + battleNet.map { it.second }).sumOf { it.length() }.coerceAtLeast(1L)
var done = 0L
var shown = -1
fun advance(f: File) {
done += f.length()
val percent = (done * 100 / total).toInt()
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
fun details(folder: File): Details {
var size = 0L
var modified = folder.lastModified()
folder.walkTopDown().filter { it.isFile }.forEach { file ->
size += file.length()
modified = maxOf(modified, file.lastModified())
}
ZipOutputStream(zip.outputStream().buffered()).use { z ->
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).invariantSeparatorsPath, f); advance(f) }
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
battleNet.forEach { (name, f) -> addEntry(z, "$BATTLENET_DIR/$name", f); advance(f) }
}
return zip
return Details(size, modified)
}
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
z.putNextEntry(ZipEntry(name))
val w = z.bufferedWriter()
LogRedactor.scrubForShare(f, w)
w.flush()
z.closeEntry()
fun deleteSession(context: Context, folder: File): Boolean {
if (runCatching { SessionPaths.current()?.canonicalFile == folder.canonicalFile }.getOrDefault(false)) return false
val knownSession = runCatching { folder.canonicalFile }.getOrNull() in sessions(context).mapNotNull { runCatching { it.canonicalFile }.getOrNull() }
return knownSession && folder.isDirectory && folder.deleteRecursively()
}
private fun liveSteamLogs(context: Context, folder: File): List<File> {
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
val logs = File(SessionPrefs.activeSteamRoot(context), "logs")
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
fun prepareEnhanced(context: Context, folder: () -> File?, done: (List<File>) -> Unit) {
if (progress != null) return
progress = 0f
Thread({
val zips = runCatching {
folder()?.let { dir ->
EnhancedSessionLogShare.create(context, dir, onProgress = { p ->
main.post { if (progress != null) progress = p }
})
}.orEmpty()
}.onFailure { Log.w("SessionLogShare", "could not package enhanced diagnostics", it) }
.getOrDefault(emptyList())
main.post { progress = null; done(zips) }
}, "share-diagnostics").start()
}
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
fun zipFolder(context: Context, folder: File, out: File = shareDir(context), onProgress: ((Float) -> Unit)? = null): File? {
return EnhancedSessionLogShare.createLegacy(context, folder, onProgress, out)
}
const val STORES_DIR = "stores"
private const val RECENT_DAYS = 7
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
private const val BATTLENET_DIR = "battlenet"
private fun battleNetLogs(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
fun logsUnder(dir: File, prefix: String) = dir.listFiles { f -> f.isDirectory && f.name.startsWith(prefix) }.orEmpty().map { File(it, "Logs") }
return newest("droiddeck", listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")), 2, setOf("battlenet.log", "spawned.log")) +
newest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6) +
newest("agent", listOf(File(data, "Agent/Logs")) + logsUnder(File(data, "Agent"), "Agent."), 10, byDir = true) +
newest("setup", logsUnder(File(data, "Setup"), ""), 3, byDir = true)
}
private fun newest(folder: String, dirs: List<File>, count: Int, names: Set<String>? = null, byDir: Boolean = false): List<Pair<String, File>> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dirs.flatMap { dir ->
dir.listFiles { f -> f.isFile && f.name.endsWith(".log") && (names == null || f.name in names) && f.lastModified() >= since && f.length() <= STEAM_LOG_MAX_BYTES }.orEmpty().toList()
}.sortedByDescending { it.lastModified() }.take(count).map { f ->
(if (byDir) "$folder/${f.parentFile?.parentFile?.name}/${f.name}" else "$folder/${f.name}") to f
}
}
private fun recent(dir: File): List<File> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
}
internal fun shareDir(context: Context): File = File(context.cacheDir, "share")
fun clear(context: Context) {
shareDir(context).deleteRecursively()
@@ -131,4 +98,19 @@ object SessionLogShare {
send.clipData = ClipData.newRawUri(zip.name, uri)
return Intent.createChooser(send, context.getString(R.string.logshare_chooser)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
fun shareEnhancedIntent(context: Context, zips: List<File>): Intent {
require(zips.isNotEmpty())
val uris = ArrayList(zips.map { FileProvider.getUriForFile(context, context.packageName + ".logs", it) })
val send = Intent(Intent.ACTION_SEND_MULTIPLE)
.setType("application/zip")
.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
.putExtra(Intent.EXTRA_SUBJECT, zips.first().name.substringBeforeLast('-'))
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
send.clipData = ClipData.newUri(context.contentResolver, zips.first().name, uris.first()).also { clip ->
for (i in 1 until uris.size) clip.addItem(ClipData.Item(uris[i]))
}
return Intent.createChooser(send, context.getString(R.string.logshare_chooser))
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
@@ -26,7 +26,8 @@ object SessionPaths {
@Synchronized
fun beginOrCurrent(context: Context, label: String? = null): File {
dir?.let { if (it.isDirectory) return it }
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
val enhanced = EnhancedDiagnostics.isArmed(context)
val parent = if (SessionPrefs.logsEnabled(context) || enhanced) SessionFiles.logDirectory(context)
else File(context.cacheDir, "session-logs")
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
val last = parent.listFiles()?.mapNotNull { f ->
@@ -36,9 +37,13 @@ object SessionPaths {
var number = last + 1
var made = File(parent, "$day-${"%02d".format(Locale.US, number)}-$what")
while (made.exists()) made = File(parent, "$day-${"%02d".format(Locale.US, ++number)}-$what")
EnhancedDiagnostics.clearRecordFor(context, made)
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
dir = made
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
if (enhanced && !EnhancedDiagnostics.consumeInto(context, made)) {
Log.e(TAG, "could not activate enhanced diagnostics for $made")
}
Log.i(TAG, "session logs: $made" + if (parent == SessionFiles.logDirectory(context)) "" else " (logs off: discarded at the end)")
return made
}
@@ -8,6 +8,8 @@ import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
import java.io.File
@@ -504,6 +506,17 @@ object SessionPrefs {
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
}
@JvmStatic
fun ensurePowerVrAutoDrivers(context: Context) {
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context)) return
ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr())
}
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) {
if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return
prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply()
}
fun gpuAutoInstalled(context: Context): Set<String> =
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
@@ -775,8 +788,62 @@ object SessionPrefs {
@JvmStatic
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
fun venus(context: Context): Boolean = prefs(context).getBoolean("venus", false)
fun hostVulkanApi(context: Context): String = prefs(context).getString("hostVulkanApi", "").orEmpty()
fun setHostVulkanApi(context: Context, api: String) {
if (api != hostVulkanApi(context)) prefs(context).edit().putString("hostVulkanApi", api).apply()
}
fun bridgeFellBack(context: Context): Boolean = prefs(context).getBoolean("bridgeFellBack", false)
fun bridgeFellBackForMemory(context: Context): Boolean = prefs(context).getString("bridgeFallbackReason", "") == "memory"
fun setBridgeFellBack(context: Context, on: Boolean, reason: String = "") {
prefs(context).edit().putBoolean("bridgeFellBack", on).putString("bridgeFallbackReason", if (on) reason else "").apply()
}
fun steamGpuCompositing(context: Context): Boolean {
if (!steamGpuCompositingAllowed()) {
if (prefs(context).getBoolean("steamGpuCompositing", false))
prefs(context).edit().putBoolean("steamGpuCompositing", false).apply()
return false
}
return prefs(context).getBoolean("steamGpuCompositing", false)
}
fun steamGpuCompositingAllowed(): Boolean =
!com.droiddeck.launcher.core.DeviceSupport.adreno() && !com.droiddeck.launcher.core.DeviceSupport.mali()
fun setSteamGpuCompositing(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("steamGpuCompositing", on && steamGpuCompositingAllowed()).apply()
}
fun takeMemoryKillNotice(context: Context): Boolean {
val on = prefs(context).getBoolean("memoryKillNotice", false)
if (on) prefs(context).edit().putBoolean("memoryKillNotice", false).apply()
return on
}
fun setMemoryKillNotice(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("memoryKillNotice", on).apply()
}
fun maliFallbackByAuto(context: Context): String = prefs(context).getString("maliFallbackByAuto", "").orEmpty()
fun maliFallbackKnown(context: Context): Boolean = prefs(context).contains("maliFallbackByAuto")
fun setMaliFallbackByAuto(context: Context, route: String) {
prefs(context).edit().putString("maliFallbackByAuto", route).apply()
}
fun setVenus(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("venus", on).apply()
}
fun setVkBridge(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridge", on).apply()
prefs(context).edit().putBoolean("vkBridge", on).putBoolean("bridgeFellBack", false).apply()
}
@JvmStatic
@@ -786,6 +853,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("bridgeProtonDxvk", on).apply()
}
@JvmStatic
fun vkBridgeSafe(context: Context): Boolean = prefs(context).getBoolean("vkBridgeSafe", true)
fun setVkBridgeSafe(context: Context, on: Boolean) {
@@ -824,7 +892,7 @@ object SessionPrefs {
key = "logs",
oldValue = logsEnabled(context),
newValue = on,
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
newEffective = gameDebugLogsEffective(context, on, gameDebugLogsEnabled(context)),
)
}
@@ -837,7 +905,7 @@ object SessionPrefs {
key = "gameDebugLogsEnabled",
oldValue = gameDebugLogsEnabled(context),
newValue = on,
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
newEffective = gameDebugLogsEffective(context, logsEnabled(context), on),
)
}
@@ -850,8 +918,7 @@ object SessionPrefs {
): Boolean {
if (oldValue == newValue) return true
val saved = prefs(context)
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
SessionPaths.currentSessionLogsRetained(context)
val oldEffective = gameDebugLogsEffective(context)
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
if (oldEffective == newEffective) {
if (saved.edit().putBoolean(key, newValue).commit()) return true
@@ -887,6 +954,20 @@ object SessionPrefs {
}
}
fun detailedGraphicsLogs(context: Context): Boolean =
prefs(context).getBoolean("detailedGraphicsLogs", false)
fun setDetailedGraphicsLogs(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("detailedGraphicsLogs", on).apply()
}
internal fun gameDebugLogsEffective(
context: Context,
logs: Boolean = logsEnabled(context),
gameLogs: Boolean = gameDebugLogsEnabled(context),
): Boolean = EnhancedDiagnostics.isCurrentSessionActive(context) ||
(logs && gameLogs && SessionPaths.currentSessionLogsRetained(context))
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import android.app.Notification
import android.app.NotificationChannel
@@ -405,6 +406,7 @@ class SessionService : Service() {
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
SessionLogCapture.stopFor(dir)
try {
GraphicsReport.finish(dir)
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
} finally {
SessionPaths.release(this, dir)
@@ -424,6 +426,21 @@ class SessionService : Service() {
return lines
}
/** Whether a kernel release ("6.1.157-android14-11") is older than [major].[minor]; false if unreadable. */
internal fun kernelBefore(release: String, major: Int, minor: Int): Boolean {
val m = Regex("""^(\d+)\.(\d+)""").find(release) ?: return false
val (a, b) = m.destructured
return a.toInt() < major || (a.toInt() == major && b.toInt() < minor)
}
/** Whether the newest finished session's log shows Xwayland itself crashing. */
private fun lastXwaylandCrashed(): Boolean = runCatching {
val last = SessionPaths.sessionFolders(this).filter { it != SessionPaths.current() }.lastOrNull() ?: return false
val log = File(last, "session.log").takeIf { it.isFile } ?: return false
log.useLines { lines -> lines.any { it.contains("(EE) Segmentation fault") } } &&
log.useLines { lines -> lines.any { it.contains("X11 I/O error") || it.contains("Xwayland", ignoreCase = true) } }
}.getOrDefault(false)
private fun tuDebugOverride(): String? = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH)
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }?.takeIf { it.isNotEmpty() }
@@ -435,6 +452,13 @@ class SessionService : Service() {
private fun runSession(gen: Int) {
SessionPrefs.ensurePowerVrAutoDrivers(this)
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
if (SessionPrefs.venus(this)) VenusComponent.hostVulkanTooOld(this)?.let {
Log.w(TAG, "venus: off for this session - the phone's driver reports Vulkan $it and gamescope needs 1.2 or newer; the session uses the PanVK pair or the bridge")
}
}
SessionTerminal.clear()
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)
try {
@@ -452,10 +476,19 @@ class SessionService : Service() {
val stillStarting = { gen == sessionGen && SessionState.running }
val prootPack = LinuxRuntime.patchedProot(this) || AddonPack.PROOT.await(this, stillStarting)
val directAudioPack = AddonPack.DIRECTAUDIO.await(this, stillStarting)
val systemVulkan = SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(this))
val powerVrPack = !systemVulkan || (stillStarting() && AddonPack.POWERVR.await(this, stillStarting))
if (!stillStarting()) {
Log.i(TAG, "session stopped while add-on packs were downloading")
return
}
if (!powerVrPack) {
val message = getString(R.string.session_powervr_missing)
Log.e(TAG, "powervr pack unavailable; the system graphics runtime cannot be prepared")
failSession(gen, "POWERVR_MISSING", message, -1)
stopSession(-1, gen)
return
}
if (!directAudioPack) {
Log.w(TAG, "directaudio pack unavailable; game audio drivers will not be staged")
mainHandler.post {
@@ -476,7 +509,21 @@ class SessionService : Service() {
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
SessionFiles.stage(this, root, startsSession = true)
try {
if (systemVulkan) {
SystemVulkanDriver.prepare(this)
if (!stillStarting()) {
Log.i(TAG, "session stopped while the system graphics runtime was unpacking")
return
}
pruneSystemVulkanRuntime()
}
SessionFiles.stage(this, root, startsSession = true)
} catch (error: Exception) {
Log.e(TAG, "Could not prepare the session graphics runtime", error)
stopSession(-1, gen)
return
}
SessionArtifacts.awaitCollections()
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
VacDiagnostics.arm(this)
@@ -512,18 +559,32 @@ class SessionService : Service() {
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "forced components", it) }
}
addClientEnvironment(guest, steamHere, agentEnvironment)
try {
addClientEnvironment(guest, steamHere, agentEnvironment)
} catch (e: IllegalStateException) {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
stopSession(-1, gen)
return
}
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size
val pulse = startAudio(guest, sessionDir, directAudioPack)
startVkBridge(guest, sessionDir)
if (VenusComponent.wanted(this)) {
components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) })
}
if (steamHere) {
val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock"))
encoder.attach(this)
components.add(encoder)
guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath)
}
startVkBridge(guest, sessionDir)
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "clocks.log")).let {
it.attach(this)
components.add(it)
}
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
@@ -540,6 +601,7 @@ class SessionService : Service() {
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
@@ -569,6 +631,10 @@ class SessionService : Service() {
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1")
GraphicsReport.begin(this, sessionDir, guest)
val shellGuest = ArrayList(guest).apply {
add("SHELL=/bin/bash")
add("TERM=xterm-256color")
@@ -668,7 +734,14 @@ class SessionService : Service() {
if (gen == sessionGen) components.clear()
return
}
components.forEach { it.start() }
try {
components.forEach { it.start() }
} catch (e: Exception) {
Log.e(TAG, "Could not start the session components", e)
failSession(gen, "COMPONENT_START_FAILED", e.message ?: "Session component could not be started", -1)
stopSession(-1, gen)
return
}
val line = command.joinToString(" ") {
it.replace("\\", "\\\\").replace(" ", "\\ ")
@@ -768,6 +841,7 @@ class SessionService : Service() {
SessionState.sessionId = sessionDir.name
SessionState.eventsFile = File(sessionDir, "events.jsonl")
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
if (EnhancedDiagnostics.isActive(this, sessionDir)) SessionEvents.record("diagnostics.enhanced", mapOf("schema" to 1))
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
SessionLogCapture.start(File(sessionDir, "app.log"))
@@ -810,7 +884,12 @@ class SessionService : Service() {
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
val venus = VenusComponent.wanted(this)
if (venus) {
VenusComponent.guestEnv(this).forEach { guest.add(it) }
} else {
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
}
val linuxDriverId = SessionPrefs.linuxDriver(this)
SessionState.runtimeDriver = linuxDriverId
com.droiddeck.launcher.gpu.AutoDriverTrial.sessionStarting(
@@ -819,11 +898,39 @@ class SessionService : Service() {
?: SessionPrefs.androidDriver(this),
linuxDriverId,
)
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
val bridge = com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)
if (!bridge && !venus && SystemVulkanDriver.usesDefault(linuxDriverId)) {
SystemVulkanDriver.addEnvironment(this, guest)
}
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
guest.add("XWAYLAND_NO_GLAMOR=1")
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
}
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) guest.add("BL_RAISE_NOFILE=1")
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
val kernel = System.getProperty("os.version").orEmpty()
val old = kernelBefore(kernel, 6, 6)
val maliNode = LinuxRuntime.gpuStandIn(this) == LinuxRuntime.MALI_DEVICE
if (old || maliNode) {
guest.add("GAMESCOPE_DISABLE_EXPLICIT_SYNC=1")
Log.i(TAG, "gamescope: explicit sync off (" + (if (old) "kernel $kernel has no SYNCOBJ_EVENTFD" else "Mali stand-in node has no syncobjs") + ")")
}
}
if (!bridge && com.droiddeck.launcher.core.DeviceSupport.openDriverActive(this)) {
if (SessionPrefs.steamGpuCompositing(this)) {
Log.i(TAG, "steam: GPU web compositing (Setup's \"Steam interface: GPU drawing\")")
} else {
guest.add("BL_STEAM_SOFT_COMPOSITING=1")
Log.i(TAG, "steam: software web compositing for the open driver pair (GPU raster kept)")
}
guest.add("BL_OPEN_DRIVER=1")
LinuxRuntime.gpuStandIn(this)?.takeIf { it == LinuxRuntime.MALI_DEVICE }?.let { guest.add("BL_DRM_STANDIN=$it") }
}
val tuOverride = tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId)
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
if (!venus && com.droiddeck.launcher.core.DeviceSupport.adreno()) (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
if (SessionPrefs.zinkLazy(this)) {
guest.add("ZINK_DESCRIPTORS=lazy")
guest.add("ZINK_DEBUG=compact")
@@ -872,20 +979,17 @@ class SessionService : Service() {
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startVkBridge(guest: MutableList<String>, sessionDir: File) {
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) return
val socket = File(filesDir, "vkbridge/server.sock")
val bridge = com.droiddeck.launcher.gpu.VkBridgeComponent(socket, File(sessionDir, "vkbridge-server.log"))
bridge.attach(this)
components.add(bridge)
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "vkbridge-clocks.log")).let {
it.attach(this)
components.add(it)
}
guest.add("BL_VKBRIDGE=1")
if (SessionPrefs.steamGpuCompositing(this)) guest.add("BL_STEAM_GPU_COMPOSITING=1")
SessionPrefs.linuxDriver(this).takeIf { it.isNotEmpty() }
?.let { runCatching { LinuxVulkanDriver.resolveIcdPath(this, it) }.getOrNull() }
?.let { guest.add("BL_VKBRIDGE_FALLBACK_ICD=$it") }
guest.add("VKBRIDGE_SOCKET=" + socket.path)
guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path)
guest.add("VKBRIDGE_MODE=" + SessionPrefs.vkBridgeMode(this))
@@ -895,6 +999,8 @@ class SessionService : Service() {
}
Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}, ${SessionPrefs.vkBridgeMode(this)} mode), socket $socket")
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
val wantsDirectAudio = directAudioPack &&
@@ -1832,6 +1938,12 @@ class SessionService : Service() {
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
}
/** Background-only: preserve old runtimes until all earlier guest processes are gone. */
private fun pruneSystemVulkanRuntime() {
runCatching { SystemVulkanDriver.pruneUnused(this, !OrphanReaper.hasOtherProcesses()) }
.onFailure { Log.w(TAG, "could not prune unused system Vulkan runtimes", it) }
}
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
mainHandler.post {
try {
@@ -1971,10 +2083,12 @@ class SessionService : Service() {
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "session-teardown").start()
} else {
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
Thread({
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen, collectEnded)
@@ -23,7 +23,7 @@ object SettingsReset {
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
@@ -0,0 +1,131 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.core.SessionPart
import java.io.File
import java.io.PrintWriter
/**
* Vulkan for the session on a Mali, through Venus (the "Mali (Venus)" route; by David Cimo,
* DavidCimo/droiddeck-mali, ported to this branch).
*
* The guest's processes are glibc and cannot load the vendor's bionic driver. Instead they load
* Mesa's Venus ICD (libvulkan_virtio.so), which serializes every Vulkan call over a unix socket to
* virglrenderer's vtest server. The server runs here, on the Android side, and replays the calls
* on the device's own Vulkan driver. Both ends of the socket are under the app's files directory,
* which the session binds at its own path, so the same path works inside and out.
*/
class VenusComponent(private val logFile: File?) : SessionPart() {
@Volatile private var pid = -1
override fun start() {
val context = app()
stageIcd(context)
val libDir = context.applicationInfo.nativeLibraryDir
val socket = socket(context)
socket.delete()
val env = arrayOf(
"LD_LIBRARY_PATH=$libDir",
// vtest forks a render server per client; this is where its executable is.
"RENDER_SERVER_EXEC_PATH=$libDir/libvirgl_render_server.so",
"TMPDIR=" + context.cacheDir.path,
)
val command = "$libDir/libvirgl_test_server.so --venus --no-virgl --socket-path " + socket.path
val out = logFile?.let { runCatching { PrintWriter(java.io.FileWriter(it, true)) }.getOrNull() }
pid = HostProcess.start(command, env, context.filesDir, { status ->
Log.w(TAG, "vtest server exited: $status")
out?.let { synchronized(it) { it.println("vtest server exited: $status"); it.flush() } }
}, { line ->
Log.i(TAG, line)
out?.let { synchronized(it) { it.println(line); it.flush() } }
})
Log.i(TAG, "vtest server pid $pid on $socket")
}
override fun stop() {
if (pid > 1) Process.killProcess(pid)
pid = -1
}
companion object {
private const val TAG = "Venus"
private const val ASSET = "venus/libvulkan_virtio.so"
private const val DIR = "venus"
private const val LIB = "libvulkan_virtio.so"
private const val ICD = "virtio_icd.json"
/**
* The selection rule: Venus when Setup's "Mali (Venus)" is on, on a GPU that is neither an
* Adreno nor one the system-driver route covers (PowerVR, Xclipse), and the apk carries it.
* It then replaces the Mali bridge and any open driver pair for the session.
*/
@JvmStatic
fun wanted(context: Context): Boolean =
!DeviceSupport.adreno() && !com.droiddeck.launcher.gpu.SystemVulkanDriver.isAvailable() &&
SessionPrefs.venus(context) && available(context) && hostVulkanTooOld(context) == null
/** The phone driver's Vulkan version when it is below 1.2: gamescope skips such a device, so Venus cannot run. */
@JvmStatic
fun hostVulkanTooOld(context: Context): String? {
val api = com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull()?.get("api") ?: SessionPrefs.hostVulkanApi(context)
val parts = api.split('.').mapNotNull { it.trim().toIntOrNull() }
if (parts.size < 2) return null
return api.takeIf { parts[0] < 1 || (parts[0] == 1 && parts[1] < 2) }
}
/** Whether this apk carries the Venus component (tools/venus, venus.tzst). */
@JvmStatic
fun available(context: Context): Boolean = runCatching {
context.assets.list(DIR)?.contains(LIB) == true &&
File(context.applicationInfo.nativeLibraryDir, "libvirgl_test_server.so").isFile
}.getOrDefault(false)
@JvmStatic
fun socket(context: Context): File = File(File(context.filesDir, DIR), "vtest.sock")
/** What the guest needs to find the ICD and the server. */
@JvmStatic
fun guestEnv(context: Context): List<String> {
val dir = File(context.filesDir, DIR)
return listOf(
"VK_ICD_FILENAMES=" + File(dir, ICD).path,
"VN_DEBUG=vtest",
"VTEST_SOCKET_NAME=" + socket(context).path,
// Xwayland has no DRI3 without a DRM node, so swapchains present through shared memory.
"MESA_VK_WSI_DEBUG=sw",
// The Mali compatibility layer in every process but gamescope, not only Wine: Zink
// (Steam's GL, Xwayland's glamor) requires robustness2's nullDescriptor, which the
// layer stands in for. The session script checks it and falls back to llvmpipe.
"DROIDDECK_MALI_COMPAT=1",
"BL_VENUS=1",
// gamescope's composite layout without immutable YCbCr samplers from the start
// (patch 0930): a Mali-G615 refused every composite pipeline with them, and testing
// that through Venus took the render server down.
"GAMESCOPE_NO_YCBCR_SAMPLERS=1",
)
}
/** Copies the ICD out of the APK when it changed, and writes its manifest with an absolute path. */
private fun stageIcd(context: Context) {
val dir = File(context.filesDir, DIR).apply { mkdirs() }
val lib = File(dir, LIB)
// Copied again after every app update: the asset is compressed, so its size is unknown up front.
val installed = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime
if (!lib.isFile || lib.lastModified() < installed) {
val tmp = File(dir, "$LIB.tmp")
context.assets.open(ASSET).use { input -> tmp.outputStream().use { input.copyTo(it) } }
if (!tmp.renameTo(lib)) throw java.io.IOException("could not move the Venus ICD into place")
Log.i(TAG, "staged $lib (${lib.length()} bytes)")
}
if (!FileUtils.writeString(
File(dir, ICD),
"""{"file_format_version":"1.0.1","ICD":{"library_path":"${lib.path}","api_version":"1.4.354"}}""",
)) throw java.io.IOException("could not write the Venus ICD manifest")
}
}
}
@@ -38,6 +38,7 @@ object WinComponents {
private const val MSI_CACHE = "$STORE/.packages"
private val PROTON_PROVIDES = setOf("gecko", "mono", "cjkfonts", "powershell", "VulkanRT")
private val NESTED_KEYS = setOf("url", "file_name", "file_checksum", "file_size")
private val installLock = Any()
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
@@ -61,7 +62,7 @@ object WinComponents {
class Component(
val name: String, val description: String, val provider: String, val status: String,
val dependencies: List<String>, val steps: List<Step>,
val snapshot: String = "",
val snapshot: String = "", val revision: Int = 0,
)
enum class Support { READY, NEEDS_INSTALLER, UNSUPPORTED }
@@ -127,7 +128,7 @@ object WinComponents {
name, o.optString("description"), o.optString("provider"), o.optString("status"),
(0 until deps.length()).map { deps.getString(it) }.filter { validId(it) },
(0 until steps.length()).map { steps.getJSONObject(it).let { s -> Step(s.optString("action"), s) } },
o.optString("snapshot"),
o.optString("snapshot"), o.optInt("revision", 0).coerceAtLeast(0),
)
}
if (listed.any { it.name == VCREDIST_ARM64 }) listed else listed + builtInArm64Runtime()
@@ -170,15 +171,31 @@ object WinComponents {
else -> true
}
fun installed(context: Context, id: String): String? = runCatching {
JSONObject(File(LinuxRuntime.rootDir(context), "$STORE/$id/component.json").readText()).optString("version", "?")
internal fun installedVersion(directory: File, revision: Int): String? = runCatching {
val meta = JSONObject(File(directory, "component.json").readText())
if (meta.optInt("revision", 0) < revision) null else meta.optString("version", "?")
}.getOrNull()
fun installedIds(context: Context): List<String> =
File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
.orEmpty().map { it.name }.filter { installed(context, it) != null }.sorted()
fun installed(context: Context, id: String): String? = installedVersion(
File(LinuxRuntime.rootDir(context), "$STORE/$id"), cached(context)?.firstOrNull { it.name == id }?.revision ?: 0,
)
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
internal fun downloadedIds(store: File): List<String> =
store.listFiles { f -> f.isDirectory && validId(f.name) }.orEmpty()
.filter { installedVersion(it, 0) != null }.map { it.name }.sorted()
fun downloadedIds(context: Context): List<String> = downloadedIds(File(LinuxRuntime.rootDir(context), STORE))
fun installedIds(context: Context): List<String> {
val revisions = cached(context).orEmpty().associate { it.name to it.revision }
return File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
.orEmpty().filter { installedVersion(it, revisions[it.name] ?: 0) != null }.map { it.name }.sorted()
}
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? =
synchronized(installLock) { installLocked(context, c, all, onProgress) }
private fun installLocked(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
if (support(c, all) != Support.READY) return "${c.name} cannot be installed here yet"
val order = ArrayList<Component>()
fun visit(x: Component, depth: Int) {
@@ -353,7 +370,7 @@ object WinComponents {
val version = msi?.optString("version")?.takeIf { it.isNotEmpty() }
?: Regex("""\b(\d+\.\d+(\.\d+)*)\b""").find(c.description)?.value ?: "catalog"
val meta = JSONObject()
.put("id", c.name).put("version", version)
.put("id", c.name).put("version", version).put("revision", c.revision)
.put("overrides", JSONArray(overrides.distinct()))
.put("requires", JSONArray(c.dependencies))
msi?.let { meta.put("kind", it.optString("kind", "msi")).put("product", it.optString("product")).put("notes", it.optJSONArray("notes") ?: JSONArray()) }
@@ -556,8 +573,7 @@ object WinComponents {
matches.forEach { f -> f.copyTo(File(dest, f.name.lowercase()), overwrite = true) }
}
@Synchronized
fun uninstall(context: Context, id: String) {
fun uninstall(context: Context, id: String) = synchronized(installLock) {
require(validId(id))
FileUtils.delete(File(LinuxRuntime.rootDir(context), "$STORE/$id"))
save(context, selections(context).mapValues { (_, sel) -> Selection(sel.auto - id, sel.user - id) })
@@ -52,6 +52,19 @@ object CloudPlan {
return Plan(transfer, conflicts, same)
}
/**
* Files to send. GOG objects uploaded by older builds are raw while their cloud hash is still the
* local raw MD5, so they appear in [Plan.same]; resending them stores the gzip form Galaxy reads.
* A forced GOG upload is the manual repair path and sends every local file, including unchanged
* ones the service gives no hash for; once rewritten the cloud hash is the compressed MD5.
*/
fun upSend(plan: Plan, force: Boolean, repairRawGog: Boolean, allLocal: Collection<String> = emptyList()): List<String> {
if (force) {
return (plan.transfer + plan.conflicts + if (repairRawGog) allLocal else emptyList()).distinct()
}
return (plan.transfer + if (repairRawGog) plan.same else emptyList()).distinct()
}
fun toJson(baseline: Map<String, Entry>): String = JSONObject().apply {
for ((k, e) in baseline) put(k, JSONObject().put("l", e.localMd5).put("c", e.cloudMd5 ?: "").put("t", e.cloudModified))
}.toString()
@@ -374,18 +374,31 @@ object CloudSaves {
val remote = remote(cloud) { it in files }
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val plan = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val send = if (force) plan.transfer + plan.conflicts else plan.transfer
val send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys)
val next = HashMap(base)
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
if (send.isNotEmpty()) {
backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
val data = send.associateWith { files.getValue(it).readBytes() }
val stamped = cloud.put(data)
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
val after = remote(cloud) { it in data }
for (name in data.keys) {
val stamped = HashMap<String, Long>()
val sentMd5 = HashMap<String, String>()
if (cloud is GogCloud) {
// Stream one save at a time: gzip needs a full-size buffer and uploads can be large.
val filesToSend = send.associateWith { files.getValue(it) }
val results = cloud.putFiles(filesToSend, send.associateWith { files.getValue(it).lastModified() })
for ((name, result) in results) {
if (result.modifiedMs > 0) stamped[name] = result.modifiedMs
result.md5?.let { sentMd5[name] = it }
}
} else {
val data = send.associateWith { files.getValue(it).readBytes() }
for ((name, bytes) in data) sentMd5[name] = md5(bytes)
stamped += cloud.put(data, send.associateWith { files.getValue(it).lastModified() })
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
}
val after = remote(cloud) { it in send }
for (name in send) {
val r = after[name]
next[name] = CloudPlan.Entry(md5(data.getValue(name)), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
}
}
saveBaseline(context, store, id, next)
@@ -1,24 +1,43 @@
package com.droiddeck.launcher.stores
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.security.DigestOutputStream
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.Locale
import java.util.TimeZone
import java.util.zip.CRC32
import java.util.zip.Deflater
import java.util.zip.DeflaterOutputStream
import org.json.JSONArray
import org.json.JSONObject
class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null, val readLink: String? = null)
class CloudPut(val modifiedMs: Long, val md5: String?)
interface CloudTransport {
fun list(): List<CloudFile>
fun details(file: CloudFile) {}
fun get(file: CloudFile): Pair<ByteArray, Long>
fun put(files: Map<String, ByteArray>): Map<String, Long>
fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long> = emptyMap()): Map<String, Long>
/** Uploads from files so a transport can stream instead of holding every save in memory. */
fun putFiles(files: Map<String, File>, modifiedMs: Map<String, Long> = emptyMap()): Map<String, CloudPut> {
val data = files.mapValues { it.value.readBytes() }
val digests = data.mapValues { md5Hex(it.value) }
return put(data, modifiedMs).mapValues { (name, modified) -> CloudPut(modified, digests.getValue(name)) }
}
}
private const val TIMEOUT = 30_000
@@ -47,6 +66,9 @@ internal fun gunzip(data: ByteArray): ByteArray? = try {
java.util.zip.GZIPInputStream(data.inputStream()).use { it.readBytes() }
} catch (e: Exception) { null }
/** Same gzip GOG uses on PUT: deflate level 6, mtime 0, OS Unix. */
private val GOG_GZIP_HEADER = byteArrayOf(0x1f, 0x8b.toByte(), 8, 0, 0, 0, 0, 0, 0, 3)
internal fun gzipGogPut(data: ByteArray): ByteArray {
val deflater = Deflater(6, true)
val raw = ByteArrayOutputStream()
@@ -63,14 +85,14 @@ internal fun gzipGogPut(data: ByteArray): ByteArray {
}
val crc = CRC32().also { it.update(data) }
return ByteArrayOutputStream(18 + raw.size()).apply {
write(byteArrayOf(0x1f, 0x8b.toByte(), 8, 0, 0, 0, 0, 0, 0, 3))
write(GOG_GZIP_HEADER)
write(raw.toByteArray())
writeIntLe(crc.value.toInt())
writeIntLe(data.size)
}.toByteArray()
}
private fun ByteArrayOutputStream.writeIntLe(v: Int) {
private fun OutputStream.writeIntLe(v: Int) {
write(v and 0xff)
write(v ushr 8 and 0xff)
write(v ushr 16 and 0xff)
@@ -117,13 +139,64 @@ internal fun gogRelativeNames(files: List<CloudFile>, location: String?): Pair<S
}
}
private fun md5Hex(data: ByteArray): String =
java.security.MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) }
private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }
private class GzipFile(val length: Long, val rawMd5: String, val etag: String)
/** Streams the same gzip framing as [gzipGogPut] into [dst] without reading the save into memory. */
private fun gzipFile(src: File, dst: File): GzipFile {
val raw = java.security.MessageDigest.getInstance("MD5")
val compressed = java.security.MessageDigest.getInstance("MD5")
val crc = CRC32()
var size = 0L
val file = FileOutputStream(dst)
val out = DigestOutputStream(file, compressed)
try {
out.write(GOG_GZIP_HEADER)
val deflater = Deflater(6, true)
try {
val deflate = DeflaterOutputStream(out, deflater, 64 * 1024)
src.inputStream().use { input ->
val buf = ByteArray(64 * 1024)
while (true) {
val n = input.read(buf)
if (n < 0) break
raw.update(buf, 0, n)
crc.update(buf, 0, n)
size += n
deflate.write(buf, 0, n)
}
}
deflate.finish()
} finally {
deflater.end()
}
out.writeIntLe(crc.value.toInt())
out.writeIntLe(size.toInt())
out.flush()
return GzipFile(dst.length(), raw.digest().toHex(), compressed.digest().toHex())
} finally {
out.close()
}
}
/** GOG Galaxy parses `X-Object-Meta-LocalLastModified`; objects without it fail as "invalid data". */
private val GOG_STAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx", Locale.US)
private fun gogStamp(ms: Long): String =
Instant.ofEpochMilli(ms).atOffset(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS).format(GOG_STAMP)
class GogCloud(
private val userId: String,
private val clientId: String,
private val token: String,
private val location: String? = null,
baseUrl: String? = null,
) : CloudTransport {
private val base = "https://cloudstorage.gog.com/v1/$userId/$clientId"
private val base = baseUrl ?: "https://cloudstorage.gog.com/v1/$userId/$clientId"
private val ua = "GOG Galaxy"
private var prefix: String? = location?.let { "$it/" }
@@ -190,16 +263,38 @@ class GogCloud(
return gogDecodeCloudBody(data, encoding) to modified
}
override fun put(files: Map<String, ByteArray>): Map<String, Long> = files.mapValues { (name, data) ->
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> = files.mapValues { (name, data) ->
val body = gzipGogPut(data)
putBody(name, body.inputStream(), body.size.toLong(), md5Hex(body), modifiedMs[name] ?: System.currentTimeMillis())
}
override fun putFiles(files: Map<String, File>, modifiedMs: Map<String, Long>): Map<String, CloudPut> = files.mapValues { (name, file) ->
val compressed = File.createTempFile("gog-cloud-", ".gz")
try {
val gz = gzipFile(file, compressed)
val modified = putBody(name, compressed.inputStream(), gz.length, gz.etag, modifiedMs[name] ?: file.lastModified())
CloudPut(modified, gz.rawMd5)
} finally {
compressed.delete()
}
}
private fun putBody(name: String, source: InputStream, length: Long, etag: String, modified: Long): Long {
val c = open("$base/${cloudKey(name)}", "PUT", token, ua)
c.doOutput = true
c.setRequestProperty("Content-Type", "application/octet-stream")
c.setFixedLengthStreamingMode(data.size)
c.outputStream.use { it.write(data) }
val code = c.responseCode
c.disconnect()
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
CloudFile(name, -1L).also { details(it) }.modifiedMs
try {
c.doOutput = true
c.setRequestProperty("Content-Type", "application/octet-stream")
c.setRequestProperty("Content-Encoding", "gzip")
c.setRequestProperty("Etag", etag)
c.setRequestProperty("X-Object-Meta-LocalLastModified", gogStamp(modified))
c.setFixedLengthStreamingMode(length)
c.outputStream.use { out -> source.use { it.copyTo(out, 64 * 1024) } }
val code = c.responseCode
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
return CloudFile(name, -1L).also { details(it) }.modifiedMs
} finally {
c.disconnect()
}
}
}
@@ -208,6 +303,6 @@ class EpicCloud(private val accountId: String, private val appName: String, priv
override fun get(file: CloudFile): Pair<ByteArray, Long> = com.droiddeck.launcher.stores.epic.EpicSaveSync.read(file)
override fun put(files: Map<String, ByteArray>): Map<String, Long> =
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> =
com.droiddeck.launcher.stores.epic.EpicSaveSync.write(token, accountId, appName, files)
}
@@ -97,20 +97,25 @@ object StoreInstallRoot {
fun installRoot(context: Context): File = internalRoot(context)
fun externalTarget(context: Context): Target? =
if (SessionPrefs.defaultStorageFolder(context).isNotBlank()) customTarget(context)
else detectedExternalTarget(context)
fun externalTarget(context: Context): Target? = when {
SessionPrefs.defaultStorageFolder(context).isNotBlank() -> customTarget(context)
GameStorage.disconnected(context) -> null
else -> detectedExternalTarget(context)
}
internal fun externalTarget(targets: List<Target>, internalRoot: File): Target? =
targets.firstOrNull { it.folder && it.root.absolutePath != internalRoot.absolutePath }
?: targets.firstOrNull { it.removable && it.root.absolutePath != internalRoot.absolutePath }
fun defaultTarget(context: Context): Target? = when (SessionPrefs.defaultStorage(context)) {
SessionPrefs.DEFAULT_STORAGE_INTERNAL -> Target(internalRoot(context), context.getString(com.droiddeck.launcher.R.string.games_internal), removable = false)
SessionPrefs.DEFAULT_STORAGE_EXTERNAL -> externalTarget(context)
SessionPrefs.DEFAULT_STORAGE_INTERNAL -> internalTarget(context)
SessionPrefs.DEFAULT_STORAGE_EXTERNAL -> externalTarget(context) ?: internalTarget(context)
else -> null
}
private fun internalTarget(context: Context) =
Target(internalRoot(context), context.getString(com.droiddeck.launcher.R.string.games_internal), removable = false)
fun libraryRoot(context: Context): File? = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
fun roots(context: Context): List<File> {
@@ -74,29 +74,36 @@ object StoresState {
fun register(backend: StoreBackend) { backends[backend.store] = backend }
private val refreshRequests = java.util.concurrent.atomic.AtomicInteger()
fun refresh(context: Context) {
val app = context.applicationContext
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
background("stores-refresh") {
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
val partial = StoreInstallRoot.unfinished(app)
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
main.post {
androidx.compose.runtime.snapshots.Snapshot.withMutableSnapshot {
val restored = found.toMap()
accounts.keys.toList().filter { it !in restored }.forEach { accounts.remove(it); libraryAsked.remove(it) }
accounts.putAll(restored)
installed = onDisk
unfinished = partial
engine = version
accountsLoaded = true
if (refreshRequests.getAndIncrement() > 0) return
var seen = 0
background("stores-refresh", onFailure = { if (refreshRequests.getAndSet(0) > seen) main.post { refresh(app) } }) {
do {
seen = refreshRequests.get()
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
val partial = StoreInstallRoot.unfinished(app)
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
main.post {
androidx.compose.runtime.snapshots.Snapshot.withMutableSnapshot {
val restored = found.toMap()
accounts.keys.toList().filter { it !in restored }.forEach { accounts.remove(it); libraryAsked.remove(it) }
accounts.putAll(restored)
installed = onDisk
unfinished = partial
engine = version
accountsLoaded = true
}
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
}
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
}
} while (!refreshRequests.compareAndSet(seen, 0))
}
}
@@ -206,6 +213,7 @@ object StoresState {
main.post {
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogMaintenance.reset()
logLine("${store.label}: signed out")
}
}
@@ -34,11 +34,16 @@ object BattleNetInstall {
internal const val STATE = "BNET_STATE "
internal const val DONE = "BNET_DONE "
internal const val ERROR = "BNET_ERROR "
private const val VERSIONS = "https://%s.version.battle.net/v2/products/%s/versions"
private const val CN = "cn"
private const val BUILD_INFO = ".build.info"
private const val CHECK_AGAIN_MS = 30 * 60_000L
private const val START_WAIT_MS = 60_000L
/** Blizzard serves China from battlenet.com.cn; its global version hostnames do not answer for that region. */
internal fun versionsUrl(region: String, product: String): String =
"https://" + (if (region == CN) "cn.version.battlenet.com.cn" else "$region.version.battle.net") +
"/v2/products/$product/versions"
internal val LOCALES = listOf(
"enUS", "enGB", "esMX", "esES", "ptBR", "ptPT", "frFR", "deDE", "itIT", "ruRU", "jaJP", "koKR", "plPL", "trTR",
"zhTW", "zhCN", "thTH", "arSA",
@@ -187,7 +192,7 @@ object BattleNetInstall {
checks.execute {
val local = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
?: return@execute retryLater()
val latest = runCatching { latestBuild(fetch(VERSIONS.format(Locale.ROOT, local.first, product)), local.first) }
val latest = runCatching { latestBuild(fetch(versionsUrl(local.first, product)), local.first) }
.onFailure { Log.w(TAG, "versions of $product: ${it.javaClass.simpleName}") }.getOrNull()
?: return@execute retryLater()
val behind = latest != local.second
@@ -41,7 +41,7 @@ internal object GogMaintenance {
}
fun checkInstalled(context: Context, games: List<InstalledStoreGame>) {
val user = StoreAccounts.displayName(context, Store.GOG).orEmpty()
val user = StoresState.accounts[Store.GOG].orEmpty()
if (user != account) { reset(); account = user }
if (user.isBlank()) return
games.filter { it.sidecar.store == Store.GOG && it.sidecar.isInstalled }.forEach { check(context, it) }
@@ -112,16 +112,19 @@ internal fun BarActions(
qamModifier: Modifier = Modifier,
qamInteraction: MutableInteractionSource? = null,
onQamConfirm: (() -> Unit)? = null,
showShortcuts: Boolean = false,
) {
onMenu?.let {
BarButton(stringResource(R.string.touch_droiddeck_menu), menuModifier.testTag("bottom-bar-menu"), icon = R.drawable.ic_stat_session,
active = menuActive, onClick = it)
}
onSteam?.let {
BarButton(stringResource(R.string.drawer_steam_menu), steamModifier.testTag("bottom-bar-steam"), label = "STEAM", onClick = it)
BarButton(stringResource(R.string.drawer_steam_menu), steamModifier.testTag("bottom-bar-steam"), label = "STEAM",
shortcut = if (showShortcuts) "⧉" else null, onClick = it)
}
onQam?.let {
BarButton(stringResource(R.string.drawer_open_qam), qamModifier.testTag("bottom-bar-qam"), vector = Icons.Outlined.MoreHoriz,
shortcut = if (showShortcuts) "☰" else null,
interactionSource = qamInteraction ?: remember { MutableInteractionSource() }, onConfirm = onQamConfirm, onClick = it)
}
}
@@ -483,17 +483,27 @@ fun ComponentsPage(
)
else -> {
val st = compState(l)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
val label = ComponentsManager.LABEL[l] ?: l
if (st == null) InUseBar(false, stringResource(R.string.comp_no_proton), "")
else {
val reappliedAt = view?.reappliedAt?.takeIf { it > 0 }?.let { DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(it * 1000)) }
InUseBar(
queued = st.queued != null,
sentence = (if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
.let { if (reappliedAt != null) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
note = if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
onCancel = if (st.queued != null) onCancelQueued else null,
)
Column {
InUseBar(
queued = st.queued != null,
sentence = (if (managedDxvk) stringResource(R.string.comp_in_use, label, stringResource(R.string.gpu_system_powervr)) +
(st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
else if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
.let { if (reappliedAt != null && !managedDxvk) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
note = if (managedDxvk) "" else if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
onCancel = if (st.queued != null) onCancelQueued else null,
maxLines = if (managedDxvk && st.queued != null) 3 else 2,
)
if (managedDxvk) Text(
stringResource(R.string.cmgr_powervr_dxvk_managed),
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp),
)
}
}
}
}
@@ -537,16 +547,17 @@ fun ComponentsPage(
}
else -> {
val label = ComponentsManager.LABEL[l] ?: l
val rows = installedFor(l, view, snapshot)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
val rows = installedFor(l, view, snapshot, managedDxvk)
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_stored, label))
val p = view?.proton
rows.forEachIndexed { i, item ->
val key = "row:$l:${item.file ?: item.protonVersion}"
ChoiceLine(
item.name, item.detail, item.selected, item.removable, tag = item.tag,
modifier = (if (i == 0) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
item.name, item.detail, item.selected, item.removable, tag = item.tag, enabled = !managedDxvk,
modifier = (if (i == 0 && !managedDxvk) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
onSelect = {
if (item.selected || p == null) return@ChoiceLine
if (managedDxvk || item.selected || p == null) return@ChoiceLine
val waits = if (view.inUseByGame) ctx.getString(R.string.comp_waits_long) else ctx.getString(R.string.comp_applies_long)
if (item.file != null) ask(key, right, ctx.getString(R.string.comp_swap_title, label), ctx.getString(R.string.comp_swap_body, item.name, p.name, waits), ctx.getString(R.string.comp_swap), false, item.name) {
onSwap(item.file); flyHome(key, l)
@@ -617,14 +628,19 @@ fun ComponentsPage(
}
}
else -> {
SmallButton(stringResource(R.string.comp_import_wcp), onClick = onImport)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
SmallButton(
stringResource(R.string.comp_import_wcp), onClick = onImport,
modifier = if (managedDxvk) Modifier.focusRequester(firstRow) else Modifier,
)
val st = compState(l)
val p = view?.proton
val build = p?.let { ComponentsManager.safeName(it.version) }
if (st != null && p != null && st.activeFile != null && view.originals.any { it.comp == l && it.protonVersion == build }) {
val label = ComponentsManager.LABEL[l] ?: l
Box(Modifier.trackRow("restore:$l", rowsAt)) {
FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
if (managedDxvk) SmallButton(stringResource(R.string.comp_restore_original), enabled = false) {}
else FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
ask("restore:$l", false, ctx.getString(R.string.comp_restore_title, label), ctx.getString(R.string.comp_restore_original_body, p.name, label), ctx.getString(R.string.common_restore), false, ctx.getString(R.string.comp_restore_original)) {
onRestore(build!!); flyHome("restore:$l", l)
}
@@ -770,6 +786,7 @@ fun ComponentsPage(
protonChoice = gameProtonChoice,
packages = snapshot?.packages.orEmpty(),
componentChoices = gameComponents,
systemPowerVr = gpu.systemPowerVr,
componentMenu = gameComponentMenu,
protonMenu = gameProtonMenu,
fexMenu = fexMenu,
@@ -900,6 +917,7 @@ fun ComponentsPage(
winOpen,
compat = selectedGame.protonPrefix,
steamAppId = selectedGame.appId.takeIf { selectedGame.library != Library.ADDED },
game = selectedGame,
) {
winComponentsOpen = null
winComponentsRevision++
@@ -908,11 +926,11 @@ fun ComponentsPage(
}
@Composable
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?): List<InstalledItem> {
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?, runtimeManaged: Boolean = false): List<InstalledItem> {
view ?: return emptyList()
val st = view.components[l] ?: return emptyList()
val build = ComponentsManager.safeName(view.proton.version)
val activeIsOriginal = st.activeFile == null
val activeIsOriginal = !runtimeManaged && st.activeFile == null
return view.originals.filter { it.comp == l }.map { o ->
val isCurrent = o.protonVersion == build
InstalledItem(
@@ -921,7 +939,7 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
}
}
@@ -960,11 +978,12 @@ private fun Stack(
LayerCard(
title = LayerTitle(l),
value = when (l) {
GPU_TAB -> gpuCardValue(gpu, auto)
GPU_TAB -> if (gpu.systemPowerVr) stringResource(R.string.gpu_system_powervr) else gpuCardValue(gpu, auto)
PROTON_TAB -> (view?.proton?.name ?: "") + " ▾"
else -> st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
else -> if (ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
},
swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null,
swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null && !ComponentsManager.runtimeManaged(l, gpu.systemPowerVr),
selected = l == layer,
landed = landed[l] ?: 0, ring = rings[l] ?: 0,
modifier = Modifier.focusRequester(focus.getValue(l)).onGloballyPositioned { onPlaced(l, it.boundsInRoot()) },
@@ -1031,7 +1050,7 @@ private fun LayerCard(
}
@Composable
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null) {
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null, maxLines: Int = 2) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
@@ -1040,7 +1059,7 @@ private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel:
.border(1.dp, pal.line, RoundedCornerShape(12.dp)).padding(horizontal = 14.dp, vertical = 8.dp),
) {
Box(Modifier.size(8.dp).background(if (queued) QUEUED else pal.good, CircleShape))
Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = maxLines, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (onCancel != null) FocusText(stringResource(R.string.common_cancel), pal.signal, onClick = onCancel)
else if (note.isNotEmpty() && !LocalNarrowPane.current) Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
@@ -1075,6 +1094,7 @@ private fun GameComponentOverrides(
protonChoice: ProtonDefault.GameChoice?,
packages: List<ComponentsManager.Package>,
componentChoices: Map<String, String>,
systemPowerVr: Boolean,
componentMenu: String?,
protonMenu: Boolean,
fexMenu: Boolean,
@@ -1166,6 +1186,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "dxvk",
runtimeManaged = ComponentsManager.runtimeManaged("dxvk", systemPowerVr),
packages = packages,
selectedFile = componentChoices["dxvk"],
open = componentMenu == "dxvk",
@@ -1230,13 +1251,16 @@ private fun GamePackageRow(
onMenu: (String?) -> Unit,
onPick: (String, String?) -> Unit,
onRuntimeOptions: (() -> Unit)? = null,
runtimeManaged: Boolean = false,
) {
val choices = packages.filter { it.comp == comp }
val selected = choices.firstOrNull { it.file == selectedFile }
val title = ComponentsManager.LABEL[comp] ?: comp
val enabled = !busy && (!runtimeManaged || selectedFile != null)
SettingsRow(
title,
if (selected == null) {
if (runtimeManaged) stringResource(R.string.cmgr_powervr_dxvk_managed)
else if (selected == null) {
if (proton == null) stringResource(R.string.comp_game_component_general)
else stringResource(R.string.comp_game_component_runtime, proton.name)
} else stringResource(R.string.comp_game_component_override, selected.version),
@@ -1244,18 +1268,18 @@ private fun GamePackageRow(
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Box {
ValueChip(
selected?.version ?: stringResource(R.string.comp_game_use_general),
open,
enabled = !busy,
if (runtimeManaged) stringResource(R.string.gpu_system_powervr) else selected?.version ?: stringResource(R.string.comp_game_use_general),
open && enabled,
enabled = enabled,
modifier = Modifier.widthIn(max = 240.dp),
) { onMenu(if (open) null else comp) }
AnchoredMenu(open, onDismiss = { onMenu(null) }, title = title) { first ->
AnchoredMenu(open && enabled, onDismiss = { onMenu(null) }, title = title) { first ->
MenuItem(
stringResource(R.string.comp_game_use_general),
checked = selected == null,
focusRequester = first,
) { onPick(comp, null); onMenu(null) }
choices.forEach { option ->
if (!runtimeManaged) choices.forEach { option ->
MenuItem(option.version, checked = option.file == selectedFile, detail = option.description) {
onPick(comp, option.file)
onMenu(null)
@@ -1377,13 +1401,13 @@ private fun Tag(text: String) {
@Composable
private fun ChoiceLine(
name: String, detail: String, selected: Boolean, removable: Boolean,
modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null,
modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null, enabled: Boolean = true,
onSelect: () -> Unit, onDelete: () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val hot = rememberHot(src) && enabled
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
@@ -1393,8 +1417,8 @@ private fun ChoiceLine(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f).heightIn(min = 56.dp).then(modifier)
.glideBorder(hot, ROW_SHAPE, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onSelect)
.controllerConfirm(onClick = onSelect)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onSelect)
.controllerConfirm(enabled = enabled, onClick = onSelect)
.padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).border(2.dp, if (selected) pal.signal else colors.onSurfaceVariant, CircleShape)) {
@@ -1404,7 +1428,7 @@ private fun ChoiceLine(
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis,
color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
color = if (!enabled) colors.onSurfaceVariant else if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
)
if (tag != null) Tag(tag)
}
@@ -25,6 +25,7 @@ class ControllerActions(
val onStickClick: (Boolean) -> Unit,
val onAdaptiveSticks: (Boolean) -> Unit,
val onRumble: (Boolean) -> Unit,
val onDeadZone: (Int) -> Unit,
val onSteamButton: (Boolean) -> Unit,
val onQamButton: (Boolean) -> Unit,
val onKeyboardButton: (Boolean) -> Unit,
@@ -68,6 +69,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
ToggleRow(host, "controller-stick-click", stringResource(R.string.ctrl_stick_click), stringResource(R.string.ctrl_stick_click_hint), c.stickClick, onChange = a.onStickClick)
ToggleRow(host, "controller-adaptive", stringResource(R.string.ctrl_adaptive), stringResource(R.string.ctrl_adaptive_hint), c.adaptiveSticks, onChange = a.onAdaptiveSticks)
ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, c.rumble, onChange = a.onRumble)
ChoiceRow(host, "controller-dead-zone", stringResource(R.string.ctrl_dead_zone), null, ControllerPrefs.deadZones.map { it to stringResource(R.string.ctrl_percent, it) }, c.deadZone, onPick = a.onDeadZone)
ToggleRow(host, "controller-steam", stringResource(R.string.ctrl_steam_button), null, c.steamButton, onChange = a.onSteamButton)
ToggleRow(host, "controller-qam", stringResource(R.string.ctrl_qam_button), null, c.qamButton, onChange = a.onQamButton)
ToggleRow(host, "controller-keyboard", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton, onChange = a.onKeyboardButton)
@@ -540,7 +540,7 @@ class DeckControlsPanel(
private fun move(dx: Float, dy: Float, r: Float) {
knobX = dx
knobY = dy
pad.applyTouch(this@DeckControlsPanel, inputRole) { s ->
pad.applyTouch(this@DeckControlsPanel, inputRole, if (right) PadBridge.RIGHT_STICK else PadBridge.LEFT_STICK) { s ->
if (right) { s.rightX = dx / r; s.rightY = dy / r } else { s.leftX = dx / r; s.leftY = dy / r }
}
invalidate()
@@ -153,6 +153,8 @@ private val METRICS = listOf(
HudMetric("FPS", "showFPS", R.string.drawer_hud_fps),
HudMetric("FPS graph", "showFPSGraph", R.string.hud_metric_graph),
HudMetric("FPS .1", "fpsDecimal", R.string.hud_metric_decimal),
HudMetric("1% low", "showLow1", R.string.hud_metric_low1),
HudMetric("0.1% low", "showLow01", R.string.hud_metric_low01),
HudMetric("0.01% low", "showLow001", R.string.hud_metric_low001),
HudMetric("Engine", "showEngine", R.string.hud_metric_engine),
HudMetric("GPU model", "showGpuModel", R.string.hud_metric_gpu_model),
@@ -176,6 +178,6 @@ private val METRICS = listOf(
private val HIDDEN = mapOf(
DroidDeckHudSize.PILL to setOf("FPS", "FPS graph"),
DroidDeckHudSize.MINIMAL to setOf("FPS"),
DroidDeckHudSize.TILES to setOf("FPS graph", "0.01% low"),
DroidDeckHudSize.TILES to setOf("FPS graph", "0.1% low", "0.01% low"),
DroidDeckHudSize.STRIP to setOf("FPS"),
)
@@ -102,10 +102,15 @@ class FrontEndState(
val frameGenLabel: String,
val romsDir: String?,
val logsEnabled: Boolean,
val enhancedDiagnosticsArmed: Boolean = false,
val gameDebugLogsEnabled: Boolean = false,
val gameDebugLogsNeedsRestart: Boolean = false,
val vacDiagnostics: Boolean = false,
val agentCommands: Boolean = false,
val graphicsLogs: Boolean = false,
val steamGpuDrawing: Boolean = false,
val bridgeFellBack: Boolean = false,
val bridgeFellBackMemory: Boolean = false,
val clearCachedApps: Boolean = false,
val adbPaired: Boolean = false,
val backgroundAppLimit: Int = -1,
@@ -151,6 +156,8 @@ class FrontEndState(
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val adreno: Boolean = true,
val vkBridge: Boolean = false,
val venus: Boolean = false,
val venusHostVulkan: String? = null,
val vkBridgeSafe: Boolean = true,
val bridgeProtonDxvk: Boolean = false,
val showPhantomGate: Boolean = false,
@@ -210,6 +217,7 @@ class FrontEndActions(
val onRemovePackage: (String) -> Unit,
val onRuntime: () -> Unit,
val onVkBridge: (Boolean) -> Unit = {},
val onVenus: (Boolean) -> Unit = {},
val onVkBridgeSafe: (Boolean) -> Unit = {},
val onBridgeProtonDxvk: (Boolean) -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
@@ -219,19 +227,27 @@ class FrontEndActions(
val onGameComponents: (Library.SteamGame) -> Unit = { onComponents(true) },
val onComponentsTab: (String) -> Unit = {},
val onSaveImport: (Library.SteamGame) -> Unit = {},
val onAddonImport: (Library.SteamGame, com.droiddeck.launcher.runtime.WowAddons.Target) -> Unit = { _, _ -> },
val onAddonDelete: (com.droiddeck.launcher.runtime.WowAddons.Target, String) -> Unit = { _, _ -> },
val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> },
val onPerformance: () -> Unit,
val onRoms: () -> Unit,
val onFiles: () -> Unit,
val onBrowseFiles: (File) -> Unit = {},
val onLogs: () -> Unit,
val onEnhancedDiagnostics: () -> Unit = {},
val onGameDebugLogs: () -> Unit = {},
val onVacDiagnostics: () -> Unit = {},
val onAgentCommands: () -> Unit = {},
val onGraphicsLogs: () -> Unit = {},
val onSteamGpuDrawing: () -> Unit = {},
val onClearCachedApps: (Boolean) -> Unit = {},
val onMemoryHud: (String) -> Unit = {},
val onBackgroundAppLimit: (Int) -> Unit = {},
val onShareLogs: () -> Unit = {},
val onShareSessionLog: (File) -> Unit = {},
val onSaveSessionLog: (File) -> Unit = {},
val onDeleteSessionLog: (File, () -> Unit) -> Unit = { _, done -> done() },
val onClearLogs: () -> Unit = {},
val onResetSettings: () -> Unit = {},
val onOffline: () -> Unit,
@@ -193,11 +193,13 @@ internal fun SetupPanel(
)
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_sync), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
var logsRefresh by remember { mutableStateOf(0) }
var deleteSessionLogs by remember { mutableStateOf<java.io.File?>(null) }
SetupTabs.openLauncher = false
if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false }
val chipFocus = remember { List(tabs.size) { FocusRequester() } }
var tabTurned by remember { mutableStateOf(false) }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true; if (i == 5) logsRefresh++ }
val inputModeManager = LocalInputModeManager.current
LaunchedEffect(com.droiddeck.launcher.storage.StorageState.openRequests) {
if (com.droiddeck.launcher.storage.StorageState.openPending) {
@@ -246,6 +248,8 @@ internal fun SetupPanel(
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
when (tab) {
0 -> {
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
CheckRow(
if (gpuOk) CheckState.OK else CheckState.WARN,
@@ -257,19 +261,32 @@ internal fun SetupPanel(
},
when (gpu.support) {
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.displayName(ctx), gpuName)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
else -> if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED ->
if (!s.adreno && s.venus && s.venusHostVulkan != null) stringResource(R.string.setup_gpu_venus_host_too_old, gpu.displayName(ctx), s.venusHostVulkan)
else if (!s.adreno && s.vkBridge && !com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()) stringResource(R.string.setup_gpu_bridge_unusable, gpu.displayName(ctx))
else if (!s.adreno && s.vkBridge && s.bridgeFellBack) stringResource(if (s.bridgeFellBackMemory) R.string.setup_gpu_bridge_no_memory_sharing else R.string.setup_gpu_bridge_fell_back, gpu.displayName(ctx))
else stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
else -> if (s.venus && s.venusHostVulkan != null) stringResource(R.string.setup_gpu_venus_host_too_old, gpuName, s.venusHostVulkan)
else if (s.vkBridge && !com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()) stringResource(R.string.setup_gpu_bridge_unusable, gpuName)
else if (s.vkBridge && s.bridgeFellBack) stringResource(if (s.bridgeFellBackMemory) R.string.setup_gpu_bridge_no_memory_sharing else R.string.setup_gpu_bridge_fell_back, gpuName)
else if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
else stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
},
divider = divider || (!s.adreno && s.vkBridge),
divider = divider || bridgeModeRow,
action = if (s.adreno) null else { {
SecondaryButton(
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(
stringResource(if (s.venus) R.string.setup_gpu_venus_on else R.string.setup_gpu_venus_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVenus(!s.venus) },
)
SecondaryButton(
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
)
}
} },
)
if (!s.adreno && s.vkBridge) CheckRow(
if (bridgeModeRow) CheckRow(
CheckState.OK,
stringResource(R.string.setup_bridge_safe),
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on_detail else R.string.setup_bridge_safe_off_detail),
@@ -382,11 +399,12 @@ internal fun SetupPanel(
val shownChecks = all.filterIndexed { i, _ -> checks[i] }
shownChecks.forEachIndexed { i, check -> check(i < shownChecks.lastIndex) }
}
if (passing < checks.size) {
val needsAttention = all.filterIndexed { i, _ -> !checks[i] && i != 1 }
if (needsAttention.isNotEmpty()) {
SectionTitle(stringResource(R.string.setup_needs_you), null)
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
all.forEachIndexed { i, check ->
if (!checks[i]) Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, AttentionAmber.copy(alpha = 0.5f), Shape14)) { check(false) }
needsAttention.forEach { check ->
Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, AttentionAmber.copy(alpha = 0.5f), Shape14)) { check(false) }
}
}
}
@@ -543,6 +561,10 @@ internal fun SetupPanel(
5 -> {
SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) {
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
ToggleRow(
host, "enhanced-diagnostics", stringResource(R.string.setup_enhanced_diagnostics),
stringResource(R.string.setup_enhanced_diagnostics_hint), s.enhancedDiagnosticsArmed,
) { a.onEnhancedDiagnostics() }
ToggleRow(
host, "game-debug-logs", stringResource(R.string.setup_game_debug_logs),
stringResource(if (s.gameDebugLogsNeedsRestart) R.string.setup_game_debug_logs_restart else R.string.setup_game_debug_logs_hint),
@@ -551,8 +573,48 @@ internal fun SetupPanel(
) { a.onGameDebugLogs() }
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() }
if (!s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() }
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
androidx.compose.material3.HorizontalDivider()
Text(stringResource(R.string.setup_log_sessions), fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
Text(stringResource(R.string.setup_log_export_hint), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 14.dp, end = 14.dp, bottom = 8.dp))
val sessionLogs = remember(ctx, logsRefresh) { com.droiddeck.launcher.session.SessionLogShare.sessions(ctx).asReversed() }
if (sessionLogs.isEmpty()) {
Text(stringResource(R.string.setup_log_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
}
sessionLogs.forEach { folder ->
val active = folder == com.droiddeck.launcher.session.SessionPaths.current()
var details by remember(folder) { mutableStateOf<com.droiddeck.launcher.session.SessionLogShare.Details?>(null) }
LaunchedEffect(folder, logsRefresh) {
details = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
com.droiddeck.launcher.session.SessionLogShare.details(folder)
}
}
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp)) {
Text(folder.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis)
details?.let { detail ->
Text(
stringResource(R.string.setup_log_size_date,
android.text.format.Formatter.formatShortFileSize(ctx, detail.sizeBytes),
"${android.text.format.DateFormat.getDateFormat(ctx).format(java.util.Date(detail.modifiedAt))} ${android.text.format.DateFormat.getTimeFormat(ctx).format(java.util.Date(detail.modifiedAt))}"),
fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (active) Text(stringResource(R.string.setup_log_current), fontSize = 12.sp, color = MaterialTheme.colorScheme.primary)
Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(stringResource(R.string.setup_log_share), enabled = com.droiddeck.launcher.session.SessionLogShare.progress == null, compact = true, modifier = Modifier.weight(1f)) { a.onShareSessionLog(folder) }
SecondaryButton(stringResource(R.string.setup_log_save), enabled = com.droiddeck.launcher.session.SessionLogShare.progress == null, compact = true, modifier = Modifier.weight(1f)) { a.onSaveSessionLog(folder) }
SecondaryButton(stringResource(R.string.setup_log_delete), compact = true, enabled = !active, modifier = Modifier.weight(1f)) { deleteSessionLogs = folder }
}
}
androidx.compose.material3.HorizontalDivider()
}
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint),
stringResource(R.string.setup_reset_settings_button), a.onResetSettings)
@@ -595,6 +657,20 @@ internal fun SetupPanel(
}
}
}
deleteSessionLogs?.let { folder ->
androidx.compose.material3.AlertDialog(
onDismissRequest = { deleteSessionLogs = null },
title = { Text(stringResource(R.string.setup_log_delete_title)) },
text = { Text(stringResource(R.string.setup_log_delete_message, folder.name)) },
confirmButton = {
androidx.compose.material3.TextButton(onClick = {
deleteSessionLogs = null
a.onDeleteSessionLog(folder) { logsRefresh++ }
}) { Text(stringResource(R.string.setup_log_delete)) }
},
dismissButton = { androidx.compose.material3.TextButton(onClick = { deleteSessionLogs = null }) { Text(stringResource(R.string.common_cancel)) } },
)
}
}
@Composable
@@ -73,6 +73,7 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
@@ -86,7 +87,9 @@ import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.GameRemoval
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.CloudSaves
import com.droiddeck.launcher.stores.InstalledStoreGame
@@ -136,7 +139,7 @@ internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?)
}
}
internal enum class GameTab { ABOUT, ACHIEVEMENTS, LAUNCH, SAVES, INSTALL }
internal enum class GameTab { ABOUT, ACHIEVEMENTS, LAUNCH, SAVES, ADDONS, INSTALL }
@Composable
internal fun GameDetail(
@@ -180,12 +183,14 @@ internal fun GameDetail(
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
val scored = scores != null && (scores.metacritic != Lookup.None || scores.hltb != Lookup.None)
val prefix = game?.protonPrefix?.takeIf { it.isDirectory }
val addonTargets = remember(game?.gameId, game?.gameFiles) { game?.let(WowAddons::targets).orEmpty() }
val tabs = buildList {
if (description.isNotBlank() || developer.isNotBlank() || publisher.isNotBlank() || releaseDate.isNotBlank() || scored || (!s.shortcutPicker && title.isNotBlank() && title != id)) add(GameTab.ABOUT)
if (achievementState != null) add(GameTab.ACHIEVEMENTS)
val cloud = game?.library == Library.XBOX_CLOUD
if (game != null && !cloud) add(GameTab.LAUNCH)
if (game != null && game.library == Library.ADDED && prefix != null) add(GameTab.SAVES)
if (addonTargets.isNotEmpty()) add(GameTab.ADDONS)
if ((game != null && !cloud) || installed != null) add(GameTab.INSTALL)
}
var picked by remember(key) { mutableStateOf<GameTab?>(null) }
@@ -248,6 +253,7 @@ internal fun GameDetail(
} ?: stringResource(R.string.achievements_title)
GameTab.LAUNCH -> stringResource(R.string.game_tab_launch)
GameTab.SAVES -> stringResource(if (Store.byId(source).let { it == Store.GOG || it == Store.EPIC }) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.ADDONS -> stringResource(R.string.game_tab_addons)
GameTab.INSTALL -> stringResource(R.string.game_tab_install)
}
}
@@ -263,6 +269,7 @@ internal fun GameDetail(
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
GameTab.INSTALL -> InstallTab(game, installed, item, store)
}
}
@@ -857,6 +864,44 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
}
}
@Composable
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
targets.forEach { target ->
val names by produceState(emptyList<String>(), target.addOns, WowAddons.imports) {
value = withContext(Dispatchers.IO) { WowAddons.installed(target) }
}
if (targets.size > 1) SectionLabel(target.flavor)
MenuItem(
stringResource(R.string.games_import_addons), checked = false,
detail = pluralStringResource(R.plurals.games_addons_count, names.size, names.size),
) { a.onAddonImport(g, target) }
MenuItem(stringResource(R.string.games_open_addons_folder), checked = false) {
target.addOns.mkdirs()
a.onBrowseFiles(target.addOns)
}
names.forEach { name -> AddonRow(name, target, a) }
}
}
}
@Composable
private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions) {
var asking by remember(target.addOns, name) { mutableStateOf(false) }
val delete = stringResource(R.string.common_delete)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
Text(name, fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
}
if (asking) ConfirmDialog(
title = stringResource(R.string.games_delete_addon_title, name),
text = stringResource(R.string.games_delete_addon_body),
confirm = delete,
onConfirm = { a.onAddonDelete(target, name) },
onDismiss = { asking = false },
)
}
@Composable
private fun CloudRows(g: Library.SteamGame) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
@@ -89,6 +89,8 @@ class PairRow(
val complete: Boolean,
val installed: Boolean,
val active: Boolean,
/** A newer build of this installed pair (its build date), or null. */
val update: String? = null,
)
const val GPU_MODE_AUTO = "auto"
@@ -110,6 +112,9 @@ class GpuDriversState(
val supported: Boolean = true,
val unsupported: Boolean = false,
val auto: Boolean = true,
val powerVr: Boolean = false,
/** The selected runtime supplies DXVK for PowerVR game launches. */
val systemPowerVr: Boolean = false,
val pairs: List<PairRow> = emptyList(),
val busy: String? = null,
val percent: Int = -1,
@@ -138,6 +143,7 @@ class GpuDriversState(
class GpuDriversActions(
val onAuto: (Boolean) -> Unit = {},
val onPair: (String) -> Unit = {},
val onPairUpdate: (String) -> Unit = {},
val onRefresh: () -> Unit = {},
val onSelectLinux: (String) -> Unit = {},
val onSelectAndroid: (String) -> Unit = {},
@@ -258,7 +264,7 @@ internal fun GpuDriversBody(
modes.indices.forEach { choice(it, Modifier.weight(1f).fillMaxHeight()) }
}
when (gpu.mode) {
GPU_MODE_AUTO -> AutoBody(gpu)
GPU_MODE_AUTO -> AutoBody(gpu, actions)
GPU_MODE_PAIR -> PairBody(gpu, actions)
else -> MixBody(single, actions, slotFocus, onOpenSlot)
}
@@ -351,14 +357,26 @@ private fun RestartBanner(target: String, canRestart: Boolean, afterLater: Focus
}
@Composable
private fun AutoBody(gpu: GpuDriversState) {
private fun AutoBody(gpu: GpuDriversState, actions: GpuDriversActions) {
val colors = MaterialTheme.colorScheme
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
PanelTitle(
stringResource(if (gpu.activePair != null) R.string.gpu_auto_title else R.string.gpu_auto_builtin_title, gpu.gpuName),
stringResource(R.string.gpu_auto_reason, gpu.gpuFamily),
)
gpu.activePair?.let { p -> PanelRow(p.name, "${p.version} · ${p.detail}", selected = true, onClick = null) }
gpu.activePair?.let { p ->
// An open non-Adreno pair is rebuilt in place while it is tested: offer the newer build.
PanelRow(
p.name, "${p.version} · " + (p.update?.let { stringResource(R.string.proton_update_available, it) } ?: p.detail), selected = true,
trailing = when {
gpu.busy == p.key -> "${gpu.percent.coerceAtLeast(0)}%"
p.update != null -> stringResource(R.string.common_update)
else -> null
},
enabled = gpu.busy == null,
onClick = p.update?.let { { actions.onPairUpdate(p.key) } },
)
}
if (gpu.autoStatus.isNotEmpty()) Text(gpu.autoStatus, fontSize = 13.sp, color = colors.onSurfaceVariant)
}
}
@@ -376,15 +394,17 @@ private fun PairBody(gpu: GpuDriversState, actions: GpuDriversActions) {
fontSize = 13.sp, color = colors.onSurfaceVariant,
)
for (p in rows) PanelRow(
p.name, "${p.version} · ${p.detail}", selected = p.active,
p.name, "${p.version} · " + (p.update?.let { stringResource(R.string.proton_update_available, it) } ?: p.detail), selected = p.active,
badge = if (p.recommended) stringResource(R.string.gpu_autos_pick) else null,
trailing = when {
gpu.busy == p.key -> "${gpu.percent.coerceAtLeast(0)}%"
p.update != null -> stringResource(R.string.common_update)
p.installed -> stringResource(R.string.gpu_installed)
else -> stringResource(R.string.common_download)
},
enabled = gpu.busy == null,
onClick = { if (!p.active) actions.onPair(p.key) },
// A rebuilt open non-Adreno pair (same release, newer build) is updated in place.
onClick = { if (p.update != null) actions.onPairUpdate(p.key) else if (!p.active) actions.onPair(p.key) },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (gpu.pairs.any { !it.suits }) FocusText(stringResource(if (showAll) R.string.gpu_hide_other else R.string.gpu_show_other), pal.signal) { showAll = !showAll }
@@ -325,6 +325,7 @@ class DrawerActions(
val onClose: () -> Unit,
val onDismissScreen: (() -> Unit)? = null,
val components: ComponentsManager.Snapshot? = null,
val systemPowerVr: Boolean = false,
val onComponentsRefresh: () -> Unit = {},
val componentCatalog: List<ComponentsManager.CatalogItem> = emptyList(),
val componentCatalogAt: Long = 0,
@@ -494,7 +495,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (a.pipSupported) SteamActionPill(
stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"),
) { host.open = null; a.onPip() }
StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
if (docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null
val qamInteraction = remember { MutableInteractionSource() }
var qamStartedOnPress by remember { mutableStateOf(false) }
@@ -510,7 +511,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
BarActions(
onMenu = { host.open = null; a.onClose() }, menuActive = true,
onMenu = if (docked) ({ host.open = null; a.onClose() }) else null, menuActive = true,
onSteam = if (steamActions) ({ host.open = null; a.onSteamMenu?.invoke() }) else null,
onQam = if (steamActions) ({
host.open = null
@@ -522,7 +523,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
qamModifier = focus.track(page, "qam"),
qamInteraction = qamInteraction,
onQamConfirm = { host.open = null; a.onQam?.invoke() },
showShortcuts = !docked,
)
if (!docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
}
a.onAchievements?.let { show ->
DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) {
@@ -1342,7 +1345,11 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S
for (component in ComponentsManager.COMPONENTS) {
val value = profile.components.getValue(component)
if (!value.inherited) {
ProfileSummaryRow(ComponentsManager.LABEL.getValue(component), profileValueLabel(value))
ProfileSummaryRow(
ComponentsManager.LABEL.getValue(component),
if (ComponentsManager.runtimeManaged(component, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else profileValueLabel(value),
)
}
}
if (profile.startWithoutSteam) {
@@ -1451,20 +1458,23 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
)
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val options: List<Pair<String?, String>> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
label = ComponentsManager.LABEL.getValue(comp),
hint = if (value.inherited) {
hint = if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) else if (value.inherited) {
stringResource(R.string.drawer_component_inherited, value.value)
} else {
null
},
options = options,
selected = gameProfile.componentFiles[comp],
enabled = !managedDxvk || gameProfile.componentFiles[comp] != null,
valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
chipModifier = track("cmp-$comp"),
onPick = { file -> a.onGameComponent(gameProfile.appId, comp, file) },
)
@@ -1499,7 +1509,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
for (comp in ComponentsManager.COMPONENTS) {
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
Text(ComponentsManager.LABEL.getValue(comp), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(96.dp))
Text(r.components.getValue(comp).inUse, fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (ComponentsManager.runtimeManaged(comp, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else r.components.getValue(comp).inUse,
fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
}
}
@@ -1527,16 +1541,21 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val build = ComponentsManager.safeName(p.version)
for (comp in ComponentsManager.COMPONENTS) {
val st = view.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (options.isEmpty()) continue
if (options.isEmpty() && !managedDxvk) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
DrawerStackedChoice(
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) +
(st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
else st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
options, current,
enabled = !managedDxvk,
valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
note = if (view.inUseByGame) stringResource(R.string.comp_waits_long) else stringResource(R.string.comp_applies_long),
chipModifier = track("cmp-$comp"),
onPick = { v -> if (v != current || st.queued != null) a.onComponentSwap(p.id, comp, v) },
@@ -1649,11 +1668,11 @@ internal fun ComponentDownloadsDrawerGroup(
private fun <T> DrawerStackedChoice(
host: MenuHost, key: String, label: String, hint: String?,
options: List<Pair<T, String>>, selected: T, note: String? = null,
chipModifier: Modifier = Modifier, onPick: (T) -> Unit,
chipModifier: Modifier = Modifier, enabled: Boolean = true, valueLabel: String? = null, onPick: (T) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = host.open == key
val open = host.open == key && enabled
Column(
modifier = Modifier.fillMaxWidth()
.background(if (open) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
@@ -1661,7 +1680,7 @@ private fun <T> DrawerStackedChoice(
) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Box(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, modifier = chipModifier.fillMaxWidth()) {
ValueChip(valueLabel ?: options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled = enabled, modifier = chipModifier.fillMaxWidth()) {
host.open = if (open) null else key
}
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
@@ -104,6 +104,7 @@ internal fun WinComponentsDialog(
var slowCatalog by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { kotlinx.coroutines.delay(300); slowCatalog = true }
var installed by remember { mutableStateOf(emptySet<String>()) }
var freshInstalled by remember { mutableStateOf(emptySet<String>()) }
var present by remember { mutableStateOf(emptySet<String>()) }
var selection by remember { mutableStateOf(WinComponents.selection(context, appKey)) }
val picks = selection.effective
@@ -141,9 +142,11 @@ internal fun WinComponentsDialog(
findings = found
selection = withContext(Dispatchers.IO) { WinComponents.selection(context, appKey) }
present = withContext(Dispatchers.IO) { PrefixInstalledDetector.detect(compat) }
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
}
val autoDownloading by com.droiddeck.launcher.frontend.AutoComponents.downloading.collectAsState()
val repairFailures by com.droiddeck.launcher.frontend.AutoComponents.repairFailures.collectAsState()
val online = rememberOnline()
val autoChanges by com.droiddeck.launcher.frontend.AutoComponents.changes.collectAsState()
val pendingGames by com.droiddeck.launcher.frontend.AutoComponents.pendingGames.collectAsState()
@@ -152,7 +155,8 @@ internal fun WinComponentsDialog(
if (game != null) withContext(Dispatchers.IO) { com.droiddeck.launcher.frontend.AutoComponents.cachedFindings(context, appKey) }
?.let { findings = it; if (appKey !in pendingGames) findingsKnown = true }
selection = withContext(Dispatchers.IO) { WinComponents.selection(context, appKey) }
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
}
fun setUser(id: String, on: Boolean) {
selection = WinComponents.Selection(selection.auto, selection.user + (id to on))
@@ -173,15 +177,25 @@ internal fun WinComponentsDialog(
}
val all = catalog.orEmpty()
val c = all[id]
if (id in installed || c == null) { setUser(id, true); return }
if (id in installed) {
setUser(id, true)
if (c != null && id !in freshInstalled) {
com.droiddeck.launcher.frontend.AutoComponents.queueRepair(context, id,
game?.let { com.droiddeck.launcher.frontend.AutoComponents.appKey(it) }, c.revision)
}
return
}
if (c == null) { setUser(id, true); return }
busyId = id; reverting = false
progress = WinComponents.Progress(id, "", WinComponents.Phase.DOWNLOAD, -1)
progress = null
coroutine.launch {
val problem = withContext(Dispatchers.IO) {
WinComponents.install(context, c, all) { p -> progress = p }
if (WinComponents.installed(context, id) != null) null
else WinComponents.install(context, c, all) { p -> progress = p }
}
progress = null
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
if (problem != null) { error = problem; failed = id } else setUser(id, true)
busyId = null
}
@@ -244,6 +258,9 @@ internal fun WinComponentsDialog(
val status = when {
!online && id !in installed && support == Support.READY -> stringResource(R.string.wincomp_when_online)
id == failed && error != null -> stringResource(R.string.wincomp_failed, error.orEmpty())
id in repairFailures -> stringResource(R.string.wincomp_failed, repairFailures.getValue(id))
id in pendingComponents && id in installed && id !in freshInstalled -> stringResource(R.string.wincomp_repair_queued)
id in installed && id !in freshInstalled -> stringResource(R.string.wincomp_repair_required)
id in here && id !in picks -> stringResource(R.string.wincomp_already_here)
id in installed -> stringResource(R.string.wincomp_downloaded)
support == Support.NEEDS_INSTALLER -> stringResource(R.string.wincomp_needs_installer)
@@ -275,6 +292,12 @@ internal fun WinComponentsDialog(
modifier = (if (usable && focus != null) Modifier.focusRequester(focus) else Modifier)
.onFocusChanged { if (it.isFocused) switchFocused = true },
) { on -> toggle(id, on) }
if (id in repairFailures && c != null) {
SecondaryButton(stringResource(R.string.wincomp_retry), compact = true) {
com.droiddeck.launcher.frontend.AutoComponents.queueRepair(context, id,
game?.let { com.droiddeck.launcher.frontend.AutoComponents.appKey(it) }, c.revision)
}
}
}
fun firstUsable(ids: List<String>, focus: FocusRequester): (String) -> FocusRequester? {
val first = ids.firstOrNull { supportOf(it) == Support.READY }
@@ -74,6 +74,12 @@ object AppUpdates {
val updatable: Boolean,
val committedAt: Long = 0L,
val ciBuild: Boolean = BuildConfig.CI_BUILD,
/**
* A build of the non-Adreno test branch (Mali / Xclipse / PowerVR routes). The official
* channels carry the Adreno-only app: installing one over it drops those routes, so none is
* offered. Its updates are published on The412Banner/droiddeck-nonadreno-drivers.
*/
val nonAdrenoTest: Boolean = false,
)
enum class PreviewHistoryKind { CURRENT, BEHIND, RECENT }
@@ -125,6 +131,7 @@ object AppUpdates {
BuildConfig.VERSION_CODE,
releaseSigned,
BuildConfig.COMMIT_TIME,
nonAdrenoTest = BuildConfig.BUILD_LABEL.contains("non-adreno"),
)
fun release(catalog: Catalog, follow: Follow): Release? = when (follow.channel) {
@@ -191,6 +198,7 @@ object AppUpdates {
}
fun installBlock(r: Release, me: Installed = installed()): InstallBlock? = when {
me.nonAdrenoTest -> InstallBlock(R.string.upd_block_non_adreno_test)
r.apk == null -> InstallBlock(R.string.upd_block_no_apk)
r.apk.versionCode < me.versionCode -> InstallBlock(R.string.upd_block_version_code, r.apk.versionCode, me.versionCode)
else -> null
@@ -180,6 +180,28 @@ public final class WaylandCompositor {
public static native int nativeCompositorTid();
private static native String nativeCompositorFault();
private static native String nativeDisplayDriver();
/** Why the compositor cannot present, or "" while it can (or before the library is loaded). */
public static String compositorFault() {
try {
return nativeCompositorFault();
} catch (Throwable t) {
return "";
}
}
/** The driver that answered for the display, as it reports itself; "" when not known yet. */
public static String displayDriver() {
try {
return nativeDisplayDriver();
} catch (Throwable t) {
return "";
}
}
public static native void nativeSetHideShell(boolean hide);
public static native void nativeSetOutputRefreshRate(float hz);