mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10a66b2298 | ||
|
|
509c0482bf | ||
|
|
05d1795a51 | ||
|
|
87e6556993 | ||
|
|
8ff1f5dd20 | ||
|
|
93cd54c93b | ||
|
|
c8a49e853a | ||
|
|
78b3f27816 | ||
|
|
eaa095925c | ||
|
|
82b8cf1230 | ||
|
|
4163b31b02 | ||
|
|
02888834d4 | ||
|
|
ec537421ac | ||
|
|
5e23c668f3 | ||
|
|
a12ac8134a | ||
|
|
4562d61139 | ||
|
|
cc5ae4ff0b | ||
|
|
f0c52c273b |
No files matched your search
@@ -116,6 +116,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var frameGenLabel by mutableStateOf("")
|
||||
private var lossless by mutableStateOf(Lossless.State.NONE)
|
||||
private var showRemove by mutableStateOf(false)
|
||||
private var showResetSettings by mutableStateOf(false)
|
||||
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
||||
private var glThread by mutableStateOf(true)
|
||||
private var noGlError by mutableStateOf(true)
|
||||
@@ -350,6 +351,8 @@ class MainActivity : ComponentActivity() {
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||
private var zramCompression by mutableStateOf(false)
|
||||
private var zramSupported by mutableStateOf<Boolean?>(null)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var gameStorage by mutableStateOf("")
|
||||
@@ -725,6 +728,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}, "clear-logs").start()
|
||||
},
|
||||
onResetSettings = {
|
||||
if (SessionState.running) android.widget.Toast.makeText(this, R.string.setup_reset_settings_session_running, android.widget.Toast.LENGTH_LONG).show()
|
||||
else showResetSettings = true
|
||||
},
|
||||
onOffline = {
|
||||
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
|
||||
offline = OfflineMode.enabled(this)
|
||||
@@ -870,6 +877,10 @@ class MainActivity : ComponentActivity() {
|
||||
onConfirm = { showRemove = false; removeRuntime() },
|
||||
onDismiss = { showRemove = false },
|
||||
)
|
||||
if (showResetSettings) com.droiddeck.launcher.ui.ResetSettingsDialog(
|
||||
onConfirm = { gameProfiles -> resetSettings(gameProfiles) },
|
||||
onDismiss = { showResetSettings = false },
|
||||
)
|
||||
flood?.let { f -> com.droiddeck.launcher.ui.LaunchFlood(f.from, onProgress = { floodProgress = it }) { launchFlooded(f) } }
|
||||
returning?.let { r ->
|
||||
com.droiddeck.launcher.ui.FloodReturn(androidx.compose.ui.graphics.Color(r.color), r.to, onProgress = { floodProgress = it }) {
|
||||
@@ -1293,6 +1304,8 @@ class MainActivity : ComponentActivity() {
|
||||
touchMode = touchMode,
|
||||
suspendPolicy = suspendPolicy,
|
||||
steamDownloadsInBackground = steamDownloadsInBackground,
|
||||
zramCompression = if (mode == SessionService.MODE_STEAM) zramCompression else null,
|
||||
zramSupported = zramSupported,
|
||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
|
||||
@@ -1351,6 +1364,7 @@ class MainActivity : ComponentActivity() {
|
||||
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
|
||||
steamDownloadsInBackground = enabled
|
||||
},
|
||||
onZramCompression = { on -> SessionPrefs.setZramCompression(this, on); zramCompression = on },
|
||||
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
|
||||
onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on },
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
@@ -1539,6 +1553,9 @@ class MainActivity : ComponentActivity() {
|
||||
// The sheet lifts at once, on what was last read; the slow part (driver files, a walk of the
|
||||
// added-games folders, the storage volumes) lands while it rises.
|
||||
Thread({
|
||||
val zram = com.droiddeck.launcher.core.ZramSupport.supported()
|
||||
val zramOn = SessionPrefs.zramCompression(this)
|
||||
ui.post { zramSupported = zram; zramCompression = zramOn }
|
||||
drivers.refreshDrivers()
|
||||
val storage = GameStorage.options(this)
|
||||
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
|
||||
@@ -1742,6 +1759,22 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Setup's Reset all settings; the activity is recreated so every screen reads the defaults (and the language) again. */
|
||||
private fun resetSettings(gameProfiles: Boolean) {
|
||||
if (SessionState.running) return
|
||||
val scopes = steamGames.map { it.profileKey }
|
||||
Thread({
|
||||
val ok = com.droiddeck.launcher.session.SettingsReset.resetAll(this, gameProfiles, scopes)
|
||||
ui.post {
|
||||
if (isDestroyed) return@post
|
||||
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
|
||||
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
recreate()
|
||||
}
|
||||
}, "reset-settings").start()
|
||||
}
|
||||
|
||||
private fun removeRuntime() {
|
||||
if (runtimeChangesBlocked()) return
|
||||
val removal = LinuxRuntimeInstaller.beginUninstall(this) ?: return
|
||||
|
||||
@@ -1349,6 +1349,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// Turnip, not the system Adreno driver: importing the dma-bufs gamescope commits needs
|
||||
// VK_EXT_image_drm_format_modifier, which the system driver does not implement.
|
||||
val turnip = TurnipDriver(this)
|
||||
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup")
|
||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
||||
|
||||
// The output size belongs to the session, not to the Surface: gamescope's display is
|
||||
@@ -1417,6 +1418,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
)
|
||||
Log.i(TAG, "hdr: " + (if (on) "on" else if (wanted) "wanted but ${probe.reason}" else "off") + " · display ${probe.formats.ifEmpty { "SDR" }}")
|
||||
}
|
||||
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
|
||||
CompositorHost.startOrAttach(
|
||||
holder.surface, runtimeDir.path,
|
||||
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
||||
|
||||
@@ -8,7 +8,7 @@ import android.content.Context
|
||||
* permission). Running commands in the guest, evaluating JavaScript in the Steam client, session
|
||||
* environment, binary overrides and preference writes reach inside the app's sandbox - the guest
|
||||
* holds the Steam login - which the shell of a stock device otherwise cannot. They require
|
||||
* Setup > Session > Debugging tools to be on, in every build. The bridge itself cannot turn it on.
|
||||
* Setup > Diagnostics > Debugging tools to be on, in every build. The bridge itself cannot turn it on.
|
||||
*/
|
||||
object AgentAccess {
|
||||
const val MAX_REQUEST_CHARS = 256 * 1024
|
||||
@@ -33,7 +33,7 @@ object AgentAccess {
|
||||
fun requireCommands(context: Context) {
|
||||
if (!commandsAllowed(context)) throw AgentException(
|
||||
"AGENT_COMMANDS_DISABLED",
|
||||
"Debugging tools are off: turn on Setup > Session > Debugging tools on the device",
|
||||
"Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device",
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,11 @@ object AppLanguage {
|
||||
const val SYSTEM = ""
|
||||
|
||||
/** The languages the app ships, as BCP 47 tags, in the order the picker lists them. */
|
||||
val supported: List<String> = listOf("en", "es", "fr", "ru", "ja", "ko", "zh-CN", "zh-TW", "zh-HK")
|
||||
val supported: List<String> = listOf(
|
||||
"en", "id", "ms", "cs", "da", "de", "es", "es-419", "fr", "it", "hu", "nl", "nb", "pl",
|
||||
"pt-BR", "pt-PT", "ro", "fi", "sv", "vi", "tr", "el", "bg", "ru", "uk", "ar", "hi", "th",
|
||||
"ja", "ko", "zh-CN", "zh-TW", "zh-HK",
|
||||
)
|
||||
|
||||
private const val PREFS = "language"
|
||||
private const val KEY = "app_language"
|
||||
@@ -97,9 +101,18 @@ object AppLanguage {
|
||||
// 0 leaves it undefined, so only the locale is changed.
|
||||
private fun override(locale: Locale) = Configuration().apply { fontScale = 0f; setLocales(LocaleList(locale)) }
|
||||
|
||||
private val latinAmerica = setOf(
|
||||
"419", "AR", "BO", "BR", "BZ", "CL", "CO", "CR", "CU", "DO", "EC", "GT", "HN", "MX", "NI", "PA",
|
||||
"PE", "PR", "PY", "SV", "US", "UY", "VE",
|
||||
)
|
||||
|
||||
/** Which of the app's languages [locale] reads as, or null when the app does not ship it. */
|
||||
fun supportedTag(locale: Locale): String? = when (locale.language) {
|
||||
"en", "es", "fr", "ru", "ja", "ko" -> locale.language
|
||||
"en", "fr", "ru", "ja", "ko", "ms", "cs", "da", "de", "it", "hu", "nl", "nb", "pl", "ro", "fi",
|
||||
"sv", "vi", "tr", "el", "bg", "uk", "ar", "hi", "th" -> locale.language
|
||||
"in", "id" -> "id"
|
||||
"es" -> if (locale.country in latinAmerica) "es-419" else "es"
|
||||
"pt" -> if (locale.country.isEmpty() || locale.country == "BR") "pt-BR" else "pt-PT"
|
||||
"zh" -> when {
|
||||
locale.script == "Hans" -> "zh-CN"
|
||||
locale.country == "HK" || locale.country == "MO" -> "zh-HK"
|
||||
@@ -116,9 +129,33 @@ object AppLanguage {
|
||||
/** A language's name in that language, for the picker: what a reader of it looks for. */
|
||||
fun nativeName(tag: String): String = when (tag) {
|
||||
"en" -> "English"
|
||||
"es" -> "Español"
|
||||
"id" -> "Bahasa Indonesia"
|
||||
"ms" -> "Bahasa Melayu"
|
||||
"cs" -> "Čeština"
|
||||
"da" -> "Dansk"
|
||||
"de" -> "Deutsch"
|
||||
"es" -> "Español (España)"
|
||||
"es-419" -> "Español (Latinoamérica)"
|
||||
"fr" -> "Français"
|
||||
"it" -> "Italiano"
|
||||
"hu" -> "Magyar"
|
||||
"nl" -> "Nederlands"
|
||||
"nb" -> "Norsk bokmål"
|
||||
"pl" -> "Polski"
|
||||
"pt-BR" -> "Português (Brasil)"
|
||||
"pt-PT" -> "Português (Portugal)"
|
||||
"ro" -> "Română"
|
||||
"fi" -> "Suomi"
|
||||
"sv" -> "Svenska"
|
||||
"vi" -> "Tiếng Việt"
|
||||
"tr" -> "Türkçe"
|
||||
"el" -> "Ελληνικά"
|
||||
"bg" -> "Български"
|
||||
"ru" -> "Русский"
|
||||
"uk" -> "Українська"
|
||||
"ar" -> "العربية"
|
||||
"hi" -> "हिन्दी"
|
||||
"th" -> "ไทย"
|
||||
"ja" -> "日本語"
|
||||
"ko" -> "한국어"
|
||||
"zh-CN" -> "简体中文"
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import java.io.File
|
||||
|
||||
/** Whether the client's memory can be paged out to compressed swap: MADV_PAGEOUT (Linux 5.4) and a zram or other swap device. */
|
||||
object ZramSupport {
|
||||
private const val GIB = 1L shl 30
|
||||
|
||||
fun supported(): Boolean = kernelAtLeast(System.getProperty("os.version").orEmpty(), 5, 4) && swapTotalKb() > 0
|
||||
|
||||
fun recommended(context: Context): Boolean {
|
||||
if (!supported()) return false
|
||||
val memory = ActivityManager.MemoryInfo()
|
||||
context.getSystemService(ActivityManager::class.java).getMemoryInfo(memory)
|
||||
val advertised = if (Build.VERSION.SDK_INT >= 34) memory.advertisedMem else 0L
|
||||
return belowTwelveGb(advertised, memory.totalMem)
|
||||
}
|
||||
|
||||
fun belowTwelveGb(advertisedBytes: Long, totalBytes: Long): Boolean =
|
||||
if (advertisedBytes > 0) advertisedBytes < 11 * GIB else totalBytes < 10 * GIB
|
||||
|
||||
fun kernelAtLeast(release: String, major: Int, minor: Int): Boolean {
|
||||
val parts = Regex("^(\\d+)\\.(\\d+)").find(release)?.groupValues ?: return false
|
||||
val ma = parts[1].toInt()
|
||||
val mi = parts[2].toInt()
|
||||
return ma > major || (ma == major && mi >= minor)
|
||||
}
|
||||
|
||||
fun swapTotalKb(meminfo: List<String> = runCatching { File("/proc/meminfo").readLines() }.getOrDefault(emptyList())): Long =
|
||||
meminfo.firstOrNull { it.startsWith("SwapTotal:") }
|
||||
?.substringAfter(':')?.trim()?.substringBefore(' ')?.toLongOrNull() ?: 0L
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.gpu;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
|
||||
/** Setup breadcrumbs survive failures before a session log exists. No account data. */
|
||||
public final class DriverSetupLog {
|
||||
private DriverSetupLog() {}
|
||||
|
||||
public static synchronized void write(Context context, String stage) {
|
||||
Log.i("DriverSetup", stage);
|
||||
append(context.getFilesDir(), stage);
|
||||
try { append(context.getExternalFilesDir(null), stage); }
|
||||
catch (Exception ignored) { /* External storage is optional. */ }
|
||||
}
|
||||
|
||||
private static void append(File directory, String stage) {
|
||||
if (directory == null) return;
|
||||
try {
|
||||
directory.mkdirs();
|
||||
File file = new File(directory, "driver-setup.txt");
|
||||
// Keep the latest run's breadcrumbs bounded across repeated attempts.
|
||||
try (FileWriter out = new FileWriter(file, file.length() < 131072)) {
|
||||
out.write(System.currentTimeMillis() + " " + stage + "\n");
|
||||
}
|
||||
} catch (Exception ignored) { /* Diagnostics must never prevent startup. */ }
|
||||
}
|
||||
}
|
||||
@@ -45,13 +45,16 @@ import java.util.zip.ZipInputStream;
|
||||
*/
|
||||
public final class TurnipDriver {
|
||||
private static final String TAG = "TurnipDriver";
|
||||
/** Pinned A6xx/A7xx upstream build; used as the A6xx offline fallback. */
|
||||
private static final String DRIVER_A6XX = "turnip26.3.0-a6xx";
|
||||
/** Adreno 7xx (8 Gen 2/3, e.g. the Pocket FIT's A750). */
|
||||
private static final String DRIVER_A7XX = "turnip25.1.0";
|
||||
/** Adreno 8xx (8 Elite, e.g. a Fold 8's A830). */
|
||||
private static final String DRIVER_A8XX = "turnip-sdk36";
|
||||
/** The two the apk carries; never removable, unpacked on demand. */
|
||||
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(
|
||||
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER));
|
||||
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER,
|
||||
DRIVER_A6XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER_A6XX));
|
||||
/** Overrides the pick, for a device we cannot reach: a7xx, a8xx or system. */
|
||||
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
|
||||
/** Bundled drivers the user deleted: hidden from the list, their unpacked copy removed. */
|
||||
@@ -289,12 +292,14 @@ public final class TurnipDriver {
|
||||
*/
|
||||
public String install() {
|
||||
String id = choose();
|
||||
DriverSetupLog.write(context, "install.begin driver=" + id);
|
||||
if (id == null) return null;
|
||||
File dir = new File(contentDir, id);
|
||||
if (!new File(dir, "meta.json").isFile()) {
|
||||
FileUtils.delete(dir);
|
||||
if (!TarZst.extractAsset(context, "graphics_driver/adrenotools-" + id + ".tzst", dir)) {
|
||||
Log.e(TAG, "could not unpack " + id);
|
||||
DriverSetupLog.write(context, "install.unpack-failed driver=" + id);
|
||||
FileUtils.delete(dir);
|
||||
return null;
|
||||
}
|
||||
@@ -305,6 +310,7 @@ public final class TurnipDriver {
|
||||
return null;
|
||||
}
|
||||
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
|
||||
DriverSetupLog.write(context, "install.ready driver=" + id + " library=" + library);
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -338,6 +344,7 @@ public final class TurnipDriver {
|
||||
if (forced.startsWith("system")) return null;
|
||||
if (forced.startsWith("a8")) return DRIVER_A8XX;
|
||||
if (forced.startsWith("a7")) return DRIVER_A7XX;
|
||||
if (forced.startsWith("a6")) return DRIVER_A6XX;
|
||||
}
|
||||
String model = gpuModel();
|
||||
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
|
||||
@@ -348,6 +355,7 @@ public final class TurnipDriver {
|
||||
char generation = m.group(1).charAt(0);
|
||||
if (generation >= '8') return DRIVER_A8XX;
|
||||
if (generation == '7') return DRIVER_A7XX;
|
||||
if (generation == '6') return DRIVER_A6XX;
|
||||
}
|
||||
}
|
||||
// Nothing to go on: Android 16 shipped with the 8 Elite, so treat a new device as 8xx.
|
||||
|
||||
@@ -2,10 +2,12 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.text.InputType
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
import android.view.inputmethod.BaseInputConnection
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.InputConnection
|
||||
@@ -53,7 +55,10 @@ class KeyboardHost(
|
||||
return KeyConnection()
|
||||
}
|
||||
|
||||
fun toggle() = if (shown) hide() else show()
|
||||
fun toggle() = if (shown && imeVisible()) hide() else show()
|
||||
|
||||
private fun imeVisible() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R ||
|
||||
rootWindowInsets?.isVisible(WindowInsets.Type.ime()) != false
|
||||
|
||||
fun show() {
|
||||
shown = true
|
||||
|
||||
@@ -13,6 +13,7 @@ import android.util.Log
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.SteamTouchConfig.Element
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.abs
|
||||
@@ -335,7 +336,7 @@ class SteamTouchControls(
|
||||
if (editing) {
|
||||
text.textSize = r * 0.3f
|
||||
text.color = Color.argb(alpha / 2, 255, 255, 255)
|
||||
canvas.drawText("Trackpad", x, y - (text.descent() + text.ascent()) / 2, text)
|
||||
canvas.drawText(context.getString(R.string.deck_surface_trackpad), x, y - (text.descent() + text.ascent()) / 2, text)
|
||||
}
|
||||
}
|
||||
SteamTouchConfig.STEAM -> {
|
||||
@@ -579,7 +580,7 @@ class SteamTouchControls(
|
||||
SteamTouchConfig.STEAM -> "STEAM"
|
||||
SteamTouchConfig.THUMB -> "…"
|
||||
SteamTouchConfig.KEYBOARD -> "⌨"
|
||||
SteamTouchConfig.PASTE -> "Paste"
|
||||
SteamTouchConfig.PASTE -> context.getString(R.string.touch_paste)
|
||||
SteamTouchConfig.SELECT -> "⧉"
|
||||
SteamTouchConfig.START -> "☰"
|
||||
SteamTouchConfig.BUMPER_LEFT -> "LB"
|
||||
@@ -880,15 +881,15 @@ class SteamTouchControls(
|
||||
}
|
||||
|
||||
private fun controlName(type: Int) = when (type) {
|
||||
SteamTouchConfig.DPAD -> "D-pad"
|
||||
SteamTouchConfig.JOYSTICK_LEFT -> "Left stick"
|
||||
SteamTouchConfig.JOYSTICK_RIGHT -> "Right stick"
|
||||
SteamTouchConfig.TRACKPAD_LEFT -> "Left trackpad"
|
||||
SteamTouchConfig.TRACKPAD_RIGHT -> "Right trackpad"
|
||||
SteamTouchConfig.TRACKPAD_CENTER -> "Trackpad"
|
||||
SteamTouchConfig.DPAD -> context.getString(R.string.touch_dpad)
|
||||
SteamTouchConfig.JOYSTICK_LEFT -> context.getString(R.string.touch_left_stick)
|
||||
SteamTouchConfig.JOYSTICK_RIGHT -> context.getString(R.string.touch_right_stick)
|
||||
SteamTouchConfig.TRACKPAD_LEFT -> context.getString(R.string.deck_left_trackpad)
|
||||
SteamTouchConfig.TRACKPAD_RIGHT -> context.getString(R.string.deck_right_trackpad)
|
||||
SteamTouchConfig.TRACKPAD_CENTER -> context.getString(R.string.deck_surface_trackpad)
|
||||
SteamTouchConfig.STEAM -> "Steam"
|
||||
SteamTouchConfig.THUMB -> "Menu"
|
||||
SteamTouchConfig.KEYBOARD -> "Keyboard"
|
||||
SteamTouchConfig.THUMB -> context.getString(R.string.touch_menu)
|
||||
SteamTouchConfig.KEYBOARD -> context.getString(R.string.touch_keyboard)
|
||||
else -> label(type)
|
||||
}
|
||||
|
||||
@@ -899,22 +900,22 @@ class SteamTouchControls(
|
||||
val list = android.widget.LinearLayout(context).apply { orientation = android.widget.LinearLayout.VERTICAL; setPadding((12 * density).toInt(), 0, (12 * density).toInt(), 0) }
|
||||
var close: () -> Unit = {}
|
||||
val copied = prefs.getString("copiedLayout", null)
|
||||
fun item(name: String, enabled: Boolean = true, action: () -> Unit) = list.addView(android.widget.Button(context).apply {
|
||||
text = name
|
||||
fun item(name: Int, enabled: Boolean = true, action: () -> Unit) = list.addView(android.widget.Button(context).apply {
|
||||
setText(name)
|
||||
isAllCaps = false
|
||||
isEnabled = enabled
|
||||
setOnClickListener { close(); action(); invalidate() }
|
||||
})
|
||||
item("Colour and opacity…") { pickColor() }
|
||||
item("Copy this layout") {
|
||||
item(R.string.touch_color_opacity) { pickColor() }
|
||||
item(R.string.touch_copy_layout) {
|
||||
prefs.edit().putString("copiedLayout", (editElements + hidden).joinToString(";") {
|
||||
"${it.type},${it.visible},${it.x},${it.y},${it.xScale},${it.yScale}"
|
||||
}).apply()
|
||||
Toast.makeText(context, "Layout copied; paste it into any game's touch layout", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, R.string.touch_layout_copied, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
item("Paste copied layout", copied != null) { pasteLayout(copied ?: "") }
|
||||
item("Reset to Steam's default") { resetEditSet() }
|
||||
close = SteamTouchIconPicker.showPanel(host, "Layout", list, listOf("Close" to {}))
|
||||
item(R.string.touch_paste_layout, copied != null) { pasteLayout(copied ?: "") }
|
||||
item(R.string.touch_reset_layout) { resetEditSet() }
|
||||
close = SteamTouchIconPicker.showPanel(host, context.getString(R.string.ctrl_layout), list, listOf(context.getString(R.string.common_close) to {}))
|
||||
}
|
||||
|
||||
/** A copied layout onto this action set: each control the set has takes the copied place. */
|
||||
@@ -985,11 +986,12 @@ class SteamTouchControls(
|
||||
RectF(frame.left + l * s, frame.top + t * s, frame.left + r * s, frame.top + b * s)
|
||||
|
||||
private fun text(canvas: Canvas, str: String, x: Float, y: Float, size: Float, color: Int = Color.WHITE, bold: Boolean = true,
|
||||
align: Paint.Align = Paint.Align.CENTER) {
|
||||
align: Paint.Align = Paint.Align.CENTER, maxWidth: Float = 0f) {
|
||||
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
this.color = color; textSize = size; textAlign = align
|
||||
typeface = if (bold) android.graphics.Typeface.DEFAULT_BOLD else android.graphics.Typeface.DEFAULT
|
||||
}
|
||||
if (maxWidth > 0f) p.measureText(str).let { if (it > maxWidth) p.textSize = size * maxWidth / it }
|
||||
canvas.drawText(str, x, y - (p.descent() + p.ascent()) / 2, p)
|
||||
}
|
||||
|
||||
@@ -1004,7 +1006,7 @@ class SteamTouchControls(
|
||||
canvas.drawRoundRect(r, radius, radius, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = line2; style = Paint.Style.STROKE; strokeWidth = 1.2f * s })
|
||||
}
|
||||
val ink = when { !enabled -> Color.argb(110, 242, 244, 247); primary -> onAccent; else -> onSurface }
|
||||
text(canvas, text, r.centerX(), r.centerY(), 14f * s, ink)
|
||||
text(canvas, text, r.centerX(), r.centerY(), 14f * s, ink, maxWidth = r.width() - 16f * s)
|
||||
if (enabled) hots += Hot(r, onTap)
|
||||
}
|
||||
|
||||
@@ -1044,7 +1046,7 @@ class SteamTouchControls(
|
||||
BIG_PICTURE -> "Steam"
|
||||
else -> gameNames[appId] ?: run {
|
||||
val app = appId
|
||||
gameNames[app] = "app $app"
|
||||
gameNames[app] = context.getString(R.string.touch_app_id, app)
|
||||
loader.execute {
|
||||
val name = SteamTouchConfig.gameName(context, app) ?: return@execute
|
||||
handler.post { gameNames[app] = name; invalidate() }
|
||||
@@ -1061,7 +1063,7 @@ class SteamTouchControls(
|
||||
// Header: power (DroidDeck's own menu: stop, settings), the Steam mark, what is running, close.
|
||||
iconButton(canvas, ref(f, s, 494f, 18f, 531f, 55f), false, { menuOpen = false; onMenu() }) { c, r, col -> drawPower(c, r, col) }
|
||||
drawMark(canvas, f.left + 104f * s, f.top + 37f * s, 13f * s)
|
||||
text(canvas, "Touch controls", f.left + 124f * s, f.top + 30f * s, 14f * s, onSurface, align = Paint.Align.LEFT)
|
||||
text(canvas, context.getString(R.string.touch_title), f.left + 124f * s, f.top + 30f * s, 14f * s, onSurface, align = Paint.Align.LEFT)
|
||||
text(canvas, gameName(), f.left + 124f * s, f.top + 46f * s, 11f * s, muted, bold = false, align = Paint.Align.LEFT)
|
||||
closeButton(canvas, f, s) { menuOpen = false }
|
||||
val controller = options.inputMode != SteamTouchConfig.INPUT_MOUSE
|
||||
@@ -1071,10 +1073,10 @@ class SteamTouchControls(
|
||||
m -> SteamTouchConfig.INPUT_MOUSE
|
||||
else -> SteamTouchConfig.INPUT_CONTROLLER
|
||||
}))
|
||||
tile(canvas, ref(f, s, 45f, 81f, 249f, 271f), s, "Touch Controller", controller, { setModes(!controller, mouse || controller) }) { c, r, col ->
|
||||
tile(canvas, ref(f, s, 45f, 81f, 249f, 271f), s, context.getString(R.string.touch_controller), controller, { setModes(!controller, mouse || controller) }) { c, r, col ->
|
||||
drawPhonePad(c, r, col)
|
||||
}
|
||||
tile(canvas, ref(f, s, 271f, 81f, 475f, 271f), s, "Mouse", mouse, { setModes(controller || mouse, !mouse) }) { c, r, col ->
|
||||
tile(canvas, ref(f, s, 271f, 81f, 475f, 271f), s, context.getString(R.string.touch_mouse), mouse, { setModes(controller || mouse, !mouse) }) { c, r, col ->
|
||||
drawMouse(c, r, col, crossed = false)
|
||||
}
|
||||
// Under the controller: gyroscope, fade, vibrate on touch.
|
||||
@@ -1102,10 +1104,13 @@ class SteamTouchControls(
|
||||
val speed = speeds.indexOfFirst { abs(it - options.trackpadSensitivity) < 0.2f }.coerceAtLeast(1)
|
||||
iconButton(canvas, ref(f, s, 412f, 278f, 475f, 318f), mouse && relative, {
|
||||
setOptions(options.copy(trackpadSensitivity = speeds[(speed + 1) % speeds.size]))
|
||||
}) { c, r, col -> text(c, listOf("Slow", "Normal", "Fast")[speed], r.centerX(), r.centerY(), r.height() * 0.32f, col) }
|
||||
}) { c, r, col ->
|
||||
val name = context.getString(listOf(R.string.touch_speed_slow, R.string.touch_speed_normal, R.string.touch_speed_fast)[speed])
|
||||
text(c, name, r.centerX(), r.centerY(), r.height() * 0.32f, col, maxWidth = r.width() - 6f * s)
|
||||
}
|
||||
drawVolume(canvas, f, s)
|
||||
blueButton(canvas, ref(f, s, 45f, 329f, 249f, 372f), "Edit layout", s, primary = true) { menuOpen = false; startEditing() }
|
||||
blueButton(canvas, ref(f, s, 271f, 329f, 475f, 372f), "DroidDeck menu", s) { menuOpen = false; onMenu() }
|
||||
blueButton(canvas, ref(f, s, 45f, 329f, 249f, 372f), context.getString(R.string.touch_edit_layout), s, primary = true) { menuOpen = false; startEditing() }
|
||||
blueButton(canvas, ref(f, s, 271f, 329f, 475f, 372f), context.getString(R.string.touch_droiddeck_menu), s) { menuOpen = false; onMenu() }
|
||||
}
|
||||
|
||||
private val audio by lazy { context.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager }
|
||||
@@ -1173,7 +1178,7 @@ class SteamTouchControls(
|
||||
canvas.drawRoundRect(r, radius, radius, Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = if (on) accent else line; style = Paint.Style.STROKE; strokeWidth = (if (on) 2f else 1.2f) * s
|
||||
})
|
||||
text(canvas, title, r.left + 16f * s, r.top + 22f * s, 14f * s, onSurface, align = Paint.Align.LEFT)
|
||||
text(canvas, title, r.left + 16f * s, r.top + 22f * s, 14f * s, onSurface, align = Paint.Align.LEFT, maxWidth = r.width() - 72f * s)
|
||||
// A switch, top right.
|
||||
val sw = RectF(r.right - 50f * s, r.top + 12f * s, r.right - 14f * s, r.top + 32f * s)
|
||||
canvas.drawRoundRect(sw, sw.height() / 2, sw.height() / 2, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (on) accent else line2 })
|
||||
@@ -1181,7 +1186,7 @@ class SteamTouchControls(
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (on) onAccent else muted })
|
||||
val artRect = RectF(r.centerX() - 58f * s, r.top + 62f * s, r.centerX() + 58f * s, r.top + 140f * s)
|
||||
art(canvas, artRect, if (on) onSurface else muted)
|
||||
text(canvas, if (on) "On" else "Off", r.left + 16f * s, r.bottom - 18f * s, 12f * s, if (on) accent else muted, bold = false, align = Paint.Align.LEFT)
|
||||
text(canvas, context.getString(if (on) R.string.touch_on else R.string.touch_off), r.left + 16f * s, r.bottom - 18f * s, 12f * s, if (on) accent else muted, bold = false, align = Paint.Align.LEFT)
|
||||
hots += Hot(r, toggle)
|
||||
}
|
||||
|
||||
@@ -1194,9 +1199,9 @@ class SteamTouchControls(
|
||||
closeButton(canvas, f, s) { save() }
|
||||
val sets = SteamTouchConfig.actionSets(config)
|
||||
val setName = sets.firstOrNull { it.first == editSet }?.second
|
||||
val title = if (sets.size > 1 && setName != null) "${gameName()} · $setName" else "${gameName()} ${config.title ?: "Layout"}"
|
||||
text(canvas, title, f.centerX(), f.top + 30f * s, 14f * s, onSurface)
|
||||
text(canvas, "Drag controls onto the screen", f.centerX(), f.top + 47f * s, 11f * s, muted, bold = false)
|
||||
val title = if (sets.size > 1 && setName != null) "${gameName()} · $setName" else "${gameName()} ${config.title ?: context.getString(R.string.ctrl_layout)}"
|
||||
text(canvas, title, f.centerX(), f.top + 30f * s, 14f * s, onSurface, maxWidth = f.width() - 200f * s)
|
||||
text(canvas, context.getString(R.string.touch_drag_hint), f.centerX(), f.top + 47f * s, 11f * s, muted, bold = false, maxWidth = f.width() - 200f * s)
|
||||
if (sets.size > 1) {
|
||||
arrowPill(canvas, ref(f, s, 120f, 26f, 150f, 44f), -1) { stepEditSet(-1) }
|
||||
arrowPill(canvas, ref(f, s, 474f, 26f, 504f, 44f), 1) { stepEditSet(1) }
|
||||
@@ -1251,8 +1256,8 @@ class SteamTouchControls(
|
||||
shader = android.graphics.RadialGradient(wheel.centerX(), wheel.centerY(), wheel.width() / 2f, Color.WHITE, Color.TRANSPARENT, android.graphics.Shader.TileMode.CLAMP)
|
||||
})
|
||||
hots += Hot(wheel, { pickColor() })
|
||||
blueButton(canvas, ref(f, s, 45f, 329f, 232f, 372f), "Arrange", s, primary = true) { trayOpen = false }
|
||||
blueButton(canvas, ref(f, s, 254f, 329f, 441f, 372f), "Discard", s) { stopEditing() }
|
||||
blueButton(canvas, ref(f, s, 45f, 329f, 232f, 372f), context.getString(R.string.touch_arrange), s, primary = true) { trayOpen = false }
|
||||
blueButton(canvas, ref(f, s, 254f, 329f, 441f, 372f), context.getString(R.string.touch_discard), s) { stopEditing() }
|
||||
}
|
||||
|
||||
private fun arrowPill(canvas: Canvas, r: RectF, dir: Int, onTap: () -> Unit) {
|
||||
@@ -1290,7 +1295,10 @@ class SteamTouchControls(
|
||||
return RectF(x - r, y - r, x + r, y + r)
|
||||
}
|
||||
|
||||
private val contextLabels = listOf("Icon", "W−", "W+", "H−", "H+", "Hide")
|
||||
private val contextLabels by lazy {
|
||||
listOf(R.string.touch_icon, R.string.touch_narrower, R.string.touch_wider, R.string.touch_shorter, R.string.touch_taller, R.string.touch_hide)
|
||||
.map(context::getString)
|
||||
}
|
||||
|
||||
private fun contextRects(): List<RectF> {
|
||||
val e = editElements.getOrNull(selected) ?: return emptyList()
|
||||
@@ -1313,11 +1321,11 @@ class SteamTouchControls(
|
||||
canvas.drawRoundRect(m, m.width() * 0.15f, m.width() * 0.15f, p)
|
||||
drawDots(canvas, m.centerX(), m.centerY() - m.height() * 0.1f, m.width() * 0.5f, Color.WHITE)
|
||||
hots += Hot(m, { trayOpen = true })
|
||||
if (saving) text(canvas, "Saving…", width / 2f, height * 0.08f, 22f * max(unit(), 0.6f))
|
||||
if (saving) text(canvas, context.getString(R.string.touch_saving), width / 2f, height * 0.08f, 22f * max(unit(), 0.6f))
|
||||
contextRects().forEachIndexed { i, r ->
|
||||
canvas.drawRoundRect(r, r.height() * 0.3f, r.height() * 0.3f, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = surface })
|
||||
canvas.drawRoundRect(r, r.height() * 0.3f, r.height() * 0.3f, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = line2; style = Paint.Style.STROKE; strokeWidth = 1.2f })
|
||||
text(canvas, contextLabels[i], r.centerX(), r.centerY(), r.height() * 0.4f, onSurface, bold = false)
|
||||
text(canvas, contextLabels[i], r.centerX(), r.centerY(), r.height() * 0.4f, onSurface, bold = false, maxWidth = r.width() - 6f)
|
||||
hots += Hot(r, { contextTool(i) })
|
||||
}
|
||||
}
|
||||
@@ -1448,12 +1456,14 @@ class SteamTouchControls(
|
||||
val ref = visual?.ref
|
||||
val binding = visual?.binding
|
||||
if (ref == null || binding == null) {
|
||||
Toast.makeText(context, "This control has no binding in Steam to put an icon on", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, R.string.touch_no_binding, Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
val name = if (e.type == SteamTouchConfig.DPAD) "D-pad " + listOf("up", "down", "left", "right")[selectedArm] else label(e.type)
|
||||
val name = if (e.type == SteamTouchConfig.DPAD) {
|
||||
context.getString(listOf(R.string.touch_dpad_up, R.string.touch_dpad_down, R.string.touch_dpad_left, R.string.touch_dpad_right)[selectedArm])
|
||||
} else label(e.type)
|
||||
val host = parent as? android.view.ViewGroup ?: return
|
||||
SteamTouchIconPicker(context, host, appId, "Icon for $name", binding) { picked ->
|
||||
SteamTouchIconPicker(context, host, appId, context.getString(R.string.touch_icon_for, name), binding) { picked ->
|
||||
pendingBindings[ref] = picked
|
||||
rebuildVisuals()
|
||||
invalidate()
|
||||
@@ -1480,9 +1490,9 @@ class SteamTouchControls(
|
||||
}
|
||||
}, android.widget.LinearLayout.LayoutParams(dp(30), dp(30)).apply { marginEnd = dp(6) })
|
||||
}
|
||||
root.addView(android.widget.TextView(context).apply { text = "Colour" })
|
||||
root.addView(android.widget.TextView(context).apply { setText(R.string.ctrl_color) })
|
||||
root.addView(android.widget.HorizontalScrollView(context).apply { addView(swatchRow) })
|
||||
root.addView(android.widget.TextView(context).apply { text = "Opacity"; setPadding(0, dp(12), 0, 0) })
|
||||
root.addView(android.widget.TextView(context).apply { setText(R.string.ctrl_opacity); setPadding(0, dp(12), 0, 0) })
|
||||
val opacityRow = android.widget.LinearLayout(context)
|
||||
listOf(20, 35, 50, 65, 80, 100).forEach { percent ->
|
||||
opacityRow.addView(android.widget.Button(context).apply {
|
||||
@@ -1497,7 +1507,7 @@ class SteamTouchControls(
|
||||
}
|
||||
root.addView(android.widget.HorizontalScrollView(context).apply { addView(opacityRow) })
|
||||
val host = parent as? android.view.ViewGroup ?: return
|
||||
SteamTouchIconPicker.showPanel(host, "Touch layout colour", root, listOf("Done" to {}))
|
||||
SteamTouchIconPicker.showPanel(host, context.getString(R.string.touch_layout_color), root, listOf(context.getString(R.string.touch_done) to {}))
|
||||
}
|
||||
|
||||
private fun save() {
|
||||
@@ -1528,11 +1538,11 @@ class SteamTouchControls(
|
||||
handler.post {
|
||||
saving = false
|
||||
if (file == null) {
|
||||
Toast.makeText(context, "Could not save the touch layout", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, R.string.touch_save_failed, Toast.LENGTH_SHORT).show()
|
||||
invalidate()
|
||||
return@post
|
||||
}
|
||||
Toast.makeText(context, "Touch layout saved to Steam", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, R.string.touch_saved, Toast.LENGTH_SHORT).show()
|
||||
onSaved()
|
||||
stopEditing()
|
||||
reloadConfig()
|
||||
|
||||
@@ -21,6 +21,7 @@ import android.widget.HorizontalScrollView
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import com.droiddeck.launcher.R
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
@@ -50,7 +51,7 @@ class SteamTouchIconPicker(
|
||||
val root = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; setPadding(dp(16), dp(8), dp(16), 0) }
|
||||
val left = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
|
||||
val label = EditText(context).apply {
|
||||
hint = "Label (optional)"
|
||||
setHint(R.string.touch_label_hint)
|
||||
setText(current.label)
|
||||
inputType = InputType.TYPE_CLASS_TEXT
|
||||
setSingleLine()
|
||||
@@ -77,21 +78,22 @@ class SteamTouchIconPicker(
|
||||
setPadding(0, dp(8), 0, 0)
|
||||
addView(preview, LinearLayout.LayoutParams(dp(56), dp(56)))
|
||||
addView(TextView(context).apply {
|
||||
text = if (names.isEmpty()) "Steam's icons were not found" else "${names.size} icons from Steam"
|
||||
text = if (names.isEmpty()) context.getString(R.string.touch_icons_missing)
|
||||
else context.resources.getQuantityString(R.plurals.touch_icons_found, names.size, names.size)
|
||||
setPadding(dp(12), 0, 0, 0)
|
||||
})
|
||||
})
|
||||
left.addView(paletteRow("Icon colour", { foreground }) { foreground = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||
left.addView(paletteRow("Button colour", { background }) { background = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||
left.addView(paletteRow(context.getString(R.string.touch_icon_color), { foreground }) { foreground = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||
left.addView(paletteRow(context.getString(R.string.touch_button_color), { background }) { background = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||
root.addView(left, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
|
||||
root.addView(grid, LinearLayout.LayoutParams(0, dp(250), 1.2f).apply { marginStart = dp(16) })
|
||||
updatePreview(preview)
|
||||
showPanel(host, title, root, listOf(
|
||||
"No icon" to {
|
||||
context.getString(R.string.touch_no_icon) to {
|
||||
onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = "", foreground = "", background = ""))
|
||||
},
|
||||
"Cancel" to {},
|
||||
"Use" to {
|
||||
context.getString(R.string.common_cancel) to {},
|
||||
context.getString(R.string.common_use) to {
|
||||
onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = icon,
|
||||
foreground = if (icon.isEmpty()) "" else foreground, background = if (icon.isEmpty()) "" else background))
|
||||
},
|
||||
|
||||
@@ -10,29 +10,36 @@ import java.io.File
|
||||
object QuestExperimental {
|
||||
private const val TAG = "QuestExperimental"
|
||||
const val DRIVER = "turnip25.1.0-quest1"
|
||||
const val DRIVER_A6XX = "turnip26.3.0-quest2"
|
||||
|
||||
internal fun quest2(model: String, device: String, manufacturer: String): Boolean =
|
||||
model.equals("Quest 2", ignoreCase = true) ||
|
||||
((manufacturer.equals("Oculus", ignoreCase = true) || manufacturer.equals("Meta", ignoreCase = true)) &&
|
||||
device == "hollywood")
|
||||
|
||||
// Quest 2 has an A6xx GPU and cannot use this bundled A7xx driver.
|
||||
internal fun supported(model: String, device: String, manufacturer: String): Boolean =
|
||||
model.equals("Quest 3", ignoreCase = true) || model.equals("Quest 3S", ignoreCase = true) ||
|
||||
quest2(model, device, manufacturer) || model.equals("Quest 3", ignoreCase = true) || model.equals("Quest 3S", ignoreCase = true) ||
|
||||
((manufacturer.equals("Oculus", ignoreCase = true) || manufacturer.equals("Meta", ignoreCase = true)) &&
|
||||
(device == "eureka" || device == "panther"))
|
||||
|
||||
fun isSupported(): Boolean = supported(Build.MODEL, Build.DEVICE, Build.MANUFACTURER)
|
||||
fun isQuest2(): Boolean = quest2(Build.MODEL, Build.DEVICE, Build.MANUFACTURER)
|
||||
|
||||
fun initialize(context: Context) {
|
||||
if (!isSupported()) return
|
||||
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
if (!prefs.getBoolean("questDefaultsV1", false)) {
|
||||
val defaultsKey = if (isQuest2()) "quest2DefaultsV1" else "questDefaultsV1"
|
||||
if (!prefs.getBoolean(defaultsKey, false)) {
|
||||
// Auto would download an unwrapped display driver and lose the compatibility path.
|
||||
// Apply once so deliberate changes made during headset testing remain possible.
|
||||
prefs.edit()
|
||||
.putString("gpuDriverMode", SessionPrefs.GPU_DRIVERS_MANUAL)
|
||||
.putString("androidDriver", DRIVER)
|
||||
.putString("androidDriver", if (isQuest2()) DRIVER_A6XX else DRIVER)
|
||||
.putString("linuxDriver", "")
|
||||
// The existing HDR option uses SurfaceControl presentation. This is a
|
||||
// corruption workaround from upstream issue #245, not a claim of HDR accuracy.
|
||||
.putBoolean("hdr.steam", true)
|
||||
.putBoolean("questDefaultsV1", true)
|
||||
.putBoolean(defaultsKey, true)
|
||||
.apply()
|
||||
}
|
||||
val report = buildString {
|
||||
@@ -51,7 +58,7 @@ object QuestExperimental {
|
||||
appendLine("androidDriver=${SessionPrefs.androidDriver(context)}")
|
||||
appendLine("steamSurfaceControlWorkaround=${SessionPrefs.hdr(context, "steam")}")
|
||||
appendLine("GPUOBJ fallback installed in Android driver and ARM64 libblsession")
|
||||
appendLine("Experimental Quest 3/3S compatibility; 2D panel application")
|
||||
appendLine("Experimental Quest 2/3/3S compatibility; 2D panel application")
|
||||
}
|
||||
Log.i(TAG, report)
|
||||
runCatching { File(context.filesDir, "quest-startup.txt").writeText(report) }
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.CpuAllocationDefaults
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.core.ZramSupport
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import org.json.JSONObject
|
||||
@@ -86,6 +87,14 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("gameStoresSpeedTier", tier).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Hidden A/B switch for the Epic installer: "adaptive" (default: native parallel fetch written
|
||||
* straight into staged files), "batch" (the older whole-cache native fetch, then native
|
||||
* assembly; needs about twice the game's size free) or "java" (the bounded one-chunk-at-a-time
|
||||
* Java writer). No UI; set it in the `session` preferences for benchmarks.
|
||||
*/
|
||||
fun storesEpicMode(context: Context): String = prefs(context).getString("storesEpicMode", "adaptive") ?: "adaptive"
|
||||
|
||||
/** Which tab a signed-in store opens on when its chip is picked: [STORES_OPEN_LIBRARY] or [STORES_OPEN_STORE]. */
|
||||
fun storesOpenTab(context: Context): String =
|
||||
prefs(context).getString("storesOpenTab", STORES_OPEN_LIBRARY)?.takeIf { it == STORES_OPEN_STORE } ?: STORES_OPEN_LIBRARY
|
||||
@@ -1057,6 +1066,16 @@ object SessionPrefs {
|
||||
}.apply()
|
||||
}
|
||||
|
||||
/** Steam only: the client's memory goes to the device's zram while a game runs (ZramSupport). */
|
||||
fun zramCompression(context: Context): Boolean {
|
||||
val prefs = prefs(context)
|
||||
return if (prefs.contains("zramCompression")) prefs.getBoolean("zramCompression", false) else ZramSupport.recommended(context)
|
||||
}
|
||||
|
||||
fun setZramCompression(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("zramCompression", on).apply()
|
||||
}
|
||||
|
||||
// ── Game storage ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -660,6 +660,8 @@ class SessionService : Service() {
|
||||
// gamescope's realtime Vulkan queues (the session script turns this into
|
||||
// GAMESCOPE_FORCE_VULKAN_REALTIME); off unless the user turns it on.
|
||||
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
|
||||
if (SessionState.mode == MODE_STEAM && SessionPrefs.zramCompression(this) &&
|
||||
com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
|
||||
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
|
||||
// Anything else, for a device that cannot be reached with a debugger: droiddeck-env in the
|
||||
// app's own external files (envSwitchFile) holds KEY=VALUE lines that go into the session's
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
|
||||
/**
|
||||
* Setup's "Reset all settings": every choice goes back to the default its getter falls back to.
|
||||
*
|
||||
* Only settings are removed. The "session" file also holds the library (added games' names, exes,
|
||||
* appids and art picks), migration records, the drivers Auto installed, the storage and ROMs
|
||||
* folders and the one-time permission prompts; those stay, as do store sign-ins, imported drivers
|
||||
* and Lossless Scaling. Game profiles (each game's and the Default profile's environment
|
||||
* overrides) are cleared only when asked for.
|
||||
*/
|
||||
object SettingsReset {
|
||||
private const val TAG = "SettingsReset"
|
||||
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"hud", "hudDeck", "backActionsInverted", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "stretch16x9",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline",
|
||||
// Cleared so the Quest's one-time compatibility defaults are written again.
|
||||
"questDefaultsV1",
|
||||
)
|
||||
|
||||
/** Per-mode settings, stored as "<prefix><mode>". */
|
||||
internal val SESSION_PREFIXES = listOf(
|
||||
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "suspendPolicy.",
|
||||
)
|
||||
|
||||
private val STEAM_TOUCH_KEYS = listOf("feedback", "autoFade", "gyro", "shake")
|
||||
|
||||
internal fun isSessionSetting(key: String) = key in SESSION_KEYS || SESSION_PREFIXES.any { key.startsWith(it) }
|
||||
|
||||
/**
|
||||
* Resets the settings, then per-game profiles when [gameProfiles] is set ([gameScopes] are the
|
||||
* library's profile keys; scopes with saved overrides are found on their own). Blocking: call
|
||||
* off the main thread. Returns false if a part could not be reset; the rest is still done.
|
||||
* The language is not reset here: AppLanguage.setChosen changes the process locale, so the
|
||||
* caller does that on the main thread.
|
||||
*/
|
||||
fun resetAll(context: Context, gameProfiles: Boolean, gameScopes: Collection<String> = emptyList()): Boolean {
|
||||
var ok = true
|
||||
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
session.edit().apply { session.all.keys.filter { isSessionSetting(it) }.forEach { remove(it) } }.commit()
|
||||
ControllerPrefs.resetAll(context)
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
context.getSharedPreferences("frame_gen", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
context.getSharedPreferences("steam_touch", Context.MODE_PRIVATE).edit()
|
||||
.apply { STEAM_TOUCH_KEYS.forEach { remove(it) } }.commit()
|
||||
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(context, false)
|
||||
|
||||
if (gameProfiles) {
|
||||
val scopes = (gameScopes + runCatching { GameEnvironmentStore.read(context).games.keys }.getOrDefault(emptySet()) +
|
||||
SessionPrefs.gameTextureFiltering(context).keys)
|
||||
.filter { it.isNotEmpty() && GameEnvironment.validScope(it) }.toSet()
|
||||
scopes.forEach { scope ->
|
||||
runCatching { GameProfileManager.reset(context, scope) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not reset the profile of $scope", it) }
|
||||
}
|
||||
session.edit().remove("gameTextureFiltering").commit()
|
||||
runCatching { GameEnvironmentStore.save(context, GameEnvironmentStore.read(context).copy(shared = emptyMap())) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not clear the Default profile's environment", it) }
|
||||
}
|
||||
|
||||
QuestExperimental.initialize(context)
|
||||
runCatching { OfflineMode.apply(context, LinuxRuntime.rootDir(context)) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not turn offline mode off", it) }
|
||||
runCatching { GameEnvironmentStore.publish(context) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not update game environment", it) }
|
||||
Log.i(TAG, "settings reset (game profiles: $gameProfiles, ok: $ok)")
|
||||
return ok
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,7 @@ class StoreGameSidecar(
|
||||
const val VERSION = 1
|
||||
const val STATE_INSTALLED = "installed"
|
||||
const val STATE_INSTALLING = "installing"
|
||||
const val STATE_UPDATING = "updating"
|
||||
|
||||
fun file(folder: File): File = File(folder, FILE_NAME)
|
||||
|
||||
|
||||
@@ -20,13 +20,68 @@ import java.util.zip.CRC32
|
||||
* shortcut's path - and with it its appid - stays the same from one session to the next.
|
||||
*/
|
||||
object StoreInstallRoot {
|
||||
const val SPACE_UNKNOWN = -1L
|
||||
private const val INTERNAL = "root/Games/Stores"
|
||||
private const val ON_VOLUME = "Games"
|
||||
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
|
||||
|
||||
/** One place a game can be installed: the folder, its name for the dialog, and whether it is a card. */
|
||||
class Target(val root: File, val label: String, val removable: Boolean) {
|
||||
val freeBytes: Long get() = try { StatFs((if (root.isDirectory) root else root.parentFile ?: root).path).availableBytes } catch (e: Exception) { 0L }
|
||||
val freeBytes: Long get() = availableBytes(root)
|
||||
}
|
||||
|
||||
data class StorageCheck(
|
||||
val enough: Boolean,
|
||||
val requiredBytes: Long,
|
||||
val availableBytes: Long,
|
||||
val errorMessage: String? = null
|
||||
)
|
||||
|
||||
@JvmStatic
|
||||
fun availableBytes(file: File): Long = probeAvailableBytes(file, { StatFs(it.path).availableBytes }, { it.usableSpace })
|
||||
|
||||
internal fun probeAvailableBytes(file: File, statBytes: (File) -> Long, usableBytes: (File) -> Long): Long {
|
||||
var dir: File? = if (file.isDirectory) file else file.parentFile
|
||||
if (dir == null) dir = file
|
||||
while (dir != null && !dir.exists()) dir = dir.parentFile
|
||||
val existing = dir ?: return SPACE_UNKNOWN
|
||||
return try {
|
||||
statBytes(existing).coerceAtLeast(SPACE_UNKNOWN)
|
||||
} catch (e: Exception) {
|
||||
StoresState.logLine("storage: StatFs failed for store install target (${e.javaClass.simpleName})")
|
||||
try {
|
||||
// File's zero also means an unavailable measurement; only StatFs establishes zero.
|
||||
usableBytes(existing).takeIf { it > 0L } ?: SPACE_UNKNOWN
|
||||
} catch (fallback: Exception) {
|
||||
StoresState.logLine("storage: usable-space fallback failed for store install target (${fallback.javaClass.simpleName})")
|
||||
SPACE_UNKNOWN
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun insufficientSpace(required: Long, available: Long): Boolean = required > 0L && available >= 0L && available < required
|
||||
|
||||
/**
|
||||
* The catalog size is the known minimum for an install. Epic's actual chunk-cache requirement
|
||||
* is determined from its manifest before chunk downloads begin.
|
||||
*/
|
||||
fun estimatedBytesNeeded(item: CatalogItem): Long = StoreSizes.size(item).coerceAtLeast(0L)
|
||||
|
||||
/** Pre-install storage check to detect insufficient space before starting. */
|
||||
fun checkStorage(context: Context, item: CatalogItem, targetRoot: File): StorageCheck {
|
||||
val size = estimatedBytesNeeded(item)
|
||||
val existing = existingFolder(context, item.store, item.id, item.title)
|
||||
val freeTarget = availableBytes(existing ?: targetRoot)
|
||||
// Backends account for completed files on resume; the catalog cannot describe remaining work.
|
||||
// Comparing the full catalog size to remaining free space would reject valid resumes.
|
||||
if (item.store == Store.EPIC || existing != null) return StorageCheck(enough = true, requiredBytes = size, availableBytes = freeTarget)
|
||||
if (size <= 0L) return StorageCheck(enough = true, requiredBytes = 0L, availableBytes = freeTarget)
|
||||
if (insufficientSpace(size, freeTarget)) {
|
||||
val msg = context.getString(com.droiddeck.launcher.R.string.stores_storage_insufficient, formatBytes(size), formatBytes(freeTarget))
|
||||
return StorageCheck(enough = false, requiredBytes = size, availableBytes = freeTarget, errorMessage = msg)
|
||||
}
|
||||
return StorageCheck(enough = true, requiredBytes = size, availableBytes = freeTarget)
|
||||
}
|
||||
|
||||
/** The internal root: always there, always the default. */
|
||||
|
||||
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.LibraryCache
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
/**
|
||||
* What happens around a store install so the rest of the app sees the game: the sidecar is
|
||||
@@ -30,10 +32,28 @@ object StoreInstalls {
|
||||
* updated keeps its finished sidecar, so the game stays in Steam meanwhile.
|
||||
*/
|
||||
fun begin(folder: File, store: Store, id: String, title: String, cover: String?, hero: String?) {
|
||||
if (StoreGameSidecar.read(folder)?.isInstalled == true) return
|
||||
val before = StoreGameSidecar.read(folder)
|
||||
if (before?.isInstalled == true || before?.state == StoreGameSidecar.STATE_UPDATING) return
|
||||
StoreGameSidecar(store, id, title, exe = "", cover = cover, hero = hero, state = StoreGameSidecar.STATE_INSTALLING).write(folder)
|
||||
}
|
||||
|
||||
/** Epic commits verified files individually, not a whole-game transaction. Keep updates resumable. */
|
||||
@JvmStatic
|
||||
fun markUpdating(folder: File) {
|
||||
val before = StoreGameSidecar.read(folder) ?: return
|
||||
if (!before.isInstalled) return
|
||||
val stage = File.createTempFile(".droiddeck-update-", ".stage", folder)
|
||||
try {
|
||||
java.io.FileOutputStream(stage).use {
|
||||
it.write(before.copy(state = StoreGameSidecar.STATE_UPDATING, installVersion = "").toJson().toString(2).toByteArray(Charsets.UTF_8))
|
||||
it.fd.sync()
|
||||
}
|
||||
Files.move(stage.toPath(), StoreGameSidecar.file(folder).toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
|
||||
} finally {
|
||||
stage.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes an install: writes the launcher and the finished sidecar, then the art, then
|
||||
* registers the game. Runs on the caller's worker thread. The launcher and sidecar writes
|
||||
@@ -105,16 +125,18 @@ object StoreInstalls {
|
||||
/**
|
||||
* What Cancel does: everything the install wrote goes - the game folder with its sidecar and
|
||||
* the caches in [caches] - unless the folder holds a finished install being repaired or updated;
|
||||
* then only the caches go and the working game stays. Off the caller's thread; the library
|
||||
* follows when it is done, so the game reads Install again.
|
||||
* then only the caches go. An Epic `updating` folder is retained too: its verified swaps are
|
||||
* not rolled back, and it must be resumed before being advertised as installed again.
|
||||
* Off the caller's thread; the library follows when it is done.
|
||||
*/
|
||||
fun discard(context: Context, folder: File, caches: List<File>) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val keep = StoreGameSidecar.read(folder)?.isInstalled == true
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
val keep = sidecar?.isInstalled == true || sidecar?.state == StoreGameSidecar.STATE_UPDATING
|
||||
caches.forEach { deleteTree(it) }
|
||||
if (!keep) deleteTree(folder)
|
||||
StoresState.logLine(if (keep) "removed the partial update of ${folder.name}" else "removed ${folder.name}")
|
||||
StoresState.logLine(if (keep) "removed update caches for ${folder.name}; verified file swaps are retained" else "removed ${folder.name}")
|
||||
StoresState.notifyLibraryChanged(app)
|
||||
}, "store-cancel-clean").start()
|
||||
}
|
||||
|
||||
@@ -219,7 +219,25 @@ object StoresState {
|
||||
/** Starts an install into [root] (the internal root when null). */
|
||||
fun install(context: Context, item: CatalogItem, root: java.io.File? = null) {
|
||||
val app = context.applicationContext
|
||||
val target = root ?: StoreInstallRoot.installRoot(app)
|
||||
val folder = StoreInstallRoot.folderFor(app, item.store, item.id, item.title, root ?: StoreInstallRoot.installRoot(app))
|
||||
val target = folder.parentFile!!.parentFile!!
|
||||
val check = StoreInstallRoot.checkStorage(app, item, target)
|
||||
if (!check.enough) {
|
||||
val errorMsg = check.errorMessage ?: app.getString(com.droiddeck.launcher.R.string.stores_storage_insufficient, formatBytes(check.requiredBytes), formatBytes(check.availableBytes))
|
||||
val entry = com.droiddeck.launcher.stores.download.DownloadEntry(
|
||||
item.store,
|
||||
item.id,
|
||||
item.title,
|
||||
cover = item.imageUrl,
|
||||
bytesTotal = item.sizeBytes,
|
||||
location = StoreInstallRoot.labelFor(app, folder)
|
||||
)
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, target)
|
||||
com.droiddeck.launcher.stores.download.DownloadQueue.recordFailed(app, entry, errorMsg) {
|
||||
install(app, item, target)
|
||||
}
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, target)
|
||||
backends[item.store]?.install(app, item, target) ?: logLine("${item.store.label}: this build cannot install yet")
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ object AmazonBackend : StoreBackend {
|
||||
val quiet = cached.isNotEmpty() && !force
|
||||
StoresState.post {
|
||||
if (cached.isNotEmpty()) publish(app, cached)
|
||||
if (!quiet) StoresState.status[store] = "Fetching your library…"
|
||||
if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
|
||||
}
|
||||
val result = AmazonLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
|
||||
StoresState.post {
|
||||
@@ -94,7 +94,7 @@ object AmazonBackend : StoreBackend {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, "Checking sign-in…")
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(com.droiddeck.launcher.R.string.stores_sync_sign_in))
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: throw AmazonDownloadManager.InstallException("Not signed in to Amazon Games")
|
||||
StoreInstalls.begin(folder, Store.AMAZON, game.productId, game.title, item.tallImageUrl ?: item.imageUrl, item.imageUrl)
|
||||
var downloading = false
|
||||
@@ -111,7 +111,7 @@ object AmazonBackend : StoreBackend {
|
||||
override fun onSizes(downloadBytes: Long, diskBytes: Long) { handle.diskSize(diskBytes) }
|
||||
}) ?: return null
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL, "Registering with Steam…")
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering))
|
||||
AmazonLibrary.rememberSize(app, game.productId, result.bytes)
|
||||
AmazonPrefs.get(app).edit().putString("version_${game.productId}", result.versionId).apply()
|
||||
val spec = AmazonLaunchHelper.buildLaunchSpec(folder, game.title)
|
||||
|
||||
@@ -77,9 +77,10 @@ public final class AmazonDownloadManager {
|
||||
if (manifestBytes == null) throw new InstallException("The manifest could not be downloaded");
|
||||
AmazonManifest.ParsedManifest manifest = AmazonManifest.parse(manifestBytes);
|
||||
cb.onLog("amazon: " + manifest.allFiles.size() + " files, " + fmt(manifest.totalInstallSize));
|
||||
long usable = installDir.getUsableSpace();
|
||||
if (manifest.totalInstallSize > 0 && usable > 0 && manifest.totalInstallSize > usable)
|
||||
throw new InstallException("Not enough free space: need " + fmt(manifest.totalInstallSize) + ", only " + fmt(usable) + " free");
|
||||
long remainingBytes = remainingInstallBytes(manifest.allFiles, installDir);
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installDir);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(remainingBytes, usable))
|
||||
throw new InstallException("Not enough free space: need " + fmt(remainingBytes) + ", only " + fmt(usable) + " free");
|
||||
cb.onSizes(manifest.totalInstallSize, manifest.totalInstallSize);
|
||||
cb.onBytes(0, manifest.totalInstallSize, 0);
|
||||
if (cancel.get()) return null;
|
||||
@@ -184,7 +185,7 @@ public final class AmazonDownloadManager {
|
||||
AtomicLong lastSpeedMs, AtomicLong lastSpeedBytes, AtomicLong speedBps, Callback cb, AtomicBoolean cancel) {
|
||||
File destFile = new File(installDir, file.unixPath());
|
||||
File tmpFile = new File(installDir, file.unixPath() + ".tmp");
|
||||
if (destFile.exists() && destFile.length() == file.size) { totalDownloaded.addAndGet(file.size); return true; }
|
||||
if (fileComplete(file, destFile)) { totalDownloaded.addAndGet(file.size); return true; }
|
||||
String fileUrl = AmazonApiClient.appendPath(baseUrl, "files/" + file.hashHex());
|
||||
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
destFile.getParentFile().mkdirs();
|
||||
@@ -256,6 +257,21 @@ public final class AmazonDownloadManager {
|
||||
|
||||
public static boolean isInstalled(File installDir) { return new File(installDir, COMPLETE_MARKER).exists(); }
|
||||
|
||||
static long remainingInstallBytes(List<AmazonManifest.ManifestFile> files, File installDir) {
|
||||
long remaining = 0;
|
||||
for (AmazonManifest.ManifestFile file : files) {
|
||||
if (!fileComplete(file, new File(installDir, file.unixPath()))) remaining += file.size;
|
||||
}
|
||||
return remaining;
|
||||
}
|
||||
|
||||
private static boolean fileComplete(AmazonManifest.ManifestFile file, File output) {
|
||||
if (!output.isFile() || output.length() != file.size) return false;
|
||||
if (file.hashAlgorithm != 0 || file.hashBytes.length == 0) return true;
|
||||
try { return Arrays.equals(sha256(output), file.hashBytes); }
|
||||
catch (Exception e) { return false; }
|
||||
}
|
||||
|
||||
private static byte[] sha256(File file) throws Exception {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (FileInputStream fis = new FileInputStream(file)) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.stores.amazon
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
@@ -66,38 +67,38 @@ object AmazonLibrary {
|
||||
val p = AmazonPrefs.get(app)
|
||||
val cachedList = cached(app)
|
||||
if (!force && cachedList.isNotEmpty() && System.currentTimeMillis() - p.getLong(LAST_SYNC_KEY, 0L) < THROTTLE_MS) {
|
||||
backfillPosters(p, cachedList, onStatus)
|
||||
backfillPosters(app, p, cachedList, onStatus)
|
||||
return SyncResult.Throttled
|
||||
}
|
||||
onStatus("Checking sign-in…")
|
||||
onStatus(app.getString(R.string.stores_sync_sign_in))
|
||||
val creds = AmazonCredentialStore.load(app) ?: return SyncResult.NotLoggedIn
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed(StoresState.notSignedInLine(Store.AMAZON))
|
||||
onStatus("Fetching game list…")
|
||||
onStatus(app.getString(R.string.stores_sync_game_list))
|
||||
// Refused with the stored token (revoked, or an expiry read wrong): once more on a fresh one.
|
||||
val all = AmazonApiClient.getEntitlements(token, creds.deviceSerial)
|
||||
?: AmazonCredentialStore.refresh(app)?.let { AmazonApiClient.getEntitlements(it, creds.deviceSerial) }
|
||||
if (all == null) return if (cachedList.isEmpty()) SyncResult.Failed("Amazon Games did not answer for your library: refresh, or sign in again") else SyncResult.Ok(cachedList)
|
||||
if (all.isEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Amazon library") else SyncResult.Ok(cachedList)
|
||||
if (all == null) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_amazon_no_answer)) else SyncResult.Ok(cachedList)
|
||||
if (all.isEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_no_games, Store.AMAZON.label)) else SyncResult.Ok(cachedList)
|
||||
val games = all.filter { !(it.isDLC && it.parentProductId.isNotEmpty()) }.ifEmpty { all }
|
||||
.sortedWith { a, b -> a.title.compareTo(b.title, ignoreCase = true) }
|
||||
for (fresh in games) cachedList.firstOrNull { it.productId == fresh.productId }?.let { fresh.versionId = it.versionId }
|
||||
saveCache(p, games)
|
||||
p.edit().putLong(LAST_SYNC_KEY, System.currentTimeMillis()).apply()
|
||||
backfillPosters(p, games, onStatus)
|
||||
backfillPosters(app, p, games, onStatus)
|
||||
Log.i(TAG, "sync: entitlements=${all.size} games=${games.size}")
|
||||
return SyncResult.Ok(games)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "sync failed: ${e.message}")
|
||||
return SyncResult.Failed(e.message ?: "Sync failed")
|
||||
return SyncResult.Failed(e.message ?: context.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
syncing.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun backfillPosters(p: SharedPreferences, games: List<AmazonGame>, onStatus: (String) -> Unit) {
|
||||
private fun backfillPosters(app: Context, p: SharedPreferences, games: List<AmazonGame>, onStatus: (String) -> Unit) {
|
||||
val missing = games.filter { it.productId.isNotEmpty() && !p.contains("vcover_${it.productId}") }.take(POSTER_BUDGET)
|
||||
if (missing.isEmpty()) return
|
||||
onStatus("Fetching cover art…")
|
||||
onStatus(app.getString(R.string.stores_sync_cover_art))
|
||||
val pool = Executors.newFixedThreadPool(4)
|
||||
val futures = missing.map { g -> pool.submit(Callable { g.productId to StoreNet.sgdbPoster(g.title) }) }
|
||||
pool.shutdown()
|
||||
|
||||
@@ -128,7 +128,7 @@ object DownloadQueue {
|
||||
}
|
||||
}
|
||||
|
||||
private class Item(var entry: DownloadEntry, val factory: () -> DownloadJob, var job: DownloadJob? = null, val cancelled: AtomicBoolean = AtomicBoolean(false), var pauseRequested: Boolean = false) {
|
||||
private class Item(var entry: DownloadEntry, val factory: (() -> DownloadJob)? = null, val retry: (() -> Unit)? = null, var job: DownloadJob? = null, val cancelled: AtomicBoolean = AtomicBoolean(false), var pauseRequested: Boolean = false) {
|
||||
/** The shown speed's state: the last sample's clock and bytes, and the running average (bytes/s). */
|
||||
var speedAt = 0L
|
||||
var speedBytes = 0L
|
||||
@@ -185,6 +185,32 @@ object DownloadQueue {
|
||||
advance(app)
|
||||
}
|
||||
|
||||
/** Immediately records a failed download (e.g. from pre-flight storage check). */
|
||||
fun recordFailed(context: Context, entry: DownloadEntry, error: String, retry: (() -> Unit)? = null) {
|
||||
val app = context.applicationContext
|
||||
val now = System.currentTimeMillis()
|
||||
synchronized(lock) {
|
||||
if (items[entry.key]?.entry?.isActive == true) return
|
||||
items.remove(entry.key)
|
||||
heldPaused.remove(entry.key)
|
||||
items[entry.key] = Item(
|
||||
entry.copy(
|
||||
state = DownloadState.FAILED,
|
||||
error = error,
|
||||
speedBps = 0,
|
||||
etaSeconds = -1,
|
||||
startedAt = now,
|
||||
finishedAt = now
|
||||
),
|
||||
retry = retry
|
||||
)
|
||||
renumber()
|
||||
publishLocked()
|
||||
}
|
||||
StoresState.logLine("${entry.store.label}: \"${entry.name}\" failed: $error")
|
||||
StoreDownloadService.ended(app, entry.copy(state = DownloadState.FAILED, error = error), installed = false, gamesKey = null)
|
||||
}
|
||||
|
||||
fun pause(key: String) {
|
||||
val item = synchronized(lock) { items[key] } ?: return
|
||||
synchronized(lock) {
|
||||
@@ -199,14 +225,21 @@ object DownloadQueue {
|
||||
|
||||
fun resume(context: Context, key: String) {
|
||||
val app = context.applicationContext
|
||||
val retry: (() -> Unit)?
|
||||
synchronized(lock) {
|
||||
val item = items[key] ?: return
|
||||
if (item.entry.state != DownloadState.PAUSED && item.entry.state != DownloadState.FAILED) return
|
||||
retry = item.retry
|
||||
if (retry == null && item.factory == null) return
|
||||
items.remove(key)
|
||||
items[key] = Item(item.entry.copy(state = DownloadState.QUEUED, speedBps = 0, etaSeconds = -1, error = null, startedAt = System.currentTimeMillis()), item.factory)
|
||||
if (retry == null) {
|
||||
items[key] = Item(item.entry.copy(state = DownloadState.QUEUED, speedBps = 0, etaSeconds = -1, error = null, startedAt = System.currentTimeMillis()), item.factory)
|
||||
}
|
||||
renumber()
|
||||
publishLocked()
|
||||
}
|
||||
// A preflight retry rechecks storage and enqueues the real backend, never a running placeholder.
|
||||
if (retry != null) { retry(); return }
|
||||
StoresState.logLine("resumed \"${entry(key)?.name}\"")
|
||||
advance(app)
|
||||
}
|
||||
@@ -231,7 +264,7 @@ object DownloadQueue {
|
||||
item.job?.cancel(deleteFiles = true)
|
||||
} else {
|
||||
// Never started: nothing is on disk, but the job knows where it would have gone.
|
||||
Thread({ runCatching { item.factory().cancel(deleteFiles = true) } }, "store-dl-cancel").start()
|
||||
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
|
||||
}
|
||||
StoresState.logLine("cancelled \"${item.entry.name}\"")
|
||||
StoreDownloadService.finish(app, key)
|
||||
@@ -248,7 +281,7 @@ object DownloadQueue {
|
||||
val item = synchronized(lock) { items[key] } ?: return
|
||||
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
|
||||
if (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) {
|
||||
Thread({ runCatching { item.factory().cancel(deleteFiles = true) } }, "store-dl-clear").start()
|
||||
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-clear").start()
|
||||
}
|
||||
synchronized(lock) { items.remove(key); publishLocked() }
|
||||
StoreDownloadService.finish(context.applicationContext, key)
|
||||
@@ -343,7 +376,7 @@ object DownloadQueue {
|
||||
var result: String? = null
|
||||
var error: String? = null
|
||||
try {
|
||||
val job = item.factory()
|
||||
val job = checkNotNull(item.factory).invoke()
|
||||
synchronized(lock) { item.job = job }
|
||||
StoresState.logLine("${item.entry.store.label}: fetching manifest for \"${item.entry.name}\"")
|
||||
result = job.run(handle)
|
||||
|
||||
@@ -263,12 +263,16 @@ class StoreDownloadService : Service() {
|
||||
val app = context.applicationContext
|
||||
channels(app)
|
||||
val code = entry.key.hashCode()
|
||||
val n = Notification.Builder(app, DONE_CHANNEL)
|
||||
val builder = Notification.Builder(app, DONE_CHANNEL)
|
||||
.setSmallIcon(if (installed) android.R.drawable.stat_sys_download_done else android.R.drawable.stat_notify_error)
|
||||
.setContentTitle(app.getString(if (installed) R.string.stores_notification_installed else R.string.stores_notification_failed, entry.name))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(if (installed && gamesKey != null) openPage(app, gamesKey, code + 10) else openDownloads(app, code + 11))
|
||||
.build()
|
||||
if (!installed && !entry.error.isNullOrBlank()) {
|
||||
builder.setContentText(entry.error)
|
||||
builder.style = Notification.BigTextStyle().bigText(entry.error)
|
||||
}
|
||||
val n = builder.build()
|
||||
runCatching { app.getSystemService(NotificationManager::class.java)?.notify(ID + 1 + (code and 0xFFFF), n) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
val quiet = cached.isNotEmpty() && !force
|
||||
StoresState.post {
|
||||
if (cached.isNotEmpty()) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
|
||||
if (!quiet) StoresState.status[store] = "Fetching your library…"
|
||||
if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
|
||||
}
|
||||
val result = EpicLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
|
||||
StoresState.post {
|
||||
@@ -122,7 +122,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
private fun hasChunks(dir: File): Boolean = dir.isDirectory && (dir.list()?.isNotEmpty() == true)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, "Checking sign-in…")
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(com.droiddeck.launcher.R.string.stores_sync_sign_in))
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: throw EpicDownloadManager.InstallException("Not signed in to Epic Games")
|
||||
StoreInstalls.begin(folder, Store.EPIC, item.id, item.title, item.tallImageUrl ?: item.imageUrl, item.imageUrl)
|
||||
if (scratch == null && hasChunks(File(folder, ".chunks"))) handle.log("epic: resuming \"${item.title}\" with the chunks already beside it")
|
||||
@@ -146,12 +146,14 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
EpicLibrary.rememberSize(app, item.id, diskBytes)
|
||||
}
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
// Assembly overlaps chunk fetching; only the final install event advances the UI.
|
||||
if (stage == "stream") return
|
||||
handle.stage(when (stage) { "check" -> DownloadStage.MANIFEST; "verify" -> DownloadStage.VERIFY; else -> DownloadStage.INSTALL })
|
||||
handle.stageProgress(done, total, items, itemsTotal, bytes = stage == "install")
|
||||
}
|
||||
}) ?: return null
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL, "Registering with Steam…")
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering))
|
||||
EpicLibrary.rememberSize(app, item.id, result.bytes)
|
||||
val deploymentId = runCatching { JSONObject(manifestJson).optString("deploymentId", "") }.getOrDefault("")
|
||||
val exe = StoreExe.pick(folder, result.launchExe, item.title)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.stores.epic
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import org.json.JSONArray
|
||||
@@ -67,17 +68,17 @@ object EpicLibrary {
|
||||
val cachedList = cached(app)
|
||||
val lastSync = p.getLong(LAST_SYNC_KEY, 0L)
|
||||
if (!force && cachedList.isNotEmpty() && System.currentTimeMillis() - lastSync < THROTTLE_MS) return SyncResult.Throttled
|
||||
onStatus("Checking sign-in…")
|
||||
onStatus(app.getString(R.string.stores_sync_sign_in))
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: return SyncResult.NotLoggedIn
|
||||
onStatus("Fetching game list…")
|
||||
onStatus(app.getString(R.string.stores_sync_game_list))
|
||||
val raw = EpicApiClient.getLibraryItems(token)
|
||||
if (raw.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Epic library") else SyncResult.Ok(cachedList)
|
||||
if (raw.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_no_games, Store.EPIC.label)) else SyncResult.Ok(cachedList)
|
||||
val total = raw.size
|
||||
var done = 0
|
||||
for (game in raw) {
|
||||
EpicApiClient.enrichFromCatalog(token, game)
|
||||
done++
|
||||
if (done % 5 == 0) onStatus("Loading game details… ($done/$total)")
|
||||
if (done % 5 == 0) onStatus(app.getString(R.string.stores_sync_details, done, total))
|
||||
}
|
||||
val main = raw.filter { !it.isDLC }
|
||||
val display = (if (main.isEmpty()) raw else main).distinctBy { it.appName }.sortedWith { a, b -> a.title.compareTo(b.title, ignoreCase = true) }
|
||||
@@ -92,7 +93,7 @@ object EpicLibrary {
|
||||
return SyncResult.Ok(display)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "sync failed: ${e.message}")
|
||||
return SyncResult.Failed(e.message ?: "Sync failed")
|
||||
return SyncResult.Failed(e.message ?: context.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
syncing.set(false)
|
||||
}
|
||||
|
||||
@@ -9,17 +9,20 @@ import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* The native half of an Epic install in `libdroiddeckstores.so`: [run] fills the chunk cache with
|
||||
* verified, decompressed chunks for the files the manager says are pending, [assemble] writes those
|
||||
* files from the cache. Everything around them (manifest, install tags, delta pass, post-install)
|
||||
* stays in the manager.
|
||||
* The native Epic engines in `libdroiddeckstores.so`. [stream] is the install the manager uses
|
||||
* whenever the library loads: chunks fetched in parallel by the adaptive fetch core and written
|
||||
* straight into each file's staging file as they arrive, shared chunks kept in a cache of at most
|
||||
* the given budget, every file verified and swapped in with the same rules as the bounded Java
|
||||
* writer (see `stream.rs`). [run] and [assemble] are the older batch pair: [run] fills the chunk
|
||||
* cache with verified, decompressed chunks for the pending files, [assemble] writes the files from
|
||||
* it. They stay for callers that explicitly want a whole-game cache.
|
||||
*
|
||||
* The cache is `<installDir>/.chunks` when `chunkCacheDir` is `""`, else the scratch folder given -
|
||||
* the app's own cache when the game installs to a card, where the assembler drops each chunk right
|
||||
* after its last use and the folder at the end. Both calls take the same value for one install.
|
||||
* the app's own cache when the game installs to a card.
|
||||
*
|
||||
* Both block like the Java loops they replace and poll [AtomicBoolean] `cancel` every 250 ms: on
|
||||
* cancel they flip the native flag, wait up to 5 s for the run to wind down, then return.
|
||||
* All block while polling [AtomicBoolean] `cancel` every 250 ms. [run] and [assemble] flip the
|
||||
* native flag on cancel and wait up to 5 s; [stream] waits for the run to finish, because its
|
||||
* cleanup (removing unfinished staging files) must be done before the manager returns.
|
||||
*/
|
||||
object EpicNative {
|
||||
private const val TAG = "EpicNative"
|
||||
@@ -36,6 +39,18 @@ object EpicNative {
|
||||
fun onComplete(success: Boolean, error: String, bytes: Long)
|
||||
}
|
||||
|
||||
/** Callbacks from a [stream] run; every method is called on a native thread. */
|
||||
interface StreamListener {
|
||||
/** File bytes written so far (staging included), and the files verified and swapped in so far. */
|
||||
fun onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long)
|
||||
/** Engine log line (already in logcat under `EpicNative`). */
|
||||
fun onLog(line: String)
|
||||
/** Once, before the first file replaces its destination; false (or a throw) fails the run with nothing replaced. */
|
||||
fun onBeforeReplace(): Boolean
|
||||
/** Terminal; `bytes` = file bytes written. */
|
||||
fun onComplete(success: Boolean, error: String, bytes: Long)
|
||||
}
|
||||
|
||||
/** Outcome of a run. `started == false`: nothing happened on disk, the caller runs its own loop. */
|
||||
class Result(
|
||||
@JvmField val started: Boolean, @JvmField val success: Boolean, @JvmField val cancelled: Boolean,
|
||||
@@ -58,6 +73,59 @@ object EpicNative {
|
||||
fun assemble(manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, cancel: AtomicBoolean?, listener: Listener): Result =
|
||||
drive("nativeAssemble", cancel, listener) { inner -> nativeAssemble(manifest, installDir, chunkCacheDir, fileIdx, inner) }
|
||||
|
||||
/**
|
||||
* The adaptive install of the files [pendingFileIdx] (indices into the manifest's file list),
|
||||
* with at most [cacheBudget] bytes of shared chunks cached. `started == false` means nothing
|
||||
* was fetched or written and the caller runs the bounded Java writer.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun stream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long,
|
||||
cacheBudget: Long, caBundlePath: String, maxWorkers: Int, processWorkers: Int, cancel: AtomicBoolean?, listener: StreamListener,
|
||||
): Result {
|
||||
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
|
||||
val latch = CountDownLatch(1)
|
||||
val completion = AtomicReference<Completion?>(null)
|
||||
val doneRef = AtomicReference(0)
|
||||
val totalRef = AtomicReference(pendingFileIdx.size)
|
||||
val inner = object : StreamListener {
|
||||
override fun onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long) {
|
||||
doneRef.set(filesDone); totalRef.set(filesTotal)
|
||||
listener.onStreamProgress(bytesWritten, bytesTotal, filesDone, filesTotal, filesBytes)
|
||||
}
|
||||
override fun onLog(line: String) = listener.onLog(line)
|
||||
override fun onBeforeReplace(): Boolean = runCatching { listener.onBeforeReplace() }.getOrDefault(false)
|
||||
override fun onComplete(success: Boolean, error: String, bytes: Long) {
|
||||
completion.set(Completion(success, error, bytes))
|
||||
latch.countDown()
|
||||
runCatching { listener.onComplete(success, error, bytes) }
|
||||
}
|
||||
}
|
||||
val handle: Long = try {
|
||||
nativeStream(manifest, installDir, chunkCacheDir, cdnPrefixes, pendingFileIdx, expectedBytes, cacheBudget, caBundlePath, maxWorkers, processWorkers, inner)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
|
||||
return Result(false, false, false, "nativeStream: ${t.javaClass.simpleName}", 0L, 0, 0)
|
||||
}
|
||||
if (handle == 0L) return Result(false, false, false, completion.get()?.error ?: "not started", 0L, 0, totalRef.get())
|
||||
var cancelSent = false
|
||||
try {
|
||||
while (!latch.await(250, TimeUnit.MILLISECONDS)) {
|
||||
if (!cancelSent && cancel != null && cancel.get()) {
|
||||
nativeCancel(handle)
|
||||
cancelSent = true
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
nativeRelease(handle)
|
||||
}
|
||||
val c = completion.get()
|
||||
val cancelled = cancelSent || (c != null && !c.success && c.error == "cancelled")
|
||||
val success = !cancelled && c != null && c.success
|
||||
val error = when { cancelled -> "cancelled"; c == null -> "no completion"; else -> c.error }
|
||||
return Result(true, success, cancelled, error, c?.bytes ?: 0L, doneRef.get(), totalRef.get())
|
||||
}
|
||||
|
||||
private fun drive(what: String, cancel: AtomicBoolean?, listener: Listener, start: (Listener) -> Long): Result {
|
||||
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
|
||||
val latch = CountDownLatch(1)
|
||||
@@ -109,6 +177,12 @@ object EpicNative {
|
||||
@JvmStatic
|
||||
private external fun nativeAssemble(manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, listener: Listener): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeStream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long,
|
||||
cacheBudget: Long, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: StreamListener,
|
||||
): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeCancel(handle: Long)
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ object GogBackend : StoreBackend {
|
||||
val quiet = cached.isNotEmpty() && !force
|
||||
StoresState.post {
|
||||
if (cached.isNotEmpty()) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
|
||||
if (!quiet) StoresState.status[store] = "Fetching your library…"
|
||||
if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
|
||||
}
|
||||
val result = GogLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
|
||||
StoresState.post {
|
||||
@@ -106,7 +106,7 @@ object GogBackend : StoreBackend {
|
||||
}
|
||||
}, cancelled) ?: return null
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL, "Registering with Steam…")
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering))
|
||||
val sidecar = StoreGameSidecar(
|
||||
Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" },
|
||||
installVersion = result.buildId, installedAt = System.currentTimeMillis(),
|
||||
|
||||
@@ -189,11 +189,12 @@ public final class GogDownloadManager {
|
||||
installPath.mkdirs();
|
||||
long plannedBytes = 0;
|
||||
for (DepotFile df : files) plannedBytes += df.totalSize;
|
||||
if (plannedBytes > 0) {
|
||||
long usable = installPath.getUsableSpace();
|
||||
if (usable > 0 && plannedBytes > usable) {
|
||||
long remainingBytes = remainingInstallBytes(files, installPath);
|
||||
if (remainingBytes > 0) {
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(remainingBytes, usable)) {
|
||||
out.hardStop = true;
|
||||
out.error = "Not enough free space: need " + formatBytes(plannedBytes) + ", only " + formatBytes(usable) + " free";
|
||||
out.error = "Not enough free space: need " + formatBytes(remainingBytes) + ", only " + formatBytes(usable) + " free";
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -1018,7 +1019,16 @@ public final class GogDownloadManager {
|
||||
for (File f : files) if (f.isDirectory()) collectExeRecursive(f, out);
|
||||
}
|
||||
|
||||
private static final class DepotFile {
|
||||
static long remainingInstallBytes(List<DepotFile> files, File installPath) {
|
||||
long remaining = 0;
|
||||
for (DepotFile file : files) {
|
||||
File output = new File(installPath, file.relativePath);
|
||||
if (!fileVerified(output, file.totalSize, file.md5)) remaining += file.totalSize;
|
||||
}
|
||||
return remaining;
|
||||
}
|
||||
|
||||
static final class DepotFile {
|
||||
final String relativePath;
|
||||
final List<ChunkRef> chunks = new ArrayList<>();
|
||||
String md5;
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.stores.gog
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
@@ -60,9 +61,9 @@ object GogLibrary {
|
||||
val app = context.applicationContext
|
||||
val p = GogPrefs.get(app)
|
||||
val token = GogAuth.validToken(app) ?: return SyncResult.NotLoggedIn
|
||||
onStatus("Fetching game list…")
|
||||
onStatus(app.getString(R.string.stores_sync_game_list))
|
||||
val gamesJson = StoreNet.get("https://embed.gog.com/user/data/games", bearer = token, userAgent = GogAuth.GALAXY_UA)
|
||||
?: return SyncResult.Failed("Couldn't reach GOG")
|
||||
?: return SyncResult.Failed(app.getString(R.string.stores_sync_gog_unreachable))
|
||||
val ids = ArrayList<String>()
|
||||
val parsed = runCatching {
|
||||
val owned = JSONObject(gamesJson).optJSONArray("owned")
|
||||
@@ -72,7 +73,7 @@ object GogLibrary {
|
||||
if (id != "1801418160" && id != "0") ids.add(id)
|
||||
}
|
||||
}.isSuccess
|
||||
if (!parsed) return SyncResult.Failed("Error parsing library")
|
||||
if (!parsed) return SyncResult.Failed(app.getString(R.string.stores_sync_gog_unreadable))
|
||||
|
||||
val ownedSet = ids.toHashSet()
|
||||
val cachedList = cached(app)
|
||||
@@ -92,7 +93,7 @@ object GogLibrary {
|
||||
saveCache(p, list)
|
||||
return SyncResult.Ok(list.sortedBy { it.title.lowercase() }, 0)
|
||||
}
|
||||
onStatus("Syncing ${idsToFetch.size} game${if (idsToFetch.size == 1) "" else "s"}…")
|
||||
onStatus(app.resources.getQuantityString(R.plurals.stores_sync_games, idsToFetch.size, idsToFetch.size))
|
||||
val pool = Executors.newFixedThreadPool(5)
|
||||
val futures = idsToFetch.map { id -> pool.submit(Callable<GogGame?> { fetchGame(p, id, token, skipped) }) }
|
||||
pool.shutdown()
|
||||
@@ -100,7 +101,7 @@ object GogLibrary {
|
||||
for ((idx, f) in futures.withIndex()) {
|
||||
val g = runCatching { f.get() }.getOrNull()
|
||||
if (g != null) { merged[g.gameId] = g; fetched++ }
|
||||
if ((idx + 1) % 5 == 0) onStatus("Syncing… ${idx + 1}/${futures.size}")
|
||||
if ((idx + 1) % 5 == 0) onStatus(app.getString(R.string.stores_sync_progress, idx + 1, futures.size))
|
||||
}
|
||||
val finalList = merged.values.toList()
|
||||
saveCache(p, finalList)
|
||||
@@ -111,7 +112,7 @@ object GogLibrary {
|
||||
return SyncResult.Ok(finalList.sortedBy { it.title.lowercase() }, fetched)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "sync failed: ${e.message}")
|
||||
return SyncResult.Failed(e.message ?: "Sync failed")
|
||||
return SyncResult.Failed(e.message ?: context.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
syncing.set(false)
|
||||
}
|
||||
|
||||
@@ -205,6 +205,8 @@ class FrontEndActions(
|
||||
val onAgentCommands: () -> Unit = {},
|
||||
val onShareLogs: () -> Unit = {},
|
||||
val onClearLogs: () -> Unit = {},
|
||||
/** Setup's Reset all settings: asks first, then puts every setting back to its default. */
|
||||
val onResetSettings: () -> Unit = {},
|
||||
val onOffline: () -> Unit,
|
||||
val onPageBack: () -> Unit = {},
|
||||
val onTheme: (String) -> Unit = {},
|
||||
|
||||
@@ -405,6 +405,8 @@ internal fun SetupPanel(
|
||||
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
|
||||
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
|
||||
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
|
||||
ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint),
|
||||
stringResource(R.string.setup_reset_settings_button), a.onResetSettings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,29 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
@@ -53,3 +65,32 @@ fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () ->
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Setup's Reset all settings, with the choice to clear game profiles too (off unless ticked). */
|
||||
@Composable
|
||||
fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: () -> Unit) {
|
||||
var gameProfiles by remember { mutableStateOf(false) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.setup_reset_settings_title)) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(stringResource(R.string.setup_reset_settings_body))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(checked = gameProfiles, onCheckedChange = null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.setup_reset_settings_profiles), style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }) {
|
||||
Text(stringResource(R.string.setup_reset_settings_button), color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -70,6 +70,10 @@ class ModeSettings(
|
||||
val touchMode: String,
|
||||
val suspendPolicy: String,
|
||||
val steamDownloadsInBackground: Boolean = false,
|
||||
/** Steam only; null hides it. */
|
||||
val zramCompression: Boolean? = null,
|
||||
/** Null until checked off the main thread. */
|
||||
val zramSupported: Boolean? = null,
|
||||
val pipSupported: Boolean = false,
|
||||
val pipAutoEnter: Boolean = false,
|
||||
/** Steam only. */
|
||||
@@ -127,6 +131,7 @@ class ModeSettingsActions(
|
||||
val onTouch: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
|
||||
val onZramCompression: (Boolean) -> Unit = {},
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
val onOsc: (String) -> Unit,
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
@@ -303,6 +308,12 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
stringResource(R.string.mode_background_downloads_hint),
|
||||
s.steamDownloadsInBackground, onChange = a.onSteamDownloadsInBackground,
|
||||
)
|
||||
if (s.zramCompression != null) ToggleRow(
|
||||
host, "zram", stringResource(R.string.mode_zram),
|
||||
stringResource(if (s.zramSupported == false) R.string.mode_zram_unsupported else R.string.mode_zram_hint),
|
||||
s.zramCompression && s.zramSupported != false, enabled = s.zramSupported == true,
|
||||
onChange = a.onZramCompression,
|
||||
)
|
||||
}
|
||||
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
|
||||
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
|
||||
|
||||
@@ -52,7 +52,9 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
val id = key.substringAfter(':')
|
||||
val item = (StoresState.library[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
|
||||
val installed = StoresState.installedGame(store, id)
|
||||
val download = StoresState.download("${store.id}:$id")?.takeIf { it.isActive }
|
||||
val rawDownload = StoresState.download("${store.id}:$id")
|
||||
val download = rawDownload?.takeIf { it.isActive }
|
||||
val failedDownload = rawDownload?.takeIf { it.state == DownloadState.FAILED }
|
||||
// Removal asks twice: one stray press of A should not cost a download.
|
||||
val title = item?.title ?: installed?.sidecar?.title ?: id
|
||||
Rise(0) {
|
||||
@@ -79,12 +81,24 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
val state = when {
|
||||
installed != null -> stringResource(R.string.stores_eyebrow_installed) + " · " + com.droiddeck.launcher.stores.StoreInstallRoot.labelFor(ctx, installed.folder)
|
||||
download != null && download.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + download.location
|
||||
failedDownload != null && failedDownload.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + failedDownload.location
|
||||
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
|
||||
else -> stringResource(R.string.stores_eyebrow_store)
|
||||
}
|
||||
val size = (item?.sizeBytes ?: 0L).takeIf { it > 0 }?.let { " · " + formatBytes(it) } ?: ""
|
||||
Text((state + size).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = pal.signal)
|
||||
Text(title, fontSize = if (narrow) 24.sp else 30.sp, lineHeight = if (narrow) 27.sp else 33.sp, fontWeight = FontWeight.Black, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
if (!failedDownload?.error.isNullOrBlank()) {
|
||||
Text(
|
||||
failedDownload!!.error!!,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = colors.error,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Actions {
|
||||
when {
|
||||
installed != null -> {
|
||||
@@ -106,6 +120,16 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) { com.droiddeck.launcher.stores.download.DownloadQueue.resume(ctx, download.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { com.droiddeck.launcher.stores.download.DownloadQueue.cancel(ctx, download.key) }
|
||||
}
|
||||
failedDownload != null -> {
|
||||
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
|
||||
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) {
|
||||
if (item != null) StoresState.requestInstall(ctx, item)
|
||||
else com.droiddeck.launcher.stores.download.DownloadQueue.retry(ctx, failedDownload.key)
|
||||
}
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) {
|
||||
com.droiddeck.launcher.stores.download.DownloadQueue.clear(ctx, failedDownload.key)
|
||||
}
|
||||
}
|
||||
item?.owned == true && StoresState.isUnfinished(item) -> {
|
||||
InstallButton(stringResource(R.string.stores_resume_install)) { StoresState.requestInstall(ctx, item) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
|
||||
@@ -339,6 +339,7 @@ private fun Modifier.timeRim(left: () -> Float, color: Color): Modifier = drawWi
|
||||
@Composable
|
||||
private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val narrow = LocalNarrowPane.current
|
||||
val ink = Color.White
|
||||
@@ -362,8 +363,11 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
val meta = when (d.state) {
|
||||
DownloadState.INSTALLED -> stringResource(R.string.stores_installed_chip)
|
||||
DownloadState.CANCELLED -> stringResource(R.string.stores_dl_cancelled)
|
||||
// The reason is in the engine log; the row only says what is kept for Resume.
|
||||
DownloadState.FAILED -> if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone)) else stringResource(R.string.stores_dl_failed)
|
||||
DownloadState.FAILED -> {
|
||||
if (!d.error.isNullOrBlank()) stringResource(R.string.stores_dl_failed_reason, d.error)
|
||||
else if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone))
|
||||
else stringResource(R.string.stores_dl_failed)
|
||||
}
|
||||
DownloadState.PAUSED -> stringResource(R.string.stores_dl_paused)
|
||||
DownloadState.QUEUED -> if (d.queuePosition > 0) stringResource(R.string.stores_dl_queued_at, d.queuePosition) else stringResource(R.string.stores_dl_queued)
|
||||
DownloadState.RUNNING -> {
|
||||
@@ -375,7 +379,8 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(meta, fontSize = 12.sp, color = dim, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
val metaColor = if (d.state == DownloadState.FAILED) colors.error else dim
|
||||
Text(meta, fontSize = 12.sp, color = metaColor, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
if (d.state == DownloadState.RUNNING && (d.stage == DownloadStage.DOWNLOAD || d.stage == DownloadStage.INSTALL) && d.speedBps > 0) {
|
||||
Text(formatSpeed(d.speedBps), fontSize = 12.sp, color = dim, maxLines = 1)
|
||||
if (d.etaSeconds >= 0) Text(eta(d.etaSeconds), fontSize = 12.sp, color = dim, maxLines = 1)
|
||||
@@ -393,7 +398,10 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
}
|
||||
DownloadState.FAILED -> RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
|
||||
DownloadState.FAILED -> {
|
||||
RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
|
||||
CancelAction { DownloadQueue.clear(ctx, d.key) }
|
||||
}
|
||||
// Just installed (this row is on its way under the line): Play blooms where the bar gathered.
|
||||
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
|
||||
@@ -460,6 +468,7 @@ private fun StageBar(d: DownloadEntry) {
|
||||
val x = i * (segW + gap)
|
||||
drawRoundRect(colors.surfaceVariant, Offset(x, cy - h / 2f), Size(segW, h), CornerRadius(h / 2f))
|
||||
val base = when {
|
||||
d.state == DownloadState.FAILED -> colors.error
|
||||
done[i] -> pal.good
|
||||
actives[i] && paused -> pausedColor.copy(alpha = breath)
|
||||
actives[i] && stages[i] == DownloadStage.VERIFY -> verifyColor
|
||||
|
||||
@@ -72,10 +72,21 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
|
||||
Rise(1) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
targets.forEachIndexed { i, t ->
|
||||
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
|
||||
val freeBytes = t.freeBytes
|
||||
val isLow = com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, freeBytes)
|
||||
val freeText = if (freeBytes < 0L) {
|
||||
stringResource(R.string.stores_target_free_unknown)
|
||||
} else if (isLow) {
|
||||
stringResource(R.string.stores_storage_low, formatBytes(freeBytes), formatBytes(needed))
|
||||
} else {
|
||||
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
|
||||
}
|
||||
TargetRow(
|
||||
label = if (t.removable) t.label else stringResource(R.string.stores_target_internal),
|
||||
free = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
|
||||
free = freeText,
|
||||
removable = t.removable, focus = focus[i],
|
||||
warning = isLow,
|
||||
) {
|
||||
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
|
||||
StoresState.install(ctx, item, t.root)
|
||||
@@ -88,7 +99,7 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, onPick: () -> Unit) {
|
||||
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, warning: Boolean = false, onPick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
@@ -104,6 +115,6 @@ private fun TargetRow(label: String, free: String, removable: Boolean, focus: Fo
|
||||
) {
|
||||
Icon(if (removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(22.dp))
|
||||
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(free, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
Text(free, fontSize = 12.sp, color = if (warning) colors.error else colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
@@ -511,10 +511,20 @@ private fun InstallWhere(item: CatalogItem) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
targets.forEachIndexed { i, t ->
|
||||
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
|
||||
val freeBytes = t.freeBytes
|
||||
val isLow = com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, freeBytes)
|
||||
val trailingText = if (freeBytes < 0L) {
|
||||
stringResource(R.string.stores_target_free_unknown)
|
||||
} else if (isLow) {
|
||||
stringResource(R.string.stores_storage_low, formatBytes(freeBytes), formatBytes(needed))
|
||||
} else {
|
||||
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
|
||||
}
|
||||
StepChoice(
|
||||
label = if (t.removable) t.label else internalLabel,
|
||||
icon = if (t.removable) androidx.compose.material.icons.Icons.Outlined.SdCard else androidx.compose.material.icons.Icons.Outlined.Smartphone,
|
||||
trailing = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
|
||||
trailing = trailingText,
|
||||
enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(1 + i).then(if (i == defaultIndex) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string-array name="loading_hints">
|
||||
<item>La primera vez se descarga Steam. Puede tardar unos minutos.</item>
|
||||
<item>De forma predeterminada, al salir de la app Steam se pausa y continúa donde lo dejaste cuando vuelves.</item>
|
||||
<item>Tu control aparece como un control de Xbox 360. Si no, usa los controles en pantalla.</item>
|
||||
</string-array>
|
||||
<string-array name="loading_hints_desktop">
|
||||
<item>La primera vez se prepara el escritorio. Puede tardar unos minutos.</item>
|
||||
<item>De forma predeterminada, al salir de la app la sesión se pausa y continúa donde la dejaste cuando vuelves.</item>
|
||||
<item>El tacto funciona como un touchpad: arrastra para mover el puntero y toca para hacer clic.</item>
|
||||
<item>Tu control aparece como un control de Xbox 360. Si no, usa los controles en pantalla.</item>
|
||||
</string-array>
|
||||
<string name="second_library_import_hint">Agrega una biblioteca de Steam y busca juegos de Windows en ella. Los juegos que tienes usan sus entradas de Steam; el resto se convierten en accesos directos ajenos a Steam.</string>
|
||||
<string name="game_env_add">Agregar variable</string>
|
||||
<string name="game_env_xalia">Pon 0 para desactivar el asistente de navegación con control de Proton en este juego.</string>
|
||||
<string name="user_apps_add">Agregar</string>
|
||||
<string name="user_apps_added">%1$s agregada</string>
|
||||
<string name="user_apps_remove_confirm">Presiona de nuevo para quitar</string>
|
||||
<string name="user_apps_failed">No se pudo agregar la app</string>
|
||||
<string name="add_app_title">Agregar una app</string>
|
||||
<string name="add_app_confirm">Agregar</string>
|
||||
<string name="common_add_ellipsis">Agregar…</string>
|
||||
<string name="mode_osc_note">Auto muestra los controles en pantalla cuando no hay ningún control conectado.</string>
|
||||
<string name="mode_controller">Control</string>
|
||||
<string name="mode_controller_hint">Cómo ve Steam tu control. Se aplica en la próxima sesión.</string>
|
||||
<string name="mode_controller_deck">Control de Steam Deck</string>
|
||||
<string name="mode_controller_x360">Control de Xbox 360</string>
|
||||
<string name="games_add">Agregar juego</string>
|
||||
<string name="games_add_title">Agregar un juego:</string>
|
||||
<string name="mode_storage_note">Los juegos que cargan recursos desde la SD o el almacenamiento compartido pueden tener microcortes.</string>
|
||||
<string name="comp_no_proton">Aún no hay ningún Proton instalado. Inicia Steam una vez para descargar su Proton ARM64, o agrega GE-Proton o CachyOS desde Configuración.</string>
|
||||
<string name="perf_gpuclock_hint">Solo Adreno. Menos microcortes, más consumo de batería y calor.</string>
|
||||
<string name="perf_xalia_hint">Desactiva el asistente de navegación con control de Proton, que consume CPU en cada juego.</string>
|
||||
<string name="perf_fastpath_hint">Búsquedas de archivos más rápidas y menos microcortes. Desactívalo si un programa no encuentra sus archivos.</string>
|
||||
<string name="drawer_page_controller">Control</string>
|
||||
<string name="setup_manage">Administrar</string>
|
||||
<string name="setup_tab_controller">Control</string>
|
||||
<string name="setup_sign_in">Presiona Jugar en Steam e inicia sesión</string>
|
||||
<string name="setup_controller">Control</string>
|
||||
<string name="setup_controller_unavailable">Los ajustes del control no están disponibles.</string>
|
||||
<string name="setup_tool_files_hint">Explorar y administrar archivos</string>
|
||||
<string name="store_setup_text">Agrega Flatpak y lo conecta a Flathub (unos 20 MB). La primera app también descarga su runtime.</string>
|
||||
<string name="store_press_again">Presiona de nuevo para quitar</string>
|
||||
<string name="gate_no_toggle">Esta versión de Android no tiene un interruptor para ello, así que DroidDeck lo cambia mediante la Depuración inalámbrica. Tarda un minuto y no necesitas una computadora.</string>
|
||||
<string name="gate_code_needed">Ventana encontrada. Ingresa su código en la notificación.</string>
|
||||
<string name="gate_other_toggle">Depuración inalámbrica, dirección manual, ADB desde una computadora</string>
|
||||
<string name="gate_other_no_toggle">Dirección manual, ADB desde una computadora, Opciones de desarrollador</string>
|
||||
<string name="gate_some_roms">Algunas ROM agregan el interruptor de todos modos. Busca “procesos secundarios” en Opciones de desarrollador.</string>
|
||||
<string name="gate_manual_hint">Si la notificación no funciona, ingresa manualmente la dirección y el código de la ventana.</string>
|
||||
<string name="gate_enter_manually">Ingresar dirección manualmente</string>
|
||||
<string name="gate_from_computer">Desde una computadora con ADB:</string>
|
||||
<string name="wadb_enter_port">Vinculado. Ingresa el puerto de Ajustes.</string>
|
||||
<string name="wadb_computer_last">3 · ADB desde una computadora (último recurso)</string>
|
||||
<string name="wadb_computer_group">3 · ADB desde una computadora (último recurso)</string>
|
||||
<string name="ctrl_select_steam">Presiona Select para abrir el menú de Steam</string>
|
||||
<string name="ctrl_reset_all">Restablecer control</string>
|
||||
<string name="ctrl_reset_all_hint">Restaura todos los ajustes del control y la disposición</string>
|
||||
<string name="content_add_roms">Agrega juegos de %1$s a ROMs/%2$s.</string>
|
||||
<string name="desktop_remove_text">Elimina el escritorio y sus apps incluidas. Se conservan los juegos, las apps agregadas, los ajustes y las bibliotecas compartidas.</string>
|
||||
<string name="games_manage_saves">Administrar partidas guardadas</string>
|
||||
<string name="games_added">Juego agregado</string>
|
||||
<string name="deck_tab_gamepad">Control</string>
|
||||
<string name="game_shortcut_add">Agregar a la pantalla de inicio</string>
|
||||
<string name="game_shortcut_unsupported">Este launcher no puede agregar accesos directos. Usa Copiar enlace de inicio.</string>
|
||||
<string name="session_runtime_catalog_unreachable">No se pudo acceder al catálogo del runtime. Revisa la conexión y vuelve a presionar Jugar.</string>
|
||||
<string name="session_runtime_install_failed">El runtime de Linux no se instaló. Revisa el runtime en Configuración y vuelve a presionar Jugar.</string>
|
||||
<string name="session_desktop_install_failed">El escritorio no se instaló (%1$s). Revisa la conexión y presiona Escritorio de nuevo.</string>
|
||||
<string name="store_cat_audio_video">Audio y video</string>
|
||||
<string name="theme_graphite_detail">Superficies grafito, con el azul del orbe del logotipo para todo lo seleccionado, enfocado o presionado.</string>
|
||||
<string name="theme_icon_blue_detail">Fondo negro, texto blanco y el azul para todo lo seleccionado, enfocado o presionado.</string>
|
||||
<string name="pckb_key_enter">Enter ⏎</string>
|
||||
<string name="game_sync_err_added_games">La carpeta de juegos agregados no está disponible</string>
|
||||
<string name="fm_favorite_add">Agregar a Favoritos</string>
|
||||
<string name="fm_conflict_merge_hint">Combinar agrega y reemplaza archivos dentro de la carpeta existente.</string>
|
||||
<string name="fm_favorite_added">Se agregó \"%1$s\" a Favoritos</string>
|
||||
<string name="adbfix_enter_address">Ingresa la dirección IP y el puerto actuales de la Depuración inalámbrica</string>
|
||||
<string name="adbpair_six_digits">Ingresa los 6 dígitos del código</string>
|
||||
<string name="adbpair_code_rejected">Ese código no funcionó. Vuelve a abrir la ventana de vinculación e ingresa su nuevo código.</string>
|
||||
<string name="adbpair_waiting_long">Activa la Depuración inalámbrica y toca “Vincular dispositivo con código de vinculación”. Quédate en Ajustes: el código se ingresa en esta notificación.</string>
|
||||
<string name="adbpair_code_hint">Toca Ingresar código y escribe los 6 dígitos que muestra Ajustes.</string>
|
||||
<string name="adbpair_title_code">Ingresa el código de vinculación Wi-Fi</string>
|
||||
<string name="adbpair_enter_code">Ingresar código</string>
|
||||
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a una computadora con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
|
||||
<string name="stores_kv_steam_on">se agrega a Steam al instalar (interfaz Deck + Steam Input)</string>
|
||||
<string name="stores_download_manager">Administrador de descargas</string>
|
||||
<string name="games_add_all">Agregar todos los juegos de esta carpeta</string>
|
||||
<plurals name="games_added_n">
|
||||
<item quantity="one">%1$d juego agregado</item>
|
||||
<item quantity="many">%1$d juegos agregados</item>
|
||||
<item quantity="other">%1$d juegos agregados</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -278,6 +278,9 @@
|
||||
<string name="mode_suspend_steam_note">Auto pauses and resumes when shown. Native prepares Steam for sleep first. Manual waits for Resume. Never keeps running.</string>
|
||||
<string name="mode_background_downloads">Keep downloads running</string>
|
||||
<string name="mode_background_downloads_hint">Delay background suspension while Steam is actively downloading.</string>
|
||||
<string name="mode_zram">zRAM compression</string>
|
||||
<string name="mode_zram_hint">While a game runs, the Steam client\'s memory is compressed into the device\'s zram, leaving more RAM for the game. Applies the next time Steam starts.</string>
|
||||
<string name="mode_zram_unsupported">Unavailable: this device has no zram or swap, or its kernel is older than 5.4.</string>
|
||||
<string name="mode_suspend_note">Auto pauses in the background and resumes when shown. Manual waits for Resume. Never keeps running.</string>
|
||||
<string name="mode_startup">Startup</string>
|
||||
<string name="mode_steam_startup">Start Steam with DroidDeck</string>
|
||||
@@ -713,6 +716,14 @@
|
||||
<string name="setup_saved_logs">Saved session logs</string>
|
||||
<string name="setup_saved_logs_hint">Keeps the newest %1$d</string>
|
||||
<string name="setup_clear_logs">Clear logs</string>
|
||||
<string name="setup_reset_settings">Reset all settings</string>
|
||||
<string name="setup_reset_settings_hint">Puts every setting back to its default</string>
|
||||
<string name="setup_reset_settings_button">Reset</string>
|
||||
<string name="setup_reset_settings_title">Reset all settings?</string>
|
||||
<string name="setup_reset_settings_body">Display, performance, controller, theme, language and launcher settings go back to their defaults. Your games, Steam sign-in, store accounts, downloaded drivers and storage folders are kept.</string>
|
||||
<string name="setup_reset_settings_profiles">Also reset game profiles (each game\'s Proton, FEX, components and environment, and the Default profile\'s environment)</string>
|
||||
<string name="setup_reset_settings_session_running">Stop the session before resetting settings.</string>
|
||||
<string name="setup_reset_settings_partial">Settings were reset, but some parts could not be. The logs have the details.</string>
|
||||
<string name="setup_offline">Offline mode</string>
|
||||
<string name="setup_sign_in_first">Sign in to Steam first</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
@@ -2246,6 +2257,9 @@
|
||||
<string name="stores_install_title">Install %1$s:</string>
|
||||
<string name="stores_target_internal">Internal</string>
|
||||
<string name="stores_target_free">%1$s free</string>
|
||||
<string name="stores_target_free_unknown">Free space unknown</string>
|
||||
<string name="stores_storage_insufficient">Not enough free space: need %1$s, only %2$s free</string>
|
||||
<string name="stores_storage_low">Insufficient space (%1$s free, need %2$s)</string>
|
||||
<string name="stores_notification_channel">Store downloads</string>
|
||||
<string name="stores_notification_channel_hint">Shows game download progress and keeps downloads running in the background</string>
|
||||
<string name="stores_notification_one">Downloading</string>
|
||||
@@ -2357,4 +2371,72 @@
|
||||
<string name="gog_achievements_enable_store">Enable GOG achievements in Stores settings</string>
|
||||
<string name="gog_achievements_unavailable">Achievements unavailable; check session logs</string>
|
||||
<string name="achievement_unlocked">Achievement unlocked</string>
|
||||
<string name="touch_paste">Paste</string>
|
||||
<string name="touch_dpad">D-pad</string>
|
||||
<string name="touch_left_stick">Left stick</string>
|
||||
<string name="touch_right_stick">Right stick</string>
|
||||
<string name="touch_menu">Menu</string>
|
||||
<string name="touch_keyboard">Keyboard</string>
|
||||
<string name="touch_dpad_up">D-pad up</string>
|
||||
<string name="touch_dpad_down">D-pad down</string>
|
||||
<string name="touch_dpad_left">D-pad left</string>
|
||||
<string name="touch_dpad_right">D-pad right</string>
|
||||
<string name="touch_title">Touch controls</string>
|
||||
<string name="touch_controller">Touch Controller</string>
|
||||
<string name="touch_mouse">Mouse</string>
|
||||
<string name="touch_on">On</string>
|
||||
<string name="touch_off">Off</string>
|
||||
<string name="touch_speed_slow">Slow</string>
|
||||
<string name="touch_speed_normal">Normal</string>
|
||||
<string name="touch_speed_fast">Fast</string>
|
||||
<string name="touch_edit_layout">Edit layout</string>
|
||||
<string name="touch_droiddeck_menu">DroidDeck menu</string>
|
||||
<string name="touch_drag_hint">Drag controls onto the screen</string>
|
||||
<string name="touch_arrange">Arrange</string>
|
||||
<string name="touch_discard">Discard</string>
|
||||
<string name="touch_saving">Saving…</string>
|
||||
<string name="touch_icon">Icon</string>
|
||||
<string name="touch_narrower">W−</string>
|
||||
<string name="touch_wider">W+</string>
|
||||
<string name="touch_shorter">H−</string>
|
||||
<string name="touch_taller">H+</string>
|
||||
<string name="touch_hide">Hide</string>
|
||||
<string name="touch_color_opacity">Color and opacity…</string>
|
||||
<string name="touch_copy_layout">Copy this layout</string>
|
||||
<string name="touch_layout_copied">Layout copied; paste it into any game\'s touch layout</string>
|
||||
<string name="touch_paste_layout">Paste copied layout</string>
|
||||
<string name="touch_reset_layout">Reset to Steam\'s default</string>
|
||||
<string name="touch_no_binding">This control has no binding in Steam to put an icon on</string>
|
||||
<string name="touch_icon_for">Icon for %1$s</string>
|
||||
<string name="touch_layout_color">Touch layout color</string>
|
||||
<string name="touch_done">Done</string>
|
||||
<string name="touch_save_failed">Could not save the touch layout</string>
|
||||
<string name="touch_saved">Touch layout saved to Steam</string>
|
||||
<string name="touch_app_id">App %1$d</string>
|
||||
<string name="touch_label_hint">Label (optional)</string>
|
||||
<string name="touch_icons_missing">Steam\'s icons were not found</string>
|
||||
<plurals name="touch_icons_found">
|
||||
<item quantity="one">%1$d icon from Steam</item>
|
||||
<item quantity="other">%1$d icons from Steam</item>
|
||||
</plurals>
|
||||
<string name="touch_icon_color">Icon color</string>
|
||||
<string name="touch_button_color">Button color</string>
|
||||
<string name="touch_no_icon">No icon</string>
|
||||
|
||||
<string name="stores_sync_sign_in">Checking sign-in…</string>
|
||||
<string name="stores_sync_library">Fetching your library…</string>
|
||||
<string name="stores_sync_game_list">Fetching game list…</string>
|
||||
<string name="stores_sync_details">Loading game details… (%1$d/%2$d)</string>
|
||||
<plurals name="stores_sync_games">
|
||||
<item quantity="one">Syncing %1$d game…</item>
|
||||
<item quantity="other">Syncing %1$d games…</item>
|
||||
</plurals>
|
||||
<string name="stores_sync_progress">Syncing… %1$d/%2$d</string>
|
||||
<string name="stores_sync_cover_art">Fetching cover art…</string>
|
||||
<string name="stores_sync_failed">Sync failed</string>
|
||||
<string name="stores_sync_no_games">No games found in your %1$s library</string>
|
||||
<string name="stores_sync_amazon_no_answer">Amazon Games did not answer for your library: refresh, or sign in again</string>
|
||||
<string name="stores_sync_gog_unreachable">Couldn\'t reach GOG</string>
|
||||
<string name="stores_sync_gog_unreadable">Could not read your GOG library</string>
|
||||
<string name="stores_registering">Registering with Steam…</string>
|
||||
</resources>
|
||||
@@ -3,9 +3,33 @@
|
||||
AppLanguage.supported and the values-* folders. -->
|
||||
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<locale android:name="en" />
|
||||
<locale android:name="id" />
|
||||
<locale android:name="ms" />
|
||||
<locale android:name="cs" />
|
||||
<locale android:name="da" />
|
||||
<locale android:name="de" />
|
||||
<locale android:name="es" />
|
||||
<locale android:name="es-419" />
|
||||
<locale android:name="fr" />
|
||||
<locale android:name="it" />
|
||||
<locale android:name="hu" />
|
||||
<locale android:name="nl" />
|
||||
<locale android:name="nb" />
|
||||
<locale android:name="pl" />
|
||||
<locale android:name="pt-BR" />
|
||||
<locale android:name="pt-PT" />
|
||||
<locale android:name="ro" />
|
||||
<locale android:name="fi" />
|
||||
<locale android:name="sv" />
|
||||
<locale android:name="vi" />
|
||||
<locale android:name="tr" />
|
||||
<locale android:name="el" />
|
||||
<locale android:name="bg" />
|
||||
<locale android:name="ru" />
|
||||
<locale android:name="uk" />
|
||||
<locale android:name="ar" />
|
||||
<locale android:name="hi" />
|
||||
<locale android:name="th" />
|
||||
<locale android:name="ja" />
|
||||
<locale android:name="ko" />
|
||||
<locale android:name="zh-CN" />
|
||||
|
||||
@@ -112,7 +112,12 @@ On-disk protocol (what a resumed run, by either engine, relies on): a file is as
|
||||
|
||||
## `com.droiddeck.launcher.stores.epic.EpicNative`
|
||||
|
||||
Two runs make up the native half of an Epic install:
|
||||
The manager's default Epic install is the **stream** run (`nativeStream`, below): the chunks
|
||||
are fetched in parallel and written straight into staged files as they arrive. The older batch
|
||||
pair below (fetch everything into a cache, then assemble) stays for A/B benchmarks (the hidden
|
||||
`storesEpicMode=batch` preference).
|
||||
|
||||
Two runs make up the native half of a batch Epic install:
|
||||
|
||||
1. **Fetch** (`nativeStart`): fills the chunk cache with verified, decompressed chunks for the
|
||||
files the manager says are pending. The Kotlin manager still fetches and parses the manifest
|
||||
@@ -224,6 +229,50 @@ Bannerlator's `BlEpicDownload.run(...)` wraps `nativeStart` in a blocking call t
|
||||
`onComplete`, then `nativeRelease` in `finally`. The same wrapper shape fits `nativeAssemble`
|
||||
(cancel is honoured between files; a multi-GB file finishes before the run stops).
|
||||
|
||||
### `nativeStream` — the adaptive install
|
||||
|
||||
| Method | JNI signature | Symbol |
|
||||
|---|---|---|
|
||||
| `nativeStream(...)`: Long | `([BLjava/lang/String;Ljava/lang/String;[Ljava/lang/String;[IJJLjava/lang/String;IILjava/lang/Object;)J` (last parameter is the listener) | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStream` |
|
||||
|
||||
```kotlin
|
||||
@JvmStatic private external fun nativeStream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>,
|
||||
pendingFileIdx: IntArray, expectedBytes: Long, cacheBudget: Long, caBundlePath: String,
|
||||
maxWorkers: Int, processWorkers: Int, listener: StreamListener,
|
||||
): Long
|
||||
```
|
||||
|
||||
Parameters as `nativeStart`, except `expectedBytes` (the manager's `Σ fileSize` of the pending
|
||||
files, `-1` = no cross-check; no chunk count) and `cacheBudget` (the most bytes of shared chunks
|
||||
the cache may hold; the manager sizes it from free space, `0` = never cache, refetch instead).
|
||||
`chunkCacheDir` is `""` (`<installDir>/.chunks`) or a scratch directory; the manager falls back to
|
||||
`""` for a card install when internal storage cannot hold the budget.
|
||||
|
||||
What the run does (`epic/stream.rs`): a chunk one file part uses is decompressed, verified and
|
||||
written at the part's offset into that file's unique sibling `.droiddeck-epic-*.stage` file; a
|
||||
chunk several parts use is also kept in the cache, decompressed, as `<GUID>` (a later copy after
|
||||
an eviction as `<GUID>.<n>`) and deleted after its last covered part. The plan evicts by furthest
|
||||
next use when the budget would be exceeded and fetches the evicted chunk again later. Each file,
|
||||
once complete: synced, size and SHA-1 checked, `onBeforeReplace()` once for the whole run, then
|
||||
renamed over its destination. Cancel or failure removes every unfinished stage file before
|
||||
`onComplete`, leaves the destinations and the cache; success removes the cache directory.
|
||||
|
||||
Planning runs on the calling thread and also prepares the cache (keeps verified chunks this
|
||||
install needs, deletes everything else, as the Java writer does). A refusal returns `0` after a
|
||||
synchronous `onComplete(false, reason, 0)`; nothing was fetched or written, and the manager runs
|
||||
its bounded Java writer.
|
||||
|
||||
| `StreamListener` method | JNI signature | When |
|
||||
|---|---|---|
|
||||
| `onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long)` | `(JJIIJ)V` | after written parts (at most every 50 ms) and after every finished file; `filesBytes` = sizes of the files swapped in |
|
||||
| `onLog(line: String)` | `(Ljava/lang/String;)V` | engine lines: `stream-plan …`, the fetch core's lines, `stream-summary mode=adaptive …` (peak cache, peak staging, refetches, direct vs cached bytes) |
|
||||
| `onBeforeReplace(): Boolean` | `()Z` | once, before the first file replaces its destination; `false` or a throw fails the run with nothing replaced |
|
||||
| `onComplete(success: Boolean, error: String, bytes: Long)` | `(ZLjava/lang/String;J)V` | terminal, exactly once; `bytes` = file bytes written; `error` = `"cancelled"` on cancel |
|
||||
|
||||
Unlike the batch runs, the Kotlin wrapper (`EpicNative.stream`) waits for `onComplete` after a
|
||||
cancel without a time limit: the stage-file cleanup must be finished before the manager returns.
|
||||
|
||||
## `com.droiddeck.launcher.stores.amazon.AmazonNative`
|
||||
|
||||
The file-fetch pool of an Amazon Games install: one streamed HTTP GET per manifest file, SHA-256
|
||||
|
||||
@@ -18,6 +18,9 @@
|
||||
//! - [`assemble`] — the files from the cache, one sequential write each, SHA-1 checked as they
|
||||
//! are written; with a scratch cache (one the caller placed apart from the install) each chunk
|
||||
//! is deleted as soon as the last file that uses it is done.
|
||||
//! - [`stream`] — the adaptive install the manager uses by default: the chunks fetched in
|
||||
//! parallel through the fetch core and written straight into staging files as they arrive,
|
||||
//! shared chunks kept in a budgeted cache, each file verified and swapped in safely.
|
||||
//! - [`jni`] — `Java_com_droiddeck_launcher_stores_epic_EpicNative_native*` exports.
|
||||
//!
|
||||
//! The selective-install-tag, delta/resume and chunk verification rules mirrored here were ported
|
||||
@@ -31,6 +34,7 @@ pub mod driver;
|
||||
pub mod jni;
|
||||
pub mod manifest;
|
||||
pub mod plan;
|
||||
pub mod stream;
|
||||
|
||||
/// User-Agent the Java manager sends on every chunk request (`EpicDownloadManager.UA`).
|
||||
pub const USER_AGENT: &str =
|
||||
|
||||
@@ -177,6 +177,80 @@ fn write_part(
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// The window a chunk decompresses to: the manifest's, or 1 MiB for a legacy JSON manifest that
|
||||
/// names none (`EpicDownloadManager.chunkWindowSize`). The streaming installer also plans its
|
||||
/// shared-chunk cache with this size.
|
||||
pub fn chunk_window_bytes(window_size: i32) -> u64 {
|
||||
if window_size > 0 {
|
||||
window_size as u64
|
||||
} else {
|
||||
1024 * 1024
|
||||
}
|
||||
}
|
||||
|
||||
/// One downloaded body → the verified, decompressed chunk in memory, for the streaming installer
|
||||
/// (`stream.rs`), which writes most chunks straight into the files that use them and never puts
|
||||
/// them in a cache. The checks are the bounded Java writer's (`downloadChunkStreaming`), which is
|
||||
/// stricter than [`write_verified_chunk`]: a stored payload shorter than `compressedSize` is
|
||||
/// truncated, a zlib stream must reach its end, the output may not grow past the chunk's window
|
||||
/// and must fill it exactly when the manifest names one, and the SHA-1 must match when the
|
||||
/// manifest has one. `Err` = "try another CDN", exactly like a cache write that failed.
|
||||
pub fn decode_verified_chunk(
|
||||
body: &[u8],
|
||||
window_size: i32,
|
||||
expected_sha1: Option<&[u8; 20]>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let hdr = parse_chunk_header(body)?;
|
||||
let start = hdr.payload_start();
|
||||
if start > body.len() {
|
||||
return Err("Stream ended during skip".to_string());
|
||||
}
|
||||
let want = if hdr.compressed_size <= 0 {
|
||||
0
|
||||
} else {
|
||||
hdr.compressed_size as usize
|
||||
};
|
||||
let avail = body.len() - start;
|
||||
let cap = chunk_window_bytes(window_size) as usize;
|
||||
let out = if hdr.is_compressed() {
|
||||
// Java stops reading once the inflater finishes, so a body may carry less than
|
||||
// `compressedSize` as long as the stream itself is complete.
|
||||
let payload = &body[start..start + want.min(avail)];
|
||||
let mut out: Vec<u8> = Vec::with_capacity(cap + 1);
|
||||
let mut inflater = flate2::Decompress::new(true);
|
||||
let status = inflater
|
||||
.decompress_vec(payload, &mut out, flate2::FlushDecompress::Finish)
|
||||
.map_err(|e| format!("inflate: {e}"))?;
|
||||
if out.len() > cap {
|
||||
return Err("chunk exceeds expected window size".to_string());
|
||||
}
|
||||
if status != flate2::Status::StreamEnd {
|
||||
return Err("truncated compressed Epic chunk".to_string());
|
||||
}
|
||||
out
|
||||
} else {
|
||||
if avail < want {
|
||||
return Err("truncated Epic chunk".to_string());
|
||||
}
|
||||
if want > cap {
|
||||
return Err("chunk exceeds expected window size".to_string());
|
||||
}
|
||||
body[start..start + want].to_vec()
|
||||
};
|
||||
if window_size > 0 && out.len() != window_size as usize {
|
||||
return Err(format!(
|
||||
"chunk is {} bytes, window is {window_size}",
|
||||
out.len()
|
||||
));
|
||||
}
|
||||
if let Some(expected) = expected_sha1 {
|
||||
if Sha1::digest(&out).as_slice() != &expected[..] {
|
||||
return Err("Chunk SHA-1 mismatch (streaming)".to_string());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_support {
|
||||
use super::*;
|
||||
@@ -361,6 +435,29 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_in_memory_applies_the_bounded_writer_checks() {
|
||||
let data = sample_data();
|
||||
let window = data.len() as i32;
|
||||
let sha = sha1_of(&data);
|
||||
let zipped = build_chunk_body(&data, true, 2, None);
|
||||
assert_eq!(decode_verified_chunk(&zipped, window, Some(&sha)).unwrap(), data);
|
||||
let stored = build_chunk_body(&data, false, 0, None);
|
||||
assert_eq!(decode_verified_chunk(&stored, window, Some(&sha)).unwrap(), data);
|
||||
// No window and no hash (legacy JSON manifest): accepted up to 1 MiB.
|
||||
assert_eq!(decode_verified_chunk(&zipped, 0, None).unwrap(), data);
|
||||
// Window mismatch, SHA-1 mismatch, truncation, oversize.
|
||||
assert!(decode_verified_chunk(&zipped, window + 1, None).is_err());
|
||||
let err = decode_verified_chunk(&zipped, window, Some(&[7; 20])).unwrap_err();
|
||||
assert!(err.contains("SHA-1 mismatch"), "{err}");
|
||||
let cut = zipped.len() - 500;
|
||||
assert!(decode_verified_chunk(&zipped[..cut], window, None).is_err());
|
||||
assert!(decode_verified_chunk(&stored[..stored.len() - 1], 0, None)
|
||||
.unwrap_err()
|
||||
.contains("truncated"));
|
||||
assert!(decode_verified_chunk(&zipped, window - 1, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_part_file_is_cleared_before_the_attempt() {
|
||||
let dir = temp_dir("stale");
|
||||
|
||||
@@ -7,7 +7,11 @@
|
||||
//! listener: EpicNative.Listener) -> long handle (0 = not started)
|
||||
//! nativeAssemble(manifest: byte[], installDir: String, chunkCacheDir: String, fileIdx: int[],
|
||||
//! listener: EpicNative.Listener) -> long handle (0 = not started)
|
||||
//! nativeCancel(handle) — flips the run's AtomicBool; fetch or assembly stops promptly
|
||||
//! nativeStream(manifest: byte[], installDir: String, chunkCacheDir: String, cdnPrefixes: String[],
|
||||
//! pendingFileIdx: int[], expectedBytes: long, cacheBudget: long, caBundlePath: String,
|
||||
//! maxWorkers: int, processWorkers: int, listener: EpicNative.StreamListener)
|
||||
//! -> long handle (0 = not started)
|
||||
//! nativeCancel(handle) — flips the run's AtomicBool; fetch, assembly or stream stops promptly
|
||||
//! nativeRelease(handle) — frees the handle (after onComplete)
|
||||
//! ```
|
||||
//! `chunkCacheDir` = "" keeps the cache at `<installDir>/.chunks`; any other directory is a
|
||||
@@ -17,6 +21,11 @@
|
||||
//! an assembly run, per file written), `onLog(String line)`,
|
||||
//! `onComplete(boolean success, String error, long bytes)`.
|
||||
//!
|
||||
//! The stream run (`stream.rs`) writes the files as the chunks arrive; its listener has
|
||||
//! `onStreamProgress(long bytesWritten, long bytesTotal, int filesDone, int filesTotal,
|
||||
//! long filesBytes)`, `onLog(String)`, `boolean onBeforeReplace()` (called once, before the first
|
||||
//! file replaces its destination; `false` fails the run) and the same `onComplete`.
|
||||
//!
|
||||
//! Planning (manifest parse + cross-check) runs synchronously on the calling thread so a plan
|
||||
//! failure returns 0 BEFORE any fetch and Java can fall back to its own pool; the fetch runs on
|
||||
//! a new thread. JavaVM attach / GlobalRef handling is the same shape as the GOG facade.
|
||||
@@ -31,6 +40,7 @@ use jni::{JNIEnv, JavaVM};
|
||||
|
||||
use super::assemble::{build_assemble_plan, run_assemble, AssembleRequest};
|
||||
use super::driver::{build_plan, run_plan, EpicRequest};
|
||||
use super::stream::{build_stream_plan, run_stream, Hooks, StreamProgress, StreamRequest};
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
#[link(name = "log")]
|
||||
@@ -458,6 +468,184 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native
|
||||
Box::into_raw(handle) as jlong
|
||||
}
|
||||
|
||||
fn call_on_stream_progress(env: &mut JNIEnv, listener: &JObject, p: &StreamProgress) {
|
||||
if listener.is_null() {
|
||||
return;
|
||||
}
|
||||
let _ = env.call_method(
|
||||
listener,
|
||||
"onStreamProgress",
|
||||
"(JJIIJ)V",
|
||||
&[
|
||||
JValue::Long(p.bytes_written as jlong),
|
||||
JValue::Long(p.bytes_total as jlong),
|
||||
JValue::Int(p.files_done.min(i32::MAX as u64) as jint),
|
||||
JValue::Int(p.files_total.min(i32::MAX as u64) as jint),
|
||||
JValue::Long(p.files_bytes as jlong),
|
||||
],
|
||||
);
|
||||
clear_pending_exception(env);
|
||||
}
|
||||
|
||||
/// `boolean onBeforeReplace()`: the Java side marks an existing install `updating`. A thrown
|
||||
/// exception or `false` is a refusal.
|
||||
fn call_on_before_replace(env: &mut JNIEnv, listener: &JObject) -> Result<(), String> {
|
||||
if listener.is_null() {
|
||||
return Ok(());
|
||||
}
|
||||
let result = env
|
||||
.call_method(listener, "onBeforeReplace", "()Z", &[])
|
||||
.and_then(|v| v.z());
|
||||
let threw = env.exception_check().unwrap_or(false);
|
||||
clear_pending_exception(env);
|
||||
match result {
|
||||
Ok(true) if !threw => Ok(()),
|
||||
_ => Err("could not mark the install as updating".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `EpicNative.nativeStream(...)`: the adaptive install (see `stream.rs`). Parse, plan and cache
|
||||
/// preparation run on the calling thread, so a refusal returns 0 (after a synchronous
|
||||
/// `onComplete(false, reason, 0)`) before anything is fetched or written, and the manager runs
|
||||
/// the bounded Java writer instead. The run itself is on a new thread; `onComplete` fires after
|
||||
/// every unfinished staging file of a cancelled or failed run is gone.
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStream(
|
||||
mut env: JNIEnv,
|
||||
_class: JClass,
|
||||
manifest: JByteArray,
|
||||
install_dir: JString,
|
||||
chunk_cache_dir: JString,
|
||||
cdn_prefixes: JObjectArray,
|
||||
pending_file_idx: JIntArray,
|
||||
expected_bytes: jlong,
|
||||
cache_budget: jlong,
|
||||
ca_bundle_path: JString,
|
||||
max_workers: jint,
|
||||
process_workers: jint,
|
||||
listener: JObject,
|
||||
) -> jlong {
|
||||
if listener.is_null() {
|
||||
android_log("nativeStream: null listener");
|
||||
return 0;
|
||||
}
|
||||
let Ok(manifest_bytes) = env.convert_byte_array(manifest) else {
|
||||
clear_pending_exception(&mut env);
|
||||
call_on_complete(&mut env, &listener, false, "manifest bytes unreadable", 0);
|
||||
return 0;
|
||||
};
|
||||
let install_dir = jstring_to_string(&mut env, &install_dir).unwrap_or_default();
|
||||
let chunk_cache_dir = jstring_to_string(&mut env, &chunk_cache_dir).unwrap_or_default();
|
||||
let cdn_prefixes = string_array_to_vec(&mut env, &cdn_prefixes);
|
||||
let pending_file_indices: Vec<usize> = int_array_to_vec(&env, &pending_file_idx)
|
||||
.into_iter()
|
||||
.map(|i| i.max(0) as usize)
|
||||
.collect();
|
||||
let ca_bundle_path = jstring_to_string(&mut env, &ca_bundle_path).unwrap_or_default();
|
||||
let max_workers = max_workers.max(1) as usize;
|
||||
let process_workers = process_workers.max(1) as usize;
|
||||
let label = {
|
||||
let base = std::path::Path::new(&install_dir)
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
format!("epic app={base}")
|
||||
};
|
||||
log_both(
|
||||
&mut env,
|
||||
&listener,
|
||||
&format!(
|
||||
"engine=rust-stream label=\"{label}\" install_dir={install_dir} cache_dir={} cdns={} pending_files={} cache_budget={} workers={max_workers} process_workers={process_workers} manifest_bytes={}",
|
||||
if chunk_cache_dir.is_empty() { "<installDir>/.chunks" } else { chunk_cache_dir.as_str() },
|
||||
cdn_prefixes.len(),
|
||||
pending_file_indices.len(),
|
||||
cache_budget.max(0),
|
||||
manifest_bytes.len()
|
||||
),
|
||||
);
|
||||
|
||||
let req = StreamRequest {
|
||||
manifest_bytes,
|
||||
install_dir,
|
||||
chunk_cache_dir,
|
||||
cdn_prefixes,
|
||||
pending_file_indices,
|
||||
expected_bytes: if expected_bytes >= 0 {
|
||||
Some(expected_bytes as u64)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
cache_budget: cache_budget.max(0) as u64,
|
||||
ca_bundle_path,
|
||||
max_workers,
|
||||
process_workers,
|
||||
label,
|
||||
};
|
||||
let plan = match build_stream_plan(&req) {
|
||||
Ok(plan) => plan,
|
||||
Err(err) => {
|
||||
log_both(&mut env, &listener, &format!("not started: {err}"));
|
||||
call_on_complete(&mut env, &listener, false, &err, 0);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
let Ok(vm) = env.get_java_vm() else {
|
||||
clear_pending_exception(&mut env);
|
||||
call_on_complete(&mut env, &listener, false, "JavaVM unavailable", 0);
|
||||
return 0;
|
||||
};
|
||||
let Ok(listener) = env.new_global_ref(&listener) else {
|
||||
clear_pending_exception(&mut env);
|
||||
call_on_complete(&mut env, &listener, false, "listener ref failed", 0);
|
||||
return 0;
|
||||
};
|
||||
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let thread_cancel = Arc::clone(&cancel);
|
||||
let handle = Box::new(EpicDownloadHandle { cancel });
|
||||
|
||||
thread::spawn(move || {
|
||||
crate::priority::background();
|
||||
let progress = |p: &StreamProgress| {
|
||||
let Ok(mut env) = vm.attach_current_thread_as_daemon() else {
|
||||
return;
|
||||
};
|
||||
call_on_stream_progress(&mut env, listener.as_obj(), p);
|
||||
};
|
||||
let before_replace = || {
|
||||
let Ok(mut env) = vm.attach_current_thread_as_daemon() else {
|
||||
return Err("JavaVM attach failed".to_string());
|
||||
};
|
||||
call_on_before_replace(&mut env, listener.as_obj())
|
||||
};
|
||||
let log = |line: &str| {
|
||||
android_log(line);
|
||||
let Ok(mut env) = vm.attach_current_thread_as_daemon() else {
|
||||
return;
|
||||
};
|
||||
call_on_log(&mut env, listener.as_obj(), line);
|
||||
};
|
||||
let hooks = Hooks {
|
||||
progress: &progress,
|
||||
before_replace: &before_replace,
|
||||
log: &log,
|
||||
};
|
||||
let outcome = run_stream(&plan, &req, thread_cancel.as_ref(), &hooks);
|
||||
let Ok(mut env) = vm.attach_current_thread_as_daemon() else {
|
||||
return;
|
||||
};
|
||||
call_on_complete(
|
||||
&mut env,
|
||||
listener.as_obj(),
|
||||
outcome.success,
|
||||
&outcome.error,
|
||||
outcome.bytes_written,
|
||||
);
|
||||
});
|
||||
|
||||
Box::into_raw(handle) as jlong
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeCancel(
|
||||
_env: JNIEnv,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@ import android.util.Base64
|
||||
import androidx.compose.ui.semantics.SemanticsConfiguration
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
@@ -68,6 +69,13 @@ class AgentSecurityTest {
|
||||
assertFalse(AgentAccess.commandsAllowed(context))
|
||||
}
|
||||
|
||||
@Test fun theRefusalNamesTheSetupTabThatHoldsTheToggle() {
|
||||
val refusal = refused("AGENT_COMMANDS_DISABLED") { AgentAccess.requireCommands(context) }
|
||||
val tab = context.getString(R.string.setup_tab_diagnostics)
|
||||
val toggle = context.getString(R.string.setup_agent_commands)
|
||||
assertTrue(refusal.message, refusal.message!!.contains("Setup > $tab > $toggle"))
|
||||
}
|
||||
|
||||
@Test fun runCannotBypassTheToggle() {
|
||||
refused("AGENT_COMMANDS_DISABLED") { AgentAccess.requireStart(context, JSONObject().put("mode", "run")) }
|
||||
AgentAccess.requireStart(context, JSONObject().put("mode", "steam"))
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class AppLanguageTest {
|
||||
private fun tag(languageTag: String) = AppLanguage.supportedTag(Locale.forLanguageTag(languageTag))
|
||||
|
||||
private val folders = mapOf(
|
||||
"id" to "in", "ms" to "ms", "cs" to "cs", "da" to "da", "de" to "de", "es" to "es",
|
||||
"es-419" to "b+es+419", "fr" to "fr", "it" to "it", "hu" to "hu", "nl" to "nl", "nb" to "nb",
|
||||
"pl" to "pl", "pt-BR" to "pt", "pt-PT" to "pt-rPT", "ro" to "ro", "fi" to "fi", "sv" to "sv",
|
||||
"vi" to "vi", "tr" to "tr", "el" to "el", "bg" to "bg", "ru" to "ru", "uk" to "uk", "ar" to "ar",
|
||||
"hi" to "hi", "th" to "th", "ja" to "ja", "ko" to "ko", "zh-CN" to "zh-rCN", "zh-TW" to "zh-rTW",
|
||||
"zh-HK" to "zh-rHK",
|
||||
)
|
||||
|
||||
@Test fun everyLanguageReadsAsItself() {
|
||||
AppLanguage.supported.forEach { assertEquals(it, tag(it)) }
|
||||
}
|
||||
|
||||
@Test fun everyLanguageHasItsOwnName() {
|
||||
val names = AppLanguage.supported.map(AppLanguage::nativeName)
|
||||
assertEquals(names.size, names.toSet().size)
|
||||
AppLanguage.supported.forEach { assertTrue(it, AppLanguage.nativeName(it) != it) }
|
||||
}
|
||||
|
||||
@Test fun systemLocalesFindTheirLanguage() {
|
||||
assertEquals("es-419", tag("es-MX"))
|
||||
assertEquals("es-419", tag("es-US"))
|
||||
assertEquals("es", tag("es-ES"))
|
||||
assertEquals("pt-BR", tag("pt-BR"))
|
||||
assertEquals("pt-BR", tag("pt"))
|
||||
assertEquals("pt-PT", tag("pt-PT"))
|
||||
assertEquals("pt-PT", tag("pt-AO"))
|
||||
assertEquals("id", tag("in-ID"))
|
||||
assertEquals("id", tag("id-ID"))
|
||||
assertEquals("de", tag("de-AT"))
|
||||
assertEquals("ar", tag("ar-EG"))
|
||||
assertEquals("zh-HK", tag("zh-MO"))
|
||||
assertNull(tag("sw-KE"))
|
||||
assertNull(tag("nn-NO"))
|
||||
}
|
||||
|
||||
@Test fun everyLanguageShipsStringsAndIsOfferedToAndroid() {
|
||||
assertEquals(AppLanguage.supported.toSet() - "en", folders.keys)
|
||||
val res = File("src/main/res")
|
||||
folders.values.forEach { assertTrue(it, File(res, "values-$it/strings.xml").isFile) }
|
||||
val config = File(res, "xml/locales_config.xml").readText()
|
||||
val offered = Regex("""android:name="([^"]+)"""").findAll(config).map { it.groupValues[1] }.toList()
|
||||
assertEquals(AppLanguage.supported, offered)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ZramSupportTest {
|
||||
@Test
|
||||
fun kernelVersionsFromAndroidReleases() {
|
||||
assertTrue(ZramSupport.kernelAtLeast("6.12.38-android16-5-g665eafb62659-ab14778838-4k", 5, 4))
|
||||
assertTrue(ZramSupport.kernelAtLeast("5.4.0", 5, 4))
|
||||
assertFalse(ZramSupport.kernelAtLeast("4.19.157-perf+", 5, 4))
|
||||
assertFalse(ZramSupport.kernelAtLeast("", 5, 4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun underTwelveGbFromAdvertisedOrTotalMemory() {
|
||||
val gb = 1_000_000_000L
|
||||
val gib = 1L shl 30
|
||||
assertTrue(ZramSupport.belowTwelveGb(8 * gb, 0))
|
||||
assertTrue(ZramSupport.belowTwelveGb(8 * gib, 0))
|
||||
assertFalse(ZramSupport.belowTwelveGb(12 * gb, 0))
|
||||
assertFalse(ZramSupport.belowTwelveGb(12 * gib, 0))
|
||||
assertTrue(ZramSupport.belowTwelveGb(0, 7_400_000L * 1024))
|
||||
assertTrue(ZramSupport.belowTwelveGb(0, 9_300_000L * 1024))
|
||||
assertFalse(ZramSupport.belowTwelveGb(0, 11_100_000L * 1024))
|
||||
assertFalse(ZramSupport.belowTwelveGb(0, 15_600_380L * 1024))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun swapTotalComesFromMeminfo() {
|
||||
assertEquals(12582908L, ZramSupport.swapTotalKb(listOf("MemTotal: 15600380 kB", "SwapTotal: 12582908 kB")))
|
||||
assertEquals(0L, ZramSupport.swapTotalKb(listOf("SwapTotal: 0 kB")))
|
||||
assertEquals(0L, ZramSupport.swapTotalKb(emptyList()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.os.Looper
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.FrameLayout
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(manifest = Config.NONE)
|
||||
class KeyboardHostTest {
|
||||
private lateinit var imm: InputMethodManager
|
||||
private lateinit var host: KeyboardHost
|
||||
|
||||
@Before fun setUp() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
host = KeyboardHost(activity)
|
||||
activity.setContentView(FrameLayout(activity).apply { addView(host) })
|
||||
idle()
|
||||
}
|
||||
|
||||
@Config(sdk = [33])
|
||||
@Test fun toggleShowsAKeyboardTheSystemDismissed() {
|
||||
host.show()
|
||||
idle()
|
||||
imm.hideSoftInputFromWindow(host.windowToken, 0)
|
||||
idle()
|
||||
host.toggle()
|
||||
idle()
|
||||
assertTrue(shadowOf(imm).isSoftInputVisible)
|
||||
assertTrue(host.shown)
|
||||
}
|
||||
|
||||
@Config(sdk = [28])
|
||||
@Test fun toggleHidesAKeyboardThatIsShowing() {
|
||||
host.show()
|
||||
idle()
|
||||
host.toggle()
|
||||
idle()
|
||||
assertFalse(shadowOf(imm).isSoftInputVisible)
|
||||
assertFalse(host.shown)
|
||||
}
|
||||
|
||||
private fun idle() = shadowOf(Looper.getMainLooper()).idle()
|
||||
}
|
||||
@@ -23,15 +23,33 @@ class QuestExperimentalTest {
|
||||
ShadowBuild.setDevice("phone")
|
||||
}
|
||||
|
||||
@Test fun otherDevicesAndQuest2KeepTheirSettings() {
|
||||
for (model in listOf("Phone", "Quest 2")) {
|
||||
@Test fun otherDevicesKeepTheirSettings() {
|
||||
for (model in listOf("Phone", "Quest", "Quest Pro")) {
|
||||
ShadowBuild.setModel(model)
|
||||
QuestExperimental.initialize(context)
|
||||
assertEquals(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.gpuDriverMode(context))
|
||||
assertEquals("", SessionPrefs.androidDriver(context))
|
||||
assertFalse(SessionPrefs.hdr(context, "steam"))
|
||||
}
|
||||
assertFalse(QuestExperimental.supported("Quest 2", "hollywood", "Oculus"))
|
||||
assertFalse(QuestExperimental.supported("Phone", "hollywood", "Other"))
|
||||
}
|
||||
|
||||
@Test fun quest2SelectsA6xxInsteadOfQuest3DriverAndPreservesLaterChoices() {
|
||||
ShadowBuild.setModel("Quest 2")
|
||||
// A prior Quest 3 flag must not suppress Quest 2's own migration.
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
|
||||
.putBoolean("questDefaultsV1", true).commit()
|
||||
QuestExperimental.initialize(context)
|
||||
assertEquals(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.gpuDriverMode(context))
|
||||
assertEquals(QuestExperimental.DRIVER_A6XX, SessionPrefs.androidDriver(context))
|
||||
assertEquals("", SessionPrefs.linuxDriver(context))
|
||||
assertTrue(SessionPrefs.hdr(context, "steam"))
|
||||
assertTrue(QuestExperimental.supported("unknown", "hollywood", "Oculus"))
|
||||
assertTrue(QuestExperimental.supported("unknown", "hollywood", "Meta"))
|
||||
assertFalse(QuestExperimental.quest2("Quest 3", "eureka", "Meta"))
|
||||
SessionPrefs.setAndroidDriver(context, "chosen-a6xx-driver")
|
||||
QuestExperimental.initialize(context)
|
||||
assertEquals("chosen-a6xx-driver", SessionPrefs.androidDriver(context))
|
||||
}
|
||||
|
||||
@Test fun questDefaultsSelectBothCompatibilityPathsAndAreAppliedOnlyOnce() {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import org.junit.Assert.*
|
||||
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
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class SettingsResetTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
private fun prefs(name: String) = app.getSharedPreferences(name, Context.MODE_PRIVATE)
|
||||
private val session get() = prefs("session")
|
||||
|
||||
@Before fun clear() {
|
||||
listOf("session", "controller", "app-ui", "frame_gen", "steam_touch", "agent").forEach {
|
||||
prefs(it).edit().clear().commit()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun settingsGoBackToTheirDefaults() {
|
||||
SessionPrefs.setTheme(app, "ocean")
|
||||
SessionPrefs.setNoXalia(app, false)
|
||||
SessionPrefs.setFpsLimit(app, SessionService.MODE_STEAM, 30)
|
||||
SessionPrefs.setHdr(app, SessionService.MODE_DESKTOP, true)
|
||||
SessionPrefs.setResolutionChoice(app, SessionService.MODE_STEAM, "1280x800")
|
||||
SessionPrefs.setGuestHostname(app, "MyDeck")
|
||||
ControllerPrefs.setOpacity(app, 40)
|
||||
AppUiPrefs.setScale(app, 150)
|
||||
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_WINFG, 3))
|
||||
prefs("steam_touch").edit().putBoolean("gyro", false).commit()
|
||||
|
||||
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
|
||||
|
||||
assertEquals("graphite", SessionPrefs.theme(app))
|
||||
assertTrue(SessionPrefs.noXalia(app))
|
||||
assertEquals(0, SessionPrefs.fpsLimit(app, SessionService.MODE_STEAM))
|
||||
assertFalse(SessionPrefs.hdr(app, SessionService.MODE_DESKTOP))
|
||||
assertFalse(SessionPrefs.resolutionChosen(app, SessionService.MODE_STEAM))
|
||||
assertEquals(SessionPrefs.DEFAULT_GUEST_HOSTNAME, SessionPrefs.guestHostname(app))
|
||||
assertEquals(100, ControllerPrefs.read(app).opacity)
|
||||
assertEquals(AppUiPrefs.DEFAULT_SCALE, AppUiPrefs.scale(app))
|
||||
assertEquals(FrameGen.Mode.OFF.engine, FrameGen.engine(app))
|
||||
assertFalse(prefs("steam_touch").contains("gyro"))
|
||||
}
|
||||
|
||||
@Test fun libraryAndRecordsAreKept() {
|
||||
val folder = "/storage/emulated/0/Games/Foo"
|
||||
SessionPrefs.setAddedGameName(app, folder, "Foo")
|
||||
SessionPrefs.setAddedGameExe(app, folder, "$folder/foo.exe")
|
||||
SessionPrefs.addedGameAppId(app, folder, 1234L)
|
||||
SessionPrefs.setAddedGameRemoved(app, "/storage/emulated/0/Games/Bar", true)
|
||||
SessionPrefs.setGamesFoldersMigrated(app)
|
||||
SessionPrefs.setGpuAutoInstalled(app, setOf("turnip-a"))
|
||||
SessionPrefs.setRomsDir(app, "/storage/emulated/0/ROMs")
|
||||
SessionPrefs.setGameStorage(app, "/storage/ABCD-1234", "SD Card")
|
||||
SessionPrefs.setMicAsked(app)
|
||||
prefs("steam_touch").edit().putString("copiedLayout", "a:1,2").commit()
|
||||
|
||||
SettingsReset.resetAll(app, gameProfiles = false)
|
||||
|
||||
assertEquals("Foo", SessionPrefs.addedGameName(app, folder))
|
||||
assertEquals("$folder/foo.exe", SessionPrefs.addedGameExe(app, folder))
|
||||
assertEquals(1234L, SessionPrefs.addedGameStoredAppId(app, folder))
|
||||
assertEquals(listOf("/storage/emulated/0/Games/Bar"), SessionPrefs.removedAddedGames(app))
|
||||
assertTrue(SessionPrefs.gamesFoldersMigrated(app))
|
||||
assertEquals(setOf("turnip-a"), SessionPrefs.gpuAutoInstalled(app))
|
||||
assertEquals("/storage/emulated/0/ROMs", SessionPrefs.romsDir(app))
|
||||
assertEquals("/storage/ABCD-1234", SessionPrefs.gameStorage(app))
|
||||
assertTrue(SessionPrefs.micAsked(app))
|
||||
assertEquals("a:1,2", prefs("steam_touch").getString("copiedLayout", null))
|
||||
}
|
||||
|
||||
@Test fun gameTextureFilteringIsKeptUnlessGameProfilesAreReset() {
|
||||
session.edit().putString("gameTextureFiltering", """{"440":{"anisotropy":16}}""").commit()
|
||||
SettingsReset.resetAll(app, gameProfiles = false)
|
||||
assertEquals(16, SessionPrefs.gameTextureFiltering(app, "440").anisotropy)
|
||||
|
||||
SettingsReset.resetAll(app, gameProfiles = true)
|
||||
assertTrue(SessionPrefs.gameTextureFiltering(app).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun perModeKeysAreSettings() {
|
||||
listOf("resolutionCap.steam", "displayResolution.desktop", "customRes.steam", "hdr.steam", "fpsLimit.desktop", "suspendPolicy.steam")
|
||||
.forEach { assertTrue(it, SettingsReset.isSessionSetting(it)) }
|
||||
listOf("addedName:/x", "addedAppId:/x", "gpuAutoInstalled", "romsDir", "gameStorage", "micAsked", "gameTextureFiltering")
|
||||
.forEach { assertFalse(it, SettingsReset.isSessionSetting(it)) }
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,18 @@ class SteamLanguageTest {
|
||||
assertEquals("tchinese", steam("zh-HK"))
|
||||
}
|
||||
|
||||
@Test fun everyAppLanguageButHindiHasSteamsOwn() {
|
||||
com.droiddeck.launcher.core.AppLanguage.supported.forEach {
|
||||
val steam = steam(it)
|
||||
assertTrue("$it -> $steam", (steam == "english") == (it == "en" || it == "hi"))
|
||||
}
|
||||
assertEquals("brazilian", steam("pt-BR"))
|
||||
assertEquals("portuguese", steam("pt-PT"))
|
||||
assertEquals("latam", steam("es-419"))
|
||||
assertEquals("indonesian", steam("id"))
|
||||
assertEquals("malay", steam("ms"))
|
||||
}
|
||||
|
||||
@Test fun chineseFollowsTheScriptBeforeTheRegion() {
|
||||
assertEquals("tchinese", steam("zh-Hant-CN"))
|
||||
assertEquals("schinese", steam("zh-Hans-HK"))
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowStatFs
|
||||
|
||||
/** Where a store game goes: internal storage unless the user picks a card, and back to its own folder on a rerun. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@@ -59,4 +60,87 @@ class StoreInstallRootTest {
|
||||
assertTrue(dir.absolutePath.startsWith(app.cacheDir.absolutePath))
|
||||
assertEquals("a_b_c", dir.name)
|
||||
}
|
||||
|
||||
@Test fun estimatedBytesNeededUsesKnownInstallSizeForAllStores() {
|
||||
val item = CatalogItem(Store.EPIC, "game1", "Game 1", imageUrl = null, owned = true, sizeBytes = 10_000_000L)
|
||||
assertEquals(10_000_000L, StoreInstallRoot.estimatedBytesNeeded(item))
|
||||
|
||||
val gogItem = CatalogItem(Store.GOG, "game2", "Game 2", imageUrl = null, owned = true, sizeBytes = 10_000_000L)
|
||||
assertEquals(10_000_000L, StoreInstallRoot.estimatedBytesNeeded(gogItem))
|
||||
}
|
||||
|
||||
@Test fun checkStorageReportsEnoughWhenSpaceIsUnknownOrAvailable() {
|
||||
val zeroItem = CatalogItem(Store.EPIC, "game1", "Game 1", imageUrl = null, owned = true, sizeBytes = 0L)
|
||||
val check = StoreInstallRoot.checkStorage(app, zeroItem, StoreInstallRoot.internalRoot(app))
|
||||
assertTrue(check.enough)
|
||||
}
|
||||
|
||||
@Test fun availableBytesUsesNearestExistingAncestorWithoutCreatingDirectories() {
|
||||
val existing = File(app.filesDir, "storage-probe").apply { mkdirs() }
|
||||
val missing = File(existing, "not-created/another-level/game")
|
||||
ShadowStatFs.registerStats(existing.path, 1024, 100, 100)
|
||||
|
||||
assertTrue(StoreInstallRoot.availableBytes(missing) > 0L)
|
||||
assertFalse(File(existing, "not-created").exists())
|
||||
}
|
||||
|
||||
@Test fun epicDefersFullSizeChecksToItsManifestDeltaForResume() {
|
||||
val item = CatalogItem(Store.EPIC, "large", "Large", imageUrl = null, owned = true, sizeBytes = Long.MAX_VALUE)
|
||||
val check = StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app))
|
||||
assertTrue(check.enough)
|
||||
assertEquals(Long.MAX_VALUE, check.requiredBytes)
|
||||
}
|
||||
|
||||
@Test fun gogAndAmazonResumeChecksUseTheExistingVolumeAndDeferRemainingWork() {
|
||||
val card = File(app.filesDir, "resume-card").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, card.path, "Card")
|
||||
for (store in listOf(Store.GOG, Store.AMAZON)) {
|
||||
val item = CatalogItem(store, "resume-${store.id}", "Partial ${store.id}", imageUrl = null, sizeBytes = Long.MAX_VALUE)
|
||||
val folder = File(StoreInstallRoot.storeDir(File(card, "Games"), store), StoreInstallRoot.folderName(item.title, item.id)).apply { mkdirs() }
|
||||
StoreInstalls.begin(folder, store, item.id, item.title, null, null)
|
||||
val check = StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app))
|
||||
assertTrue(check.enough)
|
||||
assertEquals(StoreInstallRoot.availableBytes(folder), check.availableBytes)
|
||||
assertEquals(folder, StoreInstallRoot.folderFor(app, store, item.id, item.title))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun freshGogAndAmazonStillRejectInsufficientCatalogSpace() {
|
||||
StoreInstallRoot.internalRoot(app).mkdirs()
|
||||
ShadowStatFs.registerStats(StoreInstallRoot.internalRoot(app).path, 1024, 100, 100)
|
||||
for (store in listOf(Store.GOG, Store.AMAZON)) {
|
||||
val item = CatalogItem(store, "too-large-${store.id}", "Too large ${store.id}", imageUrl = null, sizeBytes = Long.MAX_VALUE)
|
||||
assertFalse(StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app)).enough)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun measuredZeroRejectsFreshGogAndAmazonRatherThanBeingUnknown() {
|
||||
val root = File(app.filesDir, "zero-space").apply { mkdirs() }
|
||||
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
|
||||
val missing = File(root, "not-created/game")
|
||||
assertEquals(0L, StoreInstallRoot.availableBytes(missing))
|
||||
assertFalse(File(root, "not-created").exists())
|
||||
for (store in listOf(Store.GOG, Store.AMAZON)) {
|
||||
val item = CatalogItem(store, "zero-${store.id}", "Zero ${store.id}", imageUrl = null, sizeBytes = 1L)
|
||||
val check = StoreInstallRoot.checkStorage(app, item, missing)
|
||||
assertFalse(check.enough)
|
||||
assertEquals(0L, check.availableBytes)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun failedProbesAreUnknownAndDoNotCreateOrWriteToTargets() {
|
||||
val root = File(app.filesDir, "read-only-probe").apply { mkdirs() }
|
||||
val missing = File(root, "not-created/game")
|
||||
val fail: (File) -> Long = { throw java.io.IOException("unavailable") }
|
||||
assertEquals(-1L, StoreInstallRoot.probeAvailableBytes(missing, fail, fail))
|
||||
assertEquals(-1L, StoreInstallRoot.probeAvailableBytes(missing, fail, { 0L }))
|
||||
assertEquals(42L, StoreInstallRoot.probeAvailableBytes(missing, fail, { 42L }))
|
||||
assertEquals(0L, StoreInstallRoot.probeAvailableBytes(missing, { 0L }, fail))
|
||||
assertFalse(File(root, "not-created").exists())
|
||||
assertTrue(root.listFiles().orEmpty().isEmpty())
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(1L, -1L))
|
||||
assertTrue(StoreInstallRoot.insufficientSpace(1L, 0L))
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(1L, 1L))
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(0L, 0L))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.droiddeck.launcher.stores.amazon
|
||||
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowStatFs
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class AmazonResumeSpaceTest {
|
||||
@Test fun remainingWorkRejectsMeasuredZeroButNotUnknownSpace() {
|
||||
val root = File(RuntimeEnvironment.getApplication().filesDir, "amazon-zero").apply { mkdirs() }
|
||||
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
|
||||
val files = listOf(AmazonManifest.ManifestFile("missing", 4, 0, null))
|
||||
val needed = AmazonDownloadManager.remainingInstallBytes(files, root)
|
||||
assertEquals(4L, needed)
|
||||
assertTrue(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.availableBytes(root)))
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.SPACE_UNKNOWN))
|
||||
}
|
||||
|
||||
@Test fun remainingSpaceExcludesVerifiedFilesButIncludesCorruptAndPartialFiles() {
|
||||
val root = File(RuntimeEnvironment.getApplication().filesDir, "amazon-resume").apply { mkdirs() }
|
||||
val data = byteArrayOf(1, 2, 3, 4)
|
||||
val hash = MessageDigest.getInstance("SHA-256").digest(data)
|
||||
val files = listOf("good", "corrupt", "partial", "missing").map {
|
||||
AmazonManifest.ManifestFile(it, 4, 0, hash)
|
||||
}
|
||||
File(root, "good").writeBytes(data)
|
||||
File(root, "corrupt").writeBytes(ByteArray(4))
|
||||
File(root, "partial").writeBytes(byteArrayOf(1))
|
||||
assertEquals(12L, AmazonDownloadManager.remainingInstallBytes(files, root))
|
||||
for (file in files) File(root, file.unixPath()).writeBytes(data)
|
||||
assertEquals(0L, AmazonDownloadManager.remainingInstallBytes(files, root))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.droiddeck.launcher.stores.download
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.*
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.json.JSONArray
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowStatFs
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class DownloadQueueRetryTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@After fun cleanRows() { DownloadQueue.dismissFinished(); StoreSizes.known.clear() }
|
||||
|
||||
private fun awaitFailure(key: String, error: String) {
|
||||
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
while (System.nanoTime() < until) {
|
||||
val entry = DownloadQueue.entry(key)
|
||||
if (entry?.state == DownloadState.FAILED && entry.error == error) return
|
||||
Thread.sleep(10)
|
||||
}
|
||||
fail("Expected failed real job: ${DownloadQueue.entry(key)}")
|
||||
}
|
||||
|
||||
@Test fun storageRetryRechecksThenRunsTheRealBackendAndNormalRetryStillWorks() {
|
||||
StoreInstallRoot.internalRoot(app).mkdirs()
|
||||
ShadowStatFs.registerStats(StoreInstallRoot.internalRoot(app).path, 1024, 100, 100)
|
||||
val item = CatalogItem(Store.GOG, "preflight-retry", "Preflight retry", imageUrl = null, sizeBytes = Long.MAX_VALUE)
|
||||
val runs = AtomicInteger()
|
||||
var lastTarget: File? = null
|
||||
val previous = StoresState.backend(Store.GOG)
|
||||
val backend = object : StoreBackend {
|
||||
override val store = Store.GOG
|
||||
override fun signIn(context: Context) {}
|
||||
override fun signOut(context: Context) {}
|
||||
override fun syncLibrary(context: Context, force: Boolean) {}
|
||||
override fun loadShelves(context: Context, force: Boolean) {}
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
lastTarget = root
|
||||
DownloadQueue.enqueue(context, DownloadEntry(item.store, item.id, item.title)) {
|
||||
object : DownloadQueue.DownloadJob {
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
throw IllegalStateException("backend-${runs.incrementAndGet()}")
|
||||
}
|
||||
override fun cancel(deleteFiles: Boolean) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
StoresState.register(backend)
|
||||
try {
|
||||
StoresState.install(app, item)
|
||||
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
|
||||
DownloadQueue.retry(app, item.key)
|
||||
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
|
||||
assertEquals(0, runs.get())
|
||||
StoreSizes.known[item.key] = 1
|
||||
DownloadQueue.retry(app, item.key)
|
||||
awaitFailure(item.key, "backend-1")
|
||||
DownloadQueue.retry(app, item.key)
|
||||
awaitFailure(item.key, "backend-2")
|
||||
DownloadQueue.clear(app, item.key)
|
||||
assertNull(DownloadQueue.entry(item.key))
|
||||
|
||||
// A card resume (including the restored paused path) must retain its real target.
|
||||
val card = File(app.filesDir, "retry-card").apply { mkdirs() }
|
||||
SessionPrefs.setGameStorage(app, card.path, "Card")
|
||||
val target = File(card, "Games")
|
||||
val folder = File(StoreInstallRoot.storeDir(target, item.store), StoreInstallRoot.folderName(item.title, item.id)).apply { mkdirs() }
|
||||
StoreInstalls.begin(folder, item.store, item.id, item.title, null, null)
|
||||
StoreSizes.known[item.key] = Long.MAX_VALUE
|
||||
StoresState.unfinished = StoreInstallRoot.unfinished(app)
|
||||
DownloadQueue.holdPaused(item.key)
|
||||
StoresState.requestInstall(app, item)
|
||||
assertEquals(target, lastTarget)
|
||||
assertEquals(DownloadState.PAUSED, DownloadQueue.entry(item.key)?.state)
|
||||
assertEquals(2, runs.get())
|
||||
val saved = File(app.filesDir, "store-queue.json")
|
||||
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
|
||||
var correctSavedRoot = false
|
||||
while (!correctSavedRoot && System.nanoTime() < until) {
|
||||
correctSavedRoot = runCatching {
|
||||
val rows = JSONArray(saved.readText())
|
||||
(0 until rows.length()).any { i ->
|
||||
val row = rows.getJSONObject(i)
|
||||
row.getJSONObject("item").getString("id") == item.id &&
|
||||
row.getString("root") == target.absolutePath && row.getBoolean("paused")
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
if (!correctSavedRoot) Thread.sleep(10)
|
||||
}
|
||||
assertTrue("Paused saved queue must remember the existing card root", correctSavedRoot)
|
||||
DownloadQueue.clear(app, item.key)
|
||||
} finally {
|
||||
if (previous != null) StoresState.register(previous)
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
StoresState.unfinished = emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun preflightClearRemovesTheRowWithoutRunningItsRetry() {
|
||||
val entry = DownloadEntry(Store.AMAZON, "clear-preflight", "Clear")
|
||||
DownloadQueue.recordFailed(app, entry, "storage") { fail("Clear must not retry") }
|
||||
DownloadQueue.clear(app, entry.key)
|
||||
assertNull(DownloadQueue.entry(entry.key))
|
||||
}
|
||||
|
||||
@Test fun heldPausedBackendRestoresAndResumesWithoutAPlaceholder() {
|
||||
val entry = DownloadEntry(Store.GOG, "restored-paused", "Paused")
|
||||
val ran = CountDownLatch(1)
|
||||
DownloadQueue.holdPaused(entry.key)
|
||||
DownloadQueue.enqueue(app, entry) {
|
||||
object : DownloadQueue.DownloadJob {
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
ran.countDown()
|
||||
throw IllegalStateException("restored")
|
||||
}
|
||||
override fun cancel(deleteFiles: Boolean) {}
|
||||
}
|
||||
}
|
||||
assertEquals(DownloadState.PAUSED, DownloadQueue.entry(entry.key)?.state)
|
||||
assertEquals(1L, ran.count)
|
||||
DownloadQueue.resume(app, entry.key)
|
||||
assertTrue(ran.await(5, TimeUnit.SECONDS))
|
||||
awaitFailure(entry.key, "restored")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class EpicAdaptivePlanTest {
|
||||
private val mib = 1024L * 1024
|
||||
private val gib = 1024 * mib
|
||||
|
||||
@Test fun freshInstallsNeedNoOpenStagingAllowance() {
|
||||
assertEquals(0L, EpicDownloadManager.adaptiveOpenStagingAllowance(emptyMap()))
|
||||
val old = mapOf("big.pak" to 10 * gib, "small.pak" to gib)
|
||||
assertEquals(10 * gib + EpicDownloadManager.ADAPTIVE_OPEN_WINDOW_BYTES, EpicDownloadManager.adaptiveOpenStagingAllowance(old))
|
||||
assertEquals(100 * mib, EpicDownloadManager.adaptiveOpenStagingAllowance(mapOf("a" to 60 * mib, "b" to 40 * mib)))
|
||||
}
|
||||
|
||||
@Test fun cacheBudgetIsHalfTheHeadroomCappedAndDefaultsWhenSpaceIsUnknown() {
|
||||
assertEquals(EpicDownloadManager.ADAPTIVE_CACHE_DEFAULT_BYTES, EpicDownloadManager.adaptiveCacheBudget(-1, 0))
|
||||
assertEquals(EpicDownloadManager.ADAPTIVE_CACHE_MAX_BYTES, EpicDownloadManager.adaptiveCacheBudget(100 * gib, 10 * gib))
|
||||
assertEquals(0L, EpicDownloadManager.adaptiveCacheBudget(gib, gib))
|
||||
val free = 1000 * mib
|
||||
assertEquals((free - 400 * mib - EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES) / 2, EpicDownloadManager.adaptiveCacheBudget(free, 400 * mib))
|
||||
}
|
||||
|
||||
@Test fun cardInstallKeepsTheCacheOnInternalScratchWhenItFits() {
|
||||
val plan = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 30 * gib, true, 10 * gib)
|
||||
assertNull(plan.error)
|
||||
assertFalse(plan.cacheBesideGame)
|
||||
assertEquals(EpicDownloadManager.ADAPTIVE_CACHE_MAX_BYTES, plan.cacheBudget)
|
||||
assertEquals(20 * gib, plan.gameNeed)
|
||||
assertEquals(plan.cacheBudget + EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES, plan.scratchNeed)
|
||||
}
|
||||
|
||||
@Test fun fullInternalStorageMovesTheCacheBesideTheGameInsteadOfFailing() {
|
||||
val plan = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 30 * gib, true, 100 * mib)
|
||||
assertNull(plan.error)
|
||||
assertTrue(plan.cacheBesideGame)
|
||||
assertEquals(0L, plan.scratchNeed)
|
||||
assertTrue(plan.cacheBudget > 0)
|
||||
assertEquals(20 * gib + plan.cacheBudget + EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES, plan.gameNeed)
|
||||
assertTrue(plan.gameNeed <= 30 * gib)
|
||||
}
|
||||
|
||||
@Test fun shortStorageIsNamedWithTheShortfall() {
|
||||
val card = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 10 * gib, true, 10 * gib)
|
||||
assertTrue(card.error!!.contains("game's storage"))
|
||||
assertTrue(card.error!!.contains("short by 10.0 GB"))
|
||||
val internal = EpicDownloadManager.planAdaptiveSpace(20 * gib, gib, 20 * gib, false, -1)
|
||||
assertTrue(internal.error!!.contains("game's storage"))
|
||||
assertNull(EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, -1, true, -1).error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import java.io.File
|
||||
import java.net.InetAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.SocketException
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
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
|
||||
import org.robolectric.shadows.ShadowStatFs
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class EpicBoundedInstallTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
private lateinit var server: ServerSocket
|
||||
private lateinit var worker: Thread
|
||||
private lateinit var manifest: EpicDownloadManager.Manifest
|
||||
private lateinit var root: File
|
||||
private val requests = AtomicInteger()
|
||||
private val reject = AtomicBoolean()
|
||||
private var bytes = ByteArray(256 * 1024) { (it % 251).toByte() }
|
||||
|
||||
@Before fun setUp() {
|
||||
root = temp.newFolder("game")
|
||||
ShadowStatFs.registerStats(root.path, 1_000_000_000, 1_000_000_000, 1_000_000_000)
|
||||
server = ServerSocket(0, 8, InetAddress.getByName("127.0.0.1"))
|
||||
worker = Thread {
|
||||
while (!server.isClosed) {
|
||||
val socket = try { server.accept() } catch (e: SocketException) {
|
||||
if (server.isClosed) break else throw e
|
||||
}
|
||||
socket.use {
|
||||
it.soTimeout = 5000
|
||||
val reader = it.getInputStream().bufferedReader()
|
||||
while (!reader.readLine().isNullOrEmpty()) { }
|
||||
requests.incrementAndGet()
|
||||
val out = it.getOutputStream()
|
||||
if (reject.get()) {
|
||||
out.write("HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
} else {
|
||||
val header = ByteBuffer.allocate(41).order(ByteOrder.LITTLE_ENDIAN)
|
||||
.putInt(0xB1FE3AA2.toInt()).putInt(1).putInt(41).putInt(bytes.size)
|
||||
.put(ByteArray(24)).put(0).array()
|
||||
out.write("HTTP/1.1 200 OK\r\nContent-Length: ${header.size + bytes.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
out.write(header)
|
||||
out.write(bytes)
|
||||
}
|
||||
out.flush()
|
||||
}
|
||||
}
|
||||
}.apply { start() }
|
||||
val chunk = EpicDownloadManager.ChunkInfo().apply {
|
||||
guid = intArrayOf(1, 0, 0, 0)
|
||||
windowSize = bytes.size
|
||||
fileSize = bytes.size.toLong()
|
||||
sha1 = sha(bytes)
|
||||
}
|
||||
manifest = EpicDownloadManager.Manifest().apply {
|
||||
chunkDir = "chunks"
|
||||
uniqueChunks = arrayListOf(chunk)
|
||||
cdnUrls = listOf(EpicDownloadManager.CdnUrl("http://127.0.0.1:${server.localPort}", "", ""))
|
||||
files = arrayListOf(gameFile("game.bin", 0, bytes.size / 2), gameFile("game.bin.part", bytes.size / 2, bytes.size / 2))
|
||||
}
|
||||
}
|
||||
|
||||
@After fun tearDown() { server.close(); worker.join(6000); assertFalse(worker.isAlive) }
|
||||
|
||||
private fun sha(data: ByteArray) = MessageDigest.getInstance("SHA-1").digest(data)
|
||||
|
||||
private fun gameFile(name: String, offset: Int, size: Int) = EpicDownloadManager.FileInfo().apply {
|
||||
filename = name
|
||||
sha1 = sha(bytes.copyOfRange(offset, offset + size))
|
||||
parts.add(EpicDownloadManager.ChunkPart().apply {
|
||||
guid = intArrayOf(1, 0, 0, 0)
|
||||
this.offset = offset
|
||||
this.size = size
|
||||
})
|
||||
}
|
||||
|
||||
private fun install(cancel: AtomicBoolean = AtomicBoolean(), callback: EpicDownloadManager.Callback =
|
||||
EpicDownloadManager.Callback { _, _ -> }, cache: String = "") =
|
||||
EpicDownloadManager.installManifest(manifest, root.path, cache, null, cancel, callback)
|
||||
|
||||
private fun oldInstall() {
|
||||
File(root, "game.bin").writeBytes(byteArrayOf(9, 8, 7))
|
||||
File(root, "game.bin.part").writeBytes(byteArrayOf(6, 5, 4))
|
||||
StoreGameSidecar(Store.EPIC, "game", "Game", "game.bin", installVersion = "old").write(root)
|
||||
}
|
||||
|
||||
private fun assertOldInstallIntact() {
|
||||
assertArrayEquals(byteArrayOf(9, 8, 7), File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
|
||||
assertEquals("old", StoreGameSidecar.read(root)?.installVersion)
|
||||
assertTrue(StoreGameSidecar.read(root)?.isInstalled == true)
|
||||
assertTrue(root.walk().none { it.name.endsWith(".stage") })
|
||||
}
|
||||
|
||||
@Test fun networkFailureAfterAcceptedPreflightPreservesInstalledFilesAndRecord() {
|
||||
oldInstall()
|
||||
reject.set(true)
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertTrue(requests.get() > 0)
|
||||
assertOldInstallIntact()
|
||||
}
|
||||
|
||||
@Test fun hashFailureAfterAcceptedPreflightPreservesInstalledFilesAndRecord() {
|
||||
oldInstall()
|
||||
manifest.files.first().sha1 = ByteArray(20) { 1 }
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertOldInstallIntact()
|
||||
}
|
||||
|
||||
@Test fun cancellationWhileStagingPreservesInstalledFilesAndRecord() {
|
||||
oldInstall()
|
||||
val cancel = AtomicBoolean()
|
||||
assertNull(install(cancel, EpicDownloadManager.Callback { message, _ ->
|
||||
if (message.startsWith("Downloading chunks (")) cancel.set(true)
|
||||
}))
|
||||
assertOldInstallIntact()
|
||||
}
|
||||
|
||||
@Test fun laterFailureRetainsVerifiedSwapsAndMarksMixedUpdateResumable() {
|
||||
oldInstall()
|
||||
manifest.files.last().sha1 = ByteArray(20) { 1 }
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
|
||||
val record = StoreGameSidecar.read(root)!!
|
||||
assertEquals(StoreGameSidecar.STATE_UPDATING, record.state)
|
||||
assertFalse(record.isInstalled)
|
||||
assertEquals("", record.installVersion)
|
||||
StoreInstalls.begin(root, Store.EPIC, "game", "Game", null, null)
|
||||
assertEquals("game.bin", StoreGameSidecar.read(root)?.exe)
|
||||
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
|
||||
}
|
||||
|
||||
@Test fun laterNetworkFailurePreservesTheUnreplacedOldFile() {
|
||||
oldInstall()
|
||||
val secondChunk = EpicDownloadManager.ChunkInfo().apply {
|
||||
guid = intArrayOf(2, 0, 0, 0)
|
||||
windowSize = bytes.size
|
||||
fileSize = bytes.size.toLong()
|
||||
sha1 = sha(bytes)
|
||||
}
|
||||
manifest.uniqueChunks.add(secondChunk)
|
||||
manifest.files.last().parts.single().guid = secondChunk.guid
|
||||
val callback = object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {}
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
if (stage == "stream" && items == 1) reject.set(true)
|
||||
}
|
||||
}
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install(callback = callback) }
|
||||
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
|
||||
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
|
||||
assertTrue(root.walk().none { it.name.endsWith(".stage") })
|
||||
}
|
||||
|
||||
@Test fun cancellationAfterFirstSwapLeavesAResumableMixedUpdate() {
|
||||
oldInstall()
|
||||
val cancel = AtomicBoolean()
|
||||
val callback = object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {}
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
if (stage == "stream" && items == 1) cancel.set(true)
|
||||
}
|
||||
}
|
||||
assertNull(install(cancel, callback))
|
||||
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
|
||||
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
|
||||
assertNotNull(install())
|
||||
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
|
||||
// Registration, not an individual file swap, restores the installed state.
|
||||
assertFalse(StoreGameSidecar.read(root)!!.isInstalled)
|
||||
}
|
||||
|
||||
@Test fun atomicRenameFailurePreservesDestinationAndCleansStagingWithoutDeleteFallback() {
|
||||
val destination = File(root, "game.bin").apply { mkdir() }
|
||||
File(destination, "old-content").writeText("keep")
|
||||
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertTrue(error.message.orEmpty().contains("atomically replace"))
|
||||
assertEquals("keep", File(destination, "old-content").readText())
|
||||
assertTrue(root.walk().none { it.name.endsWith(".stage") })
|
||||
}
|
||||
|
||||
@Test fun safeStagingSpaceBoundaryRejectsWithoutReclaimingAllOldOutputs() {
|
||||
// The first staged half-file must coexist with the shared chunk and BOTH old outputs.
|
||||
val old = ByteArray(bytes.size / 2) { 9 }
|
||||
File(root, "game.bin").writeBytes(old)
|
||||
File(root, "game.bin.part").writeBytes(old)
|
||||
val peak = bytes.size + old.size
|
||||
ShadowStatFs.registerStats(root.path, 1024, peak / 4096 - 1, peak / 4096 - 1)
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertEquals(0, requests.get())
|
||||
assertArrayEquals(old, File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(old, File(root, "game.bin.part").readBytes())
|
||||
ShadowStatFs.registerStats(root.path, 1024, peak / 4096, peak / 4096)
|
||||
assertNotNull(install())
|
||||
}
|
||||
|
||||
@Test fun zeroSpaceRejectsPendingFilesWhileUnknownSpaceIsNotTreatedAsZero() {
|
||||
oldInstall()
|
||||
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertOldInstallIntact()
|
||||
assertEquals(0, requests.get())
|
||||
assertTrue(com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(1, 0))
|
||||
assertFalse(com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(1, -1))
|
||||
}
|
||||
|
||||
@Test fun zeroScratchSpaceRejectsBeforeFetchWithoutTouchingInstalledOutputs() {
|
||||
oldInstall()
|
||||
val cache = temp.newFolder("full-scratch")
|
||||
ShadowStatFs.registerStats(cache.path, 1024, 0, 0)
|
||||
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install(cache = cache.path) }
|
||||
assertTrue(error.message.orEmpty().contains("Not enough internal space"))
|
||||
assertOldInstallIntact()
|
||||
assertEquals(0, requests.get())
|
||||
}
|
||||
|
||||
@Test fun installsSharedChunksAndPreservesLegitimatePartFilename() {
|
||||
assertNotNull(install())
|
||||
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
|
||||
assertEquals(1, requests.get())
|
||||
assertFalse(File(root, ".chunks").exists())
|
||||
assertNotNull(install())
|
||||
assertEquals("Verified files must not be downloaded again", 1, requests.get())
|
||||
}
|
||||
|
||||
private fun oversizedUpdate() {
|
||||
val file = manifest.files[0]
|
||||
val part = file.parts[0]
|
||||
file.parts.clear()
|
||||
repeat(100_000) {
|
||||
file.parts.add(EpicDownloadManager.ChunkPart().apply {
|
||||
guid = part.guid
|
||||
size = Int.MAX_VALUE
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun insufficientInstallSpacePreservesExistingFilesOnBothCacheLayouts() {
|
||||
val oldGame = byteArrayOf(9, 8, 7)
|
||||
val oldPart = byteArrayOf(6, 5, 4)
|
||||
File(root, "game.bin").writeBytes(oldGame)
|
||||
File(root, "game.bin.part").writeBytes(oldPart)
|
||||
oversizedUpdate()
|
||||
assertTrue(manifest.files[0].fileSize() > root.usableSpace)
|
||||
|
||||
for (cache in listOf("", temp.newFolder("scratch-rejected").path)) {
|
||||
if (cache.isNotEmpty()) ShadowStatFs.registerStats(cache, 1_000_000_000, 1_000_000_000, 1_000_000_000)
|
||||
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install(cache = cache) }
|
||||
assertTrue(error.message.orEmpty().contains("Not enough free space"))
|
||||
assertArrayEquals(oldGame, File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(oldPart, File(root, "game.bin.part").readBytes())
|
||||
}
|
||||
assertEquals(0, requests.get())
|
||||
}
|
||||
|
||||
@Test fun acceptedUpdateReplacesOutdatedFilesWithVerifiedOutputs() {
|
||||
oldInstall()
|
||||
assertNotNull(install())
|
||||
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
|
||||
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
|
||||
assertTrue(root.walk().none { it.name.endsWith(".stage") })
|
||||
}
|
||||
|
||||
@Test fun pauseKeepsCompletedFilesAndResumeReusesSharedCache() {
|
||||
val cancel = AtomicBoolean()
|
||||
val callback = object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {}
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
if (stage == "stream" && items == 1) cancel.set(true)
|
||||
}
|
||||
}
|
||||
assertNull(install(cancel, callback))
|
||||
assertTrue(File(root, "game.bin").exists())
|
||||
assertFalse(File(root, "game.bin.part").exists())
|
||||
assertEquals(1, requests.get())
|
||||
assertNotNull(install())
|
||||
assertEquals(1, requests.get())
|
||||
}
|
||||
|
||||
@Test fun cancellationDuringChunkDeliveryRemovesIncompleteOutput() {
|
||||
val cancel = AtomicBoolean()
|
||||
val callback = object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {
|
||||
if (message.startsWith("Downloading chunks (")) cancel.set(true)
|
||||
}
|
||||
}
|
||||
assertNull(install(cancel, callback))
|
||||
assertFalse(File(root, "game.bin").exists())
|
||||
assertNotNull(install())
|
||||
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
|
||||
}
|
||||
|
||||
@Test fun fileHashFailureIsExplicitAndRetryRepairsIt() {
|
||||
val expected = manifest.files[0].sha1
|
||||
manifest.files[0].sha1 = ByteArray(20) { 1 }
|
||||
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertTrue(error.message.orEmpty().contains("SHA-1 mismatch"))
|
||||
assertFalse(File(root, "game.bin").exists())
|
||||
manifest.files[0].sha1 = expected
|
||||
assertNotNull(install())
|
||||
}
|
||||
|
||||
@Test fun corruptCacheIsRefetchedAndScratchCacheIsRemovedOnSuccess() {
|
||||
val cache = temp.newFolder("scratch")
|
||||
ShadowStatFs.registerStats(cache.path, 1_000_000_000, 1_000_000_000, 1_000_000_000)
|
||||
File(cache, manifest.uniqueChunks[0].guidStr()).writeBytes(ByteArray(bytes.size))
|
||||
assertNotNull(install(cache = cache.path))
|
||||
assertEquals(1, requests.get())
|
||||
assertFalse(cache.exists())
|
||||
}
|
||||
|
||||
@Test fun networkFailureLeavesNoCompletedFileAndCanBeRetried() {
|
||||
reject.set(true)
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertFalse(File(root, "game.bin").exists())
|
||||
reject.set(false)
|
||||
assertNotNull(install())
|
||||
}
|
||||
|
||||
@Test fun boundedProgressNeverReentersDownloadAfterEnteringInstall() {
|
||||
val events = mutableListOf<String>()
|
||||
val callback = object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {
|
||||
if (message.startsWith("Downloading chunks")) events.add("download")
|
||||
if (message.startsWith("Writing")) events.add("install")
|
||||
}
|
||||
override fun onBytes(done: Long, total: Long, speedBps: Long) { events.add("download") }
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
if (stage == "install") {
|
||||
assertEquals(total, done)
|
||||
assertEquals(itemsTotal, items)
|
||||
events.add("install")
|
||||
}
|
||||
}
|
||||
}
|
||||
assertNotNull(install(callback = callback))
|
||||
val firstInstall = events.indexOf("install")
|
||||
assertTrue(firstInstall > 0)
|
||||
assertFalse(events.drop(firstInstall).contains("download"))
|
||||
}
|
||||
|
||||
@Test fun sharedChunksDoNotCompleteProgressBeforeTheRemainingFilesAreWritten() {
|
||||
val samples = mutableListOf<Pair<Long, Long>>()
|
||||
val callback = object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {}
|
||||
override fun onBytes(done: Long, total: Long, speedBps: Long) { samples.add(done to total) }
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
if (stage == "stream" && items < itemsTotal) assertTrue(samples.last().first < samples.last().second)
|
||||
}
|
||||
}
|
||||
assertNotNull(install(callback = callback))
|
||||
assertEquals(listOf(0L, bytes.size / 2L, bytes.size.toLong()), samples.map { it.first })
|
||||
assertTrue(samples.all { it.second == bytes.size.toLong() })
|
||||
}
|
||||
|
||||
@Test fun evictedSharedChunksAdvanceWriteProgressOnEveryRefetchWithoutChangingStages() {
|
||||
bytes = ByteArray((EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 1024).toInt()) { (it % 251).toByte() }
|
||||
manifest.uniqueChunks.single().apply {
|
||||
windowSize = bytes.size
|
||||
fileSize = bytes.size.toLong()
|
||||
sha1 = sha(bytes)
|
||||
}
|
||||
manifest.files = (0..2).map { gameFile("part-$it.bin", it * 1024, 1024) }
|
||||
val chunk = manifest.uniqueChunks.single()
|
||||
val estimatedPeak = EpicDownloadManager.estimatePeakAdditionalBytes(
|
||||
manifest.files,
|
||||
mapOf(chunk.guidStr() to chunk),
|
||||
emptyMap(),
|
||||
true,
|
||||
)
|
||||
assertEquals(EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 4 * 1024L, estimatedPeak)
|
||||
val samples = mutableListOf<Long>()
|
||||
val stages = mutableListOf<String>()
|
||||
val callback = object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {}
|
||||
override fun onBytes(done: Long, total: Long, speedBps: Long) {
|
||||
assertEquals(3072L, total)
|
||||
assertFalse(stages.contains("install"))
|
||||
samples.add(done)
|
||||
}
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
stages.add(stage)
|
||||
if (stage == "stream" && items < itemsTotal) assertTrue(samples.last() < total)
|
||||
}
|
||||
}
|
||||
assertNotNull(install(callback = callback))
|
||||
assertEquals(3, requests.get())
|
||||
assertEquals(listOf(0L, 1024L, 2048L, 3072L), samples)
|
||||
assertEquals("install", stages.last())
|
||||
repeat(3) { assertArrayEquals(bytes.copyOfRange(it * 1024, (it + 1) * 1024), File(root, "part-$it.bin").readBytes()) }
|
||||
}
|
||||
|
||||
@Test fun hogwartsSizedSequentialPlanFitsAvailableSpaceWithoutFullChunkCache() {
|
||||
val gib = 1024L * 1024 * 1024
|
||||
val file = EpicDownloadManager.FileInfo()
|
||||
val chunks = LinkedHashMap<String, EpicDownloadManager.ChunkInfo>()
|
||||
repeat(72) { index ->
|
||||
val chunk = EpicDownloadManager.ChunkInfo().apply {
|
||||
guid = intArrayOf(index + 1, 0, 0, 0)
|
||||
windowSize = gib.toInt()
|
||||
}
|
||||
chunks[chunk.guidStr()] = chunk
|
||||
file.parts.add(EpicDownloadManager.ChunkPart().apply {
|
||||
guid = chunk.guid
|
||||
size = chunk.windowSize
|
||||
})
|
||||
}
|
||||
val peak = EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), true)
|
||||
assertEquals(73 * gib, peak)
|
||||
assertTrue(peak < 96 * gib)
|
||||
}
|
||||
|
||||
@Test fun plannersReclaimEachOldFileOnlyAfterItsOwnVerifiedSwap() {
|
||||
val chunks = manifest.uniqueChunks.associateBy { it.guidStr() }
|
||||
val half = bytes.size / 2L
|
||||
val old = mapOf("game.bin" to half, "game.bin.part" to 100 * half)
|
||||
assertEquals(bytes.size + half, EpicDownloadManager.estimatePeakAdditionalBytes(manifest.files, chunks, emptyMap(), true, old))
|
||||
assertEquals(half, EpicDownloadManager.estimateStagedFilePeak(manifest.files, old))
|
||||
assertEquals(2 * half, EpicDownloadManager.estimateStagedFilePeak(manifest.files, emptyMap()))
|
||||
assertEquals(bytes.size.toLong(), EpicDownloadManager.estimatePeakAdditionalBytes(manifest.files, chunks, emptyMap(), false, old))
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
@@ -12,6 +14,103 @@ import org.robolectric.annotation.Config
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class EpicJsonManifestTest {
|
||||
@Test
|
||||
fun boundedInstallPeakCountsOnlyOneLiveChunkForSequentialChunks() {
|
||||
val first = chunk(1)
|
||||
val second = chunk(2)
|
||||
val file = file(part(1, 0, 100), part(2, 0, 100))
|
||||
val chunks = mapOf(first.guidStr() to first, second.guidStr() to second)
|
||||
|
||||
assertEquals(300L, EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), true))
|
||||
assertEquals(100L, EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sharedCachedChunkIsReclaimedOnlyAfterItsLastPart() {
|
||||
val shared = chunk(1)
|
||||
val files = listOf(file(part(1, 0, 60)), file(part(1, 60, 40)))
|
||||
|
||||
assertEquals(
|
||||
100L,
|
||||
EpicDownloadManager.estimatePeakAdditionalBytes(
|
||||
files, mapOf(shared.guidStr() to shared), mapOf(shared.guidStr() to 100L), true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
200L,
|
||||
EpicDownloadManager.estimatePeakAdditionalBytes(
|
||||
files, mapOf(shared.guidStr() to shared), emptyMap(), true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun distantSharedChunksAreEvictedAndRefetchedWithinTheCacheCeiling() {
|
||||
val first = chunk(1).apply { windowSize = 40 * 1024 * 1024 }
|
||||
val second = chunk(2).apply { windowSize = 40 * 1024 * 1024 }
|
||||
val files = listOf(
|
||||
file(part(1, 0, 40 * 1024 * 1024)),
|
||||
file(part(2, 0, 40 * 1024 * 1024)),
|
||||
file(part(1, 0, 40 * 1024 * 1024)),
|
||||
file(part(2, 0, 40 * 1024 * 1024)),
|
||||
)
|
||||
val chunks = mapOf(first.guidStr() to first, second.guidStr() to second)
|
||||
|
||||
val gamePeak = EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), true)
|
||||
val cachePeak = EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), false)
|
||||
|
||||
assertEquals(200L * 1024 * 1024, gamePeak)
|
||||
assertTrue(cachePeak <= EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 40L * 1024 * 1024)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resumeCacheDropsCorruptAndUnneededEntriesButKeepsVerifiedChunks() {
|
||||
val dir = java.io.File(System.getProperty("user.dir"), "build/epic-cache-test-${System.nanoTime()}")
|
||||
assertTrue(dir.mkdirs())
|
||||
try {
|
||||
val bytes = ByteArray(100) { (it % 251).toByte() }
|
||||
val expectedSha = java.security.MessageDigest.getInstance("SHA-1").digest(bytes)
|
||||
val valid = chunk(1).apply { sha1 = expectedSha }
|
||||
val corrupt = chunk(2).apply { sha1 = expectedSha }
|
||||
java.io.File(dir, valid.guidStr()).writeBytes(bytes)
|
||||
java.io.File(dir, corrupt.guidStr()).writeBytes(ByteArray(100) { 1 })
|
||||
java.io.File(dir, "orphan").writeBytes(bytes)
|
||||
|
||||
val retained = EpicDownloadManager.prepareBoundedCache(dir, listOf(valid, corrupt))
|
||||
|
||||
assertEquals(mapOf(valid.guidStr() to 100L), retained)
|
||||
assertTrue(java.io.File(dir, valid.guidStr()).exists())
|
||||
assertFalse(java.io.File(dir, corrupt.guidStr()).exists())
|
||||
assertFalse(java.io.File(dir, "orphan").exists())
|
||||
} finally {
|
||||
EpicDownloadManager.deleteDir(dir)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun referenceCountsIncludeRepeatedPartsSoCancelledFilesCanBeReplanned() {
|
||||
val pending = listOf(file(part(1, 0, 20), part(1, 20, 20)), file(part(1, 40, 60)))
|
||||
|
||||
assertEquals(3, EpicDownloadManager.chunkReferences(pending)["00000001000000000000000000000000"])
|
||||
}
|
||||
|
||||
private fun chunk(id: Int) = EpicDownloadManager.ChunkInfo().apply {
|
||||
guid = intArrayOf(id, 0, 0, 0)
|
||||
windowSize = 100
|
||||
fileSize = 100
|
||||
}
|
||||
|
||||
private fun part(id: Int, offset: Int, size: Int) = EpicDownloadManager.ChunkPart().apply {
|
||||
guid = intArrayOf(id, 0, 0, 0)
|
||||
this.offset = offset
|
||||
this.size = size
|
||||
}
|
||||
|
||||
private fun file(vararg parts: EpicDownloadManager.ChunkPart) = EpicDownloadManager.FileInfo().apply {
|
||||
filename = "test.bin"
|
||||
this.parts.addAll(parts)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blobNumbersAreDecimalBytesLeastSignificantFirst() {
|
||||
assertEquals(1L, EpicDownloadManager.blobToNum("001000000000"))
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.droiddeck.launcher.stores.gog
|
||||
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowStatFs
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GogResumeSpaceTest {
|
||||
@Test fun remainingWorkRejectsMeasuredZeroButNotUnknownSpace() {
|
||||
val root = File(RuntimeEnvironment.getApplication().filesDir, "gog-zero").apply { mkdirs() }
|
||||
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
|
||||
val files = listOf(GogDownloadManager.DepotFile("missing").apply { totalSize = 4 })
|
||||
val needed = GogDownloadManager.remainingInstallBytes(files, root)
|
||||
assertEquals(4L, needed)
|
||||
assertTrue(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.availableBytes(root)))
|
||||
assertFalse(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.SPACE_UNKNOWN))
|
||||
}
|
||||
|
||||
@Test fun remainingSpaceExcludesVerifiedFilesButIncludesCorruptAndPartialFiles() {
|
||||
val root = File(RuntimeEnvironment.getApplication().filesDir, "gog-resume").apply { mkdirs() }
|
||||
val data = byteArrayOf(1, 2, 3, 4)
|
||||
val hash = MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) }
|
||||
val files = listOf("good", "corrupt", "partial", "missing").map {
|
||||
GogDownloadManager.DepotFile(it).apply { totalSize = 4; md5 = hash }
|
||||
}
|
||||
File(root, "good").writeBytes(data)
|
||||
File(root, "corrupt").writeBytes(ByteArray(4))
|
||||
File(root, "partial").writeBytes(byteArrayOf(1))
|
||||
assertEquals(12L, GogDownloadManager.remainingInstallBytes(files, root))
|
||||
for (file in files) File(root, file.relativePath).writeBytes(data)
|
||||
assertEquals(0L, GogDownloadManager.remainingInstallBytes(files, root))
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ Player controls and observations work over authorized ADB on any build: `state`,
|
||||
`resume`, `wait`, `launch`, `quit`, `focus`, `input`, `ui`, `logs`, `screenshot`, `record`, `displays`,
|
||||
`wake`, and `access`.
|
||||
|
||||
**Setup > Session > Debugging tools** is off by default in every build, including debug builds.
|
||||
**Setup > Diagnostics > Debugging tools** is off by default in every build, including debug builds.
|
||||
It enables `run`, `guest`, `cdp`, all `env` operations, `override`, and `prefs`. The toggle switches
|
||||
directly without a confirmation dialog. The bridge refuses to change it through `ui` or preference
|
||||
writes. The existing preference key, `setting-agent-commands` test tag, JSON command names, and
|
||||
|
||||
+102
-10
@@ -24,15 +24,96 @@ scanned (`StoreInstallRoot.roots`): internal, every card, and the Steam library'
|
||||
installs an earlier build put there. `<Store>` is `GOG`, `Epic` or `Amazon`; `<title>` is the title
|
||||
with unsafe characters dropped, at most 60 characters (`StoreInstallRoot.folderName`), chosen once;
|
||||
a rerun (repair, update) lands on the folder whose sidecar carries the game's id, wherever it is.
|
||||
An Epic install on a card keeps its in-flight chunks in `cacheDir/stores/epic/<id>/`: the
|
||||
`chunkCacheDir` of both native calls (`EpicNative.run` fetches into it, `EpicNative.assemble`
|
||||
writes the files from it and drops each chunk after its last use, then the folder), and of the
|
||||
manager's own loops when the engine is not there; `""` keeps the cache beside the game, as an
|
||||
internal install has it. The scratch folder is removed on cancel-with-delete and on uninstall.
|
||||
The cache holds whole ~1 MiB chunk windows, shared with files this device does not install, so it
|
||||
is often larger than the game (Metalstorm: 9.1 GB of chunks for 4.4 GB of files); the free-space
|
||||
check, made after the delta pass, counts the missing chunks and the missing files on their own
|
||||
volumes. A successful run removes the cache.
|
||||
An Epic install on a card keeps its in-flight chunks in `cacheDir/stores/epic/<id>/`;
|
||||
`""` keeps the cache beside the game, as an internal install has it. The scratch folder is
|
||||
removed on cancel-with-delete and on uninstall.
|
||||
|
||||
Preflight resolves an existing game's folder before selecting its target root, so a resume or
|
||||
repair on a card checks and remembers that volume rather than internal storage. Fresh GOG and
|
||||
Amazon installs can reject insufficient catalog-size space immediately; existing installs defer
|
||||
to manifest checks of the files still needing work (GOG MD5, Amazon SHA-256 where supplied).
|
||||
Free-space display probes the nearest existing ancestor without creating the target folder; if
|
||||
the probe cannot determine space, it reports **Free space unknown** rather than blocking an install.
|
||||
`StoreInstallRoot` uses `-1` for unknown and preserves a measured `StatFs` zero as **0 B free**.
|
||||
Fresh GOG/Amazon preflight and all three Java backend space checks reject known zero when bytes
|
||||
remain. The read-only probe walks existing ancestors without creating directories; a failed
|
||||
`StatFs` probe can use a positive `File.usableSpace` fallback, but that API's ambiguous zero is
|
||||
unknown, not a measurement of a full disk.
|
||||
Preflight failures remain failed Downloads rows with Clear and Retry. Retry reruns preflight
|
||||
outside the worker lifecycle and then enqueues the real backend; it never occupies a queue slot
|
||||
with a placeholder job. Failures are kept in the Downloads UI, notification and logs rather than
|
||||
duplicated as transient failure toasts. Active queue persistence and ordinary backend pause/retry
|
||||
are unchanged.
|
||||
|
||||
Epic installs have three writers, all with the same per-file safety rules (below):
|
||||
|
||||
- **Adaptive (default when `libdroiddeckstores.so` loads)** - `EpicNative.stream`,
|
||||
`epic/stream.rs`. The chunks go through the shared fetch core in the order their files need
|
||||
them, with its full adaptivity (window ramp, per-host caps, in-flight byte budget, retries,
|
||||
host rotation, stall handoff). A chunk only one file part uses is verified and written straight
|
||||
into that file's staging file at the part's offset, in whatever order it arrives; no cache. A
|
||||
chunk several parts use is written into every part whose file the download has reached and kept,
|
||||
decompressed, in the cache until its last part is written. The cache has a byte budget; the plan
|
||||
simulates the install in file order and, when the budget would be exceeded, drops the cached
|
||||
chunk needed furthest ahead and downloads it again later. Files are opened only once the
|
||||
download reaches them, so the set of half-written files stays within the fetch window. All writes
|
||||
happen in the fetch core's process pool, whose completion frees the in-flight byte budget: a slow
|
||||
card throttles the download instead of growing memory. Each file's SHA-1 is computed as its
|
||||
parts are written (parts that arrived out of order are read back once the bytes before them are
|
||||
in). The run logs `stream-plan` (direct vs shared chunks, planned refetches, budget) and
|
||||
`stream-summary mode=adaptive` (peak cache, peak staging, refetches, bytes written from the
|
||||
download vs from the cache, average MB/s).
|
||||
- **Bounded Java** - when the library does not load or link, when the engine refuses the plan,
|
||||
or when the adaptive space plan does not fit while this one might. It fetches one chunk at a
|
||||
time, verifies it, and writes the required parts into the current game file. Chunks are deleted
|
||||
after their last use; reusable chunks are retained up to 64 MiB, with at most one additional
|
||||
incoming chunk before eviction. Evicted shared chunks may be downloaded again. It logs
|
||||
`epic: summary mode=java-bounded`.
|
||||
- **Batch** - the earlier native design, kept for A/B benchmarks: every chunk fetched into the
|
||||
cache in parallel, then the files assembled from it (`EpicNative.run` + `EpicNative.assemble`).
|
||||
It needs the cache and the files at once (about twice the game) and checks exactly that before
|
||||
starting; it writes files in place, so an existing install is marked `updating` before assembly.
|
||||
It logs `epic: summary mode=batch`.
|
||||
|
||||
The writer is chosen by the hidden `storesEpicMode` string in the `session` preferences:
|
||||
`adaptive` (default), `batch` or `java`. There is no UI for it; set it on a test device to compare
|
||||
the modes on the same game.
|
||||
|
||||
The adaptive space plan (`EpicDownloadManager.planAdaptiveSpace`, unit-tested in
|
||||
`EpicAdaptivePlanTest`) checks each volume for what lands on it. The game volume: the sequential
|
||||
staged-file peak (remaining file bytes, each replaced file's old copy credited only after its
|
||||
swap), plus, for an update, the largest old file plus 256 MiB for files finishing out of order
|
||||
within the fetch window, plus the cache when it is beside the game. The cache volume: the budget
|
||||
plus 64 MiB of chunks in transit. The budget is half the cache volume's free space after those
|
||||
needs, at most 1 GiB (256 MiB when free space is unknown; 0 is allowed and means every reuse is a
|
||||
refetch). On a card install the cache stays on internal scratch unless internal storage cannot
|
||||
hold at least 64 MiB of it; then the cache goes beside the game (still released chunk by chunk)
|
||||
instead of failing. A plan that does not fit names the short storage and the shortfall in the log
|
||||
and hands over to the bounded writer, whose own checks decide. Running out of space in the middle
|
||||
of an adaptive run is not destructive: a failed write fails the run, unfinished staging files are
|
||||
removed, the old files stay.
|
||||
|
||||
The Epic download bar, measured rate and ETA (adaptive and bounded) count pending file bytes written, not unique
|
||||
compressed chunks fetched. Shared chunks therefore cannot complete the bar before later files
|
||||
are written, and an evicted chunk's refetch is reflected in the time spent doing that work.
|
||||
Streaming stays in the Download stage until all files are written and verified, then enters
|
||||
Install for registration; it does not bounce between stages for each file.
|
||||
|
||||
The space check follows the manifest delta pass and simulates file writes, chunk fetches,
|
||||
and evictions, rather than adding the entire cache to the entire game. Each file is written to a
|
||||
unique sibling staging file on its output volume (never the literal `<filename>.part`, which can
|
||||
be a legitimate manifest file), size/hash verified, synced and atomically renamed over its output.
|
||||
The old file remains until that swap succeeds. The planner credits its bytes only after that
|
||||
file's complete staging write, not by subtracting all old outputs up front. Both volume checks
|
||||
must accept this safe staging peak; insufficient space is rejected explicitly, with no destructive
|
||||
delete-first fallback. An unsupported/failed atomic rename fails the install and retains the old
|
||||
destination. Completed files and
|
||||
verified cached chunks are accounted for on resume. On a card, game and cache requirements
|
||||
are checked separately. File SHA-1 hashes are checked where supplied by the manifest; failed
|
||||
or cancelled staging files are removed without deleting old outputs. A successful run removes the
|
||||
cache. A resume within a large incomplete file restarts that file, not its individual parts.
|
||||
Abrupt process termination can leave a unique staging file; unlike normal failure/cancellation,
|
||||
its cleanup is not guaranteed, and the next space probe includes its occupied bytes.
|
||||
|
||||
## The sidecar
|
||||
|
||||
@@ -59,7 +140,18 @@ store root whose sidecar says `installing`, or that has no sidecar at all, is an
|
||||
install: `AddedGames.scan` leaves it out (it is neither a game nor a Custom folder), and the Stores
|
||||
card and page offer **Resume install**, which reuses that folder - and an Epic `.chunks` beside it -
|
||||
instead of starting a fresh one (`StoreInstallRoot.existingFolder`). A finished install being
|
||||
repaired keeps its finished sidecar. The launcher and the finished sidecar are written before the
|
||||
repaired keeps its finished sidecar until Epic reaches the first verified file swap. Immediately
|
||||
before that swap Epic atomically changes the record to `"state": "updating"`, preserves launch
|
||||
choices and identifiers, and clears `installVersion`. Network/hash failures or cancellation before
|
||||
that point leave the old installed record and files intact. A later failure can leave a mixture of
|
||||
verified new files and untouched old files: replacement is atomic **per file**, not a transactional
|
||||
whole-game update or rollback. The updating folder is excluded from installed scans and offered
|
||||
for resume. Cancellation with deletion clears caches but retains that folder and its verified
|
||||
swaps; retry preserves the updating record's metadata. If marking or swapping fails, no destructive
|
||||
fallback is attempted (the conservative updating state can remain even when a swap fails).
|
||||
Completion writes the installed record with the new version only after all selected files succeed.
|
||||
An already registered live Steam shortcut is not revoked at each file swap; do not launch an
|
||||
in-progress update. The launcher and the finished sidecar are written before the
|
||||
art and the Steam registration; a failure writing them fails the download with its message.
|
||||
|
||||
`StoreGameSidecar.parse` refuses anything whose `exe` or `launcher` would point outside the folder.
|
||||
|
||||
+18
-2
@@ -1,7 +1,23 @@
|
||||
# Experimental Quest 3/3S support
|
||||
# Experimental Quest 2/3/3S support
|
||||
|
||||
Quest 3/3S runs DroidDeck as a 2D panel. This does not add immersive VR or
|
||||
OpenXR support. Quest 2 is outside the bundled Adreno 7xx driver path.
|
||||
OpenXR support. Quest 2 has a separate experimental Adreno 6xx driver path.
|
||||
|
||||
Quest 2 selects `turnip26.3.0-quest2`, a pinned Banners-Turnip A6xx/A7xx build
|
||||
with the same GPUOBJ adapter. It does not select the Quest 3 A7xx binary.
|
||||
The first Quest 2 launch applies manual driver selection and the SurfaceControl
|
||||
workaround, even if `questDefaultsV1` exists from an earlier install. Later user
|
||||
choices are retained. The separate `turnip26.3.0-a6xx` bundle provides a plain
|
||||
Adreno 6xx offline fallback for other devices; their driver Auto behavior remains.
|
||||
Neither family-wide hardware coverage nor Quest 2 operation has been verified.
|
||||
|
||||
The A6xx input URL and SHA-256 are pinned in `tools/quest/build-driver.py`.
|
||||
Both A6xx bundles are prepared by the existing local/CI wrapper build step and
|
||||
covered by runtime-input attestation. Quest 3/3S retains its original driver.
|
||||
Early installation and compositor breadcrumbs are written to `driver-setup.txt`
|
||||
in private files and, when available, the app's external files directory. They
|
||||
do not require a Steam session. The existing Quest Java crash file now also
|
||||
applies to Quest 2; native crashes still require Android logcat.
|
||||
|
||||
Install the standard DroidDeck APK on Quest 3/3S. Device detection on the
|
||||
first launch selects manual drivers, the bundled
|
||||
|
||||
+1
-1
@@ -300,7 +300,7 @@ def start_session(adb: str, serial: str, request: dict) -> dict:
|
||||
def require_commands(adb: str, serial: str) -> dict:
|
||||
access = checked(provider_call(adb, serial, "access"), "ACCESS_FAILED")
|
||||
if access.get("commands") is not True:
|
||||
raise ControlError("Debugging tools are off: turn on Setup > Session > Debugging tools on the device",
|
||||
raise ControlError("Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device",
|
||||
"AGENT_COMMANDS_DISABLED")
|
||||
return access
|
||||
|
||||
|
||||
@@ -44,6 +44,13 @@ library list, before anything is published.
|
||||
read the window's attributes first, it kept the window as override-redirect and left it out of
|
||||
`GAMESCOPE_FOCUSABLE_WINDOWS`, so the client kept its loading screen over the running game
|
||||
(Skyrim SE, A Plague Tale: Innocence, on the games' own Xwayland). MapNotify now refreshes the flag.
|
||||
- `0115-limiter-paces-per-window.patch` - this app: on a fixed-refresh output the frame limiter
|
||||
(Steam's Frame Limit) let a capped window's frames out only on every Nth refresh of a global grid,
|
||||
so a frame finished just after its slot waited a whole extra slot. At 30 on 60 Hz one picture was
|
||||
held for three or four refreshes - "small stops and ladders" with frame generation - where a game's
|
||||
own limiter slips such a frame by one refresh. The fixed-refresh branch now paces each window by
|
||||
time, as the VRR branch already did: its next frame goes out on the first refresh a capped interval
|
||||
after its last one, with half a refresh of tolerance so an on-time window keeps every Nth refresh.
|
||||
|
||||
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
|
||||
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
|
||||
@@ -0,0 +1,27 @@
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index 5b0e300..b9b07ca 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -6875,10 +6875,19 @@ static bool steamcompmgr_should_vblank_window( bool bShouldLimitFPS, uint64_t vb
|
||||
{
|
||||
if ( g_nSteamCompMgrTargetFPS && bShouldLimitFPS && nRefreshHz > nTargetFPS )
|
||||
{
|
||||
- int nVblankDivisor = nRefreshHz / nTargetFPS;
|
||||
+ if ( w && now )
|
||||
+ {
|
||||
+ uint64_t schedule = w->last_commit_first_latch_time + g_SteamCompMgrLimitedAppRefreshCycle;
|
||||
+ if ( now + g_SteamCompMgrAppRefreshCycle / 2 < schedule )
|
||||
+ bSendCallback = false;
|
||||
+ }
|
||||
+ else
|
||||
+ {
|
||||
+ int nVblankDivisor = nRefreshHz / nTargetFPS;
|
||||
|
||||
- if ( vblank_idx % nVblankDivisor != 0 )
|
||||
- bSendCallback = false;
|
||||
+ if ( vblank_idx % nVblankDivisor != 0 )
|
||||
+ bSendCallback = false;
|
||||
+ }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p9
|
||||
GAMESCOPE_SHA256=7123a37bdbcd0d76d4bd1d7490e5d2017221e036395fdd48c1e92458594ca769
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p10
|
||||
GAMESCOPE_SHA256=e8e2433ae618458135ec271a30af7e80b282ff41f9931286e9bbad614838eca0
|
||||
@@ -601,8 +601,14 @@ class Installer:
|
||||
|
||||
def put(self, source, rel):
|
||||
target = self.out / rel
|
||||
# A DuplicateFile row can name the file's own folder and name (the .NET host packages copy
|
||||
# dotnet.exe onto itself); Windows Installer takes that as nothing to do. Found and diagnosed
|
||||
# by whatsupbros on the DroidDeck Discord.
|
||||
if target.exists() and Path(source).samefile(target):
|
||||
return False
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, target)
|
||||
return True
|
||||
|
||||
def install_files(self, unpacked):
|
||||
assemblies = self.assemblies()
|
||||
@@ -664,8 +670,7 @@ class Installer:
|
||||
folder = self.directory(row["DestFolder"]) if row.get("DestFolder") else self.files[row["File_"]].rsplit("/", 1)[0]
|
||||
name = long_name(row.get("DestName", "")) or self.files[row["File_"]].rsplit("/", 1)[1]
|
||||
source = self.out / self.files[row["File_"]]
|
||||
if folder and source.is_file() and "/" not in name:
|
||||
self.put(source, folder + "/" + name)
|
||||
if folder and source.is_file() and "/" not in name and self.put(source, folder + "/" + name):
|
||||
self.counts["files"] += 1
|
||||
if missing:
|
||||
self.notes.append("%d file(s) were not in the package's cabinets" % missing)
|
||||
|
||||
@@ -489,6 +489,60 @@ case $mode in
|
||||
done
|
||||
) &
|
||||
fi
|
||||
# zRAM compression (BL_ZRAM): 20 s into a game the client and its web helpers page their memory
|
||||
# out to the device's zram (libblsession zram.c), again every 5 minutes, and read it back once
|
||||
# the game has exited. A game is running while Steam's reaper is.
|
||||
if [ "${BL_ZRAM:-0}" = 1 ]; then
|
||||
printf 0 > /tmp/.bl-zram
|
||||
step "zRAM compression: on"
|
||||
(
|
||||
bl_zram_scan() {
|
||||
_bl_game=0 _bl_pids=()
|
||||
for _d in /proc/[0-9]*; do
|
||||
IFS= read -r -d '' _c 2>/dev/null < "$_d/cmdline" || continue
|
||||
case ${_c##*/} in
|
||||
reaper) _bl_game=1 ;;
|
||||
steam|steamwebhelper) _bl_pids+=("${_d#/proc/}") ;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
bl_zram_usage() {
|
||||
local _p _k _v _u _rss=0 _swap=0
|
||||
for _p in "${_bl_pids[@]}"; do
|
||||
while read -r _k _v _u; do
|
||||
case $_k in VmRSS:) _rss=$((_rss + _v)) ;; VmSwap:) _swap=$((_swap + _v)) ;; esac
|
||||
done 2>/dev/null < "/proc/$_p/status"
|
||||
done
|
||||
echo "${#_bl_pids[@]} processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
|
||||
}
|
||||
bl_zram_send() {
|
||||
step "zRAM: $2 ($(bl_zram_usage))"
|
||||
printf '%s' "$1" > /tmp/.bl-zram
|
||||
[ "${#_bl_pids[@]}" = 0 ] || kill -URG "${_bl_pids[@]}" 2>/dev/null
|
||||
nap 5
|
||||
bl_zram_scan
|
||||
step "zRAM: done ($(bl_zram_usage))"
|
||||
}
|
||||
_bl_since=-1 _bl_packed=-1
|
||||
while kill -0 $$ 2>/dev/null; do
|
||||
bl_zram_scan
|
||||
if [ "$_bl_game" = 1 ]; then
|
||||
[ "$_bl_since" -ge 0 ] || _bl_since=$SECONDS
|
||||
if [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] &&
|
||||
{ [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 300 ]; }; then
|
||||
bl_zram_send 1 "compressing the client"
|
||||
_bl_packed=$SECONDS
|
||||
fi
|
||||
elif [ "$_bl_since" -ge 0 ]; then
|
||||
[ "$_bl_packed" -lt 0 ] || bl_zram_send 0 "game closed, reading the client back"
|
||||
_bl_since=-1 _bl_packed=-1
|
||||
fi
|
||||
nap 5
|
||||
done
|
||||
) &
|
||||
else
|
||||
rm -f /tmp/.bl-zram
|
||||
fi
|
||||
# Rockstar's launcher keeps drawing its hidden web interface for as long as a game of theirs
|
||||
# runs; droiddeck-launcher-cores holds it on one slow core while it is out of sight, from
|
||||
# gamescope's focus as the agent publishes it. BL_LAUNCHER_CORES=0 leaves launchers alone.
|
||||
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user