mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 12:56:06 +00:00
feat(xbox): install legacy EAppx titles through Windows Update (on main) (#2825)
* feat(xbox): install legacy EAppx titles through Windows Update A legacy Store title does not ship as MSIXVC. It ships as an encrypted EAppx bundle, which streaming rejects, so the store could list the game and never install it. Accept EAPPX and EAPPXBUNDLE beside MSIXVC, carry the format through the catalogue, the install record and the cached library, and dispatch legacy-install for those formats. Two backend patches do the work: - droiddeck-legacy-packages.patch lets the plan, license and extract verbs handle a legacy package, and expands a bundle in place (nesting bounded at three), decrypting each inner EAppx with the same keys. - droiddeck-legacy-install.patch adds legacy-install: resolve, license, download, extract, hoist AppxManifest.xml to the game root. Resolution asks the Xbox content service first and Windows Update second, because some legacy products return no files from the content service at all. The WU endpoint needs no Xbox credential but chains to Microsoft's ECC Product Root CA 2018, which Android's CA bundle does not carry, so that one public root is pinned for those requests. The manifest reader accepts AppxManifest.xml as well as MicrosoftGame.config, since a legacy package carries only the former. Running it against a real title exposed four things that only show up at full size: - A licence names a key by its 16-byte content id, while a bundle header names it as a (content id, package id) pair. Reading the 16-byte id yields a different pair, so a complete key file reported every key missing and no bundle could be opened. Keys are now aligned against the header's own ids before the header is judged. - Windows Update answers with several updates whose PackageContentId differs from the bundle's own. Licensing used to take the first and fail with content-http 400; every candidate is now tried in order, preferring the one the container is named after. - A container already in .xodus-container is reused rather than fetched again, so a failed run does not cost another download of tens of gigabytes. The space preflight no longer counts a container twice for the same reason. - A bundle that carries add-on packages unpacks each into its own folder, leaving the manifest one level down. Hoisting lifts the largest folder that holds a manifest, so the game still lands at the root beside its add-ons. Unpacking now reports bytes written, so the install bubble fills while a package is decrypted instead of holding a single unchanging word. * fix(xbox): unpack a legacy package across cores and report the bytes Unpacking one title ran as a single thread on a saturated core at about 40 MB/s. Files sit at independent offsets, so each worker now opens its own handle and takes every Nth file, with a 1 MiB read buffer in place of the 8 KiB default that turned one 64 KiB block into eight reads. Measured on the Forza Horizon 4 bundle, writes went from 40 MB/s to about 200 MB/s. Two things the first full-size run exposed: - The container was deleted only after the whole nested tree was unpacked, so a title that holds its package as one member held the archive and the decrypted copy at once. On this device that runs out of space partway through the second stage. The container is now deleted once its members are on disk, which frees the archive before they are decrypted. - A bundle member is written as a single file, so a counter that advances when a file finishes stays at zero for the whole of the longest stage. The reported figure now also follows the growth of the destination while that is the case, and never moves backwards when the container is freed. Progress is exact during the per-file stage: each file's declared length is added as it lands, instead of walking the whole destination every tick. * docs(xbox): record the completed legacy install The evidence section said a finished legacy install and its decrypted contents were unverified, because the first run was still unpacking when it was written. That install has now completed on the same device: the 85,219,173,025-byte container produced 79.3 GB at the game root with AppxManifest.xml and the package DLLs directly beneath it, and the launcher lists the title as installed. It also records what unpacking costs, since that decided the change: one thread held a core at 100% for about 40 MB/s and four reach about 200 MB/s, and releasing each container once its members are on disk is what keeps the peak footprint at one package rather than the archive plus its contents. The launch is not part of this evidence, and the entry says so. * fix(xbox): place the 64-bit framework beside a legacy title A Windows Update framework category lists one package per architecture under identifier-only names. The first package was unpacked, which on this device was the x86 build, so a 64-bit title got 32-bit DLLs and every load failed with STATUS_INVALID_IMAGE_FORMAT. Candidates are unpacked now and only the one whose manifest declares ProcessorArchitecture="x64" is kept. The framework folder was also never created, so a finished download failed at the move with "no such file or directory". unzip.rs belongs to this patch: legacy-install calls it and the recipe left it out, so a rebuild from the pinned source could not compile. * feat(xbox): report a UWP entry point at launch An unpacked package can name a COM class as its entry point instead of Windows.FullTrustApplication. That class is a UWP application, which expects the app model to activate a view; Wine has no host for it, so the launch died inside the loader with no explanation. The launch now reads the entry point and reports uwp-entry-point, and full-trust packages are unaffected. Forza Horizon 4 is such a package: its manifest names Forza.App. Its frameworks are installed and the loader is clean before that point. * fix(xbox): report why a launch was refused A failed prepare replaced the backend message with a fixed sign-in hint, so a title that was not installed or a runtime that refused all read as a bad account. The reason is kept, with paths and URLs dropped, and written to the store log. * fix(adb): dismiss the keyboard on Search and Go Search and Go were terminal IME actions but were not handled, so focus stayed in the field and the keyboard covered the results it had just fetched. * fix(xbox): keep a cache row without a legacy format plain Decoding added a format key with an empty value to every cached title, so a library restored from storage no longer matched the one that was saved. * test(ui): match the manifest message a legacy package reports The message covers both a MicrosoftGame.config and an AppxManifest, so the assertion follows the text the content dialog now prints. * fix(xbox): refuse to start a title that needs the Windows app model A legacy package that names an entry point other than Windows.FullTrustApplication is a UWP application. Wine has no app-model host, so starting its executable crashes inside the loader and the launch looks like nothing happened. Read the entry point from the manifest the installer already parses and stop the Play action with a message instead. Forza Horizon 4 names Forza.App, so it installs and reports as installed but cannot be started here yet. * fix(xbox): dispatch on the container format of the chosen package The catalogue records the format of the first installable desktop package, and the picker only replaced the content id. An offer that lists MSIXVC and a legacy container would then hand the legacy id to streaming, or the streamed id to legacy-install, and the install failed after resolution had succeeded. The choice now carries its own format and the catalogue value only fills a gap. * fix(xbox): keep an extraction reason that the sanitizer rewrote The extraction sanitizer replaces anything outside letters, digits, space, dot, underscore and dash with a question mark, so a reason such as "(os error 28)" arrived as "?os error 28?" and the allowlist dropped the line. The failure then showed only the stage code, with no cause. Add that replacement character to the class the allowlist accepts. * fix(xbox): print the reason a launch was refused The account channel sends a reason with a refusal, and the guest replaced it with a fixed sign-in message, so a title that was never installed still read as a bad account. The guest now shows the reason it was given, and a token holding a path is dropped whole instead of having its slashes removed and its directory names kept. * build(xbox): leave RUST_TEST_THREADS unset when the host has no value The recipe always passed the variable, empty when the host had none, and the pinned test harness rejects an empty count. On an ARM64 host that runs cargo test, so the default local build failed before compiling. * fix(xbox): rebuild the backend patches from the tree that ran The two patches in this branch were not the ones the verified install ran, and one of them did not compile. `unzip.rs` inflates deflated entries but the dependency that provides the inflater was never added, so `prepare.py` produced a tree that failed at `flate2::read::DeflateDecoder`. Anything else missing fell into the same gap: the install stage reported no bytes, so the bar held one value for the whole unpack, and a container a stopped run had finished was downloaded again. Rebuilt from the patched source, and fixed the defects a review of the patch found: - Unpacking reports bytes again: the workers count each file's declared length, and for the single-file bundle member the folder's growth stands in, which is what the device run showed. - A finished container is reused, so a retry after a failure past the download does not spend hours fetching it again. The space preflight counts it as reclaimable, since the retry truncates it first. - An install over a folder that already has a manifest replaces the old files instead of leaving the new package nested and reporting success. A first install still refuses to merge into an existing target. - The manifest search looks at the depth a nested bundle writes, not only one level down. - `withdraw_libraries` removes only the DLLs `copy_libraries` recorded copying, so a framework replacement cannot delete a library the title owns. - ZIP64 sizes and offsets stay `u64`; truncating them to `u32` read the wrong local header past 4 GiB. - The extraction checks the blockmap length against the footer's before writing, which the crate only does when asked. - The container being unpacked is never treated as a nested member, so `extract-eappx title.eappx .` no longer re-enters and deletes its own input. - `flate2` is declared and the lock is updated. `prepare.py` reproduces this from a pristine checkout and `cargo test` passes on it. * fix(xbox): apply the legacy install patch over the Nexus 0.2.15 backend * fix(xbox): install only the newest x64 build of a legacy title and size the space check at its real peak * fix(xbox): install a store package that is a plain archive instead of an XVD * fix(xbox): refuse a package entry that ends before its recorded size * fix(xbox): credit only complete staged containers toward the free space a legacy install needs * fix(xbox): bound each package entry to its data and check ZIP64 decoded sizes * fix(xbox): refuse duplicate package names and clear an unfinished download before measuring space * fix(xbox): bound package entries by the next header and stage a plain package until it validates * fix(xbox): hold the install folder lock through a legacy install * fix(xbox): fall back to an older build when Microsoft refuses the newest one a license * fix(xbox): keep the registered device across sign-out * feat(xbox): explain device-limit and license refusals, with a link to manage devices * fix(xbox): locate each build only once licensed, roll back a failed package swap, report the final license answer * fix(xbox): skip trial and preorder packages, read runtime behavior, keep licensing timeouts * fix(xbox): keep a failed package swap recoverable, size bundles up front, report key-write and framework errors cleanly * fix(xbox): drop a pending manifest check on any newer launch, keep committed backups out of restores, match the app-model order * fix(xbox): cancel pending launch checks on a new intent, remember entries a rollback could not remove * fix(xbox): clear the removal list before a restore moves old files back --------- Co-authored-by: TimmyCraft <46533729+TimmyTurner51@users.noreply.github.com>
This commit is contained in:
1 parent
7680b4d771
commit
a5d8abeab4
31 files changed
+4072
-68
No files matched your search
@@ -963,13 +963,36 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) {
|
||||
val request = gameLaunchRequest.incrementAndGet()
|
||||
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
|
||||
if (pkgStage != null) {
|
||||
onHandled()
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
return
|
||||
}
|
||||
val files = game.gameFiles
|
||||
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
|
||||
if (startGame(game, returnHome, onHandled)) onSettled()
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
|
||||
ui.post {
|
||||
when {
|
||||
request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled()
|
||||
refused -> {
|
||||
onHandled()
|
||||
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
|
||||
onSettled()
|
||||
}
|
||||
startGame(game, returnHome, onHandled) -> onSettled()
|
||||
}
|
||||
}
|
||||
}, "xbox-app-model").start()
|
||||
}
|
||||
|
||||
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean {
|
||||
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
|
||||
onHandled()
|
||||
if (SessionState.running) {
|
||||
@@ -1184,19 +1207,19 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
|
||||
}, LINK_PANEL_MS)
|
||||
val game = games.firstOrNull { it.gameIdString == id }
|
||||
if (game == null) {
|
||||
val link = intent
|
||||
fun consume() {
|
||||
if (intent !== link || pendingGameLink != id) return
|
||||
pendingGameLink = null
|
||||
intent.data = null
|
||||
intent.action = Intent.ACTION_MAIN
|
||||
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||
link.data = null
|
||||
link.action = Intent.ACTION_MAIN
|
||||
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||
}
|
||||
if (game == null) {
|
||||
consume()
|
||||
syncDualPanel()
|
||||
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else if (launchGame(game, returnHome = true)) {
|
||||
pendingGameLink = null
|
||||
intent.data = null
|
||||
intent.action = Intent.ACTION_MAIN
|
||||
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||
}
|
||||
} else launchGame(game, returnHome = true, onSettled = ::consume)
|
||||
}
|
||||
|
||||
private fun chooseGameShortcut(game: Library.SteamGame) {
|
||||
@@ -1914,6 +1937,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
gameLaunchRequest.incrementAndGet()
|
||||
if (intent.action == SteamIntegration.ACTION_SETUP) {
|
||||
gameLinkReading = false
|
||||
pendingGameLink = null
|
||||
|
||||
@@ -60,8 +60,7 @@ object StoreLaunchRequests {
|
||||
"xbox-prepare" -> runCatching { com.droiddeck.launcher.stores.xbox.XboxRuntime.prepare(app, request.getString("id")) }
|
||||
.getOrElse {
|
||||
StoresState.logLine("Xbox: launch prepare failed (${it.javaClass.simpleName}: ${it.message})")
|
||||
val reason = (it as? IllegalStateException)?.message ?: "Xbox account service is unavailable. Sign in again and retry."
|
||||
JSONObject().put("ok", false).put("reason", reason)
|
||||
JSONObject().put("ok", false).put("reason", reasonFor(it))
|
||||
}
|
||||
"ea-prepare" -> runCatching { lastLaunched = Store.EA to request.optString("id"); com.droiddeck.launcher.stores.ea.EaLaunch.prepare(app, request) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
|
||||
@@ -176,4 +175,21 @@ object StoreLaunchRequests {
|
||||
Log.w(TAG, "could not answer ${file.name}: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/// What the guest prints when a launch is refused.
|
||||
///
|
||||
/// The message is the only thing that separates a stale sign-in from a title
|
||||
/// that is not installed, so it is kept, minus anything that could carry a
|
||||
/// device path or a token: segments lookng like a path are dropped and the
|
||||
/// rest is folded to plain text.
|
||||
internal fun reasonFor(error: Throwable): String {
|
||||
val text = error.message.orEmpty()
|
||||
.split(' ')
|
||||
.filterNot { it.contains('/') || it.startsWith("http") }
|
||||
.joinToString(" ")
|
||||
.filter { it.isLetterOrDigit() || it in " .,:;_-()'" }
|
||||
.trim()
|
||||
.take(160)
|
||||
return if (text.isEmpty()) "Xbox account service is unavailable. Sign in again and retry." else text
|
||||
}
|
||||
}
|
||||
@@ -112,11 +112,21 @@ object XboxBackend : StoreBackend {
|
||||
fun selectPackage(context: Context, choice: org.json.JSONObject) {
|
||||
val pending = packageChoice ?: return
|
||||
packageChoice = null
|
||||
val item = pending.item.copy(extra = pending.item.extra + ("contentId" to choice.getString("contentId")))
|
||||
val item = pending.item.chosen(choice)
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, pending.root)
|
||||
enqueue(context.applicationContext, item, pending.root)
|
||||
}
|
||||
|
||||
/**
|
||||
* The picker can offer a package in a different container format than the
|
||||
* catalogue listed, and the installer dispatches on that format, so the
|
||||
* choice decides it and the catalogue value only fills a missing one.
|
||||
*/
|
||||
private fun CatalogItem.chosen(choice: org.json.JSONObject): CatalogItem {
|
||||
val format = choice.optString("packageFormat").takeIf { it.isNotBlank() } ?: extra["format"].orEmpty()
|
||||
return copy(extra = extra + mapOf("contentId" to choice.getString("contentId"), "format" to format))
|
||||
}
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
val app = context.applicationContext
|
||||
if (!item.extra["baseId"].isNullOrBlank()) { XboxContent.install(app, item); return }
|
||||
@@ -128,7 +138,7 @@ object XboxBackend : StoreBackend {
|
||||
val choices = XboxCatalog.objects(plan.getJSONArray("choices")).filter { it.optBoolean("supported") && it.optString("kind") == "Game" }
|
||||
check(choices.isNotEmpty()) { "This offer has no supported PC package." }
|
||||
if (plan.getString("status") == "ready" && choices.size == 1) {
|
||||
val selected = item.copy(extra = item.extra + ("contentId" to choices.single().getString("contentId")))
|
||||
val selected = item.chosen(choices.single())
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, selected, root)
|
||||
enqueue(app, selected, root)
|
||||
} else StoresState.post { packageChoice = PackageChoice(item, root, choices) }
|
||||
|
||||
@@ -18,6 +18,14 @@ internal object XboxCatalog {
|
||||
"CFQ7TTC10QFD" to "Xbox Game Pass (Starter Edition)",
|
||||
)
|
||||
|
||||
/**
|
||||
* The formats the installer can put on disk, so the catalogue never lists a
|
||||
* title it cannot install. `MSIXVC` streams in place; an EAppx container is a
|
||||
* legacy package that takes `legacy-install` instead.
|
||||
*/
|
||||
internal fun installableFormat(format: String): Boolean =
|
||||
format.equals("MSIXVC", true) || format.equals("EAPPX", true) || format.equals("EAPPXBUNDLE", true)
|
||||
|
||||
fun access(json: JSONObject, account: String, market: String, now: Instant = Instant.now(), report: (String) -> Unit = {}): Map<String, String> {
|
||||
require(json.getInt("schema") == 1 && json.getString("account") == account && json.getString("market") == market)
|
||||
val age = java.time.Duration.between(timestamp(json.getString("checkedAt")), now).seconds
|
||||
@@ -102,11 +110,15 @@ internal object XboxCatalog {
|
||||
if (!productId.matches(id) || json.optString("ProductType") != "Game") return null
|
||||
val localized = objects(json.optJSONArray("LocalizedProperties")).firstOrNull() ?: return null
|
||||
val title = localized.optString("ProductTitle").takeIf { it.isNotBlank() } ?: return null
|
||||
val packages = objects(json.optJSONArray("DisplaySkuAvailabilities")).flatMap {
|
||||
objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages"))
|
||||
}
|
||||
val packages = objects(json.optJSONArray("DisplaySkuAvailabilities"))
|
||||
.mapNotNull { it.optJSONObject("Sku")?.optJSONObject("Properties") }
|
||||
.filter { it.opt("IsTrial") != true && it.opt("IsPreOrder") != true }
|
||||
.flatMap { objects(it.optJSONArray("Packages")) }
|
||||
val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
|
||||
val installable = pc.any { it.optString("PackageFormat").equals("MSIXVC", true) }
|
||||
val installable = pc.any { installableFormat(it.optString("PackageFormat")) }
|
||||
// The installer needs the format, not just the fact that one exists: a
|
||||
// legacy container takes a different subcommand from a streamed package.
|
||||
val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty()
|
||||
val streams = cloud?.streams(id, access[id].orEmpty()) == true
|
||||
if (!installable && !streams) return null
|
||||
val images = objects(localized.optJSONArray("Images"))
|
||||
@@ -129,7 +141,8 @@ internal object XboxCatalog {
|
||||
publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"),
|
||||
description = localized.optString("ProductDescription"),
|
||||
sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L,
|
||||
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), "cloud" to flag(streams)),
|
||||
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable),
|
||||
"cloud" to flag(streams), "format" to format),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,8 @@ internal object XboxContent {
|
||||
val item = CatalogItem(Store.XBOX, id, localized?.optString("ProductTitle")?.ifBlank { id } ?: id,
|
||||
imageUrl = base.sidecar.cover, owned = access == "owned", subscription = access == "gamepass",
|
||||
sizeBytes = pkg.optLong("MaxDownloadSizeInBytes"),
|
||||
extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market, "family" to pkg.getString("PackageFamilyName")))
|
||||
extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market,
|
||||
"family" to pkg.getString("PackageFamilyName"), "format" to pkg.optString("PackageFormat")))
|
||||
Offer(item, File(base.folder, ".xbox-content/$id/.droiddeck-content.json").isFile)
|
||||
}
|
||||
StoresState.post { plan = Plan(base, offers) }
|
||||
@@ -51,7 +52,7 @@ internal object XboxContent {
|
||||
private fun packages(product: JSONObject?): List<JSONObject> = XboxCatalog.objects(product?.optJSONArray("DisplaySkuAvailabilities"))
|
||||
.filter { it.optJSONObject("Sku")?.optJSONObject("Properties")?.optBoolean("IsTrial", true) == false }
|
||||
.flatMap { XboxCatalog.objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages")) }
|
||||
.filter { pkg -> pkg.optString("PackageFormat") == "MSIXVC" &&
|
||||
.filter { pkg -> XboxCatalog.installableFormat(pkg.optString("PackageFormat")) &&
|
||||
XboxCatalog.objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
|
||||
|
||||
private val parents = java.util.concurrent.ConcurrentHashMap<String, String>()
|
||||
|
||||
@@ -249,10 +249,17 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
|
||||
block(current)
|
||||
}
|
||||
fun invalidate(app: Context, revoked: () -> Unit = {}) = storage(app) {
|
||||
java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString())
|
||||
StoreAccounts.clear(app, Store.XBOX)
|
||||
revoked()
|
||||
try {
|
||||
java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString())
|
||||
val device = StoreAccounts.read(app, Store.XBOX)?.optJSONObject("slots")?.opt(DEVICE_SLOT)
|
||||
val kept = device != null && runCatching { StoreAccounts.write(app, Store.XBOX, deviceOnly(device)) }.isSuccess
|
||||
if (!kept) StoreAccounts.clear(app, Store.XBOX)
|
||||
} finally {
|
||||
revoked()
|
||||
}
|
||||
}
|
||||
internal const val DEVICE_SLOT = "dev_license"
|
||||
internal fun deviceOnly(device: Any): JSONObject = JSONObject().put("slots", JSONObject().put(DEVICE_SLOT, device))
|
||||
fun <T> storage(app: Context, block: () -> T): T = synchronized(lock) {
|
||||
java.io.RandomAccessFile(java.io.File(StoreAccounts.dir(app, Store.XBOX), "account.lock"), "rw").use { file ->
|
||||
file.channel.lock().use { block() }
|
||||
|
||||
@@ -15,6 +15,10 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
private val paused = CountDownLatch(1)
|
||||
@Volatile private var child: Xodus.Child? = null
|
||||
@Volatile private var delete = false
|
||||
/** A legacy container has no pause protocol: the downloader is killed instead. */
|
||||
private val legacy = item.extra["format"]?.lowercase() in setOf("eappx", "eappxbundle")
|
||||
/** Release builds hide logcat from adb, so the tail is reported in the failure itself. */
|
||||
private val errors = java.util.concurrent.ConcurrentLinkedQueue<String>()
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
if (cancelled.get()) return null
|
||||
@@ -41,13 +45,21 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
val source = if (content) selected else item.id
|
||||
val guestFolder = StoreInstallRoot.guestPathForXodus(app, folder)
|
||||
val selection = if (content) emptyList() else listOf("--selected-content-id", selected)
|
||||
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
|
||||
"--progress-json", "--control-stdin") + selection).use { process ->
|
||||
// Streaming rejects a legacy container outright, so dispatch on the
|
||||
// format the catalogue recorded rather than fail after a download.
|
||||
val command = if (legacy) "legacy-install" else "streaming"
|
||||
Xodus.start(app, if (legacy) {
|
||||
listOf(command, source, guestFolder, "--market", market, "--progress-json", "--store-id", item.id) + selection
|
||||
} else {
|
||||
listOf(command, source, guestFolder, "--market", market, "--progress-json", "--control-stdin") + selection
|
||||
}).use { process ->
|
||||
child = process
|
||||
val rejected = AtomicBoolean(false)
|
||||
val rejectedLine = Regex(Xodus.SIGN_IN_REJECTED)
|
||||
val diagnostics = Xodus.diagnostics(process) { line ->
|
||||
StoresState.logLine("Xbox: $line")
|
||||
errors.add(line)
|
||||
while (errors.size > MAX_ERROR_LINES) errors.poll()
|
||||
if (line.matches(rejectedLine)) rejected.set(true)
|
||||
}
|
||||
if (cancelled.get()) process.process.destroy()
|
||||
@@ -60,7 +72,16 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
when (progress.getString("phase")) {
|
||||
"complete" -> complete = true
|
||||
"downloading", "download", "transfer" -> handle.progress(progress.getLong("completedBytes"), progress.optLong("totalBytes"))
|
||||
"finalizing", "installing" -> handle.stage(DownloadStage.INSTALL)
|
||||
// Unpacking reports files, not bytes: the frontend hands
|
||||
// over one container and the backend counts what it has
|
||||
// written, which is the only measure that moves while a
|
||||
// single multi-gigabyte member is decrypted.
|
||||
"installing" -> {
|
||||
handle.stage(DownloadStage.INSTALL)
|
||||
val total = progress.optLong("totalBytes")
|
||||
if (total > 0L) handle.stageProgress(progress.getLong("completedBytes"), total)
|
||||
}
|
||||
"finalizing" -> handle.stage(DownloadStage.INSTALL)
|
||||
else -> handle.stage(DownloadStage.MANIFEST)
|
||||
}
|
||||
}
|
||||
@@ -69,7 +90,14 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
diagnostics.join(2000)
|
||||
if (cancelled.get()) return null
|
||||
check(!rejected.get()) { app.getString(com.droiddeck.launcher.R.string.stores_xbox_sign_in_again) }
|
||||
check(process.process.exitValue() == 0 && complete) { "Xbox download did not complete. Resume to retry with fresh licenses." }
|
||||
val exit = process.process.exitValue()
|
||||
if (exit != 0 || !complete) {
|
||||
val tail = errors.toList().takeLast(MAX_ERROR_LINES)
|
||||
report(command, source, market, exit, tail)
|
||||
licenseRefusal(tail)?.let { error(app.getString(it)) }
|
||||
error("Xbox download did not complete. Resume to retry with fresh licenses." +
|
||||
tail.takeLast(3).joinToString("") { "\n$it" })
|
||||
}
|
||||
}
|
||||
if (content) {
|
||||
XboxContent.complete(app, item, folder)
|
||||
@@ -87,6 +115,21 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the backend's words beside the app, where adb can read them. */
|
||||
private fun report(command: String, source: String, market: String, exit: Int, tail: List<String>) {
|
||||
val text = buildString {
|
||||
appendLine("command: $command $source --market $market")
|
||||
appendLine("legacy: $legacy")
|
||||
appendLine("exit: $exit")
|
||||
appendLine("--- stderr (last ${tail.size} lines) ---")
|
||||
tail.forEach { appendLine(it) }
|
||||
}
|
||||
runCatching {
|
||||
app.getExternalFilesDir(null)?.let { File(it, "xbox-install.log").writeText(text) }
|
||||
}
|
||||
StoresState.logLine("Xbox install failed (exit $exit): ${tail.lastOrNull().orEmpty()}")
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
delete = deleteFiles
|
||||
@@ -98,14 +141,25 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
}
|
||||
Thread({
|
||||
runCatching {
|
||||
process.send(JSONObject().put("schema", 1).put("command", "pause"))
|
||||
paused.await(3, TimeUnit.SECONDS)
|
||||
if (!legacy) {
|
||||
process.send(JSONObject().put("schema", 1).put("command", "pause"))
|
||||
paused.await(3, TimeUnit.SECONDS)
|
||||
}
|
||||
process.close()
|
||||
}
|
||||
process.close()
|
||||
}, "xbox-download-stop").start()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val MAX_ERROR_LINES = 40
|
||||
const val DEVICES_URL = "https://account.microsoft.com/devices/content"
|
||||
private const val LICENSE_DIAGNOSTIC = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 "
|
||||
internal fun licenseRefusal(tail: List<String>): Int? = when (tail.lastOrNull { it.startsWith(LICENSE_DIAGNOSTIC) }
|
||||
?.removePrefix(LICENSE_DIAGNOSTIC)?.substringBefore(' ')) {
|
||||
"content-device-limit" -> com.droiddeck.launcher.R.string.stores_xbox_device_group_full
|
||||
"content-device-name" -> com.droiddeck.launcher.R.string.stores_xbox_license_refused
|
||||
else -> null
|
||||
}
|
||||
internal fun executable(folder: File): String = XboxManifest.executable(folder)
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,10 @@ internal object XboxLibraryCache {
|
||||
.put("image", game.imageUrl).put("poster", game.tallImageUrl).put("description", game.description)
|
||||
.put("developer", game.developer).put("publisher", game.publisher).put("size", game.sizeBytes)
|
||||
.put("access", if (game.subscription) "gamepass" else if (game.owned) "owned" else "none")
|
||||
.put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty()))
|
||||
.put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty())
|
||||
// The installer picks its subcommand from this; without it a
|
||||
// cached legacy game would fall back to streaming.
|
||||
.put("format", game.extra["format"].orEmpty()))
|
||||
}).toString()
|
||||
|
||||
internal fun decode(text: String?, account: String, market: String, now: Long = System.currentTimeMillis()): Snapshot? = runCatching {
|
||||
@@ -46,13 +49,18 @@ internal object XboxLibraryCache {
|
||||
val title = row.getString("title")
|
||||
val access = row.getString("access")
|
||||
val cloudId = row.optString("cloudId").takeIf { it.matches(Regex("[A-Z0-9]{12}")) }.orEmpty()
|
||||
val format = row.optString("format").takeIf { XboxCatalog.installableFormat(it) }.orEmpty()
|
||||
require(id.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && access in setOf("owned", "gamepass"))
|
||||
// A title with no legacy format keeps the plain shape a cache written
|
||||
// before formats existed has, so a restart round-trips unchanged.
|
||||
val extra = linkedMapOf("market" to market, "access" to access,
|
||||
"pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId)
|
||||
if (format.isNotEmpty()) extra["format"] = format
|
||||
CatalogItem(Store.XBOX, id, title, row.optString("image").takeIf { it.isNotEmpty() },
|
||||
tallImageUrl = row.optString("poster").takeIf { it.isNotEmpty() },
|
||||
description = row.optString("description"), developer = row.optString("developer"), publisher = row.optString("publisher"),
|
||||
sizeBytes = row.optLong("size"), owned = access == "owned", subscription = access == "gamepass",
|
||||
storeUrl = "https://www.xbox.com/games/store/$id", extra = mapOf("market" to market, "access" to access,
|
||||
"pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId))
|
||||
storeUrl = "https://www.xbox.com/games/store/$id", extra = extra)
|
||||
}
|
||||
require(games.map { it.id }.distinct().size == games.size)
|
||||
Snapshot(games, savedAt)
|
||||
|
||||
@@ -5,12 +5,25 @@ import org.xmlpull.v1.XmlPullParser
|
||||
|
||||
internal object XboxManifest {
|
||||
data class Info(val storeId: String, val name: String, val publisher: String, val version: String,
|
||||
val dependency: String, val related: List<String>, val executables: List<String>)
|
||||
val dependency: String, val related: List<String>, val executables: List<String>, val entryPoint: String,
|
||||
val runtimeBehavior: String = "")
|
||||
|
||||
/** A GameCore title describes itself with the config; a legacy package does not. */
|
||||
private const val GAME_CONFIG = "MicrosoftGame.config"
|
||||
private const val APPX_MANIFEST = "AppxManifest.xml"
|
||||
private const val FULL_TRUST = "Windows.FullTrustApplication"
|
||||
private const val APP_MODEL = "windowsApp"
|
||||
private val directBehaviors = setOf("packagedClassicApp", "win32App")
|
||||
|
||||
fun read(folder: File): Info {
|
||||
val manifests = folder.listFiles().orEmpty().filter { it.name.equals("MicrosoftGame.config", true) && it.isFile }
|
||||
require(manifests.size == 1) { "Missing or ambiguous MicrosoftGame.config." }
|
||||
val manifest = manifests.single()
|
||||
// Both manifests are read the same way: an identity, an executable path and,
|
||||
// for a Store package, related content.
|
||||
val files = folder.listFiles().orEmpty()
|
||||
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
|
||||
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
|
||||
require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
|
||||
val manifest = (config + legacy).single()
|
||||
val rootTag = if (config.isEmpty()) "Package" else "Game"
|
||||
require(manifest.length() <= 1_048_576)
|
||||
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
|
||||
val identities = ArrayList<List<String>>()
|
||||
@@ -18,7 +31,11 @@ internal object XboxManifest {
|
||||
val dependencies = ArrayList<String>()
|
||||
val related = ArrayList<String>()
|
||||
val entries = ArrayList<String>()
|
||||
val entryPoints = ArrayList<String>()
|
||||
val behaviors = ArrayList<String>()
|
||||
fun attribute(name: String) = parser.getAttributeValue(null, name).orEmpty()
|
||||
fun localAttribute(name: String) = (0 until parser.attributeCount)
|
||||
.firstOrNull { parser.getAttributeName(it).substringAfterLast(':') == name }?.let(parser::getAttributeValue).orEmpty()
|
||||
var root = false
|
||||
var elements = 0
|
||||
manifest.inputStream().use { input ->
|
||||
@@ -29,16 +46,22 @@ internal object XboxManifest {
|
||||
XmlPullParser.DOCDECL -> error("Xbox game manifests cannot contain a DTD.")
|
||||
XmlPullParser.START_TAG -> {
|
||||
require(++elements <= 10_000 && parser.depth <= 64) { "Xbox game manifest is too complex." }
|
||||
if (parser.depth == 1) { require(!root && parser.name == "Game"); root = true }
|
||||
if (parser.depth == 1) { require(!root && parser.name == rootTag); root = true }
|
||||
when (parser.name) {
|
||||
"Identity" -> identities.add(listOf(attribute("Name"), attribute("Publisher"), attribute("Version")))
|
||||
"StoreId" -> storeIds.add(parser.nextText().trim())
|
||||
"MainPackageDependency" -> dependencies.add(attribute("Name"))
|
||||
"RelatedProduct" -> related.add(parser.nextText().trim())
|
||||
"Executable" -> {
|
||||
val path = attribute("Name").replace('\\', '/')
|
||||
// Both carry the launch path: an attribute on the config's
|
||||
// Executable, or on the AppxManifest's Application.
|
||||
"Executable", "Application" -> {
|
||||
val path = attribute("Name").ifEmpty { attribute("Executable") }.replace('\\', '/')
|
||||
if (path.endsWith(".exe", true) && attribute("TargetDeviceFamily") in listOf("", "PC", "Windows.Desktop") &&
|
||||
!attribute("IsDevOnly").equals("true", true)) entries.add(path)
|
||||
if (parser.name == "Application") {
|
||||
attribute("EntryPoint").takeIf { it.isNotEmpty() }?.let(entryPoints::add)
|
||||
localAttribute("RuntimeBehavior").takeIf { it.isNotEmpty() }?.let(behaviors::add)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,9 +71,25 @@ internal object XboxManifest {
|
||||
require(root && identities.size <= 1 && storeIds.size <= 1 && dependencies.size <= 1) { "Invalid Xbox game manifest." }
|
||||
val ids = related.distinct()
|
||||
require(ids.size <= 128 && ids.all { it.matches(Regex("[A-Z0-9]{12}")) })
|
||||
val entry = entryPoints.distinct()
|
||||
val behavior = behaviors.distinct()
|
||||
require(entry.size <= 1 && behavior.size <= 1) { "Invalid Xbox game manifest." }
|
||||
val identity = identities.singleOrNull()
|
||||
return Info(storeIds.singleOrNull().orEmpty(), identity?.get(0).orEmpty(), identity?.get(1).orEmpty(), identity?.get(2).orEmpty(),
|
||||
dependencies.singleOrNull().orEmpty(), ids, entries)
|
||||
dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty())
|
||||
}
|
||||
|
||||
/**
|
||||
* A full trust package starts its executable directly. Anything else is activated
|
||||
* through the Windows app model, which this runtime has no host for, so starting
|
||||
* the executable would only crash.
|
||||
*/
|
||||
fun needsAppModel(folder: File): Boolean {
|
||||
val info = runCatching { read(folder) }.getOrNull() ?: return false
|
||||
val behavior = info.runtimeBehavior
|
||||
if (behavior.equals(APP_MODEL, true)) return true
|
||||
if (directBehaviors.any { it.equals(behavior, true) }) return false
|
||||
return info.entryPoint.isNotEmpty() && !info.entryPoint.equals(FULL_TRUST, true)
|
||||
}
|
||||
|
||||
fun executable(folder: File): String {
|
||||
|
||||
@@ -155,10 +155,12 @@ internal object Xodus {
|
||||
|
||||
const val SIGN_IN_REJECTED = "Microsoft content licensing rejected sign-in \\(HTTP 401\\)\\. Sign in again in Settings\\."
|
||||
|
||||
internal val reportable = Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3}|NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 [a-z0-9-]{1,48}( [0-9]{1,6})?|NEXUS_LEGACY_INSTALL_DETAIL_V1 [A-Za-z0-9 .,;-]{1,220}|NEXUS_EXTRACT_DIAGNOSTIC_V1 [a-z-]{1,48}|NEXUS_EXTRACT_DETAIL_V1 [A-Za-z0-9 ._?-]{1,220}|$SIGN_IN_REJECTED")
|
||||
|
||||
fun diagnostics(child: Child, report: (String) -> Unit = { com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $it") }): Thread = Thread({
|
||||
runCatching {
|
||||
child.process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line ->
|
||||
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{3}|$SIGN_IN_REJECTED")))
|
||||
if (line.matches(reportable))
|
||||
report(line)
|
||||
} }
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
@@ -112,7 +113,8 @@ internal fun Actions(content: @Composable () -> Unit) = FlowRow(
|
||||
) { content() }
|
||||
|
||||
@Composable
|
||||
internal fun ActionChip(t: String, ok: Boolean) = Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok) }
|
||||
internal fun ActionChip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null) =
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok, fraction, key) }
|
||||
|
||||
internal val Shape16 = RoundedCornerShape(16.dp)
|
||||
|
||||
@@ -139,13 +141,32 @@ internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Un
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Chip(t: String, ok: Boolean) {
|
||||
internal fun Chip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Text(
|
||||
t, fontSize = 12.sp, color = if (ok) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, RoundedCornerShape(99.dp)).padding(horizontal = 9.dp, vertical = 4.dp),
|
||||
)
|
||||
val shape = RoundedCornerShape(99.dp)
|
||||
val ink = if (ok) pal.good else colors.onSurfaceVariant
|
||||
Box(Modifier.clip(shape).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, shape)) {
|
||||
if (fraction != null) ChipFill(fraction, key, pal.signal.copy(alpha = 0.3f))
|
||||
Text(
|
||||
t, fontSize = 12.sp, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(horizontal = 9.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun androidx.compose.foundation.layout.BoxScope.ChipFill(fraction: Float, key: Any?, color: Color) {
|
||||
androidx.compose.runtime.key(key) {
|
||||
val target = fraction.coerceIn(0f, 1f)
|
||||
val shown = remember { Animatable(target) }
|
||||
LaunchedEffect(target) { shown.animateTo(target, androidx.compose.animation.core.tween(250, easing = androidx.compose.animation.core.LinearEasing)) }
|
||||
Box(
|
||||
Modifier.matchParentSize().drawBehind {
|
||||
drawRect(color, size = androidx.compose.ui.geometry.Size(size.width * shown.value, size.height))
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -458,7 +458,7 @@ internal fun GameActions(
|
||||
if (installed != null && id != null) {
|
||||
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
|
||||
if (download != null) {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
ActionChip(downloadLabel(download), ok = false, fraction = download.stageFraction.takeIf { it >= 0f }, key = download.stage)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
|
||||
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
|
||||
} else if (BattleNetInstall.updates[id] == true) {
|
||||
@@ -473,7 +473,7 @@ internal fun GameActions(
|
||||
}
|
||||
}
|
||||
download != null -> {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
ActionChip(downloadLabel(download), ok = false, fraction = download.stageFraction.takeIf { it >= 0f }, key = download.stage)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
|
||||
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
|
||||
|
||||
@@ -68,7 +68,7 @@ internal fun GogMaintenanceActions(game: InstalledStoreGame) {
|
||||
}
|
||||
}
|
||||
if (active) {
|
||||
ActionChip(downloadLabel(download!!), ok = false)
|
||||
ActionChip(downloadLabel(download!!), ok = false, fraction = download!!.stageFraction.takeIf { it >= 0f }, key = download!!.stage)
|
||||
if (download.interruptible) {
|
||||
SecondaryButton(stringResource(if (download.state == DownloadState.PAUSED) R.string.stores_dl_resume else R.string.stores_dl_pause)) {
|
||||
if (download.state == DownloadState.PAUSED) DownloadQueue.resume(ctx, key) else DownloadQueue.pause(key)
|
||||
|
||||
@@ -834,7 +834,9 @@ internal fun ArtCard(
|
||||
},
|
||||
)
|
||||
badge?.invoke(this)
|
||||
if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) { StateChip(chip, ChipTone.BUSY, small = true) }
|
||||
if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) {
|
||||
StateChip(chip, ChipTone.BUSY, small = true, fraction = download?.stageFraction?.takeIf { it >= 0f }, key = download?.stage)
|
||||
}
|
||||
val showName = LibraryDisplay.title || hot
|
||||
val showDetail = LibraryDisplay.size || hot
|
||||
if (showName || showDetail) Column(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -73,7 +74,7 @@ internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifi
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false) {
|
||||
internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false, fraction: Float? = null, key: Any? = null) {
|
||||
val pal = LocalPalette.current
|
||||
val (fill, ink) = when (tone) {
|
||||
ChipTone.OK -> Color(0xFF16321F) to pal.good
|
||||
@@ -82,10 +83,14 @@ internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false) {
|
||||
ChipTone.DEAL -> Color(0xFF1E3A1A) to Color(0xFF9BE27A)
|
||||
ChipTone.PLAIN -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
Text(
|
||||
text, fontSize = if (small) 9.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.3.sp, color = ink, maxLines = 1,
|
||||
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(fill).padding(horizontal = if (small) 5.dp else 8.dp, vertical = if (small) 1.dp else 2.dp),
|
||||
)
|
||||
val shape = RoundedCornerShape(6.dp)
|
||||
Box(Modifier.clip(shape).background(fill)) {
|
||||
if (fraction != null) ChipFill(fraction, key, ink.copy(alpha = 0.26f))
|
||||
Text(
|
||||
text, fontSize = if (small) 9.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.3.sp, color = ink, maxLines = 1,
|
||||
modifier = Modifier.padding(horizontal = if (small) 5.dp else 8.dp, vertical = if (small) 1.dp else 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
internal enum class ChipTone { OK, BUSY, WARN, DEAL, PLAIN }
|
||||
@@ -61,6 +61,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -371,6 +372,11 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
}
|
||||
DownloadState.FAILED -> {
|
||||
if (d.store == Store.XBOX && d.error == stringResource(R.string.stores_xbox_device_group_full)) {
|
||||
RoundAction(Icons.AutoMirrored.Filled.OpenInNew, stringResource(R.string.stores_xbox_manage_devices)) {
|
||||
runCatching { ctx.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(com.droiddeck.launcher.stores.xbox.XboxInstaller.DEVICES_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
}
|
||||
RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
|
||||
CancelAction { DownloadQueue.clear(ctx, d.key) }
|
||||
}
|
||||
|
||||
@@ -453,6 +453,20 @@ internal fun AdbTextField(
|
||||
onDoneLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
// Search and Go are terminal: leaving them unhandled
|
||||
// keeps focus in the field, so the keyboard would stay
|
||||
// up over the results it was used to find.
|
||||
imeAction in setOf(ImeAction.Search, ImeAction.Go) &&
|
||||
(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
post {
|
||||
clearFocus()
|
||||
(context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)
|
||||
as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user