mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 05:16:01 +00:00
chore: merge main into feat/bt-controller-trinket
This commit is contained in:
commit
1288874810
483 files changed
+43320
-2284
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),
|
||||
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,8 +305,31 @@ 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).lowercase())
|
||||
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
|
||||
return
|
||||
}
|
||||
releaseChecking = true
|
||||
@@ -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,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var gameCores by mutableStateOf<Set<Int>>(emptySet())
|
||||
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() }
|
||||
private var noXalia by mutableStateOf(true)
|
||||
private var fastSync by mutableStateOf(false)
|
||||
private var syncFallback by mutableStateOf(true)
|
||||
@@ -194,6 +200,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)
|
||||
@@ -205,6 +212,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()
|
||||
@@ -263,6 +271,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)
|
||||
@@ -317,18 +345,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
|
||||
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else {
|
||||
HomeApp.setHomeScreenEnabled(this, true)
|
||||
refreshHomeAppState()
|
||||
manageHomeApp()
|
||||
}
|
||||
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else offerHomeScreen()
|
||||
SteamIntegration.Feature.SHORTCUTS -> {
|
||||
if (!integrationState.shortcuts) shortcutsTried = true
|
||||
if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME)
|
||||
else {
|
||||
SteamIntegration.setShortcutsListed(this, true)
|
||||
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
}
|
||||
SteamIntegration.setShortcutsListed(this, true)
|
||||
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -414,6 +435,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)) {
|
||||
@@ -537,10 +579,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)
|
||||
@@ -586,8 +633,17 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
homeChoiceOpen = false
|
||||
HomeApp.releaseUnusedHomeEntry(this)
|
||||
refreshHomeAppState()
|
||||
}
|
||||
private val gameSpaceAdd = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
homeChoiceOpen = false
|
||||
if (HomeApp.inGameSpace(this)) enableHomeScreen()
|
||||
else refreshHomeAppState()
|
||||
}
|
||||
private var homeChoiceOpen = false
|
||||
private var gameSpaceOffered = false
|
||||
|
||||
override fun startActivity(intent: Intent?) {
|
||||
val compat = protons.protonBusyId != null || ProtonExtras.installInProgress
|
||||
@@ -1021,6 +1077,9 @@ 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)
|
||||
readGameIntent(intent)
|
||||
gameSyncFolder = GameFileSync.folder(this)
|
||||
@@ -1076,6 +1135,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
FrontEndScreen(
|
||||
FrontEndState(
|
||||
installed = installed, ready = ready, available = available?.version, removalPending = removalPending, runtimeActionsBlocked = runtimeChangesBlocked(),
|
||||
vkBridge = vkBridge, venus = venus, venusHostVulkan = venusHostVulkan, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
|
||||
shortcutPicker = shortcutPicker,
|
||||
shortcutLibraryScanning = shortcutLibraryScanning,
|
||||
gameSyncFolder = gameSyncFolder,
|
||||
@@ -1083,8 +1143,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),
|
||||
@@ -1154,8 +1216,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() },
|
||||
@@ -1224,6 +1291,24 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onInstallPackage = { id -> installPackage(id) },
|
||||
onRemovePackage = { id -> removePackage(id) },
|
||||
onRuntime = { onRuntimeButton() },
|
||||
onVkBridge = { 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
|
||||
if (on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
|
||||
},
|
||||
onFrameGenPick = { mode ->
|
||||
FrameGen.set(this, mode)
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
@@ -1236,6 +1321,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 },
|
||||
@@ -1253,6 +1345,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(
|
||||
@@ -1261,6 +1362,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)
|
||||
@@ -1276,11 +1385,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)
|
||||
@@ -1376,8 +1514,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
integrationState = readIntegration()
|
||||
},
|
||||
onHomeScreen = { on ->
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
if (on && HomeApp.hasGameSpace(this)) offerHomeScreen()
|
||||
else {
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
}
|
||||
},
|
||||
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
|
||||
onBackActionsInverted = { inverted ->
|
||||
@@ -1448,6 +1589,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() },
|
||||
@@ -1566,6 +1708,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()
|
||||
@@ -1701,6 +1846,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (!homeChoiceOpen) {
|
||||
HomeApp.releaseUnusedHomeEntry(this)
|
||||
refreshHomeAppState()
|
||||
}
|
||||
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
|
||||
compatLaunchVisible = true
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
@@ -1777,6 +1926,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
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) }
|
||||
@@ -1791,12 +1943,19 @@ class FrontEndActivity : ComponentActivity() {
|
||||
else @Suppress("DEPRECATION") state.getParcelable(key)
|
||||
|
||||
override fun onDestroy() {
|
||||
gameLaunchRequest.incrementAndGet()
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onRestart() {
|
||||
super.onRestart()
|
||||
homeChoiceOpen = false
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
if (!homeChoiceOpen) HomeApp.releaseUnusedHomeEntry(this)
|
||||
unregisterReceiver(wifiLocationReceiver)
|
||||
unregisterReceiver(mediaReceiver)
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
|
||||
@@ -1876,12 +2035,32 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun offerHomeScreen() {
|
||||
if (!gameSpaceOffered && HomeApp.hasGameSpace(this) && !HomeApp.inGameSpace(this)) {
|
||||
gameSpaceOffered = true
|
||||
val opened = runCatching { gameSpaceAdd.launch(HomeApp.gameSpaceAddIntent()) }.isSuccess
|
||||
if (opened) {
|
||||
homeChoiceOpen = true
|
||||
android.widget.Toast.makeText(this, R.string.setup_home_game_space_first, android.widget.Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
}
|
||||
enableHomeScreen()
|
||||
}
|
||||
|
||||
private fun enableHomeScreen() {
|
||||
HomeApp.setHomeScreenEnabled(this, true)
|
||||
refreshHomeAppState()
|
||||
manageHomeApp()
|
||||
}
|
||||
|
||||
private fun manageHomeApp() {
|
||||
homeChoiceOpen = true
|
||||
val request = HomeApp.roleRequestIntent(this)
|
||||
if (request != null) {
|
||||
homeRoleRequest.launch(request)
|
||||
} else {
|
||||
HomeApp.openSystemHomeSettings(this)
|
||||
} else if (runCatching { homeRoleRequest.launch(HomeApp.settingsIntent()) }.isFailure) {
|
||||
homeChoiceOpen = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1985,6 +2164,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) },
|
||||
@@ -2534,6 +2714,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
|
||||
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)
|
||||
fastSync = SessionPrefs.fastSync(this)
|
||||
syncFallback = SessionPrefs.syncFallback(this)
|
||||
@@ -2554,6 +2739,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) {
|
||||
@@ -2570,15 +2781,23 @@ class FrontEndActivity : ComponentActivity() {
|
||||
offline = OfflineMode.enabled(this)
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
ready = LinuxRuntime.isInstalled(this)
|
||||
vkBridge = SessionPrefs.vkBridge(this)
|
||||
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
|
||||
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
|
||||
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
|
||||
ui.post { autoUpdateRuntime() }
|
||||
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)
|
||||
@@ -2674,7 +2893,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
Thread({ checkCatalog() }, "catalog").start()
|
||||
return
|
||||
}
|
||||
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()) { showNonAdreno = release; return }
|
||||
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)) { showNonAdreno = release; return }
|
||||
install(release)
|
||||
}
|
||||
|
||||
@@ -2693,7 +2912,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
showPhantomGate = true
|
||||
return false
|
||||
}
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)
|
||||
if (warn && available != null) { showNonAdreno = available; return false }
|
||||
startActivity(intent)
|
||||
return true
|
||||
@@ -2815,6 +3034,9 @@ 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
|
||||
private const val COMPONENT_RESTORE_MS = 60_000L
|
||||
|
||||
@@ -24,6 +24,9 @@ import kotlin.math.roundToInt
|
||||
|
||||
object HomeApp {
|
||||
private const val ICON_DP = 72
|
||||
private const val GAME_SPACE = "cn.nubia.gamelauncher"
|
||||
private const val GAME_SPACE_ADD = "cn.nubia.gamelauncher.action.GAME_MANAGER"
|
||||
private val GAME_SPACE_GAMES = Uri.parse("content://cn.nubia.gamelauncher.db.AppAddProvider/appadd")
|
||||
|
||||
data class LaunchableApp(
|
||||
val label: String,
|
||||
@@ -54,6 +57,24 @@ object HomeApp {
|
||||
)
|
||||
}
|
||||
|
||||
fun hasGameSpace(context: Context): Boolean =
|
||||
runCatching { context.packageManager.getPackageInfo(GAME_SPACE, 0) }.isSuccess
|
||||
|
||||
fun inGameSpace(context: Context): Boolean =
|
||||
runCatching {
|
||||
context.contentResolver.query(GAME_SPACE_GAMES, arrayOf("component"), null, null, null)?.use { rows ->
|
||||
val prefix = context.packageName + ","
|
||||
generateSequence { if (rows.moveToNext()) rows.getString(0) else null }.any { it.startsWith(prefix) }
|
||||
}
|
||||
}.getOrNull() ?: true
|
||||
|
||||
fun gameSpaceAddIntent(): Intent = Intent(GAME_SPACE_ADD).setPackage(GAME_SPACE)
|
||||
|
||||
fun releaseUnusedHomeEntry(context: Context) {
|
||||
if (isHomeScreenEnabled(context) && !isDefault(context) && hasGameSpace(context))
|
||||
setHomeScreenEnabled(context, false)
|
||||
}
|
||||
|
||||
fun isDefault(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val roles = context.getSystemService(RoleManager::class.java)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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() {
|
||||
|
||||
@@ -18,7 +18,6 @@ object AgentEnv {
|
||||
private const val TAG = "AgentEnv"
|
||||
private const val FILE = "agent-env.json"
|
||||
private const val GUEST_BIN = "/opt/droiddeck-agent/bin"
|
||||
private const val BASE_PATH = "/usr/local/bin:/usr/bin:/bin"
|
||||
private val NAME = Regex("[A-Za-z0-9._-]{1,64}")
|
||||
private val KEY = Regex("[A-Za-z_][A-Za-z0-9_]*")
|
||||
private val lock = Any()
|
||||
@@ -160,7 +159,7 @@ object AgentEnv {
|
||||
}
|
||||
|
||||
private fun pathOf(lines: List<String>) =
|
||||
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: BASE_PATH
|
||||
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: LinuxRuntime.GUEST_PATH
|
||||
|
||||
private fun bin(context: Context): File {
|
||||
val root = LinuxRuntime.rootDir(context).canonicalFile.toPath()
|
||||
|
||||
@@ -26,6 +26,10 @@ object AgentGuest {
|
||||
private set
|
||||
var keyboardRequests by mutableIntStateOf(0)
|
||||
private set
|
||||
var gameTextField by mutableStateOf(false)
|
||||
private set
|
||||
var gameProgram by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var keyboardDismissals by mutableIntStateOf(0)
|
||||
private set
|
||||
@Volatile private var keyboardRoute = false
|
||||
@@ -43,7 +47,7 @@ object AgentGuest {
|
||||
observer?.stopWatching()
|
||||
observer = null
|
||||
lastFocusKey = null
|
||||
main.post { steamKeyboard = false; desktopTextField = false }
|
||||
main.post { steamKeyboard = false; desktopTextField = false; gameTextField = false; gameProgram = null }
|
||||
val dir = dir(context)
|
||||
dir.deleteRecursively()
|
||||
dir.mkdirs()
|
||||
@@ -59,6 +63,7 @@ object AgentGuest {
|
||||
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
|
||||
"keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) }
|
||||
"ime.json" -> readJson(File(dir, path))?.let { recordTextField(this, it) }
|
||||
"wine-ime.json" -> readJson(File(dir, path))?.let { recordGameTextField(this, it) }
|
||||
"keyboard-request.json" -> readJson(File(dir, path))?.let { recordKeyboardRequest(this) }
|
||||
"keyboard-dismiss.json" -> readJson(File(dir, path))?.let { recordKeyboardDismiss(this) }
|
||||
}
|
||||
@@ -71,7 +76,7 @@ object AgentGuest {
|
||||
synchronized(lock) {
|
||||
observer?.stopWatching()
|
||||
observer = null
|
||||
main.post { steamKeyboard = false; desktopTextField = false }
|
||||
main.post { steamKeyboard = false; desktopTextField = false; gameTextField = false; gameProgram = null }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,6 +134,16 @@ object AgentGuest {
|
||||
SessionEvents.record("ime.changed", mapOf("textField" to focused, "seq" to snapshot.optInt("seq")))
|
||||
}
|
||||
|
||||
private fun recordGameTextField(source: FileObserver, snapshot: JSONObject) {
|
||||
val focused = snapshot.optBoolean("textField")
|
||||
val program = snapshot.optString("program").takeIf { it.isNotEmpty() }
|
||||
synchronized(lock) {
|
||||
if (source !== observer) return
|
||||
main.post { gameProgram = program; gameTextField = focused }
|
||||
}
|
||||
SessionEvents.record("game.ime.changed", mapOf("textField" to focused, "program" to program, "seq" to snapshot.optInt("seq")))
|
||||
}
|
||||
|
||||
private fun recordFocus(snapshot: JSONObject) {
|
||||
val fields = linkedMapOf<String, Any?>(
|
||||
"focusedApp" to snapshot.opt("focusedApp"),
|
||||
|
||||
@@ -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}" + 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,11 +3,43 @@ 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 {
|
||||
fun adreno(): Boolean =
|
||||
private val adrenoGpu by lazy {
|
||||
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
||||
}
|
||||
|
||||
fun adreno(): Boolean = adrenoGpu
|
||||
|
||||
fun graphicsAvailable(): Boolean = graphicsAvailable(adreno(), SystemVulkanDriver.isAvailable())
|
||||
|
||||
internal fun graphicsAvailable(adreno: Boolean, powerVrReady: Boolean): Boolean = adreno || powerVrReady
|
||||
|
||||
fun vkBridge(context: Context): Boolean =
|
||||
bridgeUsable() && !com.droiddeck.launcher.session.VenusComponent.wanted(context) &&
|
||||
com.droiddeck.launcher.session.SessionPrefs.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? {
|
||||
|
||||
@@ -243,6 +243,8 @@ object AddedGameArt {
|
||||
val steam: (String, File, Set<Slot>) -> Boolean,
|
||||
val sgdbGame: (String, Int?, String) -> Int?,
|
||||
val sgdb: (String, Int, File, Set<Slot>) -> Boolean,
|
||||
val sgdbExactGame: (String, Int?, String) -> Int? = { _, _, _ -> null },
|
||||
val battleNetArt: (Context, BattleNet.Title) -> Boolean = { _, _ -> false },
|
||||
)
|
||||
|
||||
private val network = Sources(
|
||||
@@ -251,6 +253,8 @@ object AddedGameArt {
|
||||
steam = ::download,
|
||||
sgdbGame = SteamGridDb::gameId,
|
||||
sgdb = SteamGridDb::download,
|
||||
sgdbExactGame = SteamGridDb::exactGameId,
|
||||
battleNetArt = { context, title -> BattleNet.fetchCovers(context, listOf(BattleNet.artTitle(title))) },
|
||||
)
|
||||
|
||||
private val EXTRAS = setOf(Slot.LOGO, Slot.ICON)
|
||||
@@ -288,6 +292,9 @@ object AddedGameArt {
|
||||
var changed = false
|
||||
for (game in games) {
|
||||
if (forgetOtherAppsArt(context, game)) changed = true
|
||||
if (forgetNameMatchedBattleNetArt(context, game)) changed = true
|
||||
val battleNetTitle = game.storeId?.takeIf { game.source == Store.BATTLENET.id }?.let(BattleNet::title)
|
||||
if (battleNetTitle != null && runCatching { sources.battleNetArt(context, battleNetTitle) }.getOrDefault(false)) changed = true
|
||||
val cache = cacheDir(context, game)
|
||||
val start = missing(context, game)
|
||||
val again = refetch(cache) intersect start
|
||||
@@ -318,7 +325,7 @@ object AddedGameArt {
|
||||
if (need.isNotEmpty() && sgdbKey.isNotEmpty()) {
|
||||
if (sgdbDown) asked = false else try {
|
||||
val gridId = remembered(File(cache, "sgdb-id"), keyChangedAt) {
|
||||
sources.sgdbGame(sgdbKey, match.appId, game.name)?.toString()
|
||||
(if (battleNetTitle != null) sources.sgdbExactGame else sources.sgdbGame)(sgdbKey, match.appId, game.name)?.toString()
|
||||
}?.toIntOrNull()
|
||||
if (gridId != null && sources.sgdb(sgdbKey, gridId, cache, need)) changed = true
|
||||
} catch (e: Exception) {
|
||||
@@ -343,6 +350,21 @@ object AddedGameArt {
|
||||
if (slots.isEmpty()) File(cache, REFETCH).delete() else File(cache, REFETCH).writeText(slots.joinToString(",") { it.key })
|
||||
}
|
||||
|
||||
internal const val BATTLENET_ART_CHECKED = "battlenet-art-2"
|
||||
|
||||
internal fun forgetNameMatchedBattleNetArt(context: Context, game: AddedGames.Game): Boolean {
|
||||
val title = game.storeId?.takeIf { game.source == Store.BATTLENET.id }?.let(BattleNet::title) ?: return false
|
||||
val cache = cacheDir(context, game)
|
||||
val checked = File(cache, BATTLENET_ART_CHECKED)
|
||||
if (title.steam != null || checked.isFile) return false
|
||||
val dropped = EXTRAS.filter { File(cache, SteamGridDb.cacheName(it)).delete() }
|
||||
EXTRAS.forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() }
|
||||
listOf("sgdb-id", EXTRAS_TRIED).forEach { File(cache, it).delete() }
|
||||
cache.mkdirs()
|
||||
checked.writeText("")
|
||||
return dropped.isNotEmpty()
|
||||
}
|
||||
|
||||
internal fun forgetOtherAppsArt(context: Context, game: AddedGames.Game): Boolean {
|
||||
val cache = cacheDir(context, game)
|
||||
val recorded = SteamMatch.get(context, game.folder.path)?.takeIf { it.appId != null }
|
||||
|
||||
@@ -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,24 +177,39 @@ 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()
|
||||
|
||||
private fun libraryDepotInstalls(context: Context): List<File> =
|
||||
SteamLibraries.list(context).flatMap { SteamLibraries.depotInstalls(File(it.path, "steamapps/common")) }
|
||||
|
||||
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(
|
||||
@@ -205,15 +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 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)
|
||||
}
|
||||
@@ -259,6 +280,7 @@ object AddedGames {
|
||||
entries.map { File(it.folder) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
|
||||
SessionPrefs.removedAddedGames(context).map { File(it) }.filter { owns(it) && groupGames(it) == null }.maxByOrNull { canonical(it).length }?.let { return it }
|
||||
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
|
||||
libraryDepotInstalls(context).firstOrNull(::holds)?.let { return it }
|
||||
val removed = SessionPrefs.removedAddedGames(context)
|
||||
val dirs = listOfNotNull(
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||
@@ -376,6 +398,7 @@ object AddedGames {
|
||||
}
|
||||
AddedExes.list(context).filter { it.folder !in removed }.forEach { out.add(canonical(File(it.folder))) }
|
||||
StoreInstallRoot.gameFolders(context).forEach { out.add(canonical(it)) }
|
||||
libraryDepotInstalls(context).filter { it.path !in removed }.forEach { out.add(canonical(it)) }
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -392,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 }
|
||||
@@ -420,7 +443,14 @@ object AddedGames {
|
||||
?.takeIf { SessionPrefs.adoptAddedGameExe(context, folder.path, picked, it.path, rev) }
|
||||
val exe = adopted ?: found
|
||||
val guestExe = if (adopted != null) guestPath(context, adopted) ?: return else foundGuest
|
||||
val storeExe = sidecar?.exeFile(folder)
|
||||
val launched = adopted ?: chosen ?: storeExe?.takeIf { it.isFile }
|
||||
val storeOwnExe = launched != null && storeExe != null && canonical(launched) == canonical(storeExe)
|
||||
val sidecarDir = sidecar?.workdir?.takeIf { storeOwnExe }?.let { dir ->
|
||||
guestPath(context, if (dir.isEmpty()) folder else File(folder, dir))
|
||||
}
|
||||
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
|
||||
?: sidecarDir
|
||||
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
|
||||
val steamId = config?.let { steamRoute(it, appId) }
|
||||
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
||||
|
||||
@@ -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) }
|
||||
|
||||
@@ -70,15 +70,22 @@ object SteamGridDb {
|
||||
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
|
||||
}
|
||||
|
||||
fun gameId(key: String, steamAppId: Int?, name: String): Int? {
|
||||
fun gameId(key: String, steamAppId: Int?, name: String): Int? = gameId(key, steamAppId, name, ::match)
|
||||
|
||||
fun exactGameId(key: String, steamAppId: Int?, name: String): Int? = gameId(key, steamAppId, name, ::exactMatch)
|
||||
|
||||
private fun gameId(key: String, steamAppId: Int?, name: String, pick: (String, List<Pair<Int, String>>) -> Int?): Int? {
|
||||
if (steamAppId != null) {
|
||||
json(key, "$API/games/steam/$steamAppId")?.optJSONObject("data")?.optInt("id")?.takeIf { it > 0 }?.let { return it }
|
||||
}
|
||||
val term = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
|
||||
val results = json(key, "$API/search/autocomplete/$term")?.optJSONArray("data") ?: return null
|
||||
return match(name, (0 until results.length()).map { results.getJSONObject(it) }.map { it.optInt("id") to it.optString("name") })
|
||||
return pick(name, (0 until results.length()).map { results.getJSONObject(it) }.map { it.optInt("id") to it.optString("name") })
|
||||
}
|
||||
|
||||
internal fun exactMatch(name: String, results: List<Pair<Int, String>>): Int? =
|
||||
results.firstOrNull { (id, got) -> id > 0 && AddedGameArt.nameMatch(name, got) == 3 }?.first
|
||||
|
||||
internal fun match(name: String, results: List<Pair<Int, String>>): Int? =
|
||||
results.map { (id, got) -> id to AddedGameArt.nameMatch(name, got) }
|
||||
.filter { it.second > 0 && it.first > 0 }
|
||||
|
||||
@@ -14,8 +14,8 @@ object SteamLaunchOptions {
|
||||
private const val TAG = "SteamLaunchOptions"
|
||||
private val STEAM = listOf("UserLocalConfigStore", "Software", "Valve", "Steam")
|
||||
|
||||
fun current(context: Context, appId: Int): String =
|
||||
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId).orEmpty()
|
||||
fun current(context: Context, appId: Int): String? =
|
||||
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId)
|
||||
|
||||
enum class Saved { YES, NO, DESKTOP }
|
||||
|
||||
@@ -35,7 +35,8 @@ object SteamLaunchOptions {
|
||||
internal fun steam(steamHome: File, appId: Int): String? {
|
||||
val config = AddedGames.accountConfig(steamHome) ?: return null
|
||||
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
|
||||
return launchOptions(text, appId)
|
||||
if (section(text, STEAM) == null) return null
|
||||
return launchOptions(text, appId).orEmpty()
|
||||
}
|
||||
|
||||
internal fun write(steamHome: File, appId: Int, options: String): Boolean {
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import java.io.File
|
||||
|
||||
data class AppVulkan(
|
||||
val major: Int,
|
||||
val minor: Int,
|
||||
val shaderInt64: Boolean?,
|
||||
val maxPushConstants: Int?,
|
||||
val source: String,
|
||||
) {
|
||||
fun atLeast(major: Int, minor: Int): Boolean = this.major > major || (this.major == major && this.minor >= minor)
|
||||
|
||||
val label: String
|
||||
get() = "Vulkan $major.$minor, shaderInt64 ${shaderInt64?.let { if (it) "yes" else "no" } ?: "?"}, " +
|
||||
"push constants ${maxPushConstants ?: "?"} ($source)"
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AppVulkan"
|
||||
const val BRIDGE_FILE = "apps-vulkan"
|
||||
|
||||
fun detect(context: Context): AppVulkan? {
|
||||
if (!DeviceSupport.vkBridge(context)) return null
|
||||
val native = VulkanInfo.query()
|
||||
val file = File(VkBridgeComponent.cacheDir(context), BRIDGE_FILE)
|
||||
val fromBridge = FileUtils.readString(file)?.let { fromBridgeFile(it, native["device"], native["api"]) }
|
||||
val found = fromBridge ?: fromDriver(native)
|
||||
Log.i(TAG, found?.label ?: "unknown (driver query: ${native["error"] ?: "no api line"})")
|
||||
return found
|
||||
}
|
||||
|
||||
internal fun fromBridgeFile(text: String, driverDevice: String?, driverApi: String? = null): AppVulkan? {
|
||||
val map = keyValues(text)
|
||||
val device = map["device"]
|
||||
if (device != null && driverDevice != null && device != driverDevice) return null
|
||||
val fileDriver = version(map["driver_api"])
|
||||
val native = version(driverApi)
|
||||
if (fileDriver != null && native != null && fileDriver != native) return null
|
||||
val promoted = map["promotion"]?.trim()?.lowercase() == "on"
|
||||
val (major, minor) = (if (promoted) version(map["api"]) else fileDriver ?: version(map["api"])) ?: return null
|
||||
return AppVulkan(major, minor, bool(map["shader_int64"]), map["max_push_constants"]?.toIntOrNull(),
|
||||
if (promoted) "bridge, promoted" else "bridge")
|
||||
}
|
||||
|
||||
internal fun fromDriver(map: Map<String, String>): AppVulkan? {
|
||||
val (major, minor) = version(map["api"]) ?: return null
|
||||
return AppVulkan(major, minor, bool(map["shader_int64"]), map["max_push_constants"]?.toIntOrNull(), "driver")
|
||||
}
|
||||
|
||||
private fun keyValues(text: String): Map<String, String> = text.lineSequence().mapNotNull { line ->
|
||||
val eq = line.indexOf('=')
|
||||
if (eq <= 0) null else line.substring(0, eq).trim() to line.substring(eq + 1).trim()
|
||||
}.toMap()
|
||||
|
||||
private fun version(v: String?): Pair<Int, Int>? {
|
||||
val parts = v?.trim()?.split('.') ?: return null
|
||||
if (parts.size < 2) return null
|
||||
val major = parts[0].toIntOrNull() ?: return null
|
||||
val minor = parts[1].toIntOrNull() ?: return null
|
||||
return major to minor
|
||||
}
|
||||
|
||||
private fun bool(v: String?): Boolean? = when (v?.trim()?.lowercase()) {
|
||||
"1", "yes", "true" -> true
|
||||
"0", "no", "false" -> false
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
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
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import java.io.FileWriter
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
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
|
||||
|
||||
@Synchronized override fun start() {
|
||||
if (stopped || running) return
|
||||
running = true
|
||||
thread = Thread({ run() }, "clock-log").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
@Synchronized override fun stop() {
|
||||
stopped = true
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
val policies = File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.startsWith("policy") }
|
||||
?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList()
|
||||
val gpuCandidates = gpuSources()
|
||||
val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null }
|
||||
val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager
|
||||
val time = SimpleDateFormat("HH:mm:ss", Locale.US)
|
||||
try {
|
||||
FileWriter(logFile, true).use { w ->
|
||||
w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n")
|
||||
w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n")
|
||||
for (source in gpuCandidates) {
|
||||
val f = File(source)
|
||||
val state = when {
|
||||
!f.exists() -> continue
|
||||
firstNumber(source) != null -> "readable"
|
||||
else -> "refused"
|
||||
}
|
||||
w.write("gpu source $source: $state\n")
|
||||
}
|
||||
w.write("gpu clock from: ${gpu ?: "nothing readable"}\n")
|
||||
w.flush()
|
||||
while (running && logFile.length() < MAX_BYTES) {
|
||||
val line = StringBuilder(time.format(Date()))
|
||||
for (p in policies) {
|
||||
val cur = firstNumber(File(p, "scaling_cur_freq").path)
|
||||
val max = firstNumber(File(p, "scaling_max_freq").path)
|
||||
val hw = firstNumber(File(p, "cpuinfo_max_freq").path)
|
||||
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
|
||||
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
|
||||
}
|
||||
gpu?.let { line.append(" | gpu ${mhz(firstNumber(it))} MHz") }
|
||||
if (power != null && Build.VERSION.SDK_INT >= 29) {
|
||||
line.append(" | thermal ${power.currentThermalStatus}")
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
val h = power.getThermalHeadroom(10)
|
||||
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 }
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "clock log stopped: $e")
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
private const val MAX_BYTES = 4L shl 20
|
||||
|
||||
private fun gpuSources(): List<String> {
|
||||
val list = mutableListOf(
|
||||
"/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/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")
|
||||
}
|
||||
return list.distinct()
|
||||
}
|
||||
|
||||
private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull()
|
||||
|
||||
private fun firstNumber(path: String): Long? =
|
||||
runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
|
||||
|
||||
private fun mhz(raw: Long?): String = when {
|
||||
raw == null -> "?"
|
||||
raw > 10_000_000 -> (raw / 1_000_000).toString()
|
||||
raw > 10_000 -> (raw / 1_000).toString()
|
||||
else -> raw.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ object DeviceInfo {
|
||||
val vk = VulkanInfo.query()
|
||||
val gpu = GpuInfo.detect()
|
||||
return listOf(
|
||||
chip(), gpu(gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
chip(), gpu(context, gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
).filter { it.rows.isNotEmpty() }
|
||||
}
|
||||
|
||||
@@ -51,9 +51,9 @@ object DeviceInfo {
|
||||
add("Family", read("/sys/devices/soc0/family"))
|
||||
})
|
||||
|
||||
private fun gpu(gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
|
||||
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)"
|
||||
@@ -66,7 +66,7 @@ object DeviceInfo {
|
||||
add("Clock range", gpuRange())
|
||||
add("Load", read("$kgsl/gpu_busy_percentage")?.let { if (it.endsWith("%")) it else "$it %" })
|
||||
add("Temperature", read("$kgsl/temp")?.toLongOrNull()?.let { if (it > 1000) "${it / 1000} °C" else "$it °C" })
|
||||
add("Support", gpu.supportText)
|
||||
add("Support", gpu.supportText(SessionPrefs.vkBridge(context)))
|
||||
})
|
||||
|
||||
private fun cpu() = Section("CPU", buildList<Pair<String, String>> {
|
||||
@@ -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,17 +61,36 @@ 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 {
|
||||
support != Support.UNSUPPORTED -> supportText
|
||||
bridge -> "Runs through the Mali bridge, on the phone's own Vulkan driver"
|
||||
else -> "Not supported with the Mali bridge off: Turnip needs an Adreno (Snapdragon) GPU"
|
||||
}
|
||||
|
||||
fun supportText(context: Context, bridge: Boolean): String = when {
|
||||
support != Support.UNSUPPORTED -> supportText(context)
|
||||
bridge -> context.getString(R.string.gpuinfo_bridge)
|
||||
else -> context.getString(R.string.gpuinfo_bridge_off)
|
||||
}
|
||||
|
||||
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
|
||||
@@ -79,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,
|
||||
@@ -124,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,10 +306,15 @@ 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)) {
|
||||
Log.i(TAG, "Mali bridge: the compositor uses the system Vulkan driver");
|
||||
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) {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
|
||||
class VkBridgeComponent(private val socket: File, private val logFile: File) : SessionPart() {
|
||||
@Volatile private var pid = -1
|
||||
@Volatile private var exited = false
|
||||
|
||||
override fun start() {
|
||||
stop()
|
||||
val binary = File(app().applicationInfo.nativeLibraryDir, BINARY)
|
||||
if (!binary.isFile) {
|
||||
Log.e(TAG, "server missing at $binary; the session will have no Vulkan")
|
||||
return
|
||||
}
|
||||
socket.parentFile?.mkdirs()
|
||||
val cacheDir = cacheDir(app())
|
||||
writeMode(cacheDir, com.droiddeck.launcher.session.SessionPrefs.vkBridgeMode(app()))
|
||||
if (VkBridgeNative.start(app(), socket, logFile, cacheDir)) {
|
||||
Log.i(TAG, "server ready in the app's process at $socket")
|
||||
return
|
||||
}
|
||||
socket.delete()
|
||||
exited = false
|
||||
val cmd = listOf(binary.absolutePath, "--socket", socket.absolutePath, "--log", logFile.absolutePath,
|
||||
"--cache-dir", cacheDir.absolutePath)
|
||||
.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||
val env = arrayOf("HOME=" + app().filesDir)
|
||||
pid = HostProcess.start(cmd, env, app().filesDir, { status ->
|
||||
exited = true
|
||||
Log.w(TAG, "server exited with status $status")
|
||||
runCatching { logFile.appendText("== vkbridge server exited with status $status\n") }
|
||||
}, { line -> Log.i(TAG, line) })
|
||||
val began = System.currentTimeMillis()
|
||||
val deadline = began + 15_000L
|
||||
while (!socket.exists() && !exited && System.currentTimeMillis() < deadline) {
|
||||
try { Thread.sleep(50L) } catch (e: InterruptedException) { Thread.currentThread().interrupt(); break }
|
||||
}
|
||||
val waited = System.currentTimeMillis() - began
|
||||
Log.i(TAG, if (socket.exists()) "server ready (pid $pid) at $socket after $waited ms"
|
||||
else "server NOT ready (pid $pid, exited=$exited) after $waited ms; see $logFile")
|
||||
if (!socket.exists() && VkBridgeNative.start(app(), socket, logFile, cacheDir)) Log.i(TAG, "server ready in the app's process at $socket")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
if (pid > 0) {
|
||||
Process.killProcess(pid)
|
||||
pid = -1
|
||||
}
|
||||
if (!VkBridgeNative.serving) socket.delete()
|
||||
}
|
||||
|
||||
override fun suspendPid(): Int = pid
|
||||
|
||||
companion object {
|
||||
private const val TAG = "VkBridge"
|
||||
private const val CACHE_DIR = "vkbridge-pipelines"
|
||||
private const val MODE_FILE = "mode"
|
||||
|
||||
fun cacheDir(context: Context): File {
|
||||
val dir = File(context.filesDir, CACHE_DIR)
|
||||
val old = File(context.cacheDir, CACHE_DIR)
|
||||
if (old.isDirectory) migrate(old, dir)
|
||||
dir.mkdirs()
|
||||
return dir
|
||||
}
|
||||
|
||||
fun writeMode(dir: File, mode: String) {
|
||||
val file = File(dir, MODE_FILE)
|
||||
if (runCatching { file.readText().trim() }.getOrNull() == mode) return
|
||||
val tmp = File(dir, "$MODE_FILE.tmp")
|
||||
runCatching {
|
||||
tmp.writeText(mode + "\n")
|
||||
if (!tmp.renameTo(file)) error("rename failed")
|
||||
Log.i(TAG, "bridge mode: $mode")
|
||||
}.onFailure { Log.w(TAG, "could not write $file: $it"); tmp.delete() }
|
||||
}
|
||||
|
||||
private fun migrate(old: File, dir: File) {
|
||||
val moved = if (!dir.exists()) old.renameTo(dir) else false
|
||||
if (!moved) {
|
||||
dir.mkdirs()
|
||||
old.listFiles()?.forEach { f ->
|
||||
val to = File(dir, f.name)
|
||||
if (to.exists()) return@forEach
|
||||
if (!f.renameTo(to)) runCatching { f.copyRecursively(to, overwrite = false) }
|
||||
}
|
||||
old.deleteRecursively()
|
||||
}
|
||||
Log.i(TAG, "bridge cache moved from $old to $dir")
|
||||
}
|
||||
|
||||
const val BINARY = "libvkbridge_server.so"
|
||||
const val GUEST_ICD = "/usr/local/share/vkbridge/droidbridge_icd.json"
|
||||
const val GUEST_LIB = "/usr/local/lib/vkbridge/libvulkan_droidbridge.so"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
object VkBridgeNative {
|
||||
private const val TAG = "VkBridge"
|
||||
|
||||
@Volatile private var loaded: Boolean? = null
|
||||
|
||||
private fun load(context: Context): Boolean {
|
||||
loaded?.let { return it }
|
||||
val ok = try {
|
||||
val dev = File(context.filesDir, "vkbridge/dev/libvkbridge_jni.so")
|
||||
val debuggable = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
|
||||
if (debuggable && dev.isFile) {
|
||||
Log.w(TAG, "in-app server from the development override $dev")
|
||||
System.load(dev.absolutePath)
|
||||
} else {
|
||||
System.loadLibrary("vkbridge_jni")
|
||||
}
|
||||
true
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "in-app server unavailable: $e")
|
||||
false
|
||||
}
|
||||
loaded = ok
|
||||
return ok
|
||||
}
|
||||
|
||||
@Volatile var serving = false
|
||||
private set
|
||||
|
||||
fun start(context: Context, socket: File, log: File, cacheDir: File): Boolean {
|
||||
if (!load(context)) return false
|
||||
val ok = try {
|
||||
nativeStart(socket.absolutePath, log.absolutePath, cacheDir.absolutePath) == 1
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "in-app server failed to start: $e")
|
||||
false
|
||||
}
|
||||
if (ok) serving = true
|
||||
return ok
|
||||
}
|
||||
|
||||
@JvmStatic private external fun nativeStart(socket: String, log: String, cacheDir: String): Int
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -14,6 +14,8 @@ import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.ui.Motion
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
@@ -56,7 +58,10 @@ class DroidDeckHudHost(context: Context) {
|
||||
if (!gpuName.isNullOrBlank()) handler.post { this@DroidDeckHudHost.gpuName = cleanGpuName(gpuName) }
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
handler.post {
|
||||
onPresentingWindowChanged?.invoke()
|
||||
applyShown()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,8 +179,9 @@ class DroidDeckHudHost(context: Context) {
|
||||
private fun applyShown() {
|
||||
if (!running) return
|
||||
val show = !hidden && !backgrounded
|
||||
view?.visibility = if (show) View.VISIBLE else View.GONE
|
||||
showing = show
|
||||
val visible = show && SessionState.mode != SessionService.MODE_DESKTOP
|
||||
view?.visibility = if (visible) View.VISIBLE else View.GONE
|
||||
showing = visible
|
||||
if (show != polling) {
|
||||
polling = show
|
||||
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
|
||||
@@ -208,14 +214,20 @@ class DroidDeckHudHost(context: Context) {
|
||||
file
|
||||
}.getOrNull()
|
||||
|
||||
private fun sessionResolution(): String {
|
||||
val (width, height) = SessionState.outputSize
|
||||
return "${width}x${height}"
|
||||
}
|
||||
|
||||
private fun refreshLabels(hud: DroidDeckHudView) {
|
||||
if (feed.engine.isNotBlank() && !feed.steamFocused) engine = feed.engine
|
||||
hud.setEngineLabel(engine)
|
||||
if (gpuName.isNotBlank()) hud.setGpuModel(gpuName)
|
||||
hud.setResolution(if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString {
|
||||
val feedResolution = if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString {
|
||||
append(feed.outputWidth).append('x').append(feed.outputHeight)
|
||||
if (feed.refreshMilliHz > 0) append(" @ ").append((feed.refreshMilliHz + 499) / 1000).append("Hz")
|
||||
} else "")
|
||||
} else ""
|
||||
hud.setResolution(feedResolution.ifBlank { sessionResolution() })
|
||||
val pid = feed.pid
|
||||
if (pid > 0 && pid != protonPid) {
|
||||
protonPid = pid
|
||||
|
||||
@@ -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"
|
||||
@@ -698,6 +702,9 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
contentW = max(contentW, pad + w + pad)
|
||||
}
|
||||
|
||||
private fun hasGpuStats(s: HudMetrics.Snapshot): Boolean =
|
||||
s.gpuPercent != null || s.gpuTempC != null || s.gpuClockMhz != null
|
||||
|
||||
private fun buildFull(s: HudMetrics.Snapshot) {
|
||||
val rowPx = sp(12f); val unitPx = rowPx * 0.62f
|
||||
val pad = sp(10f); val lineGap = sp(4f); val lvGap = sp(8f)
|
||||
@@ -709,7 +716,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
rows.add(HudRow(Span("DISP", colDisp, rowPx), listOf(Span(displayServer, colValue, rowPx))))
|
||||
if (hdrState != DroidDeckHudHdr.NONE)
|
||||
rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx)))
|
||||
if (showGPU) {
|
||||
if (showGPU && hasGpuStats(s)) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
|
||||
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
|
||||
@@ -720,9 +727,9 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (showCPU) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
|
||||
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
||||
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
|
||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
||||
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
||||
rows.add(HudRow(Span("CPU", colCpu, rowPx), v))
|
||||
}
|
||||
if (showVram && s.vramText() != null)
|
||||
@@ -747,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)))
|
||||
}
|
||||
@@ -796,15 +805,16 @@ 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) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
|
||||
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
|
||||
if (showGpuTemp && s.gpuTempC != null) HudMetrics.formatTemp(s.gpuTempC.toFloat(), tempDisplay, false)
|
||||
else s.gpuClockMhz?.let { "${it}MHz" }, false))
|
||||
if (showCPU) tiles.add(Tile("CPU", colCpu, numUnit(s.cpuPercent?.toString(), "%", valPx, unitPx),
|
||||
listOfNotNull(if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null,
|
||||
s.cpuClockMhz?.toString()).joinToString(" · ").ifBlank { null }, false))
|
||||
listOfNotNull(s.cpuClockMhz?.let { "${it}MHz" },
|
||||
if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null)
|
||||
.joinToString(" · ").ifBlank { null }, false))
|
||||
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
|
||||
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
|
||||
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
|
||||
@@ -881,7 +891,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
|
||||
run {
|
||||
val l = ArrayList<Span>()
|
||||
if (showGPU) { l += Span("GPU ${s.gpuPercent ?: "—"}%", colGpu, stkPx) }
|
||||
if (showGPU && s.gpuPercent != null) { l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx) }
|
||||
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
|
||||
if (l.isNotEmpty()) stack.add(l)
|
||||
}
|
||||
@@ -959,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()
|
||||
@@ -975,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)
|
||||
}
|
||||
@@ -1038,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))
|
||||
@@ -1137,7 +1157,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
val left = ArrayList<HudRow>()
|
||||
if (showGpuModel && gpuNameText().isNotBlank())
|
||||
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
|
||||
if (showGPU) {
|
||||
if (showGPU && hasGpuStats(s)) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
|
||||
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
|
||||
@@ -1148,9 +1168,9 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (showCPU) {
|
||||
val v = ArrayList<Span>()
|
||||
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
|
||||
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
||||
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
|
||||
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
|
||||
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
|
||||
left.add(HudRow(Span("CPU", colCpu, rowPx), v))
|
||||
}
|
||||
if (showPerCore) {
|
||||
@@ -1204,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)))
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.os.Environment
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
|
||||
class Cpu(val percent: Int, val perCore: IntArray)
|
||||
@@ -48,6 +50,7 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
}
|
||||
|
||||
fun cpuTempC(): Int? {
|
||||
externalCpuTemp()?.let { return it }
|
||||
var sum = 0f
|
||||
var count = 0
|
||||
for (zone in LinuxRuntime.cpuTempZones()) {
|
||||
@@ -58,6 +61,13 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
return if (count == 0) null else (sum / count).toInt()
|
||||
}
|
||||
|
||||
/** Optional ADB helper feed: /sdcard/DroidDeck/cpu-temp, written from the host while a session runs. */
|
||||
private fun externalCpuTemp(): Int? {
|
||||
val file = File(Environment.getExternalStorageDirectory(), "DroidDeck/cpu-temp")
|
||||
if (!file.isFile || System.currentTimeMillis() - file.lastModified() > CPU_TEMP_FRESH_MS) return null
|
||||
return readFloat(file)?.takeIf { it.isFinite() && it in -20f..150f }?.roundToInt()
|
||||
}
|
||||
|
||||
fun gpuPercent(): Int? {
|
||||
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/perf_now"))
|
||||
val source = feed ?: LinuxRuntime.gpuLoadSource()?.let(::File) ?: return null
|
||||
@@ -92,7 +102,8 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024)
|
||||
}
|
||||
|
||||
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
|
||||
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
|
||||
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
|
||||
|
||||
fun battery(): Battery? {
|
||||
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
|
||||
@@ -132,6 +143,7 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
|
||||
const val VRAM_FILE = "run/droiddeck-hud/gpu-mem"
|
||||
private const val FEED_FRESH_MS = 10_000L
|
||||
private const val VRAM_FRESH_MS = 15_000L
|
||||
private const val CPU_TEMP_FRESH_MS = 10_000L
|
||||
private val WHITESPACE = Regex("\\s+")
|
||||
|
||||
private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull()
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -66,6 +66,10 @@ class DirectTouchHold(
|
||||
held = false
|
||||
}
|
||||
|
||||
fun cancelPendingHold() {
|
||||
handler.removeCallbacks(hold)
|
||||
}
|
||||
|
||||
fun onTouch(event: MotionEvent): Boolean {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
||||
if (liftPending) {
|
||||
|
||||
@@ -7,7 +7,7 @@ object GuestKeys {
|
||||
fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean {
|
||||
val down = event.action == KeyEvent.ACTION_DOWN
|
||||
if (!down && event.action != KeyEvent.ACTION_UP) return false
|
||||
var evdev = EvdevKeys.fromKeyCode(event.keyCode)
|
||||
var evdev = if (isKeyboardEscape(event.keyCode, event.scanCode)) KEY_ESC else EvdevKeys.fromKeyCode(event.keyCode)
|
||||
val ch = event.unicodeChar
|
||||
val plain = if (ch > 0) EvdevKeys.unshiftedChar(ch) else 0
|
||||
if (evdev <= 0 && ch > 0) {
|
||||
@@ -27,5 +27,9 @@ object GuestKeys {
|
||||
return true
|
||||
}
|
||||
|
||||
fun isKeyboardEscape(keyCode: Int, scanCode: Int): Boolean =
|
||||
keyCode == KeyEvent.KEYCODE_BACK && scanCode == KEY_ESC
|
||||
|
||||
private const val KEY_ESC = 1
|
||||
private const val KEY_LEFTSHIFT = 42
|
||||
}
|
||||
@@ -45,6 +45,62 @@ object HomeButtonShortcuts {
|
||||
fun onDeviceRemoved(device: Int) = input.onDeviceRemoved(device)
|
||||
}
|
||||
|
||||
object SystemKeyCapture {
|
||||
private var owner: Any? = null
|
||||
private var active: () -> Boolean = { false }
|
||||
private var send: (KeyEvent) -> Unit = {}
|
||||
private val held = HashMap<Pair<Int, Int>, KeyEvent>()
|
||||
private val releasing = HashSet<Pair<Int, Int>>()
|
||||
internal var isKeyboard: (KeyEvent) -> Boolean = ::fromKeyboard
|
||||
|
||||
fun attach(owner: Any, active: () -> Boolean, send: (KeyEvent) -> Unit) {
|
||||
this.owner = owner
|
||||
this.active = active
|
||||
this.send = send
|
||||
}
|
||||
|
||||
fun detach(owner: Any) {
|
||||
if (this.owner !== owner) return
|
||||
held.values.forEach { send(KeyEvent.changeAction(it, KeyEvent.ACTION_UP)) }
|
||||
releasing += held.keys
|
||||
held.clear()
|
||||
this.owner = null
|
||||
active = { false }
|
||||
send = {}
|
||||
}
|
||||
|
||||
internal fun captures(keyCode: Int, metaState: Int): Boolean = when {
|
||||
keyCode == KeyEvent.KEYCODE_META_LEFT || keyCode == KeyEvent.KEYCODE_META_RIGHT -> true
|
||||
metaState and KeyEvent.META_META_ON != 0 -> true
|
||||
metaState and KeyEvent.META_ALT_ON != 0 -> keyCode == KeyEvent.KEYCODE_TAB || keyCode == KeyEvent.KEYCODE_ESCAPE
|
||||
else -> false
|
||||
}
|
||||
|
||||
private fun fromKeyboard(event: KeyEvent): Boolean =
|
||||
event.device?.let { !it.isVirtual && it.keyboardType == android.view.InputDevice.KEYBOARD_TYPE_ALPHABETIC } == true
|
||||
|
||||
fun onKeyEvent(event: KeyEvent): Boolean {
|
||||
val key = event.deviceId to event.keyCode
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
releasing -= key
|
||||
} else if (key in releasing) {
|
||||
if (event.action == KeyEvent.ACTION_UP) releasing -= key
|
||||
return true
|
||||
}
|
||||
val taken = when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> {
|
||||
val take = key in held || (event.repeatCount == 0 && active() && isKeyboard(event) && captures(event.keyCode, event.metaState))
|
||||
if (take) held[key] = KeyEvent(event)
|
||||
take
|
||||
}
|
||||
KeyEvent.ACTION_UP -> held.remove(key) != null
|
||||
else -> false
|
||||
}
|
||||
if (taken) send(event)
|
||||
return taken
|
||||
}
|
||||
}
|
||||
|
||||
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
|
||||
private var bottomScreen: BottomScreenWatch? = null
|
||||
|
||||
@@ -58,7 +114,8 @@ class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListen
|
||||
bottomScreen = null
|
||||
}
|
||||
|
||||
override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event)
|
||||
override fun onKeyEvent(event: KeyEvent) =
|
||||
SystemKeyCapture.onKeyEvent(event) || HomeButtonShortcuts.onKeyEvent(this, event)
|
||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) { event?.let { bottomScreen?.onEvent(it) } }
|
||||
override fun onInterrupt() { HomeButtonShortcuts.release() }
|
||||
override fun onInputDeviceAdded(deviceId: Int) {}
|
||||
|
||||
@@ -89,21 +89,31 @@ class KeyboardHost(
|
||||
clearFocus()
|
||||
}
|
||||
|
||||
fun type(text: CharSequence?) {
|
||||
if (text.isNullOrEmpty()) return
|
||||
val events = map.getEvents(text.toString().toCharArray())
|
||||
if (events != null) {
|
||||
for (event in events) sendKeyEvent(event)
|
||||
} else {
|
||||
for (ch in text) {
|
||||
val t = System.currentTimeMillis()
|
||||
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
|
||||
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
|
||||
sendKeyEvent(CharKeyEvent(down, ch))
|
||||
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun tap(keyCode: Int) {
|
||||
val t = System.currentTimeMillis()
|
||||
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
|
||||
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
|
||||
}
|
||||
|
||||
private inner class KeyConnection : BaseInputConnection(this, false) {
|
||||
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
if (text.isNullOrEmpty()) return true
|
||||
val events = map.getEvents(text.toString().toCharArray())
|
||||
if (events != null) {
|
||||
for (event in events) sendKeyEvent(event)
|
||||
} else {
|
||||
for (ch in text) {
|
||||
val t = System.currentTimeMillis()
|
||||
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
|
||||
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
|
||||
sendKeyEvent(CharKeyEvent(down, ch))
|
||||
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
|
||||
}
|
||||
}
|
||||
type(text)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -123,12 +133,6 @@ class KeyboardHost(
|
||||
return true
|
||||
}
|
||||
|
||||
private fun tap(keyCode: Int) {
|
||||
val t = System.currentTimeMillis()
|
||||
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
|
||||
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
|
||||
}
|
||||
|
||||
override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence = ""
|
||||
override fun getTextAfterCursor(n: Int, flags: Int): CharSequence = ""
|
||||
override fun getSelectedText(flags: Int): CharSequence? = null
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
@@ -59,15 +60,20 @@ class OnScreenControls(
|
||||
return dx * dx + dy * dy <= hit * hit
|
||||
}
|
||||
|
||||
fun drag(x: Float, y: Float) {
|
||||
fun drag(x: Float, y: Float): Boolean {
|
||||
var dx = x - ax
|
||||
var dy = y - ay
|
||||
val d = sqrt(dx * dx + dy * dy)
|
||||
if (d > radius) { dx = dx / d * radius; dy = dy / d * radius }
|
||||
val atLimit = d > radius
|
||||
if (atLimit) { dx = dx / d * radius; dy = dy / d * radius }
|
||||
if (!atLimit && abs(dx - kx) < MIN_STICK_MOVE_PX && abs(dy - ky) < MIN_STICK_MOVE_PX) return false
|
||||
kx = dx; ky = dy; dirty = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private val stickRedraw = ThrottledRedraw(this, STICK_REDRAW_MS)
|
||||
|
||||
private val controls = listOf(
|
||||
Control("up", "dpad", -1, 26f, 0f, -52f),
|
||||
Control("right", "dpad", -1, 26f, 52f, 0f),
|
||||
@@ -211,6 +217,7 @@ class OnScreenControls(
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
stickRedraw.cancel()
|
||||
releaseAll()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
@@ -512,6 +519,7 @@ class OnScreenControls(
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (editing) return onEditTouch(event)
|
||||
if (event.getToolType(event.actionIndex) == MotionEvent.TOOL_TYPE_MOUSE) return false
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val index = event.actionIndex
|
||||
@@ -541,8 +549,9 @@ 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
|
||||
}
|
||||
requestUnbufferedDispatch(event)
|
||||
if (SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
|
||||
apply()
|
||||
return true
|
||||
}
|
||||
@@ -551,13 +560,14 @@ class OnScreenControls(
|
||||
if (keyboardPressedBy != -1) return true
|
||||
if (quickPressedBy != -1) return true
|
||||
var changed = false
|
||||
var stickMoved = false
|
||||
for (index in 0 until event.pointerCount) {
|
||||
val pointer = event.getPointerId(index)
|
||||
if (forwardedPointerBits and (1 shl pointer) != 0) continue
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
|
||||
if (stick != null) { stick.drag(x, y); changed = true; continue }
|
||||
if (stick != null) { stickMoved = stick.drag(x, y) || stickMoved; continue }
|
||||
val over = controlAt(x, y)?.takeIf { it.stick < 0 }
|
||||
for (control in controls) {
|
||||
if (control.stick < 0 && control.pressedBy == pointer && control !== over) {
|
||||
@@ -570,7 +580,7 @@ class OnScreenControls(
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (changed) apply()
|
||||
if (changed) apply() else if (stickMoved) apply(stickOnly = true)
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
@@ -684,15 +694,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
|
||||
}
|
||||
}
|
||||
@@ -704,7 +717,7 @@ class OnScreenControls(
|
||||
else -> control.target != ControllerPrefs.OFF
|
||||
}
|
||||
|
||||
private fun apply() {
|
||||
private fun apply(stickOnly: Boolean = false) {
|
||||
val bridge = pad
|
||||
if (bridge == null || editing) { invalidate(); return }
|
||||
val qamHeld = controls.any { it.id == "qam" && it.pressedBy != -1 }
|
||||
@@ -712,7 +725,10 @@ class OnScreenControls(
|
||||
bridge.setSystemButtons(controls.any { it.id == "guide" && it.pressedBy != -1 }, qamHeld)
|
||||
} else {
|
||||
bridge.setSystemButtons(false, qamHeld)
|
||||
bridge.applyTouch { 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(stickWrites) { state ->
|
||||
val used = HashSet<String>()
|
||||
val held = HashSet<String>()
|
||||
for (control in controls) {
|
||||
@@ -736,7 +752,7 @@ class OnScreenControls(
|
||||
for (target in used) write(state, target, target in held)
|
||||
}
|
||||
}
|
||||
invalidate()
|
||||
if (stickOnly) stickRedraw.request() else invalidate()
|
||||
}
|
||||
|
||||
private fun write(state: PadState, target: String, down: Boolean) {
|
||||
@@ -778,6 +794,8 @@ class OnScreenControls(
|
||||
|
||||
private companion object {
|
||||
const val DOUBLE_TAP_MS = 300L
|
||||
const val STICK_REDRAW_MS = 33L
|
||||
const val MIN_STICK_MOVE_PX = 1f
|
||||
const val MIN_FACE_MM = 9.5f
|
||||
const val FULL_SIZE_HEIGHT_MM = 85f
|
||||
const val BOTTOM_MARGIN_MM = 5f
|
||||
|
||||
@@ -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 Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
@@ -150,7 +155,7 @@ public final class PadBridge {
|
||||
chordButtonPressed = false;
|
||||
qamChordGeneration++;
|
||||
chordHandler.removeCallbacksAndMessages(null);
|
||||
state.clear();
|
||||
clearPlayerState(0);
|
||||
publish();
|
||||
}
|
||||
|
||||
@@ -177,7 +182,7 @@ public final class PadBridge {
|
||||
playerWriters[slot].destroy();
|
||||
playerWriters[slot] = null;
|
||||
}
|
||||
if (playerStates[slot] != null) playerStates[slot].clear();
|
||||
clearPlayerState(slot);
|
||||
}
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
@@ -187,7 +192,7 @@ public final class PadBridge {
|
||||
qamTapPressed = false;
|
||||
qamChordGeneration++;
|
||||
if (open) {
|
||||
state.clear();
|
||||
clearPlayerState(0);
|
||||
writer.writePad(state);
|
||||
writer.close();
|
||||
open = false;
|
||||
@@ -353,6 +358,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;
|
||||
@@ -366,25 +430,24 @@ 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);
|
||||
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;
|
||||
@@ -406,7 +469,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) {
|
||||
@@ -434,6 +497,10 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
|
||||
applyTouch(0, mutation);
|
||||
}
|
||||
|
||||
public synchronized void applyTouch(int stickWrites, java.util.function.Consumer<PadState> mutation) {
|
||||
if (!builtinPad) return;
|
||||
if (touchRoute != null && touchRoute.active()) {
|
||||
mutation.accept(routedTouch);
|
||||
@@ -453,7 +520,8 @@ public final class PadBridge {
|
||||
return;
|
||||
}
|
||||
routedTouch.clear();
|
||||
mutation.accept(state);
|
||||
retainedSticks[0] &= ~stickWrites;
|
||||
mutateState(mutation);
|
||||
activeControllerId = NO_CONTROLLER;
|
||||
slotControllers.set(0, NO_CONTROLLER);
|
||||
notePlayerInput();
|
||||
@@ -463,7 +531,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();
|
||||
@@ -490,11 +558,11 @@ public final class PadBridge {
|
||||
routedTouch.clear();
|
||||
backQamPressed = false;
|
||||
releaseBackPaddles();
|
||||
state.clear();
|
||||
clearPlayerState(0);
|
||||
publish();
|
||||
for (int slot = 1; slot < SLOTS; slot++) {
|
||||
clearPlayerState(slot);
|
||||
if (playerWriters[slot] == null) continue;
|
||||
playerStates[slot].clear();
|
||||
publish(slot);
|
||||
}
|
||||
}
|
||||
@@ -534,7 +602,7 @@ public final class PadBridge {
|
||||
if (!homeGuidePressed) return;
|
||||
clearBackQamWrites();
|
||||
homeGuidePressed = false;
|
||||
state.clear();
|
||||
clearPlayerState(0);
|
||||
publish();
|
||||
}
|
||||
|
||||
@@ -557,7 +625,7 @@ public final class PadBridge {
|
||||
writeBackQamReport(modifier, modifierAt);
|
||||
}
|
||||
if (!pressed && !backQamPressed && !homeGuidePressed) {
|
||||
backQamAxesBlocked = hasAxes(state);
|
||||
backQamAxesBlocked = hasQamAxes();
|
||||
if (!backQamWrites.isEmpty()) {
|
||||
PadState neutral = new PadState();
|
||||
neutral.copyFrom(lastWrittenReport);
|
||||
@@ -573,7 +641,7 @@ public final class PadBridge {
|
||||
if (!backQamPressed && backQamWrites.isEmpty()) return;
|
||||
clearBackQamWrites();
|
||||
backQamPressed = false;
|
||||
state.clear();
|
||||
clearPlayerState(0);
|
||||
publish();
|
||||
}
|
||||
|
||||
@@ -609,15 +677,18 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
private void writePad(PadState report) {
|
||||
if (backQamAxesBlocked && !hasAxes(state)) 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
|
||||
? hasChordStickInput(rawSticks[0][0], rawSticks[0][1]) : state.leftX != 0f || state.leftY != 0f;
|
||||
boolean right = (retainedSticks[0] & 2) != 0
|
||||
? hasChordStickInput(rawSticks[0][2], rawSticks[0][3]) : state.rightX != 0f || state.rightY != 0f;
|
||||
return left || right || state.leftTrigger != 0f || state.rightTrigger != 0f;
|
||||
}
|
||||
|
||||
private static void clearAxes(PadState pad) {
|
||||
@@ -727,7 +798,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;
|
||||
@@ -775,7 +846,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);
|
||||
}
|
||||
|
||||
@@ -793,11 +864,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;
|
||||
@@ -886,14 +957,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);
|
||||
@@ -906,8 +969,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
|
||||
|
||||
|
||||
|
||||
@@ -51,6 +51,15 @@ val PC_KEY_ROWS: List<List<PcKey>> = listOf(
|
||||
|
||||
val PC_MODIFIERS: Set<Int> = setOf(42, 54, 29, 97, 56, 100, 125)
|
||||
|
||||
// Sticky modifiers are excluded: hiding a locked modifier would leave it pressed forever.
|
||||
val PC_KEY_HIDDEN_GROUPS: Map<String, Set<Int>> = mapOf(
|
||||
"function" to ((59..68).toSet() + setOf(1, 87, 88)),
|
||||
"nav" to setOf(110, 111, 102, 107, 104, 109),
|
||||
"arrows" to setOf(103, 105, 108, 106),
|
||||
)
|
||||
|
||||
val PC_KEY_GROUP_IDS: Map<Int, String> = mapOf(0 to "function", 1 to "nav", 2 to "arrows")
|
||||
|
||||
val PC_KEYS: Map<Int, PcKey> = PC_KEY_ROWS.flatten().associateBy { it.code }
|
||||
|
||||
fun pcKeyLabel(context: Context, code: Int): String {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,7 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
|
||||
private var guideY = -1f
|
||||
private val addPress = Runnable { addX = pressX; addY = pressY; onAdd?.invoke() }
|
||||
private var editing = false
|
||||
val isEditing get() = editing
|
||||
private var selected: Entry? = null
|
||||
private var dragX = 0f
|
||||
private var dragY = 0f
|
||||
@@ -811,6 +812,7 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean = if (editing) editTouch(event) else playTouch(event)
|
||||
|
||||
private fun playTouch(event: MotionEvent): Boolean {
|
||||
if (event.getToolType(event.actionIndex) == MotionEvent.TOOL_TYPE_MOUSE) return false
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val index = event.actionIndex
|
||||
|
||||
@@ -21,8 +21,8 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
|
||||
}?.let { return it }
|
||||
val picked = entries.any { it != NONE && it.id == remembered }
|
||||
return when {
|
||||
dashboard && !picked -> DASHBOARD
|
||||
deckPad -> DECK_CONTROLS
|
||||
dashboard && !picked -> DASHBOARD
|
||||
else -> KEYBOARD_TRACKPAD
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,11 +19,20 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
|
||||
private var published = false
|
||||
private var shared: String? = null
|
||||
private var echo: String? = null
|
||||
private var capture: ((String?) -> Unit)? = null
|
||||
private var captureBefore: String? = null
|
||||
private var captureLate: (() -> Unit)? = null
|
||||
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh(changed = true) }
|
||||
private val guestListener = object : WaylandCompositor.ClipboardListener {
|
||||
override fun onGuestClipboardText(text: String) {
|
||||
handler.post {
|
||||
if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
|
||||
val taken = capture?.takeIf { text != captureBefore }
|
||||
if (taken != null && WaylandCompositor.isClipboardListener(this)) {
|
||||
capture = null
|
||||
handler.removeCallbacks(captureTimeout)
|
||||
WaylandCompositor.setClipboardText(shared)
|
||||
taken(text)
|
||||
} else if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
|
||||
val current = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
|
||||
shared = text
|
||||
published = true
|
||||
@@ -36,6 +45,21 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
private val captureTimeout = Runnable {
|
||||
val taken = capture ?: return@Runnable
|
||||
capture = null
|
||||
captureLate?.invoke()
|
||||
taken(null)
|
||||
}
|
||||
|
||||
fun captureGuest(timeoutMs: Long, onTimeout: () -> Unit = {}, onText: (String?) -> Unit) {
|
||||
capture?.let { handler.removeCallbacks(captureTimeout); it(null) }
|
||||
capture = onText
|
||||
captureLate = onTimeout
|
||||
captureBefore = shared
|
||||
handler.postDelayed(captureTimeout, timeoutMs)
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (active) return
|
||||
active = true
|
||||
@@ -47,6 +71,8 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
|
||||
fun stop() {
|
||||
if (!active) return
|
||||
active = false
|
||||
handler.removeCallbacks(captureTimeout)
|
||||
capture?.let { capture = null; it(null) }
|
||||
clipboard.removePrimaryClipChangedListener(androidListener)
|
||||
WaylandCompositor.clearClipboardListener(guestListener)
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
|
||||
@@ -107,6 +107,7 @@ class SteamTouchControls(
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)? = null
|
||||
|
||||
private var editing = false
|
||||
var onEditingChanged: ((Boolean) -> Unit)? = null
|
||||
private var editElements: MutableList<Element> = mutableListOf()
|
||||
private var hidden: MutableList<Element> = mutableListOf()
|
||||
private var selected = -1
|
||||
@@ -139,6 +140,7 @@ class SteamTouchControls(
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
handler.removeCallbacks(poll)
|
||||
moveRedraw.cancel()
|
||||
sensors.unregisterListener(shakeListener)
|
||||
releaseAll()
|
||||
super.onDetachedFromWindow()
|
||||
@@ -546,7 +548,7 @@ class SteamTouchControls(
|
||||
return bits
|
||||
}
|
||||
|
||||
private fun publish() {
|
||||
private fun publish(moving: Boolean = false) {
|
||||
var buttons = 0L
|
||||
val sticks = ShortArray(4)
|
||||
val pads = ShortArray(6)
|
||||
@@ -577,7 +579,7 @@ class SteamTouchControls(
|
||||
}
|
||||
}
|
||||
device.setControls(buttons, sticks, pads)
|
||||
invalidate()
|
||||
if (moving) moveRedraw.request() else invalidate()
|
||||
}
|
||||
|
||||
fun releaseAll() {
|
||||
@@ -586,6 +588,8 @@ class SteamTouchControls(
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private val moveRedraw = ThrottledRedraw(this, MOVE_REDRAW_MS)
|
||||
|
||||
private fun keepHeldFingers() {
|
||||
val moved = SteamTouchConfig.remapHeld(fingers.mapValues { it.value.element?.type }, live())
|
||||
fingers.keys.retainAll(moved.keys)
|
||||
@@ -614,6 +618,7 @@ class SteamTouchControls(
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (event.getToolType(event.actionIndex) == MotionEvent.TOOL_TYPE_MOUSE) return false
|
||||
val index = event.actionIndex
|
||||
lastTouchMs = android.os.SystemClock.uptimeMillis()
|
||||
if (faded) { faded = false; invalidate() }
|
||||
@@ -634,7 +639,7 @@ class SteamTouchControls(
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
fingers[event.getPointerId(index)] = Finger(e, x, y)
|
||||
if (feedback) performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
requestUnbufferedDispatch(event)
|
||||
if (com.droiddeck.launcher.session.SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
|
||||
publish()
|
||||
return true
|
||||
}
|
||||
@@ -653,7 +658,7 @@ class SteamTouchControls(
|
||||
}
|
||||
}
|
||||
}
|
||||
publish()
|
||||
publish(moving = true)
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
@@ -702,6 +707,7 @@ class SteamTouchControls(
|
||||
fun startEditing() {
|
||||
releaseAll()
|
||||
editing = true
|
||||
onEditingChanged?.invoke(true)
|
||||
editSets.clear()
|
||||
selected = -1
|
||||
pendingBindings.clear()
|
||||
@@ -752,8 +758,13 @@ class SteamTouchControls(
|
||||
actionSet = saved
|
||||
}
|
||||
|
||||
fun cancelEditing() {
|
||||
if (editing) stopEditing()
|
||||
}
|
||||
|
||||
private fun stopEditing() {
|
||||
editing = false
|
||||
onEditingChanged?.invoke(false)
|
||||
trayOpen = false
|
||||
trayDrag = null
|
||||
selected = -1
|
||||
@@ -1469,6 +1480,7 @@ class SteamTouchControls(
|
||||
companion object {
|
||||
private const val TAG = "SteamTouch"
|
||||
private const val POLL_MS = 150L
|
||||
private const val MOVE_REDRAW_MS = 33L
|
||||
const val BIG_PICTURE = 769
|
||||
private const val ICON_PX = 128
|
||||
private const val MARK_D = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z" +
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.view.View
|
||||
|
||||
internal class ThrottledRedraw(private val view: View, private val intervalMs: Long) {
|
||||
private var last = 0L
|
||||
private val redraw = Runnable {
|
||||
last = SystemClock.uptimeMillis()
|
||||
view.invalidate()
|
||||
}
|
||||
|
||||
fun request() {
|
||||
view.removeCallbacks(redraw)
|
||||
view.postDelayed(redraw, (last + intervalMs - SystemClock.uptimeMillis()).coerceAtLeast(0L))
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
view.removeCallbacks(redraw)
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ data class TouchGestureConfig(
|
||||
val showGestureDebugOverlay: Boolean = false,
|
||||
val gestureThreshold: Int = DEFAULT_GESTURE_THRESHOLD,
|
||||
val mouseDragMovementMode: String = MOUSE_DRAG_MOVEMENT_DIRECT,
|
||||
val relativeMouseMode: Int = RELATIVE_MOUSE_AUTO,
|
||||
) {
|
||||
|
||||
fun toJson(): String {
|
||||
@@ -75,6 +76,7 @@ data class TouchGestureConfig(
|
||||
put(KEY_SHOW_GESTURE_DEBUG_OVERLAY, showGestureDebugOverlay)
|
||||
put(KEY_GESTURE_THRESHOLD, gestureThreshold)
|
||||
put(KEY_MOUSE_DRAG_MOVEMENT_MODE, mouseDragMovementMode)
|
||||
put(KEY_RELATIVE_MOUSE_MODE, relativeMouseMode)
|
||||
}.toString()
|
||||
}
|
||||
|
||||
@@ -91,6 +93,10 @@ data class TouchGestureConfig(
|
||||
|
||||
const val MOUSE_DRAG_MOVEMENT_DIRECT = "direct"
|
||||
const val MOUSE_DRAG_MOVEMENT_RELATIVE = "relative"
|
||||
|
||||
const val RELATIVE_MOUSE_AUTO = 0
|
||||
const val RELATIVE_MOUSE_ON = 1
|
||||
const val RELATIVE_MOUSE_OFF = 2
|
||||
const val ACTION_SHOW_KEYBOARD = "show_keyboard"
|
||||
const val ACTION_KEY_ESC = "key_ESC"
|
||||
const val ACTION_KEY_TILDE = "key_TILDE"
|
||||
@@ -114,6 +120,7 @@ data class TouchGestureConfig(
|
||||
private const val KEY_LONG_PRESS_MOUSE_BEHAVIOR = "longPressMouseBehavior"
|
||||
private const val KEY_LONG_PRESS_DELAY = "longPressDelay"
|
||||
private const val KEY_DIRECT_HOLD_BEHAVIOR = "directHoldBehavior"
|
||||
private const val KEY_RELATIVE_MOUSE_MODE = "relativeMouseMode"
|
||||
private const val KEY_DOUBLE_TAP_ENABLED = "doubleTapEnabled"
|
||||
private const val KEY_DOUBLE_TAP_DELAY = "doubleTapDelay"
|
||||
private const val KEY_TWO_FINGER_DRAG_ENABLED = "twoFingerDragEnabled"
|
||||
@@ -191,6 +198,7 @@ data class TouchGestureConfig(
|
||||
mouseDragMovementMode = normalizeMouseDragMovementMode(
|
||||
obj.optString(KEY_MOUSE_DRAG_MOVEMENT_MODE, MOUSE_DRAG_MOVEMENT_DIRECT),
|
||||
),
|
||||
relativeMouseMode = normalizeRelativeMouseMode(obj.optInt(KEY_RELATIVE_MOUSE_MODE, RELATIVE_MOUSE_AUTO)),
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
fallbackDefaults()
|
||||
@@ -205,6 +213,10 @@ data class TouchGestureConfig(
|
||||
return if (value == MOUSE_BEHAVIOR_CLICK) MOUSE_BEHAVIOR_CLICK else MOUSE_BEHAVIOR_HOLD
|
||||
}
|
||||
|
||||
private fun normalizeRelativeMouseMode(mode: Int): Int {
|
||||
return if (mode in RELATIVE_MOUSE_AUTO..RELATIVE_MOUSE_OFF) mode else RELATIVE_MOUSE_AUTO
|
||||
}
|
||||
|
||||
private fun normalizeMouseDragMovementMode(mode: String?): String {
|
||||
return if (mode == MOUSE_DRAG_MOVEMENT_RELATIVE) {
|
||||
MOUSE_DRAG_MOVEMENT_RELATIVE
|
||||
|
||||
@@ -61,13 +61,18 @@ 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 }
|
||||
|
||||
private const val COVER_RETRY_MS = 24 * 3600_000L
|
||||
|
||||
internal fun artTitle(title: Title) = TITLES.firstOrNull { it.code == title.code } ?: title
|
||||
|
||||
private fun coverDir(context: Context, title: Title) =
|
||||
File(context.filesDir, "battlenet-art/${(TITLES.firstOrNull { it.code == title.code } ?: title).uid}")
|
||||
File(context.filesDir, "battlenet-art/${artTitle(title).uid}")
|
||||
|
||||
fun cover(context: Context, title: Title): File? = art(context, title).cover
|
||||
|
||||
@@ -79,7 +84,7 @@ object BattleNet {
|
||||
var got = false
|
||||
for (title in titles) {
|
||||
val dir = coverDir(context, title)
|
||||
val tried = File(dir, ".tried")
|
||||
val tried = File(dir, ".tried-2")
|
||||
val wide = File(dir, BLIZZARD)
|
||||
val done = File(dir, "p.jpg").isFile && (title.shop == null || wide.isFile)
|
||||
if (done || System.currentTimeMillis() - tried.lastModified() < COVER_RETRY_MS) continue
|
||||
@@ -87,11 +92,15 @@ object BattleNet {
|
||||
if (title.steam != null && runCatching { art.download(title.steam.toString(), dir) }.getOrDefault(false)) got = true
|
||||
if (title.shop != null && !wide.isFile) {
|
||||
val cover = File(dir, BLIZZARD_COVER).takeUnless { File(dir, "p.jpg").isFile }
|
||||
if (runCatching { com.droiddeck.launcher.stores.battlenet.BlizzardArt.fetch(title.shop, wide, cover) }
|
||||
.onFailure { Log.w(TAG, "Blizzard art for ${title.uid}: ${it.javaClass.simpleName}") }.getOrDefault(false)) got = true
|
||||
if (runCatching { com.droiddeck.launcher.stores.battlenet.BlizzardArt.fetch(title.code, title.shop, wide, cover) }
|
||||
.onFailure { Log.w(TAG, "Blizzard art for ${title.uid}: ${it.javaClass.simpleName}") }.getOrDefault(false)) {
|
||||
got = true
|
||||
File(dir, OLD_BLIZZARD).delete()
|
||||
File(dir, OLD_BLIZZARD_COVER).delete()
|
||||
}
|
||||
}
|
||||
if (!File(dir, "p.jpg").isFile && !File(dir, BLIZZARD_COVER).isFile && key.isNotEmpty()) {
|
||||
val id = runCatching { com.droiddeck.launcher.frontend.SteamGridDb.gameId(key, title.steam, title.name) }.getOrNull()
|
||||
val id = runCatching { com.droiddeck.launcher.frontend.SteamGridDb.exactGameId(key, title.steam, title.name) }.getOrNull()
|
||||
if (id != null && runCatching { com.droiddeck.launcher.frontend.SteamGridDb.download(key, id, dir) }.getOrDefault(false)) got = true
|
||||
}
|
||||
runCatching { tried.writeText("") ; tried.setLastModified(System.currentTimeMillis()) }
|
||||
@@ -111,13 +120,15 @@ object BattleNet {
|
||||
|
||||
class Art(val cover: File?, val header: File?)
|
||||
|
||||
private const val BLIZZARD = "blizzard.jpg"
|
||||
private const val BLIZZARD_COVER = "p-blizzard.jpg"
|
||||
private const val BLIZZARD = "blizzard-2.jpg"
|
||||
private const val BLIZZARD_COVER = "p-blizzard-2.jpg"
|
||||
private const val OLD_BLIZZARD = "blizzard.jpg"
|
||||
private const val OLD_BLIZZARD_COVER = "p-blizzard.jpg"
|
||||
|
||||
fun art(context: Context, title: Title): Art {
|
||||
val dir = coverDir(context, title)
|
||||
fun first(vararg names: String) = names.map { File(dir, it) }.firstOrNull { it.isFile }
|
||||
return Art(first("p.jpg", BLIZZARD_COVER), first(BLIZZARD, "header.jpg"))
|
||||
return Art(first("p.jpg", BLIZZARD_COVER, OLD_BLIZZARD_COVER), first(BLIZZARD, OLD_BLIZZARD, "header.jpg"))
|
||||
}
|
||||
|
||||
fun prefix(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/compatdata/$APP_ID")
|
||||
@@ -156,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? {
|
||||
|
||||
@@ -200,6 +200,7 @@ object BwrapSpawner {
|
||||
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
|
||||
|
||||
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
|
||||
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
|
||||
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
|
||||
if (driver == null || !File("/dev/kgsl-3d0").exists()) return null
|
||||
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
|
||||
@@ -222,6 +223,28 @@ object BwrapSpawner {
|
||||
return binds
|
||||
}
|
||||
|
||||
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? {
|
||||
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so")
|
||||
if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
|
||||
val binds = ArrayList<Bind>()
|
||||
binds.add(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_droidbridge.so"))
|
||||
val sockDir = File(socket).parent ?: return null
|
||||
binds.add(Bind(sockDir, sockDir))
|
||||
val icd = File(root.parentFile, "vkbridge_icd.json")
|
||||
val api = runCatching {
|
||||
JSONObject(File(rootfs, "usr/local/share/vkbridge/droidbridge_icd.json").readText()).getJSONObject("ICD").getString("api_version")
|
||||
}.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null }
|
||||
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n")
|
||||
binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json"))
|
||||
env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
|
||||
env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json"
|
||||
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
|
||||
env["MESA_LOADER_DRIVER_OVERRIDE"] = "zink"
|
||||
env["GALLIUM_DRIVER"] = "zink"
|
||||
}
|
||||
return binds
|
||||
}
|
||||
|
||||
private fun preload(session: List<Bind>, rootfs: String, env: MutableMap<String, String>): List<Bind> {
|
||||
val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
|
||||
?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: return emptyList()
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
@@ -39,15 +40,16 @@ object DesktopLanguage {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (!DesktopCatalog.desktopInstalled(root)) return true
|
||||
val entry = DesktopCatalog.desktopEntry(context)
|
||||
val pending = candidates(locale).filterNot { marker(root, entry.version, it).isFile }
|
||||
val tag = "${entry.version}-${BuildConfig.DESKTOP_KDE_TAG}"
|
||||
val pending = candidates(locale).filterNot { marker(root, tag, it).isFile }
|
||||
if (pending.isEmpty()) return true
|
||||
val base = baseUrl(entry.url)
|
||||
val base = baseUrl(BuildConfig.DESKTOP_KDE_URL)
|
||||
val index = parseIndex(Downloader.downloadString(base + INDEX) ?: return false)
|
||||
var complete = true
|
||||
for (name in pending) {
|
||||
val pack = index[name]
|
||||
if (pack == null) {
|
||||
FileUtils.writeString(marker(root, entry.version, name), ABSENT)
|
||||
FileUtils.writeString(marker(root, tag, name), ABSENT)
|
||||
continue
|
||||
}
|
||||
val download = File(context.cacheDir, "i18n-$name-${pack.sha256.take(12)}.download")
|
||||
@@ -56,7 +58,7 @@ object DesktopLanguage {
|
||||
base + "desktop-kde-i18n-$name.tar.zst", download, true, pack.sha256, java.util.function.Consumer<Float> { },
|
||||
) && pack.sha256.equals(Hashes.sha256(download), ignoreCase = true) &&
|
||||
LinuxRuntimeInstaller.extract(context, download, root, null)
|
||||
if (ok) FileUtils.writeString(marker(root, entry.version, name), pack.sha256) else complete = false
|
||||
if (ok) FileUtils.writeString(marker(root, tag, name), pack.sha256) else complete = false
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "language pack $name: $e")
|
||||
complete = false
|
||||
|
||||
@@ -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 {
|
||||
@@ -251,12 +249,36 @@ class LinuxNetworkLinkComponent(
|
||||
}
|
||||
}
|
||||
|
||||
private fun localDnsServers(): Pair<List<String>, List<String>> {
|
||||
val active = connectivity.activeNetwork?.let { connectivity.getNetworkCapabilities(it) }
|
||||
if (active?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true) return Pair(emptyList(), emptyList())
|
||||
val servers = LinkedHashSet<String>()
|
||||
val gateways = LinkedHashSet<String>()
|
||||
for (network in connectivity.allNetworks) {
|
||||
val capabilities = connectivity.getNetworkCapabilities(network) ?: continue
|
||||
if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) continue
|
||||
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
|
||||
!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) continue
|
||||
val link = connectivity.getLinkProperties(network) ?: continue
|
||||
for (address in link.dnsServers) {
|
||||
if (address.isLinkLocalAddress || address.isLoopbackAddress || address.isAnyLocalAddress) continue
|
||||
address.hostAddress?.substringBefore('%')?.let { servers.add(it) }
|
||||
}
|
||||
link.routes.firstOrNull {
|
||||
it.isDefaultRoute && (it.gateway as? Inet4Address)?.let { g -> !g.isLoopbackAddress && !g.isAnyLocalAddress } == true
|
||||
}?.gateway?.hostAddress?.substringBefore('%')?.let { gateways.add(it) }
|
||||
}
|
||||
val order = compareBy<String>({ if (it.contains(':')) 1 else 0 })
|
||||
return Pair(servers.sortedWith(order), gateways.sortedWith(order))
|
||||
}
|
||||
|
||||
private fun writeResolver(properties: LinkProperties?) {
|
||||
val own = properties?.dnsServers.orEmpty()
|
||||
.filter { !it.isLinkLocalAddress && !it.isLoopbackAddress && !it.isAnyLocalAddress }
|
||||
.sortedBy { if (it is Inet4Address) 0 else 1 }
|
||||
.mapNotNull { it.hostAddress?.substringBefore('%') }
|
||||
val servers = (own + listOf("8.8.8.8", "1.1.1.1", "2001:4860:4860::8888")).distinct().take(6)
|
||||
val (discovered, gateways) = localDnsServers()
|
||||
val servers = (own + discovered + listOf("8.8.8.8", "1.1.1.1", "2001:4860:4860::8888") + gateways).distinct().take(6)
|
||||
val text = buildString {
|
||||
append("# Written by the app from the device's active network; edits are overwritten.\n")
|
||||
for (server in servers) append("nameserver $server\n")
|
||||
@@ -277,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
|
||||
@@ -292,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")
|
||||
}
|
||||
}
|
||||
@@ -305,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;
|
||||
|
||||
|
||||
@@ -26,6 +27,7 @@ public final class LinuxRuntime {
|
||||
public static final String EXTRA_LINUX_MODE = "linux_mode";
|
||||
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
|
||||
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
|
||||
public static final String GUEST_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games";
|
||||
private static final String SYSTEM_FONTS = "/system/fonts";
|
||||
private static final String GUEST_SYSTEM_FONTS = "/usr/local/share/fonts/android";
|
||||
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
||||
@@ -190,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");
|
||||
@@ -197,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());
|
||||
@@ -258,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) {
|
||||
@@ -269,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;
|
||||
@@ -278,10 +313,43 @@ public final class LinuxRuntime {
|
||||
return false;
|
||||
}
|
||||
|
||||
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",
|
||||
};
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
static String bridgeStandIn(java.util.function.Predicate<String> exists) {
|
||||
if (exists.test(MALI_DEVICE)) return MALI_DEVICE;
|
||||
for (String node : DRM_RENDER_NODES) if (exists.test(node)) return node;
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String deviceNumbers(String path) {
|
||||
try {
|
||||
long dev = Os.stat(path).st_rdev;
|
||||
long major = ((dev >> 8) & 0xfff) | ((dev >> 32) & ~0xfffL);
|
||||
long minor = (dev & 0xff) | ((dev >> 12) & ~0xffL);
|
||||
return major + ":" + minor;
|
||||
} catch (ErrnoException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void bindGpuNode(Context context, List<String> cmd) {
|
||||
String standIn = gpuStandIn(context);
|
||||
if (standIn == null) return;
|
||||
boolean kgsl = standIn.equals(KGSL_DEVICE);
|
||||
StructStat st;
|
||||
try {
|
||||
st = Os.stat(KGSL_DEVICE);
|
||||
st = Os.stat(standIn);
|
||||
} catch (ErrnoException e) {
|
||||
return;
|
||||
}
|
||||
@@ -301,13 +369,14 @@ public final class LinuxRuntime {
|
||||
Files.write(new File(drm, "dev").toPath(),
|
||||
(major + ":" + minor + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
Files.write(new File(device, "uevent").toPath(),
|
||||
"DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n".getBytes(StandardCharsets.UTF_8));
|
||||
(kgsl ? "DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n" : "DRIVER=mali\nMODALIAS=platform:mali\n")
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
File subsystem = new File(device, "subsystem");
|
||||
if (!Files.isSymbolicLink(subsystem.toPath())) {
|
||||
Os.symlink("/sys/bus/platform", subsystem.getPath());
|
||||
}
|
||||
File driver = new File(device, "driver");
|
||||
if (!Files.isSymbolicLink(driver.toPath())) {
|
||||
if (kgsl && !Files.isSymbolicLink(driver.toPath())) {
|
||||
Os.symlink("/sys/bus/platform/drivers/msm_drm", driver.getPath());
|
||||
}
|
||||
} catch (IOException | ErrnoException e) {
|
||||
@@ -315,7 +384,7 @@ public final class LinuxRuntime {
|
||||
}
|
||||
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
|
||||
bind(cmd, dri.getPath() + ":/dev/dri");
|
||||
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
|
||||
bind(cmd, standIn + ":/dev/dri/" + node);
|
||||
bindDrmClass(base, cmd, node, major + ":" + minor);
|
||||
}
|
||||
|
||||
|
||||
@@ -130,7 +130,8 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
if (!owner) return join(job, listener);
|
||||
try {
|
||||
job.ok = installOnce(context.getApplicationContext(), release, new ProgressListener() {
|
||||
Context app = context.getApplicationContext();
|
||||
ProgressListener progress = new ProgressListener() {
|
||||
@Override public void onProgress(String stage, int percent) {
|
||||
onProgress(Step.OTHER, stage, percent);
|
||||
}
|
||||
@@ -141,7 +142,10 @@ public final class LinuxRuntimeInstaller {
|
||||
job.percent = percent;
|
||||
for (ProgressListener l : job.listeners) l.onProgress(step, stage, percent);
|
||||
}
|
||||
});
|
||||
};
|
||||
boolean desktop = DesktopCatalog.INSTANCE.desktopInstalled(app);
|
||||
job.ok = installOnce(app, release, progress);
|
||||
if (job.ok && desktop) keepDesktop(app, progress);
|
||||
return job.ok;
|
||||
} finally {
|
||||
synchronized (JOB_LOCK) {
|
||||
@@ -151,6 +155,28 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
private static void keepDesktop(Context context, ProgressListener progress) {
|
||||
String problem;
|
||||
try {
|
||||
problem = DesktopCatalog.INSTANCE.install(context, DesktopCatalog.INSTANCE.desktopEntry(context), progress);
|
||||
} catch (RuntimeException e) {
|
||||
problem = e.toString();
|
||||
}
|
||||
if (problem == null) {
|
||||
Log.i(TAG, "desktop installed again for the new runtime");
|
||||
return;
|
||||
}
|
||||
Log.w(TAG, "desktop not installed again for the new runtime: " + problem);
|
||||
boolean started = false;
|
||||
for (DesktopCatalog.Entry entry : DesktopCatalog.INSTANCE.interrupted(context)) {
|
||||
if (DesktopCatalog.DESKTOP_ID.equals(entry.getId())) started = true;
|
||||
}
|
||||
if (!started) return;
|
||||
String undone = DesktopCatalog.INSTANCE.removeDesktop(context, progress);
|
||||
if (undone == null) Log.i(TAG, "rolled back the partial desktop install");
|
||||
else Log.w(TAG, "could not roll back the partial desktop install: " + undone);
|
||||
}
|
||||
|
||||
public static boolean isInstalling() {
|
||||
synchronized (JOB_LOCK) {
|
||||
return running != null && !running.removal && !running.maintenance;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
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
|
||||
@@ -198,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) }
|
||||
@@ -637,34 +643,47 @@ object ComponentsManager {
|
||||
return PreparedLaunchState(lines.toString(), keep)
|
||||
}
|
||||
|
||||
internal fun runtimeManaged(comp: String, systemPowerVr: Boolean): Boolean = comp == "dxvk" && systemPowerVr
|
||||
|
||||
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
|
||||
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))
|
||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
|
||||
.apply { if (auto) put("auto", true) })
|
||||
saveState(context, state)
|
||||
return context.getString(R.string.cmgr_swap_queued, LABEL[info.comp], info.version, p.name)
|
||||
}
|
||||
applyPackage(context, p, info, wcp, state)
|
||||
applyPackage(context, p, info, wcp, state, auto)
|
||||
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
|
||||
saveState(context, state)
|
||||
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
||||
}
|
||||
|
||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
|
||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
|
||||
ensureOriginal(context, p, info.comp, state)
|
||||
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
||||
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
||||
.put("file", wcp.name).put("label", info.version).put("protonVersion", p.version)
|
||||
.put("files", JSONObject(hashes.filterKeys { owned(info.comp, it) } as Map<*, *>))
|
||||
.put("at", System.currentTimeMillis() / 1000))
|
||||
.put("at", System.currentTimeMillis() / 1000)
|
||||
.apply { if (auto) put("auto", true) })
|
||||
Log.i(TAG, "swapped ${info.comp} ${info.version} into ${p.name} ${p.version}")
|
||||
}
|
||||
|
||||
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) }
|
||||
@@ -690,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()
|
||||
@@ -702,13 +724,14 @@ 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")
|
||||
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
|
||||
} else {
|
||||
val wcp = File(packagesDir(context), q.optString("file"))
|
||||
applyPackage(context, p, packageInfo(context, wcp), wcp, state)
|
||||
applyPackage(context, p, packageInfo(context, wcp), wcp, state, q.optBoolean("auto"))
|
||||
}
|
||||
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
|
||||
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
|
||||
@@ -1011,15 +1034,76 @@ object ComponentsManager {
|
||||
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
|
||||
activeFile.isNullOrEmpty() || !protonVersionMatches
|
||||
|
||||
internal fun bridgeDxvk(vk: AppVulkan?): ForcedPackage? = when {
|
||||
vk == null -> null
|
||||
!vk.atLeast(1, 1) -> null
|
||||
!vk.atLeast(1, 3) -> ForcedPackage(emptySet(), "dxvk", DXVK_FOR_VULKAN_1_1, "Dxvk-Linux")
|
||||
vk.shaderInt64 == false || (vk.maxPushConstants ?: 256) < 256 ->
|
||||
ForcedPackage(emptySet(), "dxvk", DXVK_FOR_VULKAN_1_3_NO_INT64, "Dxvk-Linux")
|
||||
else -> null
|
||||
}
|
||||
|
||||
internal const val DXVK_FOR_VULKAN_1_1 = "dxvk-1.10.3-linux.wcp"
|
||||
internal const val DXVK_FOR_VULKAN_1_3_NO_INT64 = "dxvk-2.6.2-linux.wcp"
|
||||
|
||||
internal fun autoDxvkUndoWanted(bridgeSession: Boolean, keepProtonDxvk: Boolean, vulkan: AppVulkan?, bridgeRule: ForcedPackage?): Boolean =
|
||||
!bridgeSession || keepProtonDxvk || (vulkan != null && bridgeRule == null)
|
||||
|
||||
private fun dropQueuedAuto(context: Context, installed: List<Proton>) = synchronized(lock) {
|
||||
val state = loadState(context)
|
||||
var changed = false
|
||||
for (p in installed) {
|
||||
val q = state.optJSONObject("queued")?.optJSONObject(p.id) ?: continue
|
||||
if (q.optJSONObject("dxvk")?.optBoolean("auto") == true) { q.remove("dxvk"); changed = true }
|
||||
}
|
||||
if (changed) saveState(context, state)
|
||||
}
|
||||
|
||||
internal fun autoChoiceStale(entry: JSONObject?, wantedFile: String?): Boolean =
|
||||
entry != null && entry.optBoolean("auto") && entry.optString("file") != wantedFile
|
||||
|
||||
internal fun catalogMatch(items: List<CatalogItem>, file: String, release: String): CatalogItem? =
|
||||
items.firstOrNull { it.file == file && it.release == release }
|
||||
|
||||
fun ensureForcedPackages(context: Context): String? = ensureForcedPackages(
|
||||
private val forcedLock = Any()
|
||||
|
||||
fun ensureForcedPackages(context: Context): String? = synchronized(forcedLock) { ensureForcedPackages(
|
||||
context, GpuInfo.detect(),
|
||||
{ file, release -> catalogItem(context, file, release) },
|
||||
{ download(context, it) {} },
|
||||
{ id, file -> swap(context, id, file) },
|
||||
)
|
||||
vulkan = AppVulkan.detect(context),
|
||||
bridgeSession = com.droiddeck.launcher.core.DeviceSupport.vkBridge(context),
|
||||
applyAuto = { id, file -> swap(context, id, file, auto = true) },
|
||||
undoAuto = { id, comp -> undoAutoChoice(context, id, comp) },
|
||||
keepProtonDxvk = SessionPrefs.bridgeProtonDxvk(context),
|
||||
autoPossible = !com.droiddeck.launcher.core.DeviceSupport.adreno(),
|
||||
) }
|
||||
|
||||
fun settleAutoDxvk(context: Context) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
runCatching { ensureForcedPackages(app) }
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
.onFailure { Log.w(TAG, "automatic DXVK", it) }
|
||||
}, "auto-dxvk").start()
|
||||
}
|
||||
|
||||
internal fun undoAutoChoice(context: Context, protonId: String, comp: String): String = synchronized(lock) {
|
||||
val p = proton(context, protonId)
|
||||
val state = loadState(context)
|
||||
val entry = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
||||
val sameProton = entry?.optString("protonVersion") == p.version
|
||||
if (sameProton && originalFile(context, p, comp).isFile)
|
||||
return restore(context, protonId, comp, safeName(p.version))
|
||||
if (sameProton) {
|
||||
Log.w(TAG, "${p.name}: its own ${LABEL[comp]} copy is gone; keeping ${entry?.optString("label")}")
|
||||
return "${LABEL[comp]}: ${p.name} keeps ${entry?.optString("label")} (its own copy is gone)"
|
||||
}
|
||||
state.sub("active").optJSONObject(p.id)?.remove(comp)
|
||||
saveState(context, state)
|
||||
"${LABEL[comp]}: ${p.name} keeps its own copy"
|
||||
}
|
||||
|
||||
internal fun ensureForcedPackages(
|
||||
context: Context,
|
||||
@@ -1027,16 +1111,35 @@ object ComponentsManager {
|
||||
lookup: (file: String, release: String) -> CatalogItem?,
|
||||
fetch: (CatalogItem) -> Unit,
|
||||
apply: (protonId: String, file: String) -> String,
|
||||
vulkan: AppVulkan? = null,
|
||||
bridgeSession: Boolean = false,
|
||||
applyAuto: (protonId: String, file: String) -> String = apply,
|
||||
undoAuto: (protonId: String, comp: String) -> String = { _, _ -> "" },
|
||||
keepProtonDxvk: Boolean = false,
|
||||
autoPossible: Boolean = true,
|
||||
): String? {
|
||||
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }
|
||||
if (rules.isEmpty()) return null
|
||||
val chooseDxvk = bridgeSession && !keepProtonDxvk
|
||||
val bridgeRule = if (chooseDxvk) bridgeDxvk(vulkan) else null
|
||||
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }.map { it to false } + listOfNotNull(bridgeRule?.let { it to true })
|
||||
if (rules.isEmpty() && !autoPossible) return null
|
||||
val installed = protons(context)
|
||||
val lines = mutableListOf<String>()
|
||||
for (rule in rules) {
|
||||
fun each(p: Proton, what: () -> String): String =
|
||||
runCatching(what).getOrElse { e -> Log.w(TAG, "${p.name}: ${e.message}", e); "${p.name}: ${e.message ?: e.javaClass.simpleName}" }
|
||||
if (autoPossible && autoDxvkUndoWanted(bridgeSession, keepProtonDxvk, vulkan, bridgeRule)) {
|
||||
dropQueuedAuto(context, installed)
|
||||
val state = loadState(context)
|
||||
for (p in installed) {
|
||||
val entry = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject("dxvk")
|
||||
if (autoChoiceStale(entry, null)) lines.add(each(p) { undoAuto(p.id, "dxvk") })
|
||||
}
|
||||
}
|
||||
for ((rule, auto) in rules) {
|
||||
val state = loadState(context)
|
||||
val targets = installed.filter { p ->
|
||||
val active = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject(rule.comp)
|
||||
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version)
|
||||
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version) ||
|
||||
(auto && autoChoiceStale(active, rule.file))
|
||||
}
|
||||
if (targets.isEmpty()) continue
|
||||
val missing = missingPackage(context, rule, lookup, fetch)
|
||||
@@ -1044,9 +1147,10 @@ object ComponentsManager {
|
||||
lines.add(missing)
|
||||
continue
|
||||
}
|
||||
lines.add(targets.joinToString("; ") { apply(it.id, rule.file) })
|
||||
if (auto) lines.add("${vulkan?.label}: DXVK ${rule.file}")
|
||||
lines.add(targets.joinToString("; ") { p -> if (auto) each(p) { applyAuto(p.id, rule.file) } else apply(p.id, rule.file) })
|
||||
}
|
||||
return lines.joinToString("; ").ifEmpty { null }
|
||||
return lines.filter { it.isNotEmpty() }.joinToString("; ").ifEmpty { null }
|
||||
}
|
||||
|
||||
private fun missingPackage(
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
}
|
||||
pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
|
||||
refresh()
|
||||
createMissing(feeds.map { it.file })
|
||||
describeSources()
|
||||
Log.i(TAG, "hud: kgsl stats from the session's own: $sources")
|
||||
true
|
||||
@@ -354,6 +355,10 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
|
||||
fun guestLoadDir(root: File) = File(root, GUEST_LOAD_DIR.removePrefix("/"))
|
||||
|
||||
// A feed with no value yet (the HUD hidden at start) still needs its file, or binds() leaves its node out for
|
||||
// the whole session.
|
||||
internal fun createMissing(files: List<File>) = files.forEach { runCatching { it.createNewFile() } }
|
||||
|
||||
/** True when this app can see kgsl but none of its GPU load nodes (SELinux-blocked, e.g. the Retroid Pocket Duo). */
|
||||
fun loadBlocked(): Boolean = File(KGSL).exists() && !File(GPUBUSY).canRead() && LOAD_SOURCES.none { File(it).canRead() }
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -4,7 +4,7 @@ import java.io.File
|
||||
|
||||
object OverlayShown {
|
||||
fun check(root: File): Boolean {
|
||||
val config = File(root, "tmp").listFiles { f -> f.name.startsWith("mangohud.") }
|
||||
val config = File(root, "tmp").listFiles { f -> f.name.startsWith("mangohud.") || f.name == "droiddeck-mangohud.conf" }
|
||||
?.maxByOrNull { it.lastModified() } ?: return false
|
||||
return runCatching { !config.readText().contains("no_display") }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -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,18 +169,31 @@ 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",
|
||||
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"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
|
||||
|
||||
@@ -348,6 +350,41 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
|
||||
}
|
||||
|
||||
const val PC_KEYBOARD_SIZE_DEFAULT = 47
|
||||
const val WOW_CHAT_VOICE = "voice"
|
||||
const val WOW_CHAT_KEYBOARD = "keyboard"
|
||||
val PC_KEYBOARD_SIZE_RANGE = 25..70
|
||||
const val PC_KEYBOARD_OPACITY_DEFAULT = 100
|
||||
val PC_KEYBOARD_OPACITY_RANGE = 30..100
|
||||
|
||||
fun pcKeyboardSize(context: Context): Int =
|
||||
prefs(context).getInt("pcKeyboardSize", PC_KEYBOARD_SIZE_DEFAULT).takeIf { it in PC_KEYBOARD_SIZE_RANGE } ?: PC_KEYBOARD_SIZE_DEFAULT
|
||||
|
||||
fun setPcKeyboardSize(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("pcKeyboardSize", percent.coerceIn(PC_KEYBOARD_SIZE_RANGE)).apply()
|
||||
}
|
||||
|
||||
fun wowChatInput(context: Context): String? =
|
||||
prefs(context).getString("wowChatInput", null)?.takeIf { it == WOW_CHAT_VOICE || it == WOW_CHAT_KEYBOARD }
|
||||
|
||||
fun setWowChatInput(context: Context, mode: String?) {
|
||||
prefs(context).edit().apply { if (mode == null) remove("wowChatInput") else putString("wowChatInput", mode) }.apply()
|
||||
}
|
||||
|
||||
fun pcKeyboardOpacity(context: Context): Int =
|
||||
prefs(context).getInt("pcKeyboardOpacity", PC_KEYBOARD_OPACITY_DEFAULT).takeIf { it in PC_KEYBOARD_OPACITY_RANGE } ?: PC_KEYBOARD_OPACITY_DEFAULT
|
||||
|
||||
fun setPcKeyboardOpacity(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("pcKeyboardOpacity", percent.coerceIn(PC_KEYBOARD_OPACITY_RANGE)).apply()
|
||||
}
|
||||
|
||||
fun pcKeyboardHiddenKeys(context: Context): Set<String> =
|
||||
idList(prefs(context).getString("pcKeyboardHiddenKeys", null)).toSet()
|
||||
|
||||
fun setPcKeyboardHiddenKeys(context: Context, hidden: Set<String>) {
|
||||
prefs(context).edit().putString("pcKeyboardHiddenKeys", hidden.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
fun droidDeckHudConfig(context: Context): String? = prefs(context).getString("__KEEP_droidDeckHud__", null)
|
||||
|
||||
fun setDroidDeckHudConfig(context: Context, config: String) {
|
||||
@@ -478,6 +515,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()
|
||||
|
||||
@@ -746,6 +794,84 @@ object SessionPrefs {
|
||||
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
|
||||
@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).putBoolean("bridgeFellBack", false).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun bridgeProtonDxvk(context: Context): Boolean = prefs(context).getBoolean("bridgeProtonDxvk", false)
|
||||
|
||||
fun setBridgeProtonDxvk(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("bridgeProtonDxvk", on).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun vkBridgeSafe(context: Context): Boolean = prefs(context).getBoolean("vkBridgeSafe", true)
|
||||
|
||||
fun setVkBridgeSafe(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("vkBridgeSafe", on).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun vkBridgeMode(context: Context): String = if (vkBridgeSafe(context)) "safe" else "performance"
|
||||
|
||||
fun setZinkLazy(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("zinkLazy", on).apply()
|
||||
}
|
||||
@@ -775,7 +901,7 @@ object SessionPrefs {
|
||||
key = "logs",
|
||||
oldValue = logsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
|
||||
newEffective = gameDebugLogsEffective(context, on, gameDebugLogsEnabled(context)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -788,7 +914,7 @@ object SessionPrefs {
|
||||
key = "gameDebugLogsEnabled",
|
||||
oldValue = gameDebugLogsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
|
||||
newEffective = gameDebugLogsEffective(context, logsEnabled(context), on),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -801,8 +927,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
|
||||
@@ -838,6 +963,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
|
||||
@@ -372,9 +373,10 @@ class SessionService : Service() {
|
||||
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
|
||||
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
|
||||
synchronized(stopLock) {
|
||||
val gen = synchronized(stopLock) {
|
||||
SessionState.steamClientArch = null
|
||||
SessionState.running = true
|
||||
++sessionGen
|
||||
}
|
||||
if (SessionState.stopRequested) {
|
||||
stopSession(0)
|
||||
@@ -385,7 +387,6 @@ class SessionService : Service() {
|
||||
SessionState.guestPid = -1
|
||||
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
|
||||
com.droiddeck.launcher.wayland.CompositorHost.newSession()
|
||||
val gen = ++sessionGen
|
||||
SessionPrefs.backgroundAppLimit(this).takeIf { it != com.droiddeck.launcher.core.BackgroundAppLimit.OFF }
|
||||
?.let { com.droiddeck.launcher.core.BackgroundAppLimit.applyAsync(this, it) }
|
||||
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
|
||||
@@ -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,13 +452,20 @@ 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 {
|
||||
LinuxRuntime.writeAccounts(this)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not write the guest's passwd/group", e)
|
||||
stopSession(-1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -468,15 +501,29 @@ class SessionService : Service() {
|
||||
} else {
|
||||
val message = getString(R.string.session_proot_missing)
|
||||
Log.e(TAG, "$message (pack ready=$prootPack)")
|
||||
SessionEvents.fail("PROOT_MISSING", message, -1)
|
||||
stopSession(-1)
|
||||
failSession(gen, "PROOT_MISSING", message, -1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
}
|
||||
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)
|
||||
@@ -489,7 +536,7 @@ class SessionService : Service() {
|
||||
GameEnvironmentStore.publish(this)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not publish the game environment", e)
|
||||
stopSession(-1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
@@ -512,17 +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)
|
||||
}
|
||||
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)
|
||||
@@ -539,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()
|
||||
@@ -568,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")
|
||||
@@ -587,7 +654,7 @@ class SessionService : Service() {
|
||||
val program = SessionState.program
|
||||
if (program.isNullOrEmpty()) {
|
||||
Log.e(TAG, "run mode without a program")
|
||||
stopSession(65)
|
||||
stopSession(65, gen)
|
||||
return
|
||||
}
|
||||
guest.add(program)
|
||||
@@ -667,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(" ", "\\ ")
|
||||
@@ -682,7 +756,7 @@ class SessionService : Service() {
|
||||
}
|
||||
val program = programStatus(sessionRoot)
|
||||
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
|
||||
stopSession(program ?: status ?: -1)
|
||||
stopSession(program ?: status ?: -1, gen)
|
||||
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() })
|
||||
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
|
||||
if (gen != sessionGen || !SessionState.running) {
|
||||
@@ -704,8 +778,8 @@ class SessionService : Service() {
|
||||
SessionEvents.guestStarted(pid)
|
||||
} else {
|
||||
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
|
||||
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", pid)
|
||||
stopSession(-1)
|
||||
failSession(gen, "GUEST_START_FAILED", "The guest process could not be started", pid)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
if (gen == sessionGen && SessionState.running) {
|
||||
@@ -767,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"))
|
||||
@@ -774,13 +849,19 @@ class SessionService : Service() {
|
||||
return sessionDir
|
||||
}
|
||||
|
||||
private fun relativeMouseForSession(): Int {
|
||||
val game = if (SessionState.mode == MODE_RUN) SessionState.program?.let { "program:$it" }
|
||||
else SessionState.gameId?.toLongOrNull()?.toString()
|
||||
return com.droiddeck.launcher.input.GesturePrefs.read(this, game).relativeMouseMode
|
||||
}
|
||||
|
||||
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) {
|
||||
guest.add("/usr/bin/env")
|
||||
guest.add("-i")
|
||||
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
|
||||
guest.add("HOME=/root")
|
||||
guest.add("USER=root")
|
||||
guest.add("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games")
|
||||
guest.add("PATH=" + LinuxRuntime.GUEST_PATH)
|
||||
guest.add("TERM=xterm-256color")
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
val appLocale = com.droiddeck.launcher.core.AppLanguage.effective(this)
|
||||
@@ -803,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(
|
||||
@@ -812,11 +898,39 @@ class SessionService : Service() {
|
||||
?: SessionPrefs.androidDriver(this),
|
||||
linuxDriverId,
|
||||
)
|
||||
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")
|
||||
@@ -845,6 +959,7 @@ class SessionService : Service() {
|
||||
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
|
||||
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
|
||||
if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1")
|
||||
relativeMouseForSession().takeIf { it != 0 }?.let { guest.add("gamescope_relative_mouse=$it") }
|
||||
if (com.droiddeck.launcher.core.ZramSupport.supported()) {
|
||||
guest.add("BL_ZRAM=1")
|
||||
if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_RAM_CAP_MB=$it") }
|
||||
@@ -864,6 +979,26 @@ class SessionService : Service() {
|
||||
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
|
||||
}
|
||||
|
||||
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)
|
||||
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))
|
||||
LinuxRuntime.gpuStandIn(this)?.let { node ->
|
||||
guest.add("BL_DRM_STANDIN=$node")
|
||||
LinuxRuntime.deviceNumbers(node)?.let { guest.add("VKBRIDGE_DRM_RENDER=$it") }
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -1803,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 {
|
||||
@@ -1866,11 +2007,22 @@ class SessionService : Service() {
|
||||
}, "tracer-priority").start()
|
||||
}
|
||||
|
||||
private fun stopSession(status: Int) {
|
||||
cancelQueuedSteamGame()
|
||||
gameExitWatchToken++
|
||||
private fun failSession(gen: Int, code: String, message: String, status: Int?) {
|
||||
synchronized(stopLock) {
|
||||
if (gen == sessionGen) SessionEvents.fail(code, message, status)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopSession(status: Int, gen: Int? = null) {
|
||||
if (gen != null && gen != sessionGen) {
|
||||
Log.i(TAG, "ignoring a stop from session $gen; session $sessionGen is current")
|
||||
return
|
||||
}
|
||||
completeNativeSleep()
|
||||
val (ended, endedArch) = synchronized(stopLock) {
|
||||
if (gen != null && gen != sessionGen) return
|
||||
cancelQueuedSteamGame()
|
||||
gameExitWatchToken++
|
||||
if (!SessionState.running) return
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
|
||||
@@ -1931,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)
|
||||
|
||||
@@ -17,12 +17,12 @@ object SettingsReset {
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition", "railLabels",
|
||||
"stretch16x9", "picturePosition", "railLabels", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"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",
|
||||
|
||||
@@ -126,8 +126,23 @@ object SteamLibraries {
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun gameCount(library: File): Int =
|
||||
File(library, "steamapps").list()?.count { it.startsWith("appmanifest_") && it.endsWith(".acf") } ?: 0
|
||||
internal fun gameCount(library: File): Int {
|
||||
val steamapps = File(library, "steamapps")
|
||||
val manifests = steamapps.list()?.count { it.startsWith("appmanifest_") && it.endsWith(".acf") } ?: return 0
|
||||
return manifests + depotInstalls(File(steamapps, "common")).size
|
||||
}
|
||||
|
||||
/** Finished downloads another client left without a Steam manifest; the importer registers them from depot.config. */
|
||||
fun depotInstalls(common: File): List<File> {
|
||||
val managed = AddedGames.steamInstallDirs(common)
|
||||
return common.listFiles { f ->
|
||||
f.isDirectory && f.name.lowercase() !in managed &&
|
||||
File(f, ".download_complete").isFile && depotRecord(File(f, ".DepotDownloader"))
|
||||
}.orEmpty().sortedBy { it.name.lowercase() }
|
||||
}
|
||||
|
||||
private fun depotRecord(dir: File): Boolean = File(dir, "depot.config").isFile ||
|
||||
File(dir, "completed").list()?.any { it.matches(Regex("\\d+_\\d+\\.manifest")) } == true
|
||||
|
||||
fun rename(context: Context, id: String, label: String) {
|
||||
val name = clean(label).takeIf { it.isNotEmpty() } ?: return
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -11,6 +11,8 @@ class StoreGameSidecar(
|
||||
val title: String,
|
||||
val exe: String,
|
||||
val launcher: String? = null,
|
||||
/** The working directory a store's launch task asks for: "" is the game folder, null means the exe's folder. */
|
||||
val workdir: String? = null,
|
||||
val args: List<String> = emptyList(),
|
||||
val env: Map<String, String> = emptyMap(),
|
||||
val installVersion: String = "",
|
||||
@@ -30,12 +32,12 @@ class StoreGameSidecar(
|
||||
fun launcherFile(folder: File): File? = launcher?.takeIf { it.isNotEmpty() }?.let { File(folder, it) }
|
||||
|
||||
fun copy(
|
||||
exe: String = this.exe, launcher: String? = this.launcher, args: List<String> = this.args,
|
||||
exe: String = this.exe, launcher: String? = this.launcher, workdir: String? = this.workdir, args: List<String> = this.args,
|
||||
env: Map<String, String> = this.env, installVersion: String = this.installVersion,
|
||||
installedAt: Long = this.installedAt, cover: String? = this.cover, hero: String? = this.hero,
|
||||
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic, cloud: Boolean = this.cloud, achievements: Boolean = this.achievements,
|
||||
logo: String? = this.logo,
|
||||
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements, logo)
|
||||
) = StoreGameSidecar(store, id, title, exe, launcher, workdir, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements, logo)
|
||||
|
||||
fun toJson(): JSONObject = JSONObject().apply {
|
||||
put("version", VERSION)
|
||||
@@ -48,6 +50,7 @@ class StoreGameSidecar(
|
||||
if (store != Store.AMAZON) put("cloud", cloud)
|
||||
if (store == Store.GOG) put("achievements", achievements)
|
||||
if (!launcher.isNullOrEmpty()) put("launcher", launcher)
|
||||
if (workdir != null) put("workdir", workdir)
|
||||
if (args.isNotEmpty()) put("args", JSONArray(args))
|
||||
if (env.isNotEmpty()) put("env", JSONObject(env as Map<*, *>))
|
||||
if (installVersion.isNotEmpty()) put("installVersion", installVersion)
|
||||
@@ -116,13 +119,16 @@ class StoreGameSidecar(
|
||||
if (exe.isEmpty() && state == STATE_INSTALLED) return null
|
||||
if (exe.isNotEmpty() && !relativeInside(exe)) return null
|
||||
val launcher = o.optString("launcher", "").replace('\\', '/').takeIf { it.isNotEmpty() && relativeInside(it) }
|
||||
val workdir = if (!o.has("workdir")) null else o.optString("workdir", "")
|
||||
.replace('\\', '/').removePrefix("./").trimEnd('/')
|
||||
.let { if (it.isEmpty() || it == ".") "" else it.takeIf(::relativeInside) }
|
||||
val args = o.optJSONArray("args")?.let { a -> List(a.length()) { a.optString(it) }.filter { it.isNotEmpty() } } ?: emptyList()
|
||||
val env = LinkedHashMap<String, String>()
|
||||
o.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.optString(k) } }
|
||||
val extra = LinkedHashMap<String, String>()
|
||||
o.optJSONObject("extra")?.let { e -> e.keys().forEach { k -> extra[k] = e.optString(k) } }
|
||||
return StoreGameSidecar(
|
||||
store, id, title, exe, launcher, args, env,
|
||||
store, id, title, exe, launcher, workdir = workdir, args = args, env = env,
|
||||
installVersion = o.optString("installVersion", ""),
|
||||
installedAt = o.optLong("installedAt", 0L),
|
||||
cover = o.optString("cover", "").ifEmpty { null },
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -22,7 +22,8 @@ object StoreLaunch {
|
||||
|
||||
fun launcherText(sidecar: StoreGameSidecar): String {
|
||||
val exe = sidecar.exe.replace('/', '\\')
|
||||
val dir = exe.substringBeforeLast('\\', "")
|
||||
val dir = sidecar.workdir?.let { if (it.isEmpty()) "" else it.replace('/', '\\') }
|
||||
?: exe.substringBeforeLast('\\', "")
|
||||
val lines = ArrayList<String>()
|
||||
lines += "@echo off"
|
||||
lines += "setlocal"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -17,6 +17,41 @@ internal object BlizzardArt {
|
||||
private val OG = Regex("""<meta property="og:image" content="(https://[^"]+)"""")
|
||||
private val THUMB = Regex("""\\?"imageUrl\\?":\\?"(//catalog\.blzstatic\.com/[^"\\]+)""")
|
||||
private val HOSTS = listOf(".blzstatic.com", ".blz-contentstack.com", "blz-contentstack-images.akamaized.net")
|
||||
private const val KEY_ART_ASSETS = "https://blz-contentstack-images.akamaized.net/v3/assets/bltf408a0557f4e4998/"
|
||||
private const val KEY_ART_CATALOG = "https://catalog.blzstatic.com/"
|
||||
internal val KEY_ART = mapOf(
|
||||
"WoW" to "${KEY_ART_ASSETS}blt80af93933ab07df3/68b8bf2d804a9776216cd63e/Midnight_keyart.png",
|
||||
"WoWC" to "${KEY_ART_ASSETS}blt6a80c8e7260f84f2/690d2219b415dd246153245b/BCC.png",
|
||||
"WoWF" to "${KEY_ART_ASSETS}blt1d58537e928b17c5/6ae2c99668c747dd1b4f558b/WoW_Forever_AnimatedTrailerSupportAssets_BnetShop_1920x1080.png",
|
||||
"D3" to "${KEY_ART_CATALOG}/f96/8d92f4d8bd316d3787f02d8a86935d6a-Store_Product_960x540_D3.jpg",
|
||||
"D3CN" to "${KEY_ART_CATALOG}/f96/8d92f4d8bd316d3787f02d8a86935d6a-Store_Product_960x540_D3.jpg",
|
||||
"S2" to "${KEY_ART_ASSETS}blt4b6d6857f147a6de/61254804841f180993fedb61/6885-32192.png",
|
||||
"S1" to "${KEY_ART_ASSETS}blt03d69a4563a6ae63/6a34b50f799ece2cb2da248c/9458-28298.jpg",
|
||||
"WTCG" to "${KEY_ART_ASSETS}blt5a3d84e1d0b2bbcf/662aea9f842cecfd4fd95327/HS_Key_Art_SG2.png",
|
||||
"Hero" to "${KEY_ART_ASSETS}blt73de967d17ca81ca/67db7dea931b380b4c76239a/Hanamura_Loading_Screen7.png",
|
||||
"W3" to "${KEY_ART_ASSETS}blt66c211421d2c5495/6a7e66d8dee8846a67cba6fa/WC_Rebirth_Announce_BnetShop_ComparsionCard_Reforged_1920x1080.png",
|
||||
"VIPR" to "${KEY_ART_ASSETS}bltd11d425fcbbe3c46/63eecbbd1e040260dfbede83/BO4_(2).png",
|
||||
"ODIN" to "${KEY_ART_CATALOG}/ffe/5e9926e8de75095fa953b8e71aea966c-_Kronos-Bnet_Game-Card_Feature_3A_Standard-960x540.jpg",
|
||||
"LAZR" to "${KEY_ART_CATALOG}/7f/ec4770b465f107f24f9a46a66d163ab9-Lazarus-Bnet_Placeholder-Card_PDG-960x540-For_20200331.jpg",
|
||||
"ZEUS" to "${KEY_ART_ASSETS}blt3e4e126b8153648b/63eeca6b998e686b2e53b748/CW-keyArt-thumb.jpg",
|
||||
"FORE" to "${KEY_ART_ASSETS}bltff4d6ec7afd2e49a/63f695ff583a5b674fbcde69/CODVG_Reveal_Ultimate_Keyart_Textless-Bnet-Launcher_Content_UI_(Phoenix)-1920x1080_01a_FINAL.jpg",
|
||||
"AUKS" to "${KEY_ART_ASSETS}bltd31831eda9199937/62abc0df5cbe472513c0ce59/Cortez_Base_Game-Bnet_Game-Card_Feature-960x540.jpg",
|
||||
"PNTA" to "${KEY_ART_ASSETS}bltd6fa384b60ff3fbd/64cc2fe367e57a3aa2cec653/Jupiter_Coming_Soon-Bnet_Game-Content_UI_(Phoenix)-EN-1920x1080_textless.jpg",
|
||||
"WLBY" to "${KEY_ART_ASSETS}blt861e34883e31a113/63eec7f166192b60e0205205/CB4_Launch_Keyart_CTA_02-Bnet-Launcher_Launcher_2.0-1920x1080_textless.jpg",
|
||||
"RTRO" to "${KEY_ART_ASSETS}bltc2737ca8175c8330/620d7693f2a06e30446fa9c7/BCO_PR_Shop_Assets_prod-thumb_TS01.jpg",
|
||||
"ANBS" to "${KEY_ART_ASSETS}bltcd126fd51eb09be1/6a21ee1fc451656b3d6841b5/DI_Art_Warlock-Login_illustration_(all_classes)-Illustration_(2).png",
|
||||
"Fen" to "${KEY_ART_ASSETS}blt8de255bf153ad1e2/63d0275cd791066264c678f4/en_D4_pre-purchase_blog_1920x1080_Primary_TS01.jpg",
|
||||
"D1" to "${KEY_ART_ASSETS}bltf183b52d38f5d94e/65a089802357a8ed25a05da1/blizzard_diablo_launch_desktop_shopproductasset_bchbnet_stat_enus_1920x1080_EE01.png",
|
||||
"W1" to "${KEY_ART_ASSETS}blt20214ec16801085a/65a07418cd72b186912c1fac/blizzard_warcraft1_launch_desktop_shopproductasset_bchbnet_stat_enus_1920x1080_EE01.png",
|
||||
"W2" to "${KEY_ART_ASSETS}blt45a874eacd7a27e4/65a08bf2db6bb9361a1fbc63/blizzard_warcraft2_launch_desktop_shopproductasset_bchbnet_stat_enus_1920x1080_EE01.png",
|
||||
"W1R" to "${KEY_ART_CATALOG}/7d/405b3c58ecc70c495dcf4b333cdd9e01-WC01_keyArt_finalcopy.png",
|
||||
"W2R" to "${KEY_ART_CATALOG}/7d/924e7c287781c84865b662d20029680c-WC02_KeyArt_finalcopyV2.png",
|
||||
"GRY" to "${KEY_ART_ASSETS}bltd22bde30bb1b973e/652d87d52c84c8e75f881b5f/SplashAnims_landscape_1.png",
|
||||
"ARIS" to "${KEY_ART_ASSETS}bltc5face49eea05c7e/67ca48cb4b61d73198918ba6/shop_product_feature_card_aries_standard.webp",
|
||||
"SCOR" to "${KEY_ART_ASSETS}blt82dbffc2b51e8aa1/67a562cc7113284f3b17ff7d/phx_notification_browsing_card_scorpio_announce.webp",
|
||||
"ARK" to "${KEY_ART_ASSETS}blt4a061067c30285dc/6837812aedfd13b46a16c38b/shop_asset_gallery_card_arkansas_wishlist.webp",
|
||||
"AQUA" to "${KEY_ART_ASSETS}blte982469df0746ee4/672ea9f71dee4754a60cde05/shop_product_edition_card_avowed_standard.jpg",
|
||||
)
|
||||
|
||||
internal fun imageUrl(page: String): String? {
|
||||
val og = OG.find(page)?.groupValues?.get(1)?.takeUnless { "youtube" in it || "maxresdefault" in it }
|
||||
@@ -24,16 +59,23 @@ internal object BlizzardArt {
|
||||
return (sequenceOf(og) + thumbs).filterNotNull().firstOrNull(::allowed)
|
||||
}
|
||||
|
||||
private fun allowed(url: String): Boolean {
|
||||
internal fun allowed(url: String): Boolean {
|
||||
val host = runCatching { URL(url).host }.getOrNull() ?: return false
|
||||
return HOSTS.any { h -> host == h.trimStart('.') || host.endsWith(h) }
|
||||
}
|
||||
|
||||
fun fetch(slug: String, wide: File, cover: File?): Boolean {
|
||||
val page = get(URL(SHOP + slug), MAX_PAGE, true)?.toString(Charsets.UTF_8) ?: return false
|
||||
val url = imageUrl(page) ?: return false
|
||||
val bytes = get(URL(url.substringBefore('?') + "?imwidth=$WIDE"), MAX_IMAGE, false) ?: return false
|
||||
val art = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return false
|
||||
private fun image(url: String): Bitmap? {
|
||||
val bytes = get(URL(url.substringBefore('?') + "?imwidth=$WIDE"), MAX_IMAGE, false) ?: return null
|
||||
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
}
|
||||
|
||||
private fun shopImage(slug: String): Bitmap? {
|
||||
val page = get(URL(SHOP + slug), MAX_PAGE, true)?.toString(Charsets.UTF_8) ?: return null
|
||||
return imageUrl(page)?.let(::image)
|
||||
}
|
||||
|
||||
fun fetch(code: String, slug: String, wide: File, cover: File?): Boolean {
|
||||
val art = runCatching { KEY_ART[code]?.let(::image) }.getOrNull() ?: shopImage(slug) ?: return false
|
||||
try {
|
||||
val scaled = if (art.width > WIDE) Bitmap.createScaledBitmap(art, WIDE, art.height * WIDE / art.width, true) else art
|
||||
save(scaled, wide)
|
||||
|
||||
@@ -133,6 +133,7 @@ object GogBackend : StoreBackend {
|
||||
val installedLanguage = result.language?.takeIf { it.isNotEmpty() } ?: language
|
||||
val sidecar = StoreGameSidecar(
|
||||
Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" },
|
||||
workdir = result.workDir,
|
||||
installVersion = result.buildId, installedAt = System.currentTimeMillis(),
|
||||
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
|
||||
logo = item.logoUrl ?: fetchLogo(game.gameId),
|
||||
|
||||
@@ -39,7 +39,7 @@ object GogComet {
|
||||
var status by mutableStateOf("off")
|
||||
private set
|
||||
|
||||
fun enabled(context: Context) = GogPrefs.get(context).getBoolean("achievements", false)
|
||||
fun enabled(context: Context) = GogPrefs.get(context).getBoolean("achievements", true)
|
||||
|
||||
fun setEnabled(context: Context, on: Boolean) {
|
||||
GogPrefs.get(context).edit().putBoolean("achievements", on).apply()
|
||||
|
||||
@@ -23,11 +23,15 @@ import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -63,6 +67,8 @@ public final class GogDownloadManager {
|
||||
public List<String> dependencies = new ArrayList<>();
|
||||
public boolean dependenciesRead = false;
|
||||
public String language;
|
||||
/** GOG's working directory for the exe: "" is the install root, null when no task declared it. */
|
||||
public String workDir;
|
||||
Result(String exeRelative, String buildId, long bytes) { this.exeRelative = exeRelative; this.buildId = buildId; this.bytes = bytes; }
|
||||
}
|
||||
|
||||
@@ -259,7 +265,9 @@ public final class GogDownloadManager {
|
||||
if (clientId != null && !clientId.isEmpty()) GogPrefs.get(ctx).edit().putString("client_id_" + game.gameId, clientId).apply();
|
||||
String clientSecret = manifest.optString("clientSecret", null);
|
||||
if (clientSecret != null && !clientSecret.isEmpty()) GogPrefs.get(ctx).edit().putString("client_secret_" + game.gameId, clientSecret).apply();
|
||||
out.result = new Result(pickExe(installPath, tempExe, game.title), gm.buildId, planned);
|
||||
GameTask task = pickTask(installPath, game.gameId, tempExe, game.title);
|
||||
out.result = new Result(task == null ? "" : task.path, gm.buildId, planned);
|
||||
if (task != null) out.result.workDir = task.workDir;
|
||||
out.result.dependencies = dependencies;
|
||||
out.result.dependenciesRead = true;
|
||||
out.result.language = resolved;
|
||||
@@ -430,7 +438,9 @@ public final class GogDownloadManager {
|
||||
if (anyFailed.get()) { out.error = "one or more files failed to download"; return out; }
|
||||
cb.onProgress("Finishing…", 96);
|
||||
writeFile(new File(installPath, MARKER), ("{\"gameId\":\"" + game.gameId + "\",\"generation\":1}").getBytes("UTF-8"));
|
||||
out.result = new Result(pickExe(installPath, null, game.title), "", planned);
|
||||
GameTask task = pickTask(installPath, game.gameId, null, game.title);
|
||||
out.result = new Result(task == null ? "" : task.path, "", planned);
|
||||
if (task != null) out.result.workDir = task.workDir;
|
||||
return out;
|
||||
} catch (Exception e) {
|
||||
out.error = "exception: " + e.getClass().getSimpleName();
|
||||
@@ -480,11 +490,14 @@ public final class GogDownloadManager {
|
||||
for (InstallerPart part : parts) new File(installPath, part.filename).delete();
|
||||
deleteDir(new File(installPath, "tmp"));
|
||||
deleteDir(new File(installPath, "commonappdata"));
|
||||
String exe = pickExe(installPath, null, game.title);
|
||||
GameTask task = pickTask(installPath, game.gameId, null, game.title);
|
||||
String exe = task == null ? "" : task.path;
|
||||
if (exe.isEmpty()) throw new InstallException("The installer was extracted but no game executable was found");
|
||||
cb.onLog("gog: installer extracted natively; game exe " + exe);
|
||||
GogMaintenance.captureOffline(game.gameId, installPath, downloads);
|
||||
return new Result(exe, "", total);
|
||||
Result result = new Result(exe, "", total);
|
||||
result.workDir = task.workDir;
|
||||
return result;
|
||||
} catch (InstallerException e) {
|
||||
throw e;
|
||||
} catch (InstallException e) {
|
||||
@@ -1071,21 +1084,188 @@ public final class GogDownloadManager {
|
||||
dir.delete();
|
||||
}
|
||||
|
||||
static String pickExe(File installPath, String tempExe, String title) {
|
||||
/**
|
||||
* GOG's own manifest names the game's play task: Blood Omen's is kain.exe while dxconfig.exe is
|
||||
* its separate tool task (#680). The product's own {@code goggame-<id>.info} decides when it has
|
||||
* one; any other {@code goggame-*.info} in the folder is only the fallback. Builds without a
|
||||
* manifest fall through to the hint and search below.
|
||||
*/
|
||||
private static GameTask declaredGameTask(File installPath, String gameId) {
|
||||
File own = gameId == null || gameId.isEmpty() ? null : new File(installPath, "goggame-" + gameId + ".info");
|
||||
if (own != null && !own.isFile()) own = null;
|
||||
List<File> others = new ArrayList<>();
|
||||
File[] files = installPath.listFiles();
|
||||
if (files != null) {
|
||||
Arrays.sort(files);
|
||||
for (File f : files) {
|
||||
if (f.equals(own) || !f.isFile() || !f.getName().startsWith("goggame-") || !f.getName().endsWith(".info")) continue;
|
||||
others.add(f);
|
||||
}
|
||||
}
|
||||
if (own != null) {
|
||||
GameTask task = bestGameTask(installPath, own);
|
||||
if (task != null) return task;
|
||||
}
|
||||
GameTask best = null;
|
||||
for (File manifest : others) {
|
||||
GameTask task = bestGameTask(installPath, manifest);
|
||||
if (task != null && (best == null || task.rank > best.rank)) best = task;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
static final class GameTask {
|
||||
final String path;
|
||||
/** GOG's working directory for the task: "" is the install root, null when no task declared it. */
|
||||
final String workDir;
|
||||
final int rank;
|
||||
GameTask(String path, String workDir, int rank) { this.path = path; this.workDir = workDir; this.rank = rank; }
|
||||
}
|
||||
|
||||
/** The task this manifest would be played from, or null when it names none that exists. */
|
||||
private static GameTask bestGameTask(File installPath, File manifest) {
|
||||
JSONArray tasks;
|
||||
try {
|
||||
tasks = new JSONObject(new String(Files.readAllBytes(manifest.toPath()), StandardCharsets.UTF_8))
|
||||
.optJSONArray("playTasks");
|
||||
} catch (Exception ignored) {
|
||||
return null; // A truncated manifest is not a reason to fail an install that downloaded fine.
|
||||
}
|
||||
if (tasks == null) return null;
|
||||
GameTask best = null;
|
||||
for (int i = 0; i < tasks.length(); i++) {
|
||||
JSONObject task = tasks.optJSONObject(i);
|
||||
if (task == null) continue;
|
||||
int rank = taskRank(task);
|
||||
if (rank == 0 || (best != null && rank <= best.rank)) continue;
|
||||
String path = task.optString("path", "").replace('\\', '/').replaceAll("/+", "/").replaceFirst("^(\\.?/)+", "");
|
||||
if (path.isEmpty()) continue;
|
||||
File exe = new File(installPath, path);
|
||||
if (!exe.isFile() || gogSupportExe(exe.getName()) || !inside(installPath, exe)) continue;
|
||||
best = new GameTask(path, taskWorkDir(installPath, task), rank);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* GOG runs a task from its declared working directory, and from the installation root when the
|
||||
* task declares none. The Witcher's play task is {@code System\witcher.exe}; started from
|
||||
* {@code System} hand-built shortcuts cannot find the game's {@code Data} folder, so the root is
|
||||
* recorded as "" and reaches the shortcut's Start In. A directory that leaves the folder, or is
|
||||
* not there, falls back to the root rather than to a guess.
|
||||
*/
|
||||
private static String taskWorkDir(File installPath, JSONObject task) {
|
||||
String dir = task.optString("workingDir", "").replace('\\', '/').replaceAll("/+", "/").trim();
|
||||
while (dir.startsWith("./")) dir = dir.substring(2);
|
||||
dir = dir.replaceAll("^/+", "").replaceAll("/+$", "");
|
||||
if (dir.isEmpty() || dir.equals(".")) return "";
|
||||
File folder = new File(installPath, dir);
|
||||
return folder.isDirectory() && inside(installPath, folder) ? dir : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* GOG's categories that launch the game: a primary task wins, and a primary {@code launcher} is
|
||||
* how GOG ships games that start through one. Only a primary {@code launcher} counts: GOG files
|
||||
* the configuration tool beside a game as a non-primary {@code launcher}, so that one falls to
|
||||
* the search rather than becoming the game. {@code tool} and {@code document} name no game.
|
||||
*/
|
||||
private static int taskRank(JSONObject task) {
|
||||
String category = task.optString("category").toLowerCase(Locale.ROOT);
|
||||
boolean primary = task.optBoolean("isPrimary", false);
|
||||
if ("game".equals(category)) return primary ? 4 : 2;
|
||||
if ("launcher".equals(category)) return primary ? 3 : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* GOG's Galaxy support executables sit in the game folder but install or patch its Galaxy files,
|
||||
* never play the game. The Witcher: Enhanced Edition ships
|
||||
* {@code galaxy_the_witcher_enhanced_edition_2.1.0.15.exe}, and its build metadata even names
|
||||
* that file as the temp executable: launching it is the same 32-bit Inno Setup stub that stops
|
||||
* at "Path not found" under ARM64 FEX (#694). Play tasks and the name search both step over it.
|
||||
*/
|
||||
private static boolean gogSupportExe(String path) {
|
||||
return new File(path.replace('\\', '/')).getName().toLowerCase(Locale.ROOT).startsWith("galaxy_");
|
||||
}
|
||||
|
||||
/** Whether the canonical path of {@code file} stays below {@code root}. */
|
||||
private static boolean inside(File root, File file) {
|
||||
try {
|
||||
return file.getCanonicalPath().startsWith(root.getCanonicalPath() + File.separator);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Exe names that belong to the config or tool shims around the game, not to the game. */
|
||||
private static final String[] TOOL_STEM_PARTS = {
|
||||
"config", "setting", "setup", "install", "unins", "touchup", "crashreport",
|
||||
"report", "editor", "launcher", "diagnostic",
|
||||
};
|
||||
|
||||
static GameTask pickTask(File installPath, String gameId, String tempExe, String title) {
|
||||
GameTask declared = declaredGameTask(installPath, gameId);
|
||||
if (declared != null) return declared;
|
||||
if (tempExe != null) {
|
||||
File hinted = new File(installPath, tempExe);
|
||||
if (hinted.isFile()) return relative(installPath, hinted);
|
||||
String hint = tempExe.replace('\\', '/');
|
||||
File hinted = new File(installPath, hint);
|
||||
if (!gogSupportExe(hint) && hinted.isFile() && inside(installPath, hinted)) return new GameTask(relative(installPath, hinted), null, 0);
|
||||
}
|
||||
List<File> candidates = new ArrayList<>();
|
||||
collectExeRecursive(installPath, candidates);
|
||||
if (candidates.isEmpty()) return "";
|
||||
String key = title.toLowerCase().replaceAll("[^a-z0-9]", "");
|
||||
File best = candidates.get(0);
|
||||
for (File f : candidates) {
|
||||
String n = f.getName().toLowerCase().replaceAll("\\.exe$", "").replaceAll("[^a-z0-9]", "");
|
||||
if (!n.isEmpty() && (n.equals(key) || key.startsWith(n) || n.startsWith(key))) { best = f; break; }
|
||||
if (candidates.isEmpty()) return null;
|
||||
String key = title.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", "");
|
||||
List<String> words = new ArrayList<>();
|
||||
for (String word : title.toLowerCase(Locale.ROOT).split("[^a-z0-9]+")) {
|
||||
if (word.length() >= 4 && !words.contains(word)) words.add(word);
|
||||
}
|
||||
return relative(installPath, best);
|
||||
Map<File, Integer> scores = new HashMap<>();
|
||||
for (File f : candidates) scores.put(f, exeScore(f, key, words));
|
||||
Collections.sort(candidates, (a, b) -> {
|
||||
int byScore = Integer.compare(scores.get(b), scores.get(a));
|
||||
if (byScore != 0) return byScore;
|
||||
int byDepth = Integer.compare(depth(installPath, a), depth(installPath, b));
|
||||
if (byDepth != 0) return byDepth;
|
||||
int bySize = Long.compare(b.length(), a.length());
|
||||
if (bySize != 0) return bySize;
|
||||
return relative(installPath, a).compareTo(relative(installPath, b));
|
||||
});
|
||||
return new GameTask(relative(installPath, candidates.get(0)), null, 0);
|
||||
}
|
||||
|
||||
static String pickExe(File installPath, String gameId, String tempExe, String title) {
|
||||
GameTask task = pickTask(installPath, gameId, tempExe, title);
|
||||
return task == null ? "" : task.path;
|
||||
}
|
||||
|
||||
/**
|
||||
* A word of the game's title in the exe name is the strongest hint: Blood Omen's kain.exe beats
|
||||
* the dxconfig.exe beside it (#680). Config and tool exes lose even when their name is the only
|
||||
* one resembling the title, and the depth penalty keeps a bundled tool below the game's own
|
||||
* folder. Before this, whatever the folder listing returned first was kept.
|
||||
*/
|
||||
private static int exeScore(File f, String key, List<String> words) {
|
||||
String stem = f.getName().toLowerCase(Locale.ROOT).replaceAll("\\.exe$", "").replaceAll("[^a-z0-9]", "");
|
||||
int score = 0;
|
||||
if (!stem.isEmpty() && !key.isEmpty()) {
|
||||
if (stem.equals(key)) score += 120;
|
||||
else if (key.startsWith(stem) || stem.startsWith(key)) score += 80;
|
||||
}
|
||||
for (String word : words) {
|
||||
if (stem.equals(word)) { score += 100; break; }
|
||||
if (stem.contains(word)) { score += 40; break; }
|
||||
}
|
||||
for (String part : TOOL_STEM_PARTS) {
|
||||
if (stem.contains(part)) { score -= 110; break; }
|
||||
}
|
||||
return score;
|
||||
}
|
||||
|
||||
private static int depth(File root, File f) {
|
||||
String path = relative(root, f);
|
||||
int depth = 0;
|
||||
for (int i = 0; i < path.length(); i++) if (path.charAt(i) == '/') depth++;
|
||||
return depth;
|
||||
}
|
||||
|
||||
private static String relative(File root, File f) {
|
||||
@@ -1099,7 +1279,7 @@ public final class GogDownloadManager {
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null) return;
|
||||
for (File f : files) {
|
||||
if (f.isFile() && f.getName().toLowerCase().endsWith(".exe")) {
|
||||
if (f.isFile() && f.getName().toLowerCase().endsWith(".exe") && !gogSupportExe(f.getName())) {
|
||||
String path = f.getAbsolutePath().toLowerCase();
|
||||
if (!path.contains("redist") && !path.contains("unins") && !path.contains("setup") && !path.contains("crash")
|
||||
&& !path.contains("report") && !path.contains("helper") && !path.contains("dotnet") && !path.contains("vcredist")
|
||||
|
||||
@@ -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) }
|
||||
@@ -386,7 +386,9 @@ internal object GogMaintenance {
|
||||
transfer(context, Proposal(folder, old, target, GogOperation.UPDATE, bytes, disk), null, cancelled, callback)
|
||||
if (cancelled.get()) return null
|
||||
target.write(folder)
|
||||
val result = GogDownloadManager.Result(GogDownloadManager.pickExe(folder, null, game.title), build.id, disk)
|
||||
val task = GogDownloadManager.pickTask(folder, game.gameId, null, game.title)
|
||||
val result = GogDownloadManager.Result(task?.path ?: "", build.id, disk)
|
||||
result.workDir = task?.workDir
|
||||
result.language = target.language
|
||||
result.dependencies = target.manifest.optJSONArray("dependencies")?.strings().orEmpty()
|
||||
result.dependenciesRead = true
|
||||
|
||||
@@ -49,7 +49,9 @@ import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -60,6 +62,8 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedGameArt
|
||||
@@ -192,7 +196,7 @@ internal fun SteamGameArtEditor(
|
||||
game: com.droiddeck.launcher.frontend.Library.SteamGame, onClose: () -> Unit, onChanged: () -> Unit,
|
||||
) {
|
||||
val target = remember(game.appId) { ArtTarget.of(game) }
|
||||
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged, launchAppId = game.appId)
|
||||
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -208,25 +212,17 @@ internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Uni
|
||||
@Composable
|
||||
private fun ArtOnlyEditor(
|
||||
name: String, target: ArtTarget?, refresh: Any?, describe: (Context) -> List<AddedGameArt.SlotState>,
|
||||
onClose: () -> Unit, onChanged: () -> Unit, launchAppId: Int? = null,
|
||||
onClose: () -> Unit, onChanged: () -> Unit,
|
||||
) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val scope = rememberCoroutineScope()
|
||||
val shown = rememberShown(onClose)
|
||||
val close = { shown.targetState = false }
|
||||
var version by remember { mutableIntStateOf(0) }
|
||||
var arts by remember { mutableStateOf<List<AddedGameArt.SlotState>>(emptyList()) }
|
||||
var artSlot by remember { mutableStateOf<AddedGameArt.Slot?>(null) }
|
||||
var logoOpen by remember { mutableStateOf(false) }
|
||||
var launchOptions by remember { mutableStateOf<String?>(null) }
|
||||
var launchVersion by remember { mutableIntStateOf(0) }
|
||||
var editingLaunch by remember { mutableStateOf<String?>(null) }
|
||||
var launchSaving by remember { mutableStateOf(false) }
|
||||
var launchError by remember { mutableStateOf<Int?>(null) }
|
||||
val position = rememberLogoPosition(target, version)
|
||||
LaunchedEffect(version, refresh) { if (target != null) arts = withContext(Dispatchers.IO) { describe(app) } }
|
||||
LaunchedEffect(launchAppId, launchVersion) { if (launchAppId != null) launchOptions = withContext(Dispatchers.IO) { SteamLaunchOptions.current(app, launchAppId) } }
|
||||
val first = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } }
|
||||
AppDialog(shown, close, "artEditor", wide = false, maxWidth = 460.dp) {
|
||||
@@ -236,19 +232,10 @@ private fun ArtOnlyEditor(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
|
||||
) {
|
||||
if (launchAppId != null) {
|
||||
FieldRow(stringResource(R.string.edit_launch_options), focus = first, onClick = { if (!launchSaving) launchOptions?.let { editingLaunch = it } }) {
|
||||
val options = launchOptions
|
||||
if (options == null || launchSaving) Loading() else ValueText(options.ifEmpty { "—" }, muted = options.isEmpty())
|
||||
}
|
||||
val error = launchError
|
||||
if (error != null) Text(stringResource(error), fontSize = 12.sp, color = colors.error, modifier = Modifier.padding(start = 4.dp))
|
||||
else Text(stringResource(R.string.edit_launch_options_steam_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp))
|
||||
}
|
||||
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = if (launchAppId != null) 8.dp else 2.dp))
|
||||
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp))
|
||||
for (slot in AddedGameArt.Slot.values()) key(slot) {
|
||||
val state = arts.firstOrNull { it.slot == slot }
|
||||
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER && launchAppId == null) first else null, onClick = { if (target != null) artSlot = slot }) {
|
||||
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER) first else null, onClick = { if (target != null) artSlot = slot }) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
SlotThumb(slot, state?.file)
|
||||
if (state != null) ValueText(artSourceLabel(state.source), muted = true) else Loading()
|
||||
@@ -258,27 +245,6 @@ private fun ArtOnlyEditor(
|
||||
PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
|
||||
}
|
||||
}
|
||||
val before = editingLaunch
|
||||
if (before != null && launchAppId != null) TextEntryDialog(stringResource(R.string.edit_launch_options), before, onDismiss = { editingLaunch = null }) { value ->
|
||||
if (launchSaving || value == before.trim()) return@TextEntryDialog
|
||||
launchSaving = true
|
||||
scope.launch {
|
||||
try {
|
||||
val saved = withContext(Dispatchers.IO) { SteamLaunchOptions.set(app, launchAppId, value, before) }
|
||||
launchError = when (saved) {
|
||||
SteamLaunchOptions.Saved.YES -> null
|
||||
SteamLaunchOptions.Saved.DESKTOP -> R.string.edit_launch_options_desktop
|
||||
SteamLaunchOptions.Saved.NO -> R.string.edit_launch_options_not_saved
|
||||
}
|
||||
if (saved == SteamLaunchOptions.Saved.YES) launchOptions = value else {
|
||||
launchOptions = null
|
||||
launchVersion++
|
||||
}
|
||||
} finally {
|
||||
launchSaving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
val chosen = target ?: return
|
||||
artSlot?.let { slot ->
|
||||
ArtChooserDialog(chosen, slot, arts.firstOrNull { it.slot == slot }, onBack = { artSlot = null }, onCloseAll = { artSlot = null; close() }) { version++; onChanged() }
|
||||
@@ -287,6 +253,72 @@ private fun ArtOnlyEditor(
|
||||
if (logoOpen && loaded != null) LogoPositionHost(chosen, arts, loaded, onBack = { logoOpen = false }, onCloseAll = { logoOpen = false; close() }) { version++; onChanged() }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SteamLaunchOptionsPanel(appId: Int) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val scope = rememberCoroutineScope()
|
||||
var options by remember(appId) { mutableStateOf<String?>(null) }
|
||||
var version by remember(appId) { mutableIntStateOf(0) }
|
||||
var editing by remember(appId) { mutableStateOf<String?>(null) }
|
||||
var saving by remember(appId) { mutableStateOf(false) }
|
||||
var loading by remember(appId) { mutableStateOf(false) }
|
||||
var error by remember(appId) { mutableStateOf<Int?>(null) }
|
||||
LaunchedEffect(appId, version) {
|
||||
options = withContext(Dispatchers.IO) { SteamLaunchOptions.current(app, appId) } ?: options.orEmpty()
|
||||
loading = false
|
||||
}
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
DisposableEffect(lifecycle, appId) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME && !saving) {
|
||||
loading = true
|
||||
version++
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
val value = options
|
||||
MenuItem(
|
||||
stringResource(R.string.edit_launch_options), checked = false, enabled = value != null && !saving && !loading,
|
||||
detail = if (value == null || saving || loading) "…" else value.ifEmpty { "—" },
|
||||
) { if (!saving && !loading) options?.let { editing = it } }
|
||||
val message = error
|
||||
Text(
|
||||
stringResource(message ?: R.string.edit_launch_options_steam_hint),
|
||||
fontSize = 12.sp,
|
||||
color = if (message == null) colors.onSurfaceVariant else colors.error,
|
||||
modifier = Modifier.padding(start = 4.dp),
|
||||
)
|
||||
}
|
||||
val before = editing
|
||||
if (before != null) TextEntryDialog(stringResource(R.string.edit_launch_options), before, onDismiss = { editing = null }) { value ->
|
||||
if (saving || value == before.trim()) return@TextEntryDialog
|
||||
saving = true
|
||||
scope.launch {
|
||||
try {
|
||||
val saved = withContext(Dispatchers.IO) { SteamLaunchOptions.set(app, appId, value, before) }
|
||||
error = when (saved) {
|
||||
SteamLaunchOptions.Saved.YES -> null
|
||||
SteamLaunchOptions.Saved.DESKTOP -> R.string.edit_launch_options_desktop
|
||||
SteamLaunchOptions.Saved.NO -> R.string.edit_launch_options_not_saved
|
||||
}
|
||||
if (saved == SteamLaunchOptions.Saved.YES) {
|
||||
options = value
|
||||
version++
|
||||
} else {
|
||||
options = null
|
||||
version++
|
||||
}
|
||||
} finally {
|
||||
saving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class LoadedPosition(val value: LogoPosition.Value?)
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -18,6 +18,7 @@ import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
@@ -86,7 +87,13 @@ import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -563,9 +570,10 @@ private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.D
|
||||
private fun AppTile(
|
||||
app: HomeApp.LaunchableApp, folderId: String?, first: Boolean,
|
||||
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
Box(modifier) {
|
||||
TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) {
|
||||
AppIcon(app, 52.dp)
|
||||
TileLabel(app.label)
|
||||
@@ -710,6 +718,7 @@ private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Uni
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
private fun FolderSheet(
|
||||
folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean,
|
||||
@@ -726,7 +735,27 @@ private fun FolderSheet(
|
||||
if (n.isNotEmpty() && n != folder.name) HomeFolders.rename(ctx, folder.id, n)
|
||||
renaming = false
|
||||
}
|
||||
val close = { if (renaming) commit(); onClose() }
|
||||
val firstApp = remember { FocusRequester() }
|
||||
val inputMode = LocalInputModeManager.current.inputMode
|
||||
val ff = LocalFrontFocus.current
|
||||
val grid = rememberLazyGridState()
|
||||
var closing by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(renaming, inputMode) {
|
||||
if (!renaming && !closing && inputMode == InputMode.Keyboard && apps.isNotEmpty()) {
|
||||
grid.scrollToItem(0)
|
||||
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
|
||||
if (!closing) runCatching { firstApp.requestFocus() }
|
||||
}
|
||||
}
|
||||
val close = {
|
||||
closing = true
|
||||
if (renaming) commit()
|
||||
onClose()
|
||||
if (inputMode == InputMode.Keyboard && ff != null) {
|
||||
runCatching { ff.items.getValue("tile:folder:${folder.id}").requestFocus() }
|
||||
.onFailure { runCatching { ff.firstTile.requestFocus() } }
|
||||
}
|
||||
}
|
||||
BackHandler { close() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
@@ -741,6 +770,13 @@ private fun FolderSheet(
|
||||
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
|
||||
.controllerBack(close)
|
||||
.focusProperties {
|
||||
exit = { dir ->
|
||||
if (dir == FocusDirection.Up || dir == FocusDirection.Down || dir == FocusDirection.Left || dir == FocusDirection.Right) FocusRequester.Cancel
|
||||
else FocusRequester.Default
|
||||
}
|
||||
}
|
||||
.focusGroup()
|
||||
.padding(16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) {
|
||||
@@ -759,11 +795,15 @@ private fun FolderSheet(
|
||||
}
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(92.dp),
|
||||
state = grid,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(apps, key = { it.key }) { app ->
|
||||
AppTile(app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder)
|
||||
AppTile(
|
||||
app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder,
|
||||
modifier = if (app === apps.first()) Modifier.focusRequester(firstApp) else Modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 483 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user