Compare commits

..
Author SHA1 Message Date
Kurt Himebauch 86190c62dc fix(ea): ask for sign-in after a rejected refresh, upload saves reached through folder aliases 2026-11-18 16:01:03 -05:00
Kurt Himebauch a113656196 fix(ea): keep real save folders in the inventory, back up any restored file, refuse duplicate or malformed cloud listings 2026-11-18 11:10:02 -05:00
Kurt Himebauch dba3fcd99e Merge branch 'main' into feat/ea-cloud-saves 2026-11-18 10:44:42 -05:00
MaxsTechReview bb5218746f fix(drivers): Auto gives Xclipse GPUs the old RADV pair only where that build supports them (#2337)
* fix: route unsupported Xclipse generations upstream

* fix: let Auto load upstream Xclipse pairs

* fix: clear stale auto-owned Xclipse RADV pair

* fix(drivers): clear independently owned fallback selections

* fix(drivers): keep independently chosen drivers when session start reconciles an unsupported Xclipse

* fix(drivers): name the Xclipse from Vulkan before session start picks which drivers Auto clears

* fix(drivers): keep the Vulkan query off the UI thread when session start reconciles Xclipse drivers

* test(drivers): control Xclipse GPU family in auto-driver reconciliation test

* fix(gpu): guard Xclipse auto-driver cleanup when running and handle open-driver bundles

* fix(gpu): keep active RADV-Xclipse-upstream bundle on unsupported Xclipse
2026-11-18 10:44:32 -05:00
Kurt Himebauch f1fccfac26 test(ea): keep the cloud save cases in EaTest 2026-11-18 10:33:24 -05:00
Kurt Himebauch ca7b7e74ec test(session): skip the /mnt view comparison on hosts where /mnt is a symlink (#2806)
rawAndStorageMountViewsOverlapButDistinctFoldersDoNot canonicalizes
/mnt/media_rw/... with the host JVM. On SteamOS and Fedora Atomic /mnt is a
symlink to var/mnt, so the path resolves to /var/mnt/media_rw/..., which no
Android device produces, and the unit suite fails there. Skip the case when
the host's /mnt is a symlink.
2026-11-18 10:22:28 -05:00
Kurt Himebauch 9ba5be4943 fix(ea): one resolved save folder per sync, refuse case collisions, and walk each folder once 2026-11-18 10:12:56 -05:00
Kurt Himebauch 0a8d6669bf ci: install the arm64 C library headers for the verified components (#2833)
* ci: install the arm64 C library headers the verified components cross-compile against

* ci: cross-compiling component recipes install the arm64 C library headers
2026-11-18 10:09:54 -05:00
Kurt Himebauch c9a0c03292 fix(ea): back up only the saves a restore replaces, refuse truncated manifests, and need a master title id 2026-11-18 10:04:37 -05:00
Dennis Zabolotnyandzdennisz 9e05e4c00c fix(input): keep held keyboard keys when pointer capture ends (#2779)
* fix(input): keep held keyboard keys when pointer capture ends

When a game gives up its pointer lock, Android pointer capture is
released and the session dropped every held input, including keyboard
keys. In a windowed session with Relative mouse on Auto, holding W to
run and releasing the mouse button after steering stopped the
character, because the key press is never sent again.

Losing pointer capture now releases only the mouse buttons, the pen and
the mouse back-button input. Keys are still released when the window
loses focus.

* fix(input): release held keys when pointer capture ends for the session menu

Opening the session menu releases pointer capture, and the menu then
consumes key events, including the key-up. A key held at that moment
would stay pressed in the guest after the menu closed. Capture loss with
the menu open now releases keys as before; other capture loss keeps them.

* fix(input): release held keys whenever another surface takes the keyboard

Capture loss released keys only while the session menu was open. The
other places that take input from the guest (on-screen keyboard,
achievements, input settings, WoW chat, touch editor, picture in picture)
have the same problem, so keys are now kept only when the session still
owns input and the game itself dropped its pointer lock.

* fix(input): release held keys when the session menu opens

While the menu is open it takes every key event, including the key-up,
so a key held when it opened stayed pressed in the guest. The keys are
now released when the menu opens, whether or not pointer capture was
active.

---------

Co-authored-by: zdennisz <15849186+zdennisz@users.noreply.github.com>
2026-11-18 09:53:39 -05:00
Kurt Himebauch 5926662170 fix(ea): fresh rules per sync, checksums required, backup before restore, and sign-in shown on the saves tab 2026-11-18 09:50:25 -05:00
Kurt Himebauch 617ce33310 Merge branch 'main' into feat/ea-cloud-saves 2026-11-18 09:43:04 -05:00
The412Banner 0a167e41c2 fix(session): Steam's install-script step no longer counts as the game for return after game (#2732) 2026-11-18 09:37:50 -05:00
Kurt Himebauch 1702f2d72d fix: trust FryMcNugget for test builds (#2830) 2026-11-18 09:11:14 -05:00
Kurt Himebauch 7d47c61e24 fix(ea): sync at EA launch and exit, keep one rule snapshot, and check the cloud copy under the write lock 2026-11-18 09:07:54 -05:00
Kurt Himebauch 7d134ae459 feat(ea): sync cloud saves through EA's cloud sync service 2026-11-18 08:25:21 -05:00
FX1922 f1be935761 feat(library): add a Hidden tab synced with Steam's hidden games (#2803)
* feat(library): add a Hidden tab synced with Steam's hidden games

* fix(library): mark the hidden collection as modified so Steam uploads it

* fix(library): make the Steam hidden write atomic and refresh the hidden set on resume

* feat(library): show an error when hiding a game can't sync with Steam

* fix(library): keep the pending Steam upload list safe when it can't be read

* fix(library): report a failed Steam sync when the upload marker can't be saved

* fix(library): refresh the Steam hidden set from disk after a failed sync

* fix(library): keep the cached hidden set when Steam's file can't be read

* fix(library): handle a malformed hidden entry and a changed Steam root

* fix(library): refuse to overwrite a malformed hidden entry

* fix(library): validate the hidden collection, keep Steam saves separate from upload status and cover cloud and uninstalled games

* fix(library): accept numeric-string ids, keep uninstalled games in the Hidden tab and hide games from the Steam home list

* fix(library): keep hidden Steam games out of the home capsule wall

* fix(library): refresh home art when the hidden set changes and track the Steam account

* fix(library): clear the cached hidden set when the Steam account changes

* fix(library): ignore a previous account's art while the home scan runs

* fix(library): conceal home art for hidden added games that carry a Steam app id
2026-11-18 07:38:34 -05:00
69 changed files with 1580 additions and 144 deletions

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
ASEbrahim
FX192
FryMcNugget
K11MCH1
KeegantheVeganat0r
kingokksa
+1 -1
View File
@@ -291,7 +291,7 @@ jobs:
- name: Build the non-Adreno test additions (Mali bridge client, Venus GL probe, Xclipse layer)
run: |
set -euo pipefail
bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libvulkan-dev
bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libc6-dev-arm64-cross libvulkan-dev
D=app/src/main/assets/linuxfs
mkdir -p "$D/usr/local/bin" "$D/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
@@ -319,7 +319,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers()
return
}
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
if (gpu.family.mali && !DriverPairs.autoEligible(gpu) &&
com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
releaseChecking = true
autoStatus = activity.getString(R.string.drivers_checking_latest)
@@ -335,14 +335,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "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) {
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) eligible=${DriverPairs.autoEligible(gpu)}")
if (gpu.family.mali && !DriverPairs.autoEligible(gpu)) {
// 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) {
if (!DriverPairs.autoEligible(gpu)) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return
}
@@ -372,7 +372,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
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)
if (gpu.name.contains("Xclipse", ignoreCase = true) && DriverPairs.xclipseNeedsUpstream(gpu.name)) {
if (!SessionState.running) SessionPrefs.ensurePowerVrAutoDrivers(activity, powerVr = true, autoOwnedOnly = true)
} else {
SessionPrefs.ensurePowerVrAutoDrivers(activity)
}
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
refreshDrivers()
}
@@ -488,7 +488,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
drawerLayerOpen = false
drawerPinned = false
if (value) drawerDocked = dockDrawer() && openDockedMenu()
if (value) {
releaseHeldKeys()
drawerDocked = dockDrawer() && openDockedMenu()
}
drawerOpenState = value
if (!value && drawerDocked) closeDockedMenu()
}
@@ -825,7 +828,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pointerCaptureRefused = false
if (usbMouse.active) updatePointerCapture()
} else {
releaseHeldGuestInput()
releaseHeldInputOnCaptureLoss()
uiHandler.postDelayed(::updatePointerCapture, 250)
}
}
@@ -5118,10 +5121,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun relativeMouseAttached(): Boolean = !isInMultiWindowMode && !glassesOutputActive && mouseAttached()
private fun sessionOwnsInput() =
resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen &&
!pipUi && !bottomOutputActive && !touchEditorOpen && !wowChatOnTop
private fun updatePointerCapture() {
if (!::surfaceView.isInitialized) return
val view = window.decorView
val want = (pointerLocked || relativeMouseAttached()) && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !bottomOutputActive && !touchEditorOpen && !wowChatOnTop && mouseAttached()
val want = (pointerLocked || relativeMouseAttached()) && sessionOwnsInput() && hasWindowFocus() && mouseAttached()
releaseDesktopMouseGrab()
updateUsbMouse(want)
if (want == view.hasPointerCapture()) return
@@ -5444,14 +5451,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun keyboardCoversPad() =
SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard
private fun releaseHeldGuestInput() {
private fun releaseHeldInputOnCaptureLoss() {
if (sessionOwnsInput()) releaseHeldPointerInput() else releaseHeldGuestInput()
}
private fun releaseHeldPointerInput() {
mouseBackInput.cancel()
cancelPen(releaseKey = true)
heldButtons.release(1 or 2 or 8 or 16)
}
private fun releaseHeldKeys() {
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
heldKeys.release(8 or 16 or 32)
}
private fun releaseHeldGuestInput() {
releaseHeldPointerInput()
releaseHeldKeys()
}
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
@@ -222,16 +222,7 @@ object Library {
internal fun concealedSteamApps(root: File): Set<Long> {
val config = AddedGames.accountConfig(root) ?: return emptySet()
val hidden = runCatching {
val entries = org.json.JSONArray(File(config, "cloudstorage/cloud-storage-namespace-1.json").readText())
val entry = (0 until entries.length()).map { entries.getJSONArray(it) }
.firstOrNull { it.optString(0) == "user-collections.hidden" }?.optJSONObject(1)
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = org.json.JSONObject(entry.optString("value"))
fun ids(key: String) = collection.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optLong(it) } }.orEmpty()
ids("added").toSet() - ids("removed").toSet()
}
}.getOrDefault(emptySet())
val hidden = SteamHidden.read(root)
val private = runCatching {
PRIVATE_APPS.find(File(config, "localconfig.vdf").readText())?.groupValues?.get(1)
?.split(',')?.mapNotNull { it.trim().toLongOrNull() }?.toSet()
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.frontend
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
internal object SteamHidden {
private const val KEY = "user-collections.hidden"
private fun file(root: File): File? = AddedGames.accountConfig(root)?.let { File(it, "cloudstorage/cloud-storage-namespace-1.json") }
class Saved(val hidden: Set<Long>, val queued: Boolean)
private fun id(member: Any?): Long? = when (member) {
is Int -> member.toLong()
is Long -> member
is String -> member.toLongOrNull()
else -> null
}
private fun ids(collection: JSONObject, key: String, strict: Boolean): List<Long> {
if (!collection.has(key)) return emptyList()
val array = collection.optJSONArray(key) ?: throw IllegalStateException(key)
return (0 until array.length()).mapNotNull { index ->
id(array.get(index)) ?: if (strict) throw IllegalStateException(key) else null
}
}
fun read(root: File): Set<Long> = readOrNull(root).orEmpty()
fun readOrNull(root: File): Set<Long>? = runCatching {
val entries = JSONArray(file(root)?.readText() ?: return null)
val slot = (0 until entries.length()).map { entries.getJSONArray(it) }.firstOrNull { it.optString(0) == KEY }
val entry = slot?.optJSONObject(1)
if (slot != null && entry == null) return null
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = JSONObject(entry.optString("value"))
ids(collection, "added", false).toSet() - ids(collection, "removed", false).toSet()
}
}.getOrNull()
fun write(root: File, appId: Long, hidden: Boolean, now: Long = System.currentTimeMillis() / 1000): Saved? = runCatching {
val target = file(root) ?: return null
val entries = JSONArray(target.readText())
val slot = (0 until entries.length()).firstOrNull { entries.getJSONArray(it).optString(0) == KEY }
val entry = if (slot == null) JSONObject().put("key", KEY) else entries.getJSONArray(slot).optJSONObject(1) ?: return null
val live = !entry.optBoolean("is_deleted")
val collection = if (live && entry.has("value")) JSONObject(entry.optString("value")) else JSONObject().put("id", "hidden")
val added = ids(collection, "added", true).filter { it != appId }
val removed = ids(collection, "removed", true).filter { it != appId }
collection.put("added", JSONArray(if (hidden) added + appId else added))
collection.put("removed", JSONArray(if (hidden) removed else removed + appId))
entry.put("value", collection.toString())
entry.put("timestamp", now)
entry.put("is_deleted", false)
entry.opt("version")?.toString()?.toLongOrNull()?.let { entry.put("version", (it + 1).toString()) }
if (slot == null) entries.put(JSONArray().put(KEY).put(entry))
val temp = File(target.parentFile, target.name + ".tmp")
temp.writeText(entries.toString())
if (!temp.renameTo(target)) {
temp.delete()
return null
}
Saved(ids(collection, "added", true).toSet() - ids(collection, "removed", true).toSet(), markModified(File(target.parentFile, "cloud-storage-namespace-1.modified.json")))
}.getOrNull()
private fun markModified(file: File): Boolean {
val pending = if (file.exists()) runCatching { JSONArray(file.readText()) }.getOrNull() ?: return false else JSONArray()
if ((0 until pending.length()).any { pending.optString(it) == KEY }) return true
val temp = File(file.parentFile, file.name + ".tmp")
val saved = runCatching {
temp.writeText(pending.put(KEY).toString())
temp.renameTo(file)
}.getOrDefault(false)
if (!saved) temp.delete()
return saved
}
}
@@ -18,6 +18,7 @@ object DriverPairs {
/** 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""")
private val SUPPORTED_XCLIPSE_MODELS = setOf("530", "920", "940")
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"
@@ -112,9 +113,12 @@ 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" }
internal fun xclipseNeedsUpstream(name: String): Boolean =
XCLIPSE_MODEL.find(name)?.groupValues?.get(1) !in SUPPORTED_XCLIPSE_MODELS
fun autoEligible(gpu: GpuInfo, sdk: Int = android.os.Build.VERSION.SDK_INT): Boolean =
recommendedKey(gpu, emptyList(), sdk = sdk) != null ||
(gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true))
fun recommendedKey(
gpu: GpuInfo, pairs: List<DriverPair>,
@@ -125,6 +129,7 @@ object DriverPairs {
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
xclipseNeedsUpstream(gpu.name) -> null
else -> NAD_RADV_XCLIPSE
}
Family.MALI_OTHER, Family.NOT_ADRENO -> return null
@@ -118,9 +118,7 @@ data class GpuInfo(
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
name = when {
family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
}
family == Family.POWERVR -> systemDriverName(SystemVulkanDriver.gpuName(), VulkanInfo.cachedOrNull())
mali != null && mali.isNotEmpty() -> mali
!adreno -> Build.HARDWARE.ifBlank { UNNAMED }
model > 0 -> "Adreno $model"
@@ -134,6 +132,9 @@ data class GpuInfo(
)
}
fun systemDriverName(gpu: String, vulkan: Map<String, String>?): String =
vulkan?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
internal fun verifiedOn(model: Int, device: String): Boolean =
model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true)
@@ -255,6 +255,18 @@ object SessionPrefs {
prefs(context).edit().putBoolean("libraryShowSize", show).apply()
}
fun libraryShowHidden(context: Context): Boolean = prefs(context).getBoolean("libraryShowHidden", false)
fun setLibraryShowHidden(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowHidden", show).apply()
}
fun libraryHidden(context: Context): Set<String> = prefs(context).getStringSet("libraryHidden", null)?.toSet().orEmpty()
fun setLibraryHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putStringSet("libraryHidden", keys.toSet()).apply()
}
fun railLabels(context: Context): Boolean = prefs(context).getBoolean("railLabels", false)
fun setRailLabels(context: Context, show: Boolean) {
@@ -685,14 +697,42 @@ object SessionPrefs {
}
@JvmStatic
fun ensurePowerVrAutoDrivers(context: Context) {
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context)) return
ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr())
fun ensurePowerVrAutoDrivers(context: Context) = reconcilePowerVrAutoDrivers(
context, SystemVulkanDriver.isPowerVr(), SystemVulkanDriver.isXclipse(),
com.droiddeck.launcher.gpu.VulkanInfo::cachedOrNull,
)
fun ensurePowerVrAutoDriversAfterGpuQuery(context: Context) = reconcilePowerVrAutoDrivers(
context, SystemVulkanDriver.isPowerVr(), SystemVulkanDriver.isXclipse(),
com.droiddeck.launcher.gpu.VulkanInfo::query,
)
internal fun reconcilePowerVrAutoDrivers(
context: Context, powerVr: Boolean, xclipse: Boolean, vulkan: () -> Map<String, String>?,
) {
val device = if (xclipse) vulkan() ?: return else null
val unsupported = unsupportedXclipse(xclipse) {
com.droiddeck.launcher.gpu.GpuInfo.systemDriverName(SystemVulkanDriver.gpuName(), device)
}
val activeKey = com.droiddeck.launcher.gpu.DriverBundle.active(context)
?.id
?.let(com.droiddeck.launcher.gpu.DriverPairs::nonAdreno)
val upstreamBundle = activeKey == com.droiddeck.launcher.gpu.DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM ||
(activeKey != null && activeKey.startsWith("${com.droiddeck.launcher.gpu.DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM}-"))
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context) && (!unsupported || upstreamBundle)) return
ensurePowerVrAutoDrivers(context, powerVr, unsupported)
}
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) {
internal fun unsupportedXclipse(xclipse: Boolean, gpuName: () -> String): Boolean =
xclipse && com.droiddeck.launcher.gpu.DriverPairs.xclipseNeedsUpstream(gpuName())
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean, autoOwnedOnly: Boolean = false) {
if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return
prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply()
val owned = gpuAutoInstalled(context)
val edit = prefs(context).edit()
if (!autoOwnedOnly || linuxDriver(context) in owned) edit.putString("linuxDriver", "")
if (!autoOwnedOnly || androidDriver(context) in owned) edit.putString("androidDriver", TurnipDriver.AUTO)
edit.apply()
}
fun gpuAutoInstalled(context: Context): Set<String> =
@@ -497,7 +497,7 @@ class SessionService : Service() {
private fun runSession(gen: Int) {
SessionPrefs.ensurePowerVrAutoDrivers(this)
SessionPrefs.ensurePowerVrAutoDriversAfterGpuQuery(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 {
@@ -40,8 +40,9 @@ object SteamGameProcess {
val appId = args.getOrNull(i + 1)
?.takeIf { it.startsWith("AppId=") }
?.removePrefix("AppId=")
val launchOptions = args.drop(i + 2).takeWhile { it != "--" }
if (appId == expectedAppId) return true
if (appId == expectedAppId && "Install=1" !in launchOptions) return true
}
if (args[i] == "-applaunch" &&
@@ -5,6 +5,11 @@ import android.content.SharedPreferences
import android.util.Log
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.ea.EaAuth
import com.droiddeck.launcher.stores.ea.EaCloud
import com.droiddeck.launcher.stores.ea.EaLibrary
import com.droiddeck.launcher.stores.ea.EaPrefs
import com.droiddeck.launcher.stores.ea.EaSaveRules
import com.droiddeck.launcher.stores.epic.EpicApiClient
import com.droiddeck.launcher.stores.epic.EpicCredentialStore
import com.droiddeck.launcher.stores.epic.EpicPrefs
@@ -32,7 +37,7 @@ object CloudSaves {
if (detail.isNotEmpty()) " detail=\"$detail\"" else ""
}
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList())
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList(), val signedIn: Boolean = true)
private fun game(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? =
StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull { f ->
@@ -44,7 +49,13 @@ object CloudSaves {
return Library.protonPrefix(context, appId and 0xFFFFFFFFL)
}
private fun prefs(context: Context, store: Store) = if (store == Store.GOG) GogPrefs.get(context) else EpicPrefs.get(context)
fun supports(store: Store?): Boolean = store == Store.GOG || store == Store.EPIC || store == Store.EA
private fun prefs(context: Context, store: Store) = when (store) {
Store.GOG -> GogPrefs.get(context)
Store.EA -> EaPrefs.get(context)
else -> EpicPrefs.get(context)
}
fun lastSync(context: Context, store: Store, id: String): Long = prefs(context, store).getLong("cloud_sync_$id", 0L)
@@ -64,6 +75,10 @@ object CloudSaves {
fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? {
val p = prefs(context, store)
if (store == Store.EA) eaRules(context, id)?.let { fresh ->
if (fresh.isEmpty()) rememberNoCloud(p, id) else p.edit().putString("cloud_template_$id", fresh).remove("cloud_template_at_$id").apply()
return fresh
}
var retryNone = false
if (p.contains("cloud_template_$id")) {
val cached = p.getString("cloud_template_$id", "") ?: ""
@@ -89,7 +104,8 @@ object CloudSaves {
val item = sidecar.extra["catalogItemId"].orEmpty()
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> ""
Store.EA -> eaRules(context, id) ?: return null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> ""
} ?: return null
p.edit()
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
@@ -150,14 +166,16 @@ object CloudSaves {
val dir = when (store) {
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
Store.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null
else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) }
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> null
}
return dir to (if (dir == null) "unresolved" else "ok")
}
fun status(context: Context, store: Store, id: String): Status {
val (dir, reason) = saveFolder(context, store, id)
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id))
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id), signedIn(context, store))
}
@@ -175,7 +193,28 @@ object CloudSaves {
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
Store.EA -> {
val sidecar = StoreGameSidecar.read(folder)
val rules = sidecar?.let { template(context, store, id, folder, it) }?.let(EaSaveRules::parse)
val base = rules?.base()
val token = EaAuth.accessToken(context)
val uid = EaAuth.load(context)?.userId.orEmpty()
val master = sidecar?.extra?.get("masterTitleId").orEmpty()
if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null
else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first)
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> null
}
private fun signedIn(context: Context, store: Store): Boolean = when (store) {
Store.EA -> EaAuth.signedIn(context)
else -> true
}
private fun eaRules(context: Context, id: String): String? {
val games = EaLibrary.cached(context)
if (games.isEmpty()) return null
return games.firstOrNull { it.offerId == id }?.cloudSaves.orEmpty()
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -305,7 +344,10 @@ object CloudSaves {
val cloud = if (dir != null) transport(context, store, id, g.first) else null
when {
dir == null -> Result("skipped", 0, 0, reason)
cloud == null && store == Store.EA && signedIn(context, store) -> Result("failed", 0, 0, "sign-in-unreachable")
cloud == null -> Result("skipped", 0, 0, "not-signed-in")
cloud is EaCloud && cloud.localDir?.canonicalPath != dir.canonicalPath -> Result("skipped", 0, 0, "rules-changed")
cloud is EaCloud && localFiles(dir).keys.groupBy { it.lowercase() }.any { it.value.size > 1 } -> Result("failed", 0, 0, "case-collision")
else -> body(dir, cloud).also { if (it.result == "ok") markSynced(context, store, id) }
}
}
@@ -325,9 +367,23 @@ object CloudSaves {
return r
}
private fun localFiles(dir: File): Map<String, File> =
if (!dir.isDirectory) emptyMap()
else dir.walkTopDown().filter { it.isFile }.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') }
private fun localFiles(dir: File): Map<String, File> {
if (!dir.isDirectory) return emptyMap()
val root = runCatching { dir.toPath().toRealPath() }.getOrNull() ?: return emptyMap()
val found = LinkedHashMap<String, File>()
fun walk(d: File, prefix: String, ancestry: Set<java.nio.file.Path>) {
for (child in d.listFiles().orEmpty()) {
val real = runCatching { child.toPath().toRealPath() }.getOrNull() ?: continue
if (!real.startsWith(root)) continue
val name = prefix + child.name
if (child.isDirectory) {
if (real !in ancestry) walk(child, "$name/", ancestry + real)
} else if (child.isFile) found[name] = child
}
}
walk(dir, "", setOf(root))
return found
}
internal fun md5(f: File): String = md5(f.readBytes())
@@ -342,13 +398,17 @@ object CloudSaves {
}
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
val files = localFiles(dir)
val files = localFiles(dir).filterKeys(cloud::wants)
val remote = remote(cloud) { it in files }
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val base = baseline(context, store, id)
val plan = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val take = if (force) plan.transfer + plan.conflicts else plan.transfer
if (take.isNotEmpty() && files.isNotEmpty()) backup(context, store, id, dir, "local")
val inside = dir.canonicalPath + File.separator
val replaced = take.mapNotNull { name ->
files[name] ?: File(dir, name).takeIf { it.isFile && runCatching { it.canonicalPath.startsWith(inside) }.getOrDefault(false) }
}
if (!backupReplaced(context, store, id, dir, replaced)) return Result("failed", 0, 0, "backup-failed")
val next = HashMap(base.orEmpty())
var bytes = 0L
for (name in take) {
@@ -371,7 +431,7 @@ object CloudSaves {
internal fun upWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
val base = baseline(context, store, id) ?: return Result("skipped", 0, 0, "no-baseline")
val files = localFiles(dir)
val files = localFiles(dir).filterKeys(cloud::wants)
if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local")
val remote = remote(cloud) { it in files }
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
@@ -397,9 +457,9 @@ object CloudSaves {
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 }
val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }
for (name in send) {
val r = after[name]
val r = cloud.committed(name) ?: after[name]
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
}
}
@@ -441,10 +501,11 @@ object CloudSaves {
private fun backupRoot(context: Context, store: Store, id: String) =
File(context.filesDir, "stores/cloud-backups/${store.id}-${id.replace(Regex("[^A-Za-z0-9._-]"), "_")}")
private fun backup(context: Context, store: Store, id: String, dir: File, kind: String) {
private fun backup(context: Context, store: Store, id: String, dir: File, kind: String): Boolean {
val root = backupRoot(context, store, id)
runCatching { dir.copyRecursively(File(root, "$kind-${System.currentTimeMillis()}"), overwrite = true) }
val copied = runCatching { dir.copyRecursively(File(root, "$kind-${System.currentTimeMillis()}"), overwrite = true) }.getOrDefault(false)
prune(root, kind)
return copied
}
private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List<CloudFile>) {
@@ -460,6 +521,27 @@ object CloudSaves {
prune(root, "cloud")
}
private fun backupReplaced(context: Context, store: Store, id: String, dir: File, replaced: List<File>): Boolean {
if (replaced.isEmpty()) return true
val base = runCatching { dir.canonicalPath + File.separator }.getOrNull() ?: return false
val root = backupRoot(context, store, id)
val stamp = "${System.currentTimeMillis()}-${java.util.UUID.randomUUID().toString().take(8)}"
val staging = File(root, "staging-$stamp")
val copied = runCatching {
for (f in replaced) {
check(f.canonicalPath.startsWith(base))
f.copyTo(File(staging, f.relativeTo(dir).path), overwrite = true)
}
check(staging.renameTo(File(root, "local-$stamp")))
}.isSuccess
if (!copied) {
staging.deleteRecursively()
return false
}
prune(root, "local")
return true
}
private fun prune(root: File, kind: String) {
root.listFiles { f -> f.name.startsWith("$kind-") }?.sortedByDescending { it.name }?.drop(BACKUPS)?.forEach { it.deleteRecursively() }
}
@@ -27,6 +27,8 @@ class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null,
class CloudPut(val modifiedMs: Long, val md5: String?)
interface CloudTransport {
fun wants(name: String): Boolean = true
fun committed(name: String): CloudFile? = null
fun list(): List<CloudFile>
fun details(file: CloudFile) {}
fun get(file: CloudFile): Pair<ByteArray, Long>
@@ -17,7 +17,7 @@ object EaAuth {
const val CLIENT_ID = "JUNO_PC_CLIENT"
private const val CLIENT_SECRET = "4mRLtYMb6vq9qglomWEaT4ChxsXWcyqbQpuBNfMPOYOiDmYYQmjuaBsF2Zp0RyVeWkfqhE9TuGgAw7te"
const val AUTH_URL = "https://accounts.ea.com/connect/auth"
private const val TOKEN_URL = "https://accounts.ea.com/connect/token"
internal var tokenUrl = "https://accounts.ea.com/connect/token"
const val REDIRECT = "qrc:///html/login_successful.html"
private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L
private val refreshLock = Any()
@@ -41,8 +41,11 @@ object EaAuth {
val personaId: String,
val displayName: String,
val eaId: String,
val rejected: Boolean = false,
)
private class Rejected(message: String) : IllegalStateException(message)
class Pending(val url: String, val verifier: String)
internal fun fromJson(o: JSONObject): Account? {
@@ -55,6 +58,7 @@ object EaAuth {
personaId = o.optString("persona_id"),
displayName = o.optString("display_name"),
eaId = o.optString("ea_id"),
rejected = o.optBoolean("refresh_rejected"),
)
}
@@ -122,14 +126,15 @@ object EaAuth {
private fun tokenCall(values: List<Pair<String, String>>): JSONObject {
val reply = EaHttp.request(
TOKEN_URL, "POST",
tokenUrl, "POST",
mapOf("Content-Type" to "application/x-www-form-urlencoded"),
EaHttp.form(values + listOf("client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET)).toByteArray(),
follow = false,
)
val json = runCatching { JSONObject(reply.text) }.getOrNull()
if (!reply.ok || json == null || json.optString("access_token").isEmpty()) {
throw IllegalStateException("EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}")
val message = "EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}"
throw if (reply.status == 400 || reply.status == 401 || reply.status == 403) Rejected(message) else IllegalStateException(message)
}
return json
}
@@ -162,6 +167,7 @@ object EaAuth {
tokenCall(listOf("grant_type" to "refresh_token", "refresh_token" to a.refreshToken))
} catch (e: Exception) {
Log.w(TAG, "refresh: ${e.message}")
if (e is Rejected) markRejected(context, a.refreshToken)
return null
}
val access = token.getString("access_token")
@@ -176,11 +182,24 @@ object EaAuth {
val record = StoreAccounts.read(app, Store.EA) ?: return false
record.put("access_token", access).put("expires_at", System.currentTimeMillis() + expiresIn * 1000)
refresh.takeIf { it.isNotEmpty() }?.let { record.put("refresh_token", it) }
record.remove("refresh_rejected")
player?.let { record.put("user_id", it.userId).put("persona_id", it.personaId).put("display_name", it.displayName).put("ea_id", it.eaId) }
StoreAccounts.write(app, Store.EA, record)
true
}
private fun markRejected(context: Context, refresh: String) = synchronized(refreshLock) {
val app = context.applicationContext
val record = StoreAccounts.read(app, Store.EA) ?: return@synchronized
if (record.optString("refresh_token") != refresh) return@synchronized
StoreAccounts.write(app, Store.EA, record.put("refresh_rejected", true))
}
fun signedIn(context: Context): Boolean {
val a = load(context) ?: return false
return a.userId.isNotEmpty() && !(a.rejected && a.expiresAt <= System.currentTimeMillis())
}
fun accessToken(context: Context): String? {
val current = load(context) ?: return null
if (fresh(current)) return current.accessToken
@@ -0,0 +1,255 @@
package com.droiddeck.launcher.stores.ea
import android.util.Base64
import android.util.Xml
import com.droiddeck.launcher.stores.CloudFile
import com.droiddeck.launcher.stores.CloudTransport
import java.io.File
import java.io.StringReader
import java.security.MessageDigest
import java.time.Instant
import org.xmlpull.v1.XmlPullParser
internal class EaCloud(
private val token: String,
private val uid: String,
private val keys: List<String>,
private val base: String,
private val rules: EaSaveRules,
val localDir: File? = null,
) : CloudTransport {
class Entry(val size: Long, val href: String, val md5: String, val created: String, val modified: String, val localName: String)
class Manifest(val lineage: String, val files: List<Entry>, val snapshots: List<String>)
private class Signed(val url: String, val headers: Map<String, String>)
private class Request(val verb: String, val resource: String, val md5: String? = null, val type: String? = null)
private var key: String? = null
private var found = false
private var listed: Map<String, String?>? = null
private val committed = HashMap<String, CloudFile>()
override fun wants(name: String): Boolean = rules.matches(base + name)
override fun committed(name: String): CloudFile? = committed[name]
override fun list(): List<CloudFile> {
val manifest = pick()
val files = manifest?.files.orEmpty().mapNotNull { e ->
val path = EaSaveRules.normalize(e.localName)
if (!path.startsWith(base, ignoreCase = true) || !rules.matches(path)) return@mapNotNull null
val md5 = hex(e.md5) ?: error("EA listed ${path.substring(base.length)} without a valid checksum")
CloudFile(localName(path.substring(base.length)), parseTime(e.modified), md5, readLink = e.href)
}
val twins = files.groupBy { it.name.lowercase() }.values.firstOrNull { it.size > 1 }
check(twins == null) { "EA lists more than one save named ${twins!!.first().name} in different cases" }
listed = files.associate { it.name.lowercase() to it.md5 }
return files
}
private fun localName(name: String): String {
var dir = localDir ?: return name
val parts = name.split('/')
val out = ArrayList<String>()
for (part in parts) {
val match = dir.listFiles()?.filter { it.name.equals(part, ignoreCase = true) }.orEmpty()
check(match.size <= 1) { "The save folder holds more than one file named $part in different cases" }
val pick = match.singleOrNull()
if (pick == null) return (out + parts.drop(out.size)).joinToString("/")
out += pick.name
dir = pick
}
return out.joinToString("/")
}
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val href = file.readLink ?: error("EA has no data for ${file.name}")
return locked("read", key ?: keys.first()) { lock, _ ->
val signed = authorize(lock, listOf(Request("GET", href))).single()
val reply = EaHttp.request(signed.url, headers = signed.headers)
check(reply.ok) { "EA cloud save download answered ${reply.status}" }
val want = file.md5 ?: error("EA listed ${file.name} without a valid checksum")
check(hex(b64(md5(reply.body))) == want) { "EA cloud save ${file.name} failed its checksum" }
reply.body to file.modifiedMs
}
}
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> {
if (key == null) pick()
check(found || keys.size == 1) { "EA has no cloud save record for this game yet; play it once in the EA app" }
val target = key ?: keys.first()
val seen = listed
return locked("write", target) { lock, body ->
val locked = manifestUrl(body)?.let { fetchManifest(it) }
check(locked != null || !found) { "EA's cloud save record disappeared" }
val current = locked ?: Manifest("{00000000-0000-0000-0000-000000000000}", emptyList(), emptyList())
if (seen != null) for (name in files.keys) {
val entry = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }
val now = entry?.let { hex(it.md5) ?: error("EA lists $name without a valid checksum") }
check(now == seen[name.lowercase()]) { "EA's cloud saves changed since they were read" }
}
val now = System.currentTimeMillis()
val added = files.map { (name, data) ->
val sum = md5(data)
val stamp = stamp(modifiedMs[name]?.takeIf { it > 0 } ?: now)
val old = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }
Entry(data.size.toLong(), "content/${data.size}-${hexOf(sum)}", b64(sum), old?.created ?: stamp, stamp, base + name) to data
}
val names = added.map { it.first.localName.lowercase() }.toSet()
val next = Manifest(current.lineage, current.files.filter { EaSaveRules.normalize(it.localName).lowercase() !in names } + added.map { it.first }, current.snapshots)
val xml = write(next).toByteArray()
val xmlMd5 = b64(md5(xml))
val requests = added.map { Request("PUT", it.first.href, it.first.md5, "application/octet-stream") } + Request("PUT", "manifest.xml", xmlMd5, "text/xml")
val signed = authorize(lock, requests)
for ((i, pair) in added.withIndex()) upload(signed[i], pair.second)
upload(signed.last(), xml)
found = true
for ((entry, _) in added) {
val name = entry.localName.substring(base.length)
committed[name] = CloudFile(name, parseTime(entry.modified), hex(entry.md5), readLink = entry.href)
}
listed = null
files.mapValues { (name, _) -> modifiedMs[name]?.takeIf { it > 0 } ?: now }
}
}
private fun pick(): Manifest? {
for (candidate in keys) {
val manifest = locked("read", candidate, missing = { null }) { _, body -> manifestUrl(body)?.let { fetchManifest(it) } }
if (manifest != null) {
key = candidate
found = true
return manifest
}
}
key = keys.first()
found = false
return null
}
private fun upload(signed: Signed, data: ByteArray) {
val reply = EaHttp.request(signed.url, "PUT", signed.headers, data)
check(reply.ok) { "EA cloud save upload answered ${reply.status}" }
}
private fun fetchManifest(url: String): Manifest? {
val reply = EaHttp.request(url)
if (reply.status == 404) return null
check(reply.ok) { "EA cloud save manifest answered ${reply.status}" }
return parse(reply.text)
}
private fun <T> locked(kind: String, key: String, missing: (() -> T)? = null, body: (String, String) -> T): T {
val reply = EaHttp.request("$HOST/lock/$kind/$uid/$key", "POST", mapOf(AUTH to token, "Content-Type" to "application/xml"), ByteArray(0))
if (reply.status == 404 && missing != null) return missing()
check(reply.ok) { "EA cloud saves answered ${reply.status}" }
val lock = reply.header(LOCK) ?: error("EA did not grant a cloud save lock")
try {
return body(lock, reply.text)
} finally {
runCatching { EaHttp.request("$HOST/lock/delete/$uid", "DELETE", mapOf(AUTH to token, LOCK to lock)) }
}
}
private fun authorize(lock: String, requests: List<Request>): List<Signed> {
val body = buildString {
append("<requests>")
for ((i, r) in requests.withIndex()) {
append("<request id=\"").append(i).append("\"><verb>").append(r.verb).append("</verb><resource>").append(escape(r.resource)).append("</resource>")
r.md5?.let { append("<md5>").append(it).append("</md5>") }
r.type?.let { append("<content-type>").append(it).append("</content-type>") }
append("</request>")
}
append("</requests>")
}
val reply = EaHttp.request("$HOST/lock/authorize/$uid", "PUT", mapOf(AUTH to token, LOCK to lock, "Content-Type" to "application/xml"), body.toByteArray())
check(reply.ok) { "EA cloud saves refused the transfer (${reply.status})" }
return signedRequests(reply.text, requests.size)
}
companion object {
private const val HOST = "https://cloudsync.juno.ea.com"
private const val AUTH = "X-Origin-AuthToken"
private const val LOCK = "X-Origin-Sync-Lock"
private val FILE = Regex("<file\\b([^>]*)>(.*?)</file>", RegexOption.DOT_MATCHES_ALL)
private val LOCAL = Regex("<localName\\b([^>]*)>([^<]*)</localName>")
private val SNAPSHOT = Regex("<snapshot>([^<]*)</snapshot>")
private val REQUEST = Regex("<request\\b[^>]*\\bid=\"(\\d+)\"[^>]*>(.*?)</request>", RegexOption.DOT_MATCHES_ALL)
private val HEADER = Regex("<header\\b([^>]*)/?>")
fun keys(masterTitleId: String, multiplayerId: String): List<String> =
if (multiplayerId.isNotEmpty()) listOf("${masterTitleId}_$multiplayerId") else listOf(masterTitleId, "${masterTitleId}_$masterTitleId")
fun manifestUrl(lockBody: String): String? = Regex("<manifest>([^<]+)</manifest>").find(lockBody)?.groupValues?.get(1)?.let(::unescape)
fun parse(xml: String): Manifest {
check(wellFormed(xml)) { "EA sent an incomplete cloud save manifest" }
val lineage = attr(Regex("<manifest\\b([^>]*)>").find(xml)?.groupValues?.get(1).orEmpty(), "lineage")
?: "{00000000-0000-0000-0000-000000000000}"
val files = FILE.findAll(xml).mapNotNull { m ->
val a = m.groupValues[1]
val local = LOCAL.find(m.groupValues[2]) ?: return@mapNotNull null
Entry(attr(a, "size")?.toLongOrNull() ?: 0, attr(a, "href").orEmpty(), attr(a, "md5").orEmpty(),
attr(local.groupValues[1], "created").orEmpty(), attr(local.groupValues[1], "lastModified").orEmpty(), unescape(local.groupValues[2]))
}.toList()
return Manifest(lineage, files, SNAPSHOT.findAll(xml).map { unescape(it.groupValues[1]) }.toList())
}
private fun wellFormed(xml: String): Boolean = runCatching {
val p = Xml.newPullParser()
p.setInput(StringReader(xml))
var root: String? = null
var depth = 0
var closed = false
while (p.next() != XmlPullParser.END_DOCUMENT) when (p.eventType) {
XmlPullParser.START_TAG -> { if (root == null) root = p.name; depth++ }
XmlPullParser.END_TAG -> { depth--; if (depth == 0) closed = true }
}
root == "manifest" && depth == 0 && closed
}.getOrDefault(false)
fun write(m: Manifest): String = buildString {
append("<manifest xmlns=\"http://origin.com/cloudsaves/manifest\" lineage=\"").append(escape(m.lineage)).append("\">\n")
for (f in m.files) {
append(" <file size=\"").append(f.size).append("\" href=\"").append(escape(f.href)).append("\" md5=\"").append(escape(f.md5)).append("\">\n")
append(" <localName created=\"").append(escape(f.created)).append("\" lastModified=\"").append(escape(f.modified)).append("\">")
append(escape(f.localName)).append("</localName>\n </file>\n")
}
for (s in m.snapshots) append(" <snapshot>").append(escape(s)).append("</snapshot>\n")
append("</manifest>\n")
}
private fun signedRequests(xml: String, count: Int): List<Signed> {
val byId = REQUEST.findAll(xml).associate { m ->
val inner = m.groupValues[2]
val url = Regex("<url>([^<]+)</url>").find(inner)?.groupValues?.get(1)?.let(::unescape) ?: error("EA sent no transfer URL")
val headers = HEADER.findAll(inner).mapNotNull { h ->
val k = attr(h.groupValues[1], "key") ?: return@mapNotNull null
k to (attr(h.groupValues[1], "value") ?: "")
}.toMap()
m.groupValues[1].toInt() to Signed(url, headers)
}
return (0 until count).map { byId[it] ?: error("EA signed ${byId.size} of $count cloud save transfers") }
}
fun stamp(ms: Long): String = Instant.ofEpochMilli(ms / 1000 * 1000).toString() + "Z"
fun parseTime(s: String): Long = runCatching { Instant.parse(s.trimEnd('Z') + "Z").toEpochMilli() }.getOrDefault(-1L)
private fun attr(attrs: String, name: String): String? = Regex("\\b$name=\"([^\"]*)\"").find(attrs)?.groupValues?.get(1)?.let(::unescape)
private fun md5(data: ByteArray) = MessageDigest.getInstance("MD5").digest(data)
private fun b64(sum: ByteArray) = Base64.encodeToString(sum, Base64.NO_WRAP)
private fun hexOf(sum: ByteArray) = sum.joinToString("") { "%02x".format(it) }
fun hex(b64: String): String? = runCatching { hexOf(Base64.decode(b64, Base64.DEFAULT)) }.getOrNull()?.takeIf { it.length == 32 }
private fun escape(s: String) = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
private fun unescape(s: String) = EaSaveRules.unescape(s)
}
}
@@ -0,0 +1,76 @@
package com.droiddeck.launcher.stores.ea
internal class EaSaveRules(val includes: List<String>, val excludes: List<String>) {
fun base(): String? {
val dirs = includes.map { pattern ->
val wild = pattern.indexOfFirst { it == '*' || it == '?' }
val fixed = if (wild < 0) pattern else pattern.substring(0, wild)
if (fixed.endsWith('/')) fixed else fixed.substringBeforeLast('/', "") + "/"
}
val parts = dirs.map { it.trimEnd('/').split('/') }
if (parts.isEmpty()) return null
val common = ArrayList<String>()
for (i in parts.minOf { it.size }.let { 0 until it }) {
val seg = parts[0][i]
if (parts.all { it[i].equals(seg, ignoreCase = true) }) common += seg else break
}
if (common.isEmpty() || !VARIABLE.matches(common[0])) return null
return common.joinToString("/") + "/"
}
fun matches(path: String): Boolean {
val p = normalize(path)
return includes.any { hit(it, p) } && excludes.none { hit(it, p) }
}
private fun hit(pattern: String, path: String): Boolean = when {
pattern.endsWith('/') -> path.startsWith(pattern, ignoreCase = true)
pattern.any { it == '*' || it == '?' } -> glob(pattern).matches(path)
else -> path.equals(pattern, ignoreCase = true)
}
private fun glob(pattern: String): Regex = Regex(
pattern.split('*').joinToString("[^/]*") { part -> part.split('?').joinToString("[^/]") { Regex.escape(it) } },
RegexOption.IGNORE_CASE,
)
companion object {
private val VARIABLE = Regex("%[A-Za-z]+%")
private val RULE = Regex("<(include|exclude)\\b[^>]*>([^<]*)</\\1>", RegexOption.IGNORE_CASE)
private val TOKENS = mapOf(
"documents" to "%DOCUMENTS%", "savedgames" to "%SAVED_GAMES%", "appdata" to "%APPDATA%",
"localappdata" to "%LOCALAPPDATA%", "programdata" to "%PROGRAMDATA%", "userprofile" to "%USERPROFILE%",
)
private val COMMENT = Regex("<!--.*?-->", RegexOption.DOT_MATCHES_ALL)
private val ENTITY = Regex("&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|quot|apos|amp);")
fun normalize(path: String) = path.replace('\\', '/')
fun parse(xml: String): EaSaveRules? {
val rules = RULE.findAll(COMMENT.replace(xml, "")).map { it.groupValues[1].lowercase() to normalize(unescape(it.groupValues[2]).trim()) }
.filter { it.second.isNotEmpty() }.toList()
val includes = rules.filter { it.first == "include" }.map { it.second }
if (includes.isEmpty()) return null
return EaSaveRules(includes, rules.filter { it.first == "exclude" }.map { it.second })
}
fun template(base: String): String? {
val variable = VARIABLE.find(base)?.takeIf { it.range.first == 0 } ?: return null
val token = TOKENS[variable.value.trim('%').lowercase()] ?: return null
return token + base.substring(variable.value.length)
}
fun unescape(s: String): String = ENTITY.replace(s) { m ->
when (val e = m.groupValues[1]) {
"lt" -> "<"
"gt" -> ">"
"quot" -> "\""
"apos" -> "'"
"amp" -> "&"
else -> runCatching { String(Character.toChars(if (e.startsWith("#x")) e.substring(2).toInt(16) else e.substring(1).toInt())) }.getOrDefault(m.value)
}
}
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.ui
import android.widget.Toast
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.LocalIndication
import androidx.compose.ui.semantics.Role
@@ -257,7 +258,7 @@ internal fun GameDetail(
stringResource(R.string.game_tab_achievements_count, stringResource(R.string.achievements_title), achievementState.done, list.size)
} ?: stringResource(R.string.achievements_title)
GameTab.LAUNCH -> stringResource(R.string.game_tab_launch)
GameTab.SAVES -> stringResource(if (Store.byId(source).let { it == Store.GOG || it == Store.EPIC }) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.SAVES -> stringResource(if (CloudSaves.supports(Store.byId(source))) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.ADDONS -> stringResource(R.string.game_tab_addons)
GameTab.INSTALL -> stringResource(R.string.game_tab_install)
}
@@ -466,7 +467,10 @@ internal fun GameActions(
}
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
if (game != null && !compactMenu) EditArtButton(game)
if (game != null && !compactMenu) {
HideButton(hideKey(game), game)
EditArtButton(game)
}
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
@@ -526,6 +530,8 @@ internal fun GameActions(
}
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
val entryKey = game?.let(::hideKey) ?: storeKey
if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game)
if (cloud && (download != null || failed != null)) {
XboxStreamButton(game.storeId.orEmpty(), game.name)
XboxLibraryButton(game.storeId.orEmpty(), item)
@@ -618,6 +624,17 @@ internal fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
}
}
internal fun hideKey(g: Library.SteamGame): String = g.storeId?.let { "${g.source}:$it" } ?: GameRef.key(g)
@Composable
internal fun HideButton(key: String, g: Library.SteamGame?) {
val ctx = LocalContext.current
rememberHiddenSync()
val hidden = LibraryHidden.isHidden(key, g)
val failed = stringResource(R.string.game_hide_failed)
SecondaryButton(stringResource(if (hidden) R.string.game_unhide else R.string.common_hide), compact = true) { if (!LibraryHidden.set(ctx, key, g, !hidden)) Toast.makeText(ctx, failed, Toast.LENGTH_LONG).show() }
}
@Composable
internal fun EditArtButton(g: Library.SteamGame) {
val open = rememberEditArt(g) ?: return
@@ -628,6 +645,10 @@ internal fun EditArtButton(g: Library.SteamGame) {
private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) {
var open by remember(g.gameId) { mutableStateOf(false) }
val edit = rememberEditArt(g)
val ctx = LocalContext.current
rememberHiddenSync()
val hidden = LibraryHidden.isHidden(hideKey(g), g)
val failed = stringResource(R.string.game_hide_failed)
Box {
SecondaryButton(stringResource(R.string.game_more)) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = stringResource(R.string.game_more), compact = true) { first ->
@@ -638,6 +659,8 @@ private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) {
MenuItem(stringResource(R.string.game_shortcut_add), checked = false, focusRequester = take()) { open = false; a.onGameShortcut(g) }
MenuItem(stringResource(R.string.game_file_export), checked = false) { open = false; a.onExportGameFile(g) }
MenuItem(stringResource(R.string.game_link_copy), checked = false) { open = false; a.onCopyGameLink(g) }
val hideKey = hideKey(g)
MenuItem(stringResource(if (hidden) R.string.game_unhide else R.string.common_hide), checked = false) { open = false; if (!LibraryHidden.set(ctx, hideKey, g, !hidden)) Toast.makeText(ctx, failed, Toast.LENGTH_LONG).show() }
edit?.let { run -> MenuItem(stringResource(R.string.game_edit_art), checked = false) { open = false; run() } }
}
}
@@ -888,7 +911,7 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
}
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(summary, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp).readable().padding(4.dp))
if (Store.byId(g.source).let { it == Store.GOG || it == Store.EPIC }) {
if (CloudSaves.supports(Store.byId(g.source))) {
SectionLabel(stringResource(R.string.store_cloud_saves))
CloudRows(g)
SectionLabel(stringResource(R.string.games_saves))
@@ -947,7 +970,7 @@ private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions)
@Composable
private fun CloudRows(g: Library.SteamGame) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON && it != Store.EA } ?: return
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
val id = g.storeId ?: return
val context = LocalContext.current.applicationContext
var busy by remember(g.gameId) { mutableStateOf<String?>(null) }
@@ -977,11 +1000,13 @@ private fun CloudRows(g: Library.SteamGame) {
StoresState.post { enabled = written?.cloud ?: enabled }
}, "cloud-switch").start()
}
val ready = st != null && supported && enabled && busy == null
val ready = st != null && supported && enabled && busy == null && st.folder != null && st.signedIn
val pending = stringResource(R.string.cloud_pending)
val summary = when {
st == null || busy != null -> pending
!supported -> stringResource(R.string.cloud_none)
!st.signedIn || st.reason == "not-signed-in" -> stringResource(R.string.cloud_signed_out)
st.folder == null -> stringResource(R.string.cloud_not_synced)
conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size)
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
else -> stringResource(R.string.cloud_never)
@@ -28,8 +28,12 @@ internal object LibraryFavorites {
internal fun toggled(keys: Set<String>, key: String): Set<String> = if (key in keys) keys - key else keys + key
internal fun inLibrarySource(source: String, entry: LibraryEntry, favorites: Set<String>): Boolean = when (source) {
LIBRARY_ALL -> true
LIBRARY_FAVORITES -> entry.favoriteKey in favorites
else -> entry.source == source
internal fun inLibrarySource(source: String, entry: LibraryEntry, favorites: Set<String>, hidden: (LibraryEntry) -> Boolean = { false }): Boolean {
val concealed = hidden(entry)
return when (source) {
LIBRARY_HIDDEN -> concealed
LIBRARY_ALL -> !concealed
LIBRARY_FAVORITES -> !concealed && entry.favoriteKey in favorites
else -> !concealed && entry.source == source
}
}
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.frontend.SteamHidden
import com.droiddeck.launcher.session.SessionPrefs
internal const val LIBRARY_HIDDEN = "hidden"
internal object LibraryHidden {
var keys by mutableStateOf<Set<String>>(emptySet())
private set
var account by mutableStateOf<java.io.File?>(null)
private set
var steam by mutableStateOf<Set<Long>>(emptySet())
private set
fun load(context: Context) {
keys = SessionPrefs.libraryHidden(context)
refreshSteam(context)
}
fun refreshSteam(context: Context) {
val root = SessionPrefs.activeSteamRoot(context)
adopt(root)
SteamHidden.readOrNull(root)?.let { steam = it }
}
private fun adopt(root: java.io.File) {
val resolved = AddedGames.accountConfig(root)
if (resolved != account) {
account = resolved
steam = emptySet()
}
}
fun steamId(game: Library.SteamGame?): Long? = game?.takeIf { Library.fromSteamClient(it) }?.appId?.toLong()
fun isHidden(key: String, game: Library.SteamGame?): Boolean = key in keys || steamId(game)?.let { it in steam } == true
fun isHidden(entry: LibraryEntry): Boolean = isHidden(entry.favoriteKey, entry.game)
fun set(context: Context, key: String, game: Library.SteamGame?, hidden: Boolean): Boolean {
val id = steamId(game)
val root = SessionPrefs.activeSteamRoot(context)
val written = id?.let { SteamHidden.write(root, it, hidden) }
if (id != null) {
adopt(root)
steam = written?.hidden ?: SteamHidden.readOrNull(root) ?: steam
}
keys = if (hidden && (id == null || written == null)) keys + key else keys - key
SessionPrefs.setLibraryHidden(context, keys)
return id == null || written?.queued == true
}
}
@Composable
internal fun rememberHiddenSync() {
val ctx = LocalContext.current
remember { LibraryHidden.load(ctx) }
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) LibraryHidden.refreshSteam(ctx) }
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
}
@@ -163,11 +163,17 @@ internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
internal const val LIBRARY_ALL = "all"
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet(), favorites: Set<String> = emptySet()): List<String> =
(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED + Library.SOURCE_COLLECTION)
internal fun librarySources(
entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet(), favorites: Set<String> = emptySet(),
hidden: (LibraryEntry) -> Boolean = { false }, showHidden: Boolean = false,
): List<String> =
(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED + Library.SOURCE_COLLECTION + LIBRARY_HIDDEN)
.filter { source ->
if (source == LIBRARY_FAVORITES) entries.any { it.favoriteKey in favorites }
else source in always || entries.any { it.source == source }
when (source) {
LIBRARY_HIDDEN -> showHidden
LIBRARY_FAVORITES -> entries.any { it.favoriteKey in favorites && !hidden(it) }
else -> source in always || entries.any { it.source == source && !hidden(it) }
}
}
internal object LibraryDisplay {
@@ -178,11 +184,14 @@ internal object LibraryDisplay {
private set
var size by mutableStateOf(true)
private set
var hidden by mutableStateOf(false)
private set
fun load(context: android.content.Context) {
level = SessionPrefs.libraryCardLevel(context).coerceIn(0, scales.lastIndex)
title = SessionPrefs.libraryShowTitle(context)
size = SessionPrefs.libraryShowSize(context)
hidden = SessionPrefs.libraryShowHidden(context)
}
fun step(context: android.content.Context, by: Int) {
@@ -199,6 +208,11 @@ internal object LibraryDisplay {
size = !size
SessionPrefs.setLibraryShowSize(context, size)
}
fun toggleHidden(context: android.content.Context) {
hidden = !hidden
SessionPrefs.setLibraryShowHidden(context, hidden)
}
}
internal object LibraryView {
@@ -228,8 +242,10 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
remember { LibraryDisplay.load(ctx) }
remember { FolderSizes.load(ctx) }
remember { LibraryFavorites.load(ctx) }
rememberHiddenSync()
val soundMode = selected == "soundtracks" || selected.startsWith("sound:")
val favorites = if (soundMode) emptySet() else LibraryFavorites.keys
val concealed: (LibraryEntry) -> Boolean = { !soundMode && LibraryHidden.isHidden(it) }
val stores = !s.shortcutPicker && !soundMode
val signedIn = Store.entries.filter { StoresState.isSignedIn(it) }
LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } }
@@ -267,7 +283,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val sources = librarySources(
all, SessionPrefs.storesTabOrder(ctx),
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.SOURCE_COLLECTION.takeIf { soundMode }).toSet(),
favorites,
favorites, concealed, LibraryDisplay.hidden && !soundMode,
)
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
val q = LibraryView.query.trim().lowercase()
@@ -290,7 +306,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val collectionItems = collectionId?.let { if (source == Store.GAMEJOLT.id) GameJoltCollections.gamesOf(it) else ItchCollections.gamesOf(it) }
val pool = if (collectionId == null) all else collectionEntries(all, collectionItems.orEmpty(), Store.byId(source) ?: Store.ITCH)
val matching = pool.filter {
inLibrarySource(source, it, favorites) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
inLibrarySource(source, it, favorites, concealed) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
}
val listUninstalled = if (collectionId == null) showUninstalled else collectionShows?.takeIf { it.first == collectionId }?.second ?: true
val trackHits by produceState<List<SoundtrackIndex.Hit>>(emptyList(), soundMode, q, source, s.soundtracks) {
@@ -317,8 +333,8 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
}
}
var savedDialog by remember { mutableStateOf(false) }
val candidates = if (listUninstalled) matching else matching.filter { it.installed }
val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed }
val candidates = if (listUninstalled || source == LIBRARY_HIDDEN) matching else matching.filter { it.installed }
val hiddenUninstalled = if (listUninstalled || source == LIBRARY_HIDDEN) 0 else matching.count { !it.installed }
val sort = s.storesSort
val sizeSort = sort == "sizeAsc" || sort == "sizeDesc"
val installedAt = StoresState.installed.associate { it.key to it.sidecar.installedAt }
@@ -539,7 +555,7 @@ private fun LibraryGrid(
}
val picker = s.shortcutPicker && e.game != null
val choose = if (picker) ({ a.onSteamGame(e.game!!) }) else null
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL || source == LIBRARY_FAVORITES)
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL || source == LIBRARY_FAVORITES || source == LIBRARY_HIDDEN)
}
LazyVerticalGrid(
columns = if (listMode) GridCells.Fixed(1) else GridCells.Adaptive(tileWidth), state = grid,
@@ -679,17 +695,19 @@ private fun LibraryHeader(
@Composable
private fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, accounts: Boolean) {
if (sources.size < 2 && !accounts) return
val chips = sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
if (!chips && !accounts) return
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp).horizontalScroll(rememberScrollState()),
) {
if (sources.size >= 2) SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) }
if (sources.size >= 2) for (src in sources) {
if (chips) SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) }
if (chips) for (src in sources) {
val store = Store.byId(src)
val dot = when {
store != null -> sourceColours(src).dot.copy(alpha = if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f)
src == LIBRARY_FAVORITES -> FavoritesColours.dot
src == LIBRARY_HIDDEN -> Color(0xFF9AA0A6)
src == Library.SOURCE_STEAM || src == Library.ADDED || src == Library.SOURCE_COLLECTION -> sourceColours(src).dot
else -> null
}
@@ -698,6 +716,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
when (src) {
Library.ADDED -> stringResource(R.string.library_filter_added)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> store?.shortLabel ?: sourceLabel(src)
},
source == src, dot,
@@ -1058,7 +1077,7 @@ internal fun DisplayButton() {
HeaderIconButton(title, Icons.Filled.Visibility, "display") {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 4,
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 5,
handle = { Icon(Icons.Filled.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
@@ -1081,6 +1100,10 @@ internal fun DisplayButton() {
stringResource(R.string.library_display_size), selected = LibraryDisplay.size, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(3),
) { LibraryDisplay.toggleSize(ctx) }
StepChoice(
stringResource(R.string.apps_filter_hidden), selected = LibraryDisplay.hidden, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(4),
) { LibraryDisplay.toggleHidden(ctx) }
}
})
}
@@ -83,12 +83,21 @@ private const val DRIFT_STEP_NS = 15_000_000L
internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
val ctx = androidx.compose.ui.platform.LocalContext.current
LaunchedEffect(Unit) { com.droiddeck.launcher.frontend.SteamFeatured.load(ctx) }
val featured = com.droiddeck.launcher.frontend.SteamFeatured.games
rememberHiddenSync()
val featuredAll = com.droiddeck.launcher.frontend.SteamFeatured.games
val signedIn = s.offlineAccount != null
val owned by produceState(emptyList<Pair<Int, java.io.File>>(), signedIn) {
value = if (!signedIn) emptyList() else withContext(Dispatchers.IO) { runCatching { Library.steamLibraryArt(ctx).shuffled() }.getOrDefault(emptyList()) }
val account = LibraryHidden.account
val scanned by produceState<Pair<java.io.File?, List<Pair<Int, java.io.File>>>>(account to emptyList(), signedIn, LibraryHidden.steam, account) {
val art = if (!signedIn) emptyList() else withContext(Dispatchers.IO) { runCatching { Library.steamLibraryArt(ctx).shuffled() }.getOrDefault(emptyList()) }
value = account to art
}
val games = remember(s.steamGames) { s.steamGames.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
val ownedAll = if (scanned.first == account) scanned.second else emptyList()
val concealed = remember(s.steamGames, LibraryHidden.keys, LibraryHidden.steam) {
LibraryHidden.steam + s.steamGames.filter { LibraryHidden.isHidden(hideKey(it), it) }.map { it.appId.toLong() }
}
val owned = remember(ownedAll, concealed) { ownedAll.filter { it.first.toLong() !in concealed } }
val featured = remember(featuredAll, concealed) { featuredAll.filter { it.appId.toLong() !in concealed } }
val games = remember(s.steamGames, LibraryHidden.keys, LibraryHidden.steam) { s.steamGames.filterNot { LibraryHidden.isHidden(hideKey(it), it) }.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
val narrow = LocalNarrowPane.current
var words by remember { mutableStateOf<Rect?>(null) }
val mode = com.droiddeck.launcher.session.SessionService.MODE_STEAM
+2
View File
@@ -1605,6 +1605,8 @@
<string name="pip_unavailable">تعذّر على Android فتح نافذة ضمن النافذة.</string>
<string name="game_more">المزيد</string>
<string name="game_edit_art">تعديل الصور</string>
<string name="game_unhide">إزالة من المخفية</string>
<string name="game_hide_failed">تعذّرت المزامنة مع Steam. أغلق Steam وحاول مرة أخرى.</string>
<string name="stores_in_steam_label">في Steam</string>
<string name="game_shortcut">اختصار</string>
<string name="game_shortcut_add">إضافة إلى الشاشة الرئيسية</string>
@@ -1651,6 +1651,8 @@
<string name="pip_unavailable">Android no pudo abrir imagen en imagen.</string>
<string name="game_more">Más</string>
<string name="game_edit_art">Editar imágenes</string>
<string name="game_unhide">Quitar de ocultas</string>
<string name="game_hide_failed">No se pudo sincronizar con Steam. Cierra Steam e inténtalo de nuevo.</string>
<string name="stores_in_steam_label">En Steam</string>
<string name="game_shortcut">Acceso directo</string>
<string name="game_shortcut_add">Agregar a la pantalla de inicio</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Android не можа да отвори картина в картината.</string>
<string name="game_more">Още</string>
<string name="game_edit_art">Редактиране на изображенията</string>
<string name="game_unhide">Премахване от скритите</string>
<string name="game_hide_failed">Синхронизирането със Steam не успя. Затворете Steam и опитайте отново.</string>
<string name="stores_in_steam_label">В Steam</string>
<string name="game_shortcut">Пряк път</string>
<string name="game_shortcut_add">Добавяне към началния екран</string>
+2
View File
@@ -1589,6 +1589,8 @@
<string name="pip_unavailable">Android nemohl otevřít obraz v obraze.</string>
<string name="game_more">Další</string>
<string name="game_edit_art">Upravit grafiku</string>
<string name="game_unhide">Odebrat ze skrytých</string>
<string name="game_hide_failed">Synchronizace se Steamem se nezdařila. Zavřete Steam a zkuste to znovu.</string>
<string name="stores_in_steam_label">Ve Steamu</string>
<string name="game_shortcut">Zkratka</string>
<string name="game_shortcut_add">Přidat na domovskou obrazovku</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Android kunne ikke åbne billede i billede.</string>
<string name="game_more">Mere</string>
<string name="game_edit_art">Rediger grafik</string>
<string name="game_unhide">Fjern fra skjulte</string>
<string name="game_hide_failed">Kunne ikke synkronisere med Steam. Luk Steam og prøv igen.</string>
<string name="stores_in_steam_label">I Steam</string>
<string name="game_shortcut">Genvej</string>
<string name="game_shortcut_add">Tilføj til hjemmeskærm</string>
+2
View File
@@ -1565,6 +1565,8 @@
<string name="pip_unavailable">Android konnte Bild im Bild nicht öffnen.</string>
<string name="game_more">Mehr</string>
<string name="game_edit_art">Grafiken bearbeiten</string>
<string name="game_unhide">Nicht mehr ausblenden</string>
<string name="game_hide_failed">Synchronisierung mit Steam fehlgeschlagen. Schließe Steam und versuche es erneut.</string>
<string name="stores_in_steam_label">In Steam</string>
<string name="game_shortcut">Verknüpfung</string>
<string name="game_shortcut_add">Zum Startbildschirm hinzufügen</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Το Android δεν μπόρεσε να ανοίξει τη λειτουργία εικόνας εντός εικόνας.</string>
<string name="game_more">Περισσότερα</string>
<string name="game_edit_art">Επεξεργασία εικαστικών</string>
<string name="game_unhide">Κατάργηση από τις κρυφές</string>
<string name="game_hide_failed">Αποτυχία συγχρονισμού με το Steam. Κλείστε το Steam και δοκιμάστε ξανά.</string>
<string name="stores_in_steam_label">Στο Steam</string>
<string name="game_shortcut">Συντόμευση</string>
<string name="game_shortcut_add">Προσθήκη στην αρχική οθόνη</string>
+2
View File
@@ -1581,6 +1581,8 @@
<string name="pip_unavailable">Android no pudo abrir imagen en imagen.</string>
<string name="game_more">Más</string>
<string name="game_edit_art">Editar imágenes</string>
<string name="game_unhide">Quitar de ocultas</string>
<string name="game_hide_failed">No se pudo sincronizar con Steam. Cierra Steam e inténtalo de nuevo.</string>
<string name="stores_in_steam_label">En Steam</string>
<string name="game_shortcut">Acceso directo</string>
<string name="game_shortcut_add">Añadir a la pantalla de inicio</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Android ei pystynyt avaamaan kuva kuvassa -tilaa.</string>
<string name="game_more">Lisää</string>
<string name="game_edit_art">Muokkaa kuvitusta</string>
<string name="game_unhide">Poista piilotetuista</string>
<string name="game_hide_failed">Synkronointi Steamin kanssa epäonnistui. Sulje Steam ja yritä uudelleen.</string>
<string name="stores_in_steam_label">Steamissa</string>
<string name="game_shortcut">Pikakuvake</string>
<string name="game_shortcut_add">Lisää aloitusnäytölle</string>
+2
View File
@@ -1580,6 +1580,8 @@
<string name="pip_unavailable">Android ne peut pas ouvrir le mode PiP.</string>
<string name="game_more">Plus</string>
<string name="game_edit_art">Modifier les illustrations</string>
<string name="game_unhide">Ne plus masquer</string>
<string name="game_hide_failed">Synchronisation avec Steam impossible. Fermez Steam et réessayez.</string>
<string name="stores_in_steam_label">Dans Steam</string>
<string name="game_shortcut">Raccourci</string>
<string name="game_shortcut_add">Ajouter à l\'écran d\'accueil</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Android पिक्चर इन पिक्चर नहीं खोल सका।</string>
<string name="game_more">और</string>
<string name="game_edit_art">आर्ट एडिट करें</string>
<string name="game_unhide">छिपे हुए से हटाएं</string>
<string name="game_hide_failed">Steam के साथ सिंक नहीं हो सका। Steam बंद करके फिर कोशिश करें।</string>
<string name="stores_in_steam_label">Steam में</string>
<string name="game_shortcut">शॉर्टकट</string>
<string name="game_shortcut_add">होम स्क्रीन पर जोड़ें</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Az Android nem tudta megnyitni a kép a képben módot.</string>
<string name="game_more">Továbbiak</string>
<string name="game_edit_art">Illusztrációk szerkesztése</string>
<string name="game_unhide">Eltávolítás a rejtettek közül</string>
<string name="game_hide_failed">Nem sikerült szinkronizálni a Steammel. Zárd be a Steamet, és próbáld újra.</string>
<string name="stores_in_steam_label">A Steamben</string>
<string name="game_shortcut">Parancsikon</string>
<string name="game_shortcut_add">Hozzáadás a kezdőképernyőhöz</string>
+2
View File
@@ -1566,6 +1566,8 @@
<string name="pip_unavailable">Android tidak dapat membuka gambar dalam gambar.</string>
<string name="game_more">Lainnya</string>
<string name="game_edit_art">Edit gambar</string>
<string name="game_unhide">Hapus dari tersembunyi</string>
<string name="game_hide_failed">Gagal menyinkronkan dengan Steam. Tutup Steam lalu coba lagi.</string>
<string name="stores_in_steam_label">Di Steam</string>
<string name="game_shortcut">Pintasan</string>
<string name="game_shortcut_add">Tambahkan ke layar utama</string>
+2
View File
@@ -1572,6 +1572,8 @@
<string name="pip_unavailable">Android non è riuscito ad aprire il picture in picture.</string>
<string name="game_more">Altro</string>
<string name="game_edit_art">Modifica grafica</string>
<string name="game_unhide">Rimuovi dai nascosti</string>
<string name="game_hide_failed">Impossibile sincronizzare con Steam. Chiudi Steam e riprova.</string>
<string name="stores_in_steam_label">In Steam</string>
<string name="game_shortcut">Scorciatoia</string>
<string name="game_shortcut_add">Aggiungi alla schermata Home</string>
+2
View File
@@ -1566,6 +1566,8 @@
<string name="pip_unavailable">Androidがピクチャーインピクチャーを開けませんでした。</string>
<string name="game_more">その他</string>
<string name="game_edit_art">アートを編集</string>
<string name="game_unhide">非表示を解除</string>
<string name="game_hide_failed">Steamと同期できませんでした。Steamを終了してもう一度お試しください。</string>
<string name="stores_in_steam_label">Steamに追加済み</string>
<string name="game_shortcut">ショートカット</string>
<string name="game_shortcut_add">ホーム画面に追加</string>
+2
View File
@@ -1566,6 +1566,8 @@
<string name="pip_unavailable">Android에서 PIP를 열 수 없습니다.</string>
<string name="game_more">더보기</string>
<string name="game_edit_art">아트 편집</string>
<string name="game_unhide">숨김 해제</string>
<string name="game_hide_failed">Steam과 동기화하지 못했습니다. Steam을 종료한 후 다시 시도하세요.</string>
<string name="stores_in_steam_label">Steam에 있음</string>
<string name="game_shortcut">바로 가기</string>
<string name="game_shortcut_add">홈 화면에 추가</string>
+2
View File
@@ -1566,6 +1566,8 @@
<string name="pip_unavailable">Android tidak dapat membuka gambar dalam gambar.</string>
<string name="game_more">Lagi</string>
<string name="game_edit_art">Sunting seni</string>
<string name="game_unhide">Alih keluar daripada tersembunyi</string>
<string name="game_hide_failed">Tidak dapat menyegerak dengan Steam. Tutup Steam dan cuba lagi.</string>
<string name="stores_in_steam_label">Dalam Steam</string>
<string name="game_shortcut">Pintasan</string>
<string name="game_shortcut_add">Tambah ke skrin utama</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Android kunne ikke åpne bilde-i-bilde.</string>
<string name="game_more">Mer</string>
<string name="game_edit_art">Rediger grafikk</string>
<string name="game_unhide">Fjern fra skjulte</string>
<string name="game_hide_failed">Kunne ikke synkronisere med Steam. Lukk Steam og prøv igjen.</string>
<string name="stores_in_steam_label">I Steam</string>
<string name="game_shortcut">Snarvei</string>
<string name="game_shortcut_add">Legg til på hjem-skjermen</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Android kon scherm-in-scherm niet openen.</string>
<string name="game_more">Meer</string>
<string name="game_edit_art">Afbeeldingen bewerken</string>
<string name="game_unhide">Niet meer verbergen</string>
<string name="game_hide_failed">Synchroniseren met Steam is mislukt. Sluit Steam en probeer het opnieuw.</string>
<string name="stores_in_steam_label">In Steam</string>
<string name="game_shortcut">Snelkoppeling</string>
<string name="game_shortcut_add">Toevoegen aan startscherm</string>
+2
View File
@@ -1589,6 +1589,8 @@
<string name="pip_unavailable">Android nie mógł otworzyć obrazu w obrazie.</string>
<string name="game_more">Więcej</string>
<string name="game_edit_art">Edytuj grafiki</string>
<string name="game_unhide">Usuń z ukrytych</string>
<string name="game_hide_failed">Nie udało się zsynchronizować ze Steamem. Zamknij Steama i spróbuj ponownie.</string>
<string name="stores_in_steam_label">W Steam</string>
<string name="game_shortcut">Skrót</string>
<string name="game_shortcut_add">Dodaj do ekranu głównego</string>
@@ -1572,6 +1572,8 @@
<string name="pip_unavailable">O Android não conseguiu abrir o ecrã no ecrã.</string>
<string name="game_more">Mais</string>
<string name="game_edit_art">Editar imagens</string>
<string name="game_unhide">Remover dos ocultos</string>
<string name="game_hide_failed">Não foi possível sincronizar com o Steam. Feche o Steam e tente novamente.</string>
<string name="stores_in_steam_label">No Steam</string>
<string name="game_shortcut">Atalho</string>
<string name="game_shortcut_add">Adicionar ao ecrã principal</string>
+2
View File
@@ -1580,6 +1580,8 @@
<string name="pip_unavailable">O Android não conseguiu abrir o picture-in-picture.</string>
<string name="game_more">Mais</string>
<string name="game_edit_art">Editar artes</string>
<string name="game_unhide">Remover dos ocultos</string>
<string name="game_hide_failed">Não foi possível sincronizar com o Steam. Feche o Steam e tente novamente.</string>
<string name="stores_in_steam_label">Na Steam</string>
<string name="game_shortcut">Atalho</string>
<string name="game_shortcut_add">Adicionar à tela inicial</string>
+2
View File
@@ -1581,6 +1581,8 @@
<string name="pip_unavailable">Android nu a putut deschide imaginea în imagine.</string>
<string name="game_more">Mai multe</string>
<string name="game_edit_art">Editează grafica</string>
<string name="game_unhide">Elimină din ascunse</string>
<string name="game_hide_failed">Nu s-a putut sincroniza cu Steam. Închide Steam și încearcă din nou.</string>
<string name="stores_in_steam_label">În Steam</string>
<string name="game_shortcut">Comandă rapidă</string>
<string name="game_shortcut_add">Adaugă pe ecranul principal</string>
+2
View File
@@ -1589,6 +1589,8 @@
<string name="pip_unavailable">Android не может открыть PiP.</string>
<string name="game_more">Ещё</string>
<string name="game_edit_art">Изменить обложку</string>
<string name="game_unhide">Убрать из скрытых</string>
<string name="game_hide_failed">Не удалось синхронизировать со Steam. Закройте Steam и повторите попытку.</string>
<string name="stores_in_steam_label">В Steam</string>
<string name="game_shortcut">Ярлык</string>
<string name="game_shortcut_add">Добавить на главный экран</string>
+2
View File
@@ -1573,6 +1573,8 @@
<string name="pip_unavailable">Android kunde inte öppna bild-i-bild.</string>
<string name="game_more">Mer</string>
<string name="game_edit_art">Redigera grafik</string>
<string name="game_unhide">Ta bort från dolda</string>
<string name="game_hide_failed">Kunde inte synkronisera med Steam. Stäng Steam och försök igen.</string>
<string name="stores_in_steam_label">I Steam</string>
<string name="game_shortcut">Genväg</string>
<string name="game_shortcut_add">Lägg till på hemskärmen</string>
+2
View File
@@ -1566,6 +1566,8 @@
<string name="pip_unavailable">Android ไม่สามารถเปิดภาพซ้อนภาพได้</string>
<string name="game_more">เพิ่มเติม</string>
<string name="game_edit_art">แก้ไขภาพปก</string>
<string name="game_unhide">นำออกจากที่ซ่อนไว้</string>
<string name="game_hide_failed">ซิงค์กับ Steam ไม่สำเร็จ ปิด Steam แล้วลองอีกครั้ง</string>
<string name="stores_in_steam_label">ใน Steam</string>
<string name="game_shortcut">ช็อตคัต</string>
<string name="game_shortcut_add">เพิ่มไปยังหน้าจอหลัก</string>
+2
View File
@@ -1565,6 +1565,8 @@
<string name="pip_unavailable">Android, pencere içinde pencereyi açamadı.</string>
<string name="game_more">Diğer</string>
<string name="game_edit_art">Görseli düzenle</string>
<string name="game_unhide">Gizlilikten çıkar</string>
<string name="game_hide_failed">Steam ile senkronize edilemedi. Steam\'i kapatıp tekrar deneyin.</string>
<string name="stores_in_steam_label">Steam\'de</string>
<string name="game_shortcut">Kısayol</string>
<string name="game_shortcut_add">Ana ekrana ekle</string>
+2
View File
@@ -1589,6 +1589,8 @@
<string name="pip_unavailable">Android не вдалося відкрити режим «Картинка в картинці».</string>
<string name="game_more">Більше</string>
<string name="game_edit_art">Змінити обкладинку</string>
<string name="game_unhide">Прибрати з прихованих</string>
<string name="game_hide_failed">Не вдалося синхронізувати зі Steam. Закрийте Steam і спробуйте ще раз.</string>
<string name="stores_in_steam_label">У Steam</string>
<string name="game_shortcut">Ярлик</string>
<string name="game_shortcut_add">Додати на головний екран</string>
+2
View File
@@ -1566,6 +1566,8 @@
<string name="pip_unavailable">Android không thể mở hình trong hình.</string>
<string name="game_more">Thêm</string>
<string name="game_edit_art">Sửa ảnh bìa</string>
<string name="game_unhide">Bỏ ẩn</string>
<string name="game_hide_failed">Không thể đồng bộ với Steam. Hãy đóng Steam rồi thử lại.</string>
<string name="stores_in_steam_label">Trong Steam</string>
<string name="game_shortcut">Shortcut</string>
<string name="game_shortcut_add">Thêm vào màn hình chính</string>
@@ -1649,6 +1649,8 @@
<string name="pip_unavailable">Android 无法打开画中画。</string>
<string name="game_more">更多</string>
<string name="game_edit_art">编辑封面</string>
<string name="game_unhide">取消隐藏</string>
<string name="game_hide_failed">无法与 Steam 同步。请关闭 Steam 后重试。</string>
<string name="stores_in_steam_label">已在 Steam 中</string>
<string name="game_shortcut">快捷方式</string>
<string name="game_shortcut_add">添加到主屏幕</string>
@@ -1565,6 +1565,8 @@
<string name="pip_unavailable">Android 無法開啟畫中畫。</string>
<string name="game_more">更多</string>
<string name="game_edit_art">編輯圖片</string>
<string name="game_unhide">取消隱藏</string>
<string name="game_hide_failed">無法與 Steam 同步。請關閉 Steam 後再試。</string>
<string name="stores_in_steam_label">在 Steam 中</string>
<string name="game_shortcut">捷徑</string>
<string name="game_shortcut_add">加至主畫面</string>
@@ -1565,6 +1565,8 @@
<string name="pip_unavailable">Android 無法開啟子母畫面。</string>
<string name="game_more">更多</string>
<string name="game_edit_art">編輯圖片</string>
<string name="game_unhide">取消隱藏</string>
<string name="game_hide_failed">無法與 Steam 同步。請關閉 Steam 後再試。</string>
<string name="stores_in_steam_label">在 Steam 中</string>
<string name="game_shortcut">捷徑</string>
<string name="game_shortcut_add">新增至主螢幕</string>
+2
View File
@@ -1757,6 +1757,8 @@
<string name="pip_unavailable">Android could not open picture in picture.</string>
<string name="game_more">More</string>
<string name="game_edit_art">Edit art</string>
<string name="game_unhide">Remove hidden</string>
<string name="game_hide_failed">Couldn\'t sync with Steam. Close Steam and try again.</string>
<string name="stores_in_steam_label">In Steam</string>
<string name="game_shortcut">Shortcut</string>
<string name="game_shortcut_add">Add to home screen</string>
@@ -8,6 +8,10 @@ import com.droiddeck.launcher.session.QuestExperimental
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.gpu.TpUbwcHint
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.gpu.VulkanInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.wayland.CompositorHost
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@@ -20,12 +24,26 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowBuild
import org.robolectric.shadows.ShadowLooper
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@Config(sdk = [28], manifest = Config.NONE, shadows = [DriverMenusAutoTest.XclipseDriver::class])
class DriverMenusAutoTest {
@Implements(SystemVulkanDriver::class)
class XclipseDriver {
companion object {
var enabled = false
@JvmStatic @Implementation fun isPowerVr() = enabled
@JvmStatic @Implementation fun isXclipse() = enabled
@JvmStatic @Implementation fun gpuName() = if (enabled) "Xclipse" else "PowerVR"
}
}
@Before fun reset() {
XclipseDriver.enabled = false
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "resolved", false)
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "cached", null)
ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "activeMode", null)
@@ -35,6 +53,42 @@ class DriverMenusAutoTest {
ShadowBuild.setDevice("eureka")
}
@Test fun unsupportedXclipseFallsBackThroughAutoAndFlagsDisplayRestart() {
XclipseDriver.enabled = true
ShadowBuild.setModel("Generic phone")
ShadowBuild.setDevice("generic")
ReflectionHelpers.setStaticField(VulkanInfo::class.java, "cached", mapOf("device" to "Xclipse 540"))
val originalFetch = TurnipReleases.fetch
TurnipReleases.fetch = { _, _, _ -> "[]" }
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setAndroidDriver(activity, "old-display")
SessionPrefs.setLinuxDriver(activity, "old-linux")
SessionPrefs.setGpuAutoInstalled(activity, setOf("old-display", "old-linux"))
ReflectionHelpers.setStaticField(CompositorHost::class.java, "started", true)
CompositorHost.displayChoice = "old-display"
try {
val menus = DriverMenus(activity, Handler(Looper.getMainLooper()))
menus.ensureAuto(force = true)
val deadline = System.currentTimeMillis() + 10000
while (menus.releaseChecking && System.currentTimeMillis() < deadline) {
Thread.sleep(10)
ShadowLooper.idleMainLooper()
}
assertFalse(menus.releaseChecking)
assertEquals(activity.getString(R.string.drivers_powervr_builtin), menus.autoStatus)
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(activity))
assertEquals("", SessionPrefs.linuxDriver(activity))
assertTrue(menus.restartPending)
} finally {
TurnipReleases.fetch = originalFetch
ReflectionHelpers.setStaticField(VulkanInfo::class.java, "cached", null)
ReflectionHelpers.setStaticField(CompositorHost::class.java, "started", false)
CompositorHost.displayChoice = null
XclipseDriver.enabled = false
}
}
@Test fun pickingTheAutoDisplayHandsBothHalvesToAuto() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MIX)
@@ -0,0 +1,101 @@
package com.droiddeck.launcher.frontend
import java.io.File
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamHiddenTest {
@get:Rule val tmp = TemporaryFolder()
private fun steamRoot(): File = tmp.newFolder("Steam").also { root ->
File(root, "config").mkdirs()
File(root, "config/loginusers.vdf").writeText(
"\"users\"\n{\n\t\"76561198352563669\"\n\t{\n\t\t\"AccountName\"\t\t\"a\"\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
}
private fun store(root: File, json: String?): File {
val dir = File(root, "userdata/392297941/config/cloudstorage").apply { mkdirs() }
return File(dir, "cloud-storage-namespace-1.json").also { f -> json?.let { f.writeText(it) } }
}
private fun hiddenEntry(file: File): JSONObject {
val entries = JSONArray(file.readText())
return (0 until entries.length()).map { entries.getJSONArray(it) }.first { it.getString(0) == "user-collections.hidden" }.getJSONObject(1)
}
@Test fun hidingAddsTheGameAndKeepsOtherEntries() {
val root = steamRoot()
val file = store(root, """[["user-collections.favorite",{"key":"user-collections.favorite","value":"{}"}],["user-collections.hidden",{"key":"user-collections.hidden","timestamp":5,"version":"7","value":"{\"id\":\"hidden\",\"name\":\"Hidden\",\"added\":[10],\"removed\":[]}"}]]""")
assertNotNull(SteamHidden.write(root, 440, true, now = 99))
assertEquals(setOf(10L, 440L), SteamHidden.read(root))
val entry = hiddenEntry(file)
assertEquals(99L, entry.getLong("timestamp"))
assertEquals("8", entry.getString("version"))
assertEquals("Hidden", JSONObject(entry.getString("value")).getString("name"))
assertEquals(2, JSONArray(file.readText()).length())
}
@Test fun unhidingTakesTheGameOutAgain() {
val root = steamRoot()
store(root, """[["user-collections.hidden",{"key":"user-collections.hidden","value":"{\"id\":\"hidden\",\"added\":[10,440],\"removed\":[]}"}]]""")
assertNotNull(SteamHidden.write(root, 440, false))
assertEquals(setOf(10L), SteamHidden.read(root))
}
@Test fun aMissingCollectionIsCreatedWhenHiding() {
val root = steamRoot()
val file = store(root, "[]")
assertNotNull(SteamHidden.write(root, 2931908220L, true))
assertEquals(setOf(2931908220L), SteamHidden.read(root))
assertFalse(hiddenEntry(file).getBoolean("is_deleted"))
}
@Test fun aDeletedCollectionIsRevivedWhenHiding() {
val root = steamRoot()
store(root, """[["user-collections.hidden",{"key":"user-collections.hidden","is_deleted":true}]]""")
assertEquals(emptySet<Long>(), SteamHidden.read(root))
assertNotNull(SteamHidden.write(root, 7, true))
assertEquals(setOf(7L), SteamHidden.read(root))
}
@Test fun withoutASteamStoreNothingIsWritten() {
val root = steamRoot()
assertNull(SteamHidden.write(root, 1, true))
assertEquals(emptySet<Long>(), SteamHidden.read(root))
}
@Test fun theCollectionIsMarkedAsPendingUploadOnce() {
val root = steamRoot()
val file = store(root, "[]")
SteamHidden.write(root, 1, true)
SteamHidden.write(root, 2, true)
assertEquals("""["user-collections.hidden"]""", File(file.parentFile, "cloud-storage-namespace-1.modified.json").readText())
}
@Test fun aMalformedMemberIsRejectedAndTheFileIsLeftAlone() {
val root = steamRoot()
val json = """[["user-collections.hidden",{"key":"user-collections.hidden","value":"{\"id\":\"hidden\",\"added\":[\"x\"],\"removed\":[]}"}]]"""
val file = store(root, json)
assertEquals(emptySet<Long>(), SteamHidden.readOrNull(root))
assertNull(SteamHidden.write(root, 1, true))
assertEquals(json, file.readText())
}
@Test fun numericStringsAreReadAndBadMembersAreSkipped() {
val root = steamRoot()
store(root, """[["user-collections.hidden",{"key":"user-collections.hidden","value":"{\"id\":\"hidden\",\"added\":[\"440\",\"x\",4.5,730],\"removed\":[]}"}]]""")
assertEquals(setOf(440L, 730L), SteamHidden.read(root))
}
}
@@ -217,13 +217,43 @@ class DriverPairsTest {
assertFalse(upstream.suits(GpuInfo("PowerVR", 0, Family.POWERVR, "", false)))
assertEquals("RADV upstream · Samsung Xclipse", upstream.name)
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(xclipse, pairs))
for (name in listOf("Samsung Xclipse 530", "Samsung Xclipse 540", "Samsung Xclipse 920"))
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(GpuInfo("Samsung Xclipse 920", 0, Family.POWERVR, "", false), pairs))
for (name in listOf("Samsung Xclipse 530"))
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(GpuInfo(name, 0, Family.POWERVR, "", false), pairs))
for (name in listOf("Samsung Xclipse 540", "Samsung Xclipse 950", "Samsung Xclipse 960", "Xclipse"))
assertEquals(DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM, DriverPairs.recommendedKey(GpuInfo(name, 0, Family.POWERVR, "", false), pairs))
assertTrue(DriverPairs.isNonAdreno("RADV-Xclipse-upstream"))
for (name in listOf("Samsung Xclipse 950", "Samsung Xclipse 960", "Xclipse")) {
val newer = GpuInfo(name, 0, Family.POWERVR, "", false)
assertEquals(DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM, DriverPairs.recommendedKey(newer, pairs))
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(newer, pairs.filter { it.key != DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM }))
for (name in listOf("Samsung Xclipse 540", "Samsung Xclipse 950", "Samsung Xclipse 960", "Xclipse"))
assertNull(DriverPairs.recommendedKey(GpuInfo(name, 0, Family.POWERVR, "", false), pairs.filter { it.key != DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM }))
}
@Test
fun autoEligibilityDoesNotDependOnPublishedXclipsePairs() {
fun mali(name: String) = GpuInfo(name, 0, GpuInfo.familyOf(false, 0, mali = name), "", false)
val xclipse540 = GpuInfo("Samsung Xclipse 540", 0, Family.POWERVR, "", false)
val xclipse920 = GpuInfo("Samsung Xclipse 920", 0, Family.POWERVR, "", false)
val upstream = TurnipReleases.Asset("Non-Adreno", "r1", "RADV-Xclipse-upstream.zip", "https://example/upstream", 9_000_000,
false, "label", "0".repeat(64), DriverPairs.nonAdreno("RADV-Xclipse-upstream"), bundle = true)
val pairs = DriverPairs.from(TurnipReleases.Check(listOf(upstream), emptyList(), emptyList(), 0L))
assertTrue(DriverPairs.autoEligible(xclipse540))
assertNull(DriverPairs.recommendedKey(xclipse540, emptyList()))
assertEquals(DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM, DriverPairs.recommendedKey(xclipse540, pairs))
assertTrue(DriverPairs.autoEligible(xclipse920))
assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(xclipse920, emptyList()))
assertTrue(DriverPairs.autoEligible(gpu(740)))
assertTrue(DriverPairs.autoEligible(mali("Mali-G57")))
assertFalse(DriverPairs.autoEligible(mali("Mali-G1-Ultra")))
assertFalse(DriverPairs.autoEligible(GpuInfo("PowerVR", 0, Family.POWERVR, "", false)))
}
@Test
fun autoEligibilityMatchesRecommendedKeyForAdrenoAndMali() {
fun mali(name: String) = GpuInfo(name, 0, GpuInfo.familyOf(false, 0, mali = name), "", false)
for (gpu in listOf(gpu(710), gpu(740), mali("Mali-G57"), mali("Mali-G925-Immortalis MC12"))) {
assertEquals(
DriverPairs.recommendedKey(gpu, emptyList(), sdk = 34) != null,
DriverPairs.autoEligible(gpu, sdk = 34),
)
}
}
@@ -186,6 +186,42 @@ class SessionInputPointerTest {
assertEquals(29 to 0, CompositorShadow.keys.last())
}
@Test fun losingPointerCaptureReleasesMouseButtonsButKeepsKeyboardKeysHeld() {
ReflectionHelpers.getField<androidx.compose.runtime.MutableState<Boolean>>(activity, "resumed\$delegate").value = true
val keys = ReflectionHelpers.getField<HeldInput>(activity, "heldKeys")
val buttons = ReflectionHelpers.getField<HeldInput>(activity, "heldButtons")
output.key(17, true)
keys.set(8, 30, true)
buttons.set(2, 272, true)
CompositorShadow.keys.clear()
CompositorShadow.events.clear()
ReflectionHelpers.callInstanceMethod<Unit>(activity, "releaseHeldInputOnCaptureLoss")
assertTrue(CompositorShadow.keys.none { it.second == 0 })
assertTrue(CompositorShadow.events.contains(Triple(3, 272, 0)))
output.key(17, false)
assertEquals(17 to 0, CompositorShadow.keys.last())
}
@Test fun losingPointerCaptureToAnotherInputSurfaceReleasesKeyboardKeys() {
ReflectionHelpers.getField<androidx.compose.runtime.MutableState<Boolean>>(activity, "resumed\$delegate").value = true
for (state in listOf("drawerOpenState", "wowChatOnTop")) {
val open: androidx.compose.runtime.MutableState<Boolean> = ReflectionHelpers.getField(activity, state + "\$delegate")
open.value = true
ReflectionHelpers.getField<HeldInput>(activity, "heldKeys").set(16, 17, true)
CompositorShadow.keys.clear()
ReflectionHelpers.callInstanceMethod<Unit>(activity, "releaseHeldInputOnCaptureLoss")
assertEquals(state, 17 to 0, CompositorShadow.keys.last())
open.value = false
}
}
@Test fun openingTheSessionMenuReleasesHeldKeyboardKeys() {
ReflectionHelpers.getField<HeldInput>(activity, "heldKeys").set(16, 17, true)
CompositorShadow.keys.clear()
ReflectionHelpers.callInstanceMethod<Unit>(activity, "setDrawerOpen", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
assertEquals(17 to 0, CompositorShadow.keys.last())
}
@Test fun horizontalWheelUsesTheSameDirectionInBothMouseBackends() {
output.scrollHorizontal(2)
assertEquals(listOf(Triple(11, 0, 240)), CompositorShadow.events)
@@ -1,26 +1,94 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.robolectric.RuntimeEnvironment
import android.net.Uri
import com.droiddeck.launcher.DriverMenusAutoTest
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.gpu.DriverBundle
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@Config(sdk = [28], manifest = Config.NONE, shadows = [DriverMenusAutoTest.XclipseDriver::class])
class PowerVrAutoDriversTest {
private val context: Context = RuntimeEnvironment.getApplication()
@Before fun reset() {
DriverMenusAutoTest.XclipseDriver.enabled = false
clearBundles()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
SessionPrefs.setLinuxDriver(context, "imported-linux")
SessionPrefs.setAndroidDriver(context, "imported-display")
}
@After fun cleanupBundles() {
clearBundles()
}
private fun clearBundles() {
File(context.filesDir, "graphics_driver").deleteRecursively()
File(context.filesDir, LinuxVulkanDriverManager.DIR_NAME).deleteRecursively()
context.getSharedPreferences("driver_bundles", Context.MODE_PRIVATE).edit().clear().commit()
}
private fun installAndSelectNonAdrenoBundle(
tag: String = "RADV-Xclipse",
packageName: String = "RADV-Xclipse",
): DriverBundle.Bundle {
fun library(libc: String) = ByteArray(64).also {
byteArrayOf(0x7f, 'E'.code.toByte(), 'L'.code.toByte(), 'F'.code.toByte(), 2, 1).copyInto(it)
it[18] = 0xB7.toByte()
} + libc.toByteArray() + ByteArray(1)
val manifest = JSONObject()
.put("package", packageName)
.put("version", "0.1.0")
.put("tag", tag)
.put(
"drivers",
JSONObject()
.put("android", JSONObject().put("path", "android"))
.put("linux", JSONObject().put("path", "linux")),
)
val entries = mapOf(
"android/meta.json" to JSONObject().put("name", "radv v0.1.0").put("libraryName", "libvulkan_radeon.so").toString().toByteArray(),
"android/libvulkan_radeon.so" to library("libc.so"),
"linux/meta.json" to JSONObject().put("name", "radv v0.1.0").put("driverVersion", "radv-test").toString().toByteArray(),
"linux/libvulkan_radeon.so" to library("libc.so.6"),
"manifest.json" to manifest.toString().toByteArray(),
)
val file = File.createTempFile("radv-bundle", ".zip", context.cacheDir)
return try {
ZipOutputStream(file.outputStream()).use { z ->
for ((name, data) in entries) {
z.putNextEntry(ZipEntry(name))
z.write(data)
z.closeEntry()
}
}
val bundle = DriverBundle.install(context, Uri.fromFile(file))
DriverBundle.select(context, bundle)
bundle
} finally {
file.delete()
}
}
@Test fun autoRepairsStaleAdrenoSelectionsOnPowerVr() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
@@ -28,17 +96,172 @@ class PowerVrAutoDriversTest {
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
}
@Test fun explicitManualChoicesRemainOnPowerVr() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_MANUAL)
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
@Test fun nonXclipsePowerVrKeepsManualPair() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true)
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
assertEquals("imported-display", SessionPrefs.androidDriver(context))
}
@Test fun unsupportedXclipseClearsAnAutoOwnedOldPair() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setLinuxDriver(context, "old-linux")
SessionPrefs.setAndroidDriver(context, "old-display")
SessionPrefs.setGpuAutoInstalled(context, setOf("old-display", "old-linux"))
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true)
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
}
@Test fun unsupportedXclipseKeepsAManualPair() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_MANUAL)
SessionPrefs.setLinuxDriver(context, "old-linux")
SessionPrefs.setAndroidDriver(context, "old-display")
SessionPrefs.setGpuAutoInstalled(context, setOf("old-display", "old-linux"))
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true)
assertEquals("old-linux", SessionPrefs.linuxDriver(context))
assertEquals("old-display", SessionPrefs.androidDriver(context))
}
@Test fun autoClearsOwnedDisplayButKeepsManualLinux() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf("imported-display"))
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true)
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
}
@Test fun autoClearsOwnedLinuxButKeepsManualDisplay() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf("imported-linux"))
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true)
assertEquals("imported-display", SessionPrefs.androidDriver(context))
assertEquals("", SessionPrefs.linuxDriver(context))
}
@Test fun adrenoAutoChoicesRemain() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = false)
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
assertEquals("imported-display", SessionPrefs.androidDriver(context))
}
@Test fun sessionStartKeepsStandaloneDriverOnUnsupportedXclipse() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setAndroidDriver(context, "standalone-display")
SessionPrefs.setGpuAutoInstalled(context, setOf("imported-linux"))
val ownedOnly = SessionPrefs.unsupportedXclipse(true) { "Samsung Xclipse 540" }
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = ownedOnly)
assertEquals("standalone-display", SessionPrefs.androidDriver(context))
assertEquals("", SessionPrefs.linuxDriver(context))
}
@Test fun sessionStartOwnershipRuleIgnoresOtherGpus() {
assertEquals(false, SessionPrefs.unsupportedXclipse(false) { "Samsung Xclipse 540" })
assertEquals(false, SessionPrefs.unsupportedXclipse(true) { "Samsung Xclipse 920" })
}
@Test fun sessionStartNamesTheXclipseFromVulkanBeforeTheOwnershipRule() {
val queried = mapOf("device" to "Samsung Xclipse 920")
assertEquals("Xclipse", GpuInfo.systemDriverName("Xclipse", null))
assertEquals("Samsung Xclipse 920", GpuInfo.systemDriverName("Xclipse", queried))
assertEquals("PowerVR", GpuInfo.systemDriverName("PowerVR", queried))
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf("imported-linux"))
val ownedOnly = SessionPrefs.unsupportedXclipse(true) { GpuInfo.systemDriverName("Xclipse", queried) }
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = ownedOnly)
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
}
@Test fun sessionStartLeavesTheGpuUnqueriedOffXclipse() {
var asked = false
assertEquals(false, SessionPrefs.unsupportedXclipse(false) { asked = true; "Xclipse" })
assertEquals(false, asked)
}
@Test fun cachedOnlySessionStartLeavesPrefsWhenTheXclipseIsUnnamed() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf("imported-display", "imported-linux"))
var reads = 0
SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) { reads++; null }
assertEquals(1, reads)
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
assertEquals("imported-display", SessionPrefs.androidDriver(context))
}
@Test fun sessionStartWithANamedXclipseClearsOnlyAutoOwnedSelections() {
DriverMenusAutoTest.XclipseDriver.enabled = true
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf("imported-linux"))
SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) {
mapOf("device" to "Samsung Xclipse 540")
}
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals("imported-display", SessionPrefs.androidDriver(context))
}
@Test fun sessionStartUnsupportedXclipseResetsAutoOwnedEvenWithBothOpenDriversSelected() {
DriverMenusAutoTest.XclipseDriver.enabled = true
val bundle = installAndSelectNonAdrenoBundle()
assertTrue(DeviceSupport.openDriverActive(context))
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf(bundle.androidId, bundle.linuxId))
SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) {
mapOf("device" to "Samsung Xclipse 540")
}
assertFalse(DeviceSupport.openDriverActive(context))
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
}
@Test fun sessionStartUnsupportedXclipseKeepsAutoOwnedUpstreamBundle() {
DriverMenusAutoTest.XclipseDriver.enabled = true
val bundle = installAndSelectNonAdrenoBundle(
tag = "RADV-Xclipse-upstream",
packageName = "RADV-Xclipse-upstream",
)
assertTrue(DeviceSupport.openDriverActive(context))
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf(bundle.androidId, bundle.linuxId))
SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) {
mapOf("device" to "Samsung Xclipse 540")
}
assertTrue(DeviceSupport.openDriverActive(context))
assertEquals(bundle.linuxId, SessionPrefs.linuxDriver(context))
assertEquals(bundle.androidId, SessionPrefs.androidDriver(context))
}
@Test fun sessionStartSupportedXclipseKeepsActiveOpenDriverBundle() {
DriverMenusAutoTest.XclipseDriver.enabled = true
val bundle = installAndSelectNonAdrenoBundle()
assertTrue(DeviceSupport.openDriverActive(context))
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf(bundle.androidId, bundle.linuxId))
SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) {
mapOf("device" to "Samsung Xclipse 920")
}
assertTrue(DeviceSupport.openDriverActive(context))
assertEquals(bundle.linuxId, SessionPrefs.linuxDriver(context))
assertEquals(bundle.androidId, SessionPrefs.androidDriver(context))
}
@Test fun sessionStartWithASupportedXclipseClearsUnownedSelections() {
DriverMenusAutoTest.XclipseDriver.enabled = true
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) {
mapOf("device" to "Samsung Xclipse 920")
}
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
}
@Test fun sessionStartReadsNoVulkanNameOffXclipse() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = false) {
throw AssertionError("queried")
}
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
}
}
@@ -30,6 +30,22 @@ class SteamGameProcessTest {
assertFalse(SteamGameProcess.matches(cmdline("python3", "/proton", "waitforexitandrun", "game.exe"), "976310"))
}
@Test fun steamsInstallScriptStepIsNotTheGame() {
val wrapper = arrayOf("/root/.local/share/Steam/linuxarm64/steam-launch-wrapper", "--oom-score-adjust", "900", "--")
val reaper = "/root/.local/share/Steam/steamrtarm64/reaper"
val proton = "/root/.local/share/Steam/compatibilitytools.d/DroidDeck-Proton 11-12.8/droiddeck-proton-wrap"
val evaluator = arrayOf(reaper, "SteamLaunch", "AppId=351710", "Install=1", "--",
proton, "run", "/root/.local/share/Steam/legacycompat/iscriptevaluator.exe", "legacycompat\\evaluatorscript_351710.vdf")
val game = arrayOf(reaper, "SteamLaunch", "AppId=351710", "--",
proton, "waitforexitandrun", "/root/.local/share/Steam/steamapps/common/Neptunia Rebirth2/NeptuniaReBirth2.exe")
assertFalse(SteamGameProcess.matches(cmdline(*evaluator), "351710"))
assertFalse(SteamGameProcess.matches(cmdline(*wrapper, *evaluator), "351710"))
assertTrue(SteamGameProcess.matches(cmdline(*game), "351710"))
assertTrue(SteamGameProcess.matches(cmdline(*wrapper, *game), "351710"))
assertTrue(SteamGameProcess.matches(cmdline(reaper, "SteamLaunch", "AppId=351710", "--", "game", "Install=1"), "351710"))
}
@Test fun shortcutCGameIdsMatchTheir32BitSteamAppId() {
val cgameId = ((976310L shl 32) or 0x02000000L).toString()
@@ -67,5 +83,9 @@ class SteamGameProcessTest {
process("200", "reaper", "SteamLaunch", "AppId=976310", "--", "proton", "waitforexitandrun", "MK11.exe")
assertTrue(SteamGameProcess.running("976310", proc))
assertFalse(SteamGameProcess.running("123", proc))
process("300", "reaper", "SteamLaunch", "AppId=351710", "Install=1", "--", "proton", "run", "iscriptevaluator.exe")
assertFalse(SteamGameProcess.running("351710", proc))
process("301", "reaper", "SteamLaunch", "AppId=351710", "--", "proton", "waitforexitandrun", "game.exe")
assertTrue(SteamGameProcess.running("351710", proc))
}
}
@@ -4,6 +4,7 @@ import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import java.io.File
import org.junit.Assert.*
import org.junit.Assume.assumeFalse
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
@@ -145,6 +146,7 @@ class SteamLibrariesTest {
}
@Test fun rawAndStorageMountViewsOverlapButDistinctFoldersDoNot() {
assumeFalse(java.nio.file.Files.isSymbolicLink(File("/mnt").toPath()))
val raw = SteamLibraries.canonical(File("/mnt/media_rw/ABCD-1234/Games"))
val storage = SteamLibraries.canonical(File("/storage/ABCD-1234/Games"))
assertEquals(storage, raw)
@@ -50,6 +50,38 @@ class CloudSavesTest {
assertEquals("v1", File(kept, "slot0.sav").readText())
}
@Test fun aFolderAliasNeverHidesTheRealSaveFromARestore() {
val game = id; val dir = dir()
File(dir, "SaveData").mkdirs(); File(dir, "SaveData/slot.sav").writeText("local")
val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "Cache").toPath(), File(dir, "SaveData").toPath()) }
org.junit.Assume.assumeTrue(link.isSuccess)
val memory = Memory().apply { files["SaveData/slot.sav"] = "cloud".toByteArray() to 1000L }
val cloud = object : CloudTransport by memory {
override fun wants(name: String) = name.startsWith("SaveData/")
}
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true)
assertEquals("cloud", File(dir, "SaveData/slot.sav").readText())
val kept = File(app.filesDir, "stores/cloud-backups/gog-$game").listFiles { f -> f.name.startsWith("local-") }!!.single()
assertEquals("local", File(kept, "SaveData/slot.sav").readText())
}
@Test fun aSaveReachedOnlyThroughAFolderAliasStillGoesUp() {
val game = id; val dir = dir()
File(dir, "Actual").mkdirs(); File(dir, "Actual/slot.sav").writeText("played")
val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "SaveData").toPath(), File(dir, "Actual").toPath()) }
org.junit.Assume.assumeTrue(link.isSuccess)
java.nio.file.Files.createSymbolicLink(File(dir, "Actual/loop").toPath(), dir.toPath())
val memory = Memory()
val cloud = object : CloudTransport by memory {
override fun wants(name: String) = name.startsWith("SaveData/")
}
CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false)
val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false)
assertEquals("uploaded", r.reason)
assertEquals(listOf("SaveData/slot.sav"), memory.puts)
assertEquals("played", String(memory.files.getValue("SaveData/slot.sav").first))
}
@Test fun aFileChangedOnBothSidesIsLeftForTheUser() {
val game = id; val dir = dir()
val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L }
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.stores.ea
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.CloudSaves
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreLaunch
@@ -413,4 +414,137 @@ class EaTest {
assertTrue(!EaAuth.storeRefreshed(app, "late", 3600, "r3"))
assertNull(EaAuth.load(app))
}
private fun tokenServer(status: String): java.net.ServerSocket {
val server = java.net.ServerSocket(0)
Thread {
runCatching {
server.accept().use { socket ->
val input = socket.getInputStream()
val head = StringBuilder()
while (!head.endsWith("\r\n\r\n")) head.append(input.read().takeIf { it >= 0 }?.toChar() ?: break)
val length = Regex("(?i)content-length: *(\\d+)").find(head)?.groupValues?.get(1)?.toInt() ?: 0
repeat(length) { input.read() }
val body = """{"error":"invalid_grant"}""".toByteArray()
socket.getOutputStream().apply {
write("HTTP/1.1 $status\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray())
write(body)
flush()
}
}
}
}.apply { isDaemon = true; start() }
return server
}
@Test fun aRejectedRefreshAsksForSignInWhileAnUnreachableOneKeepsTheSessionForARetry() {
val app = org.robolectric.RuntimeEnvironment.getApplication()
val real = EaAuth.tokenUrl
try {
com.droiddeck.launcher.stores.StoreAccounts.write(app, Store.EA,
JSONObject().put("access_token", "old").put("refresh_token", "r").put("expires_at", 1L).put("user_id", "1"))
EaAuth.tokenUrl = "http://127.0.0.1:1/"
assertNull(EaAuth.accessToken(app))
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
tokenServer("503 Service Unavailable").use { server ->
EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/"
assertNull(EaAuth.accessToken(app))
}
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
tokenServer("400 Bad Request").use { server ->
EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/"
assertNull(EaAuth.accessToken(app))
}
assertFalse(CloudSaves.status(app, Store.EA, "x").signedIn)
assertTrue(EaAuth.storeRefreshed(app, "new", 3600, "r2"))
assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn)
} finally {
EaAuth.tokenUrl = real
EaAuth.signOut(app)
}
}
private val heat = """<saveFileCriteria>
<include order="0">%Documents%/Need for Speed Heat/SaveGame/savegame/</include>
<include order="1">%Documents%/Need for Speed Heat/SaveGame/wraps/</include>
<include order="2">%Documents%/Need for Speed Heat/settings/PROFILEOPTIONS</include>
</saveFileCriteria>"""
@Test fun rulesFindTheFolderTheyShareAndPickOnlyTheirFiles() {
val rules = EaSaveRules.parse(heat)!!
assertEquals("%Documents%/Need for Speed Heat/", rules.base())
assertEquals("%DOCUMENTS%/Need for Speed Heat/", EaSaveRules.template(rules.base()!!))
assertTrue(rules.matches("%Documents%/Need for Speed Heat/SaveGame/savegame/1"))
assertTrue(rules.matches("%documents%\\need for speed heat\\settings\\PROFILEOPTIONS"))
assertFalse(rules.matches("%Documents%/Need for Speed Heat/settings/PROFILEOPTIONS.bak"))
assertFalse(rules.matches("%Documents%/Need for Speed Heat/Logs/crash.txt"))
}
@Test fun globsStayInsideTheirFolderAndExcludesWin() {
val bf = EaSaveRules.parse("""<saveFileCriteria><include order="0">%Documents%/Battlefield 6/settings/*.xml</include>
<include order="2">%Documents%/Battlefield 6/settings/*.sav</include></saveFileCriteria>""")!!
assertEquals("%Documents%/Battlefield 6/settings/", bf.base())
assertTrue(bf.matches("%Documents%/Battlefield 6/settings/a.sav"))
assertFalse(bf.matches("%Documents%/Battlefield 6/settings/sub/a.sav"))
val le = EaSaveRules.parse("""<saveFileCriteria>
<exclude order="0">%Documents%/BioWare/Mass Effect Legendary Edition/Config/</exclude>
<include order="1">%Documents%/BioWare/Mass Effect Legendary Edition/</include></saveFileCriteria>""")!!
assertTrue(le.matches("%Documents%/BioWare/Mass Effect Legendary Edition/Save/ME1/x.pcsav"))
assertFalse(le.matches("%Documents%/BioWare/Mass Effect Legendary Edition/Config/GamerSettings.ini"))
assertNull(EaSaveRules.parse("<saveFileCriteria></saveFileCriteria>"))
assertNull(EaSaveRules.parse("""<saveFileCriteria><include order="0">C:/Games/x/</include></saveFileCriteria>""")!!.base())
}
@Test fun aManifestKeepsItsFilesSnapshotsAndEaTimestampsThroughAWrite() {
val xml = """<manifest xmlns="http://origin.com/cloudsaves/manifest" lineage="{00000000-0000-0000-0000-000000000000}">
<file size="115352" href="content/115352-c7996be80a6e38d1f8ef28866b114f8b" md5="x5lr6ApuONH47yiGaxFPiw==">
<localName created="2022-10-17T23:51:04ZZ" lastModified="2022-10-17T23:51:04ZZ">%Documents%/Need for Speed Heat/SaveGame/savegame/1</localName>
</file>
<snapshot>80cmnqT/rIKQRmciINSVhQ==</snapshot>
</manifest>"""
val m = EaCloud.parse(xml)
assertEquals(1, m.files.size)
assertEquals("c7996be80a6e38d1f8ef28866b114f8b", EaCloud.hex(m.files[0].md5))
assertEquals(1666050664000L, EaCloud.parseTime(m.files[0].modified))
assertEquals("2022-10-17T23:51:04ZZ", EaCloud.stamp(1666050664123L))
val again = EaCloud.parse(EaCloud.write(m))
assertEquals(m.files.single().localName, again.files.single().localName)
assertEquals(m.files.single().href, again.files.single().href)
assertEquals(m.files.single().created, again.files.single().created)
assertEquals(m.files.single().modified, again.files.single().modified)
assertEquals(m.files.single().size, again.files.single().size)
assertEquals(m.files.single().md5, again.files.single().md5)
assertEquals(listOf("80cmnqT/rIKQRmciINSVhQ=="), again.snapshots)
assertEquals(m.lineage, again.lineage)
}
@Test fun commentedRulesAreIgnoredAndNamesKeepTheirSpaces() {
val rules = EaSaveRules.parse("""<saveFileCriteria>
<!-- <exclude order="0">%Documents%/Game/Config/</exclude> -->
<include order="1"> %Documents%/Game/ </include></saveFileCriteria>""")!!
assertEquals(listOf("%Documents%/Game/"), rules.includes)
assertTrue(rules.excludes.isEmpty())
assertTrue(rules.matches("%Documents%/Game/Config/a.ini"))
assertEquals("%Documents%/Game/slot.sav ", EaSaveRules.normalize("%Documents%\\Game\\slot.sav "))
}
@Test fun aTruncatedManifestIsRefused() {
val cut = runCatching { EaCloud.parse("""<manifest lineage="{1}"><file size="1" href="content/1-a" md5="x5lr6ApuONH47yiGaxFPiw==">""") }
assertTrue(cut.isFailure)
val open = runCatching { EaCloud.parse("""<manifest lineage="{1}"><file size="1" href="content/1-a" md5="x5lr6ApuONH47yiGaxFPiw=="><localName>%Documents%/a</localName></manifest>""") }
assertTrue(open.isFailure)
}
@Test fun snapshotEntitiesAreDecodedOnceAndWrittenBackTheSame() {
val m = EaCloud.parse("""<manifest lineage="{1}"><snapshot>abc&#x2B;def</snapshot></manifest>""")
assertEquals(listOf("abc+def"), m.snapshots)
assertEquals(listOf("abc+def"), EaCloud.parse(EaCloud.write(m)).snapshots)
}
@Test fun cloudKeysFollowTheMultiplayerId() {
assertEquals(listOf("195133_195133"), EaCloud.keys("195133", "195133"))
assertEquals(listOf("52209", "52209_52209"), EaCloud.keys("52209", ""))
assertEquals("https://x/y?a=1&b=2", EaCloud.manifestUrl("<sync><manifest>https://x/y?a=1&amp;b=2</manifest></sync>"))
assertTrue(CloudSaves.supports(Store.EA))
}
}
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.frontend.Library
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class LibraryHiddenTest {
private fun steam(id: Int, name: String) = LibraryEntry("app:$id", Library.SOURCE_STEAM, name, Library.SteamGame(id, name, null, "Steam library"), null, true)
private val tf2 = steam(440, "Team Fortress 2")
private val cs = steam(10, "Counter-Strike")
private val hiddenSet = setOf(tf2.favoriteKey)
private val hidden: (LibraryEntry) -> Boolean = { it.favoriteKey in hiddenSet }
@Test fun hiddenGamesLeaveAllAndTheirStoreTab() {
assertFalse(inLibrarySource(LIBRARY_ALL, tf2, emptySet(), hidden))
assertFalse(inLibrarySource(Library.SOURCE_STEAM, tf2, emptySet(), hidden))
assertTrue(inLibrarySource(LIBRARY_ALL, cs, emptySet(), hidden))
assertTrue(inLibrarySource(Library.SOURCE_STEAM, cs, emptySet(), hidden))
}
@Test fun hiddenGamesLeaveFavorites() {
assertFalse(inLibrarySource(LIBRARY_FAVORITES, tf2, setOf(tf2.favoriteKey), hidden))
}
@Test fun theHiddenSourceHoldsOnlyHiddenGames() {
assertTrue(inLibrarySource(LIBRARY_HIDDEN, tf2, emptySet(), hidden))
assertFalse(inLibrarySource(LIBRARY_HIDDEN, cs, emptySet(), hidden))
}
@Test fun theHiddenTabIsLastAndOnlyWhenEnabled() {
val entries = listOf(tf2, cs)
assertEquals(listOf(Library.SOURCE_STEAM), librarySources(entries, emptyList(), hidden = hidden))
assertEquals(listOf(Library.SOURCE_STEAM, LIBRARY_HIDDEN), librarySources(entries, emptyList(), hidden = hidden, showHidden = true))
}
@Test fun aStoreTabWithOnlyHiddenGamesDisappears() {
assertEquals(emptyList<String>(), librarySources(listOf(tf2), emptyList(), hidden = hidden))
}
}
+6 -2
View File
@@ -29,6 +29,7 @@
"ndk": true,
"packages": [
"gcc-aarch64-linux-gnu",
"libc6-dev-arm64-cross",
"g++-aarch64-linux-gnu",
"libvulkan1",
"mesa-vulkan-drivers"
@@ -155,7 +156,8 @@
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet/version"
],
"packages": [
"gcc-aarch64-linux-gnu"
"gcc-aarch64-linux-gnu",
"libc6-dev-arm64-cross"
]
},
"arm64-preloads": {
@@ -178,6 +180,7 @@
],
"packages": [
"gcc-aarch64-linux-gnu",
"libc6-dev-arm64-cross",
"g++-aarch64-linux-gnu"
],
"source_inputs": [
@@ -245,7 +248,8 @@
"app/src/main/assets/linuxfs/usr/local/bin/droiddeck-vkbridge-smoke"
],
"packages": [
"gcc-aarch64-linux-gnu"
"gcc-aarch64-linux-gnu",
"libc6-dev-arm64-cross"
]
},
"dirt-ws2": {
@@ -255,7 +255,7 @@ def create_prefix(compat_data, proton, timeout=120):
CLOUD_TIMEOUT = 15.0
CLOUD_STORES = ("gog", "epic")
CLOUD_STORES = ("gog", "epic", "ea")
STORE_GAME = 10
RAN = 11
RAN_FAILED = 12
@@ -304,7 +304,6 @@ def exited(argv, code=0):
if found is not None and launch_dir and str(found[1].get("store")) == "ea":
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": str(found[1].get("id"))}, timeout=1.0)
log("ea %s exited" % found[1].get("id"))
return 0
if found is None or not launch_dir or not cloud_on(found[1]):
return 0
store, game = str(found[1].get("store")), str(found[1].get("id"))
@@ -1601,7 +1600,7 @@ def main(argv):
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
prefix_id = os.path.basename(compat_data) if compat_data else ""
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
if launch_dir and cloud_on(sidecar):
if launch_dir and cloud_on(sidecar) and store != "ea":
made = create_prefix(compat_data, os.environ.get("DD_STORE_PROTON", ""))
if made != "present":
log("cloud %s %s prefix=%s" % (store, game, made))
@@ -1670,11 +1669,10 @@ def main(argv):
log("epic prefix=%s %s" % (prefix_id or "?", provision_prefix(compat_data)))
if store == "ea":
prepare_ea(folder, sidecar, compat_data, launch_dir)
return STORE_GAME
if not cloud_on(sidecar):
if store in CLOUD_STORES:
log("cloud %s %s down result=skipped reason=off" % (store, game))
return 0
return STORE_GAME if store == "ea" else 0
if launch_dir:
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT)
if answer is None:
+28
View File
@@ -225,6 +225,34 @@ class CloudHooks(unittest.TestCase):
self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1])
self.assertEqual('cloud-up', asked[2][0]['op'])
def test_an_ea_game_with_cloud_saves_asks_after_its_preparation_and_exit(self):
ident = 'Origin.OFR.50.0002694'
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='ea', ident=ident)
bat = str(folder / '.droiddeck-launch.bat')
asked = []
env = {'DD_LAUNCH_DIR': str(Path(root) / 'session')}
record = lambda channel, request, timeout=5.0: asked.append(request) or {'result': 'ok'}
with patch.dict(os.environ, env), \
patch.object(store, 'prepare_ea', side_effect=lambda *a: asked.append({'op': 'prepared'})), \
patch.object(store, 'create_prefix', side_effect=AssertionError('EA prepares its own prefix')), \
patch.object(store, 'ask', side_effect=record):
self.assertEqual(store.STORE_GAME, store.main([bat]))
self.assertEqual(['prepared', 'cloud-down'], [r['op'] for r in asked])
self.assertEqual({'op': 'cloud-down', 'store': 'ea', 'id': ident}, asked[1])
self.assertEqual(0, store.main(['--exited', bat]))
self.assertEqual(['ea-exited', 'cloud-up'], [r['op'] for r in asked[2:]])
self.assertEqual({'op': 'cloud-up', 'store': 'ea', 'id': ident}, asked[3])
sidecar = json.loads((folder / store.SIDECAR).read_text())
sidecar['cloud'] = False
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
asked.clear()
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea'), patch.object(store, 'ask', side_effect=record):
self.assertEqual(store.STORE_GAME, store.main([bat]))
self.assertEqual([], asked)
self.assertEqual(0, store.main(['--exited', bat]))
self.assertEqual(['ea-exited'], [r['op'] for r in asked])
def test_a_first_launch_creates_the_prefix_before_the_cloud_download(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='epic', ident='fa4240e5')
+1 -1
View File
@@ -10,7 +10,7 @@ Steam on the desktop). The app installs it into `files/linuxfs` and runs it unde
scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds KGSL
UBWC 5/6 (backported from upstream Mesa) and the KGSL device numbers for WSI (from
[Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)). It also carries Icenowy Zheng's upstream
Zink fix that keeps the Imagination depth/stencil swizzle off colour views (Mesa d55418dae7). A GLX fix stops `glXQueryDrawable` calling a NULL swap-interval hook on plain drisw screens (no kopper or DRI3), which crashed SDL3 clients such as steamwebhelper.
Zink fix that keeps the Imagination depth/stencil swizzle off colour views (Mesa d55418dae7).
- The runtime's built-in Vulkan driver is DroidDeck's DD-Turnip Linux build (`DD_TURNIP_URL` and
`DD_TURNIP_SHA256` in `base.env`): Ubuntu's Turnip is diverted to `libvulkan_freedreno.so.distrib`
because it lacks the Adreno 8xx fixes. Zink, EGL and llvmpipe stay Ubuntu's.
@@ -1,47 +0,0 @@
From f48c22e082cd0ae2271f33581e7b43484ff9df3b Mon Sep 17 00:00:00 2001
From: pgm1207 <104554896+pgm1207@users.noreply.github.com>
Date: Wed, 18 Nov 2026 12:08:27 +0100
Subject: [PATCH] glx: don't call a NULL getSwapInterval in glXQueryDrawable
__glXGetDrawableAttribute() calls driScreen.getSwapInterval() for
GLX_SWAP_INTERVAL_EXT and GLX_LATE_SWAPS_TEAR_EXT without checking it.
The hook is only set by dri3_glx.c and by drisw_glx.c when kopper is in
use. On a plain drisw screen (LIBGL_KOPPER_DISABLE=true, or an X server
without DRI3) it is NULL, so a client that queries the swap interval,
such as SDL3, crashes with a jump to address 0.
glXGetSwapIntervalEXT() already checks the hook and returns 0 when it is
missing. Do the same here: report an interval of 0 and no late swap
tearing. GLX_MAX_SWAP_INTERVAL_EXT already reads as 0 on such screens.
Cc: mesa-stable
Signed-off-by: pgm1207 <104554896+pgm1207@users.noreply.github.com>
---
src/glx/glx_pbuffer.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/src/glx/glx_pbuffer.c b/src/glx/glx_pbuffer.c
index 8c09d4b..9ecee6a 100644
--- a/src/glx/glx_pbuffer.c
+++ b/src/glx/glx_pbuffer.c
@@ -313,13 +313,15 @@ __glXQueryDrawable(Display * dpy, GLXDrawable drawable,
if (pdraw) {
if (attribute == GLX_SWAP_INTERVAL_EXT) {
- *value = abs(pdraw->psc->driScreen.getSwapInterval(pdraw));
+ *value = pdraw->psc->driScreen.getSwapInterval ?
+ abs(pdraw->psc->driScreen.getSwapInterval(pdraw)) : 0;
return 1;
} else if (attribute == GLX_MAX_SWAP_INTERVAL_EXT) {
*value = pdraw->psc->driScreen.maxSwapInterval;
return 1;
} else if (attribute == GLX_LATE_SWAPS_TEAR_EXT) {
- *value = pdraw->psc->driScreen.getSwapInterval(pdraw) < 0;
+ *value = pdraw->psc->driScreen.getSwapInterval ?
+ pdraw->psc->driScreen.getSwapInterval(pdraw) < 0 : 0;
return 1;
}
}
--
2.56.1