Merge remote-tracking branch 'upstream/main' into feat/itch-browse

This commit is contained in:
FX192 committed 2026-10-24 12:46:26 +03:00
commit 7e87cdacb5
77 files changed
+2048 -303

No files matched your search

+1
View File
@@ -34,6 +34,7 @@
android:localeConfig="@xml/locales_config"
android:networkSecurityConfig="@xml/network_security_config"
android:allowBackup="false"
android:allowAudioPlaybackCapture="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
@@ -8,6 +8,7 @@ add_library(droiddeckwayland SHARED
src/sc_layer.c
src/ahb_swapchain.c
src/waylandcomp_jni.c
src/gpu_clock_pin.c
src/droiddeck_ext.c
src/wl_dmabuf.c
src/wl_clipboard.c
@@ -808,10 +808,14 @@ static uint32_t nominal_refresh_ns(void) {
}
static int64_t presented_ns(int64_t render_ns) {
if (!g_tick_vsync_ns || render_ns - g_last_vsync_ns > (int64_t)nominal_refresh_ns() ||
render_ns < g_tick_vsync_ns)
int64_t tick = g_tick_vsync_ns;
int64_t refresh = (int64_t)nominal_refresh_ns();
if (!tick || render_ns - g_last_vsync_ns > refresh)
return render_ns;
return g_tick_vsync_ns;
int64_t delta = render_ns - tick;
if (delta > refresh || -delta > refresh)
return render_ns;
return tick;
}
static void feedback_present_all(struct wl_list *list, int64_t t) {
@@ -0,0 +1,170 @@
#include "gpu_clock_pin.h"
#include <android/log.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdint.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include "../../adrenotools/src/hook/kgsl.h"
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_t worker;
static bool joinable;
static atomic_bool running;
struct pin {
int fd;
unsigned int context;
unsigned int memory;
unsigned int timestamp;
unsigned long gpuaddr;
uint32_t nop;
void *commands;
size_t size;
};
static struct pin pin = { .fd = -1 };
static void release_pin(void) {
if (pin.context) {
struct kgsl_drawctxt_destroy destroy = { .drawctxt_id = pin.context };
ioctl(pin.fd, IOCTL_KGSL_DRAWCTXT_DESTROY, &destroy);
}
if (pin.commands) munmap(pin.commands, pin.size);
if (pin.memory) {
struct kgsl_gpumem_free_id free_memory = { .id = pin.memory };
ioctl(pin.fd, IOCTL_KGSL_GPUMEM_FREE_ID, &free_memory);
}
if (pin.fd >= 0) close(pin.fd);
pin = (struct pin) { .fd = -1 };
}
static bool submit_pin(void) {
struct kgsl_command_object object = {
.gpuaddr = pin.gpuaddr,
.size = 2 * sizeof(uint32_t),
.flags = KGSL_CMDLIST_IB,
.id = pin.memory,
};
struct kgsl_gpu_command command = {
.flags = KGSL_CMDBATCH_PWR_CONSTRAINT,
.cmdlist = (uintptr_t)&object,
.cmdsize = sizeof(object),
.numcmds = 1,
.context_id = pin.context,
};
if (ioctl(pin.fd, IOCTL_KGSL_GPU_COMMAND, &command) < 0) return false;
pin.timestamp = command.timestamp;
return true;
}
static bool prepare_pin(void) {
pin.fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
if (pin.fd < 0) return false;
struct kgsl_devinfo info = {0};
struct kgsl_device_getproperty device_info = {
.type = KGSL_PROP_DEVICE_INFO, .value = &info, .sizebytes = sizeof(info),
};
if (ioctl(pin.fd, IOCTL_KGSL_DEVICE_GETPROPERTY, &device_info) < 0) return false;
unsigned int core = info.chip_id >> 24;
if (!core) core = info.gpu_id / 100;
if (core < 3) { errno = ENODEV; return false; }
pin.nop = core >= 5 ? 0x70100001 : 0xc0001000;
struct kgsl_drawctxt_create context = {
.flags = KGSL_CONTEXT_NO_GMEM_ALLOC | KGSL_CONTEXT_PREAMBLE | KGSL_CONTEXT_PWR_CONSTRAINT,
};
if (ioctl(pin.fd, IOCTL_KGSL_DRAWCTXT_CREATE, &context) < 0) return false;
pin.context = context.drawctxt_id;
struct kgsl_device_constraint_pwrlevel level = { .level = KGSL_CONSTRAINT_PWR_MAX };
struct kgsl_device_constraint constraint = {
.type = KGSL_CONSTRAINT_PWRLEVEL,
.context_id = pin.context,
.data = &level,
.size = sizeof(level),
};
struct kgsl_device_getproperty property = {
.type = KGSL_PROP_PWR_CONSTRAINT,
.value = &constraint,
.sizebytes = sizeof(constraint),
};
if (ioctl(pin.fd, IOCTL_KGSL_SETPROPERTY, &property) < 0) return false;
struct kgsl_gpumem_alloc_id memory = { .size = 4096 };
if (ioctl(pin.fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &memory) < 0) return false;
pin.memory = memory.id;
pin.gpuaddr = memory.gpuaddr;
pin.size = memory.mmapsize;
void *commands = mmap(NULL, pin.size, PROT_READ | PROT_WRITE, MAP_SHARED, pin.fd,
(off_t)pin.memory << 12);
if (commands == MAP_FAILED) return false;
pin.commands = commands;
// A3xx/A4xx use type-3 CP_NOP; newer cores use type-7 with zero odd-parity bits.
uint32_t *words = commands;
words[0] = pin.nop;
words[1] = 0;
struct kgsl_gpumem_sync_cache sync = { .id = pin.memory, .op = KGSL_GPUMEM_CACHE_CLEAN };
if (ioctl(pin.fd, IOCTL_KGSL_GPUMEM_SYNC_CACHE, &sync) < 0) return false;
return submit_pin();
}
static void *hold_pin(void *unused) {
(void)unused;
while (atomic_load(&running)) {
struct kgsl_device_waittimestamp_ctxtid wait = {
.context_id = pin.context,
.timestamp = pin.timestamp,
.timeout = 100,
};
if (ioctl(pin.fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait) < 0) {
if (errno == EINTR || errno == ETIMEDOUT) continue;
break;
}
// Constraints expire after idle_timer (normally 80 ms); renew with a NOP, keeping devfreq alive.
usleep(25000);
if (atomic_load(&running) && !submit_pin()) break;
}
if (atomic_exchange(&running, false))
__android_log_print(ANDROID_LOG_WARN, "GpuClockPin", "constraint stopped: %s", strerror(errno));
release_pin();
return NULL;
}
bool gpu_clock_pin_set(bool on) {
pthread_mutex_lock(&lock);
if (joinable) {
if (on && atomic_load(&running)) {
pthread_mutex_unlock(&lock);
return true;
}
atomic_store(&running, false);
pthread_join(worker, NULL);
joinable = false;
}
bool ok = true;
if (on) {
ok = prepare_pin();
if (ok) {
atomic_store(&running, true);
int error = pthread_create(&worker, NULL, hold_pin, NULL);
if (error) {
atomic_store(&running, false);
errno = error;
ok = false;
} else {
joinable = true;
}
}
if (!ok) {
int error = errno;
release_pin();
errno = error;
}
}
pthread_mutex_unlock(&lock);
return ok;
}
@@ -0,0 +1,5 @@
#pragma once
#include <stdbool.h>
bool gpu_clock_pin_set(bool on);
@@ -16,6 +16,7 @@
#include "effects_chain.h"
#include "cardboard.h"
#include "droiddeck_color.h"
#include "gpu_clock_pin.h"
extern int droiddeck_wayland_run(void);
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
@@ -634,8 +635,14 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE
extern void adrenotools_set_turbo(bool turbo);
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
(void)env; (void)clazz;
adrenotools_set_turbo(on == JNI_TRUE);
(void)clazz;
if (!gpu_clock_pin_set(on == JNI_TRUE)) {
int saved_errno = errno;
jclass error = (*env)->FindClass(env, "java/lang/IllegalStateException");
if (error) (*env)->ThrowNew(env, error, strerror(saved_errno));
}
// Clear a legacy global pin when recovering its marker after an app upgrade or crash.
if (on != JNI_TRUE) adrenotools_set_turbo(false);
}
JNIEXPORT jint JNICALL
@@ -163,7 +163,7 @@ class FrontEndActivity : ComponentActivity() {
private var directAudio by mutableStateOf(false)
private var picturePosition by mutableStateOf("center")
private var stretch16x9 by mutableStateOf(false)
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherFullscreen by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
@@ -544,12 +544,12 @@ class FrontEndActivity : ComponentActivity() {
}
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.putExtra(SessionActivity.EXTRA_STEAMVR, steamVr)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.returnTo(returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
return true
}
return startSession(Intent(this, SessionActivity::class.java)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.returnTo(returnHome)
.apply {
if (game.gameIdString == com.droiddeck.launcher.gpu.SteamVr.APP_ID) {
putExtra(SessionActivity.EXTRA_STEAMVR, true)
@@ -560,6 +560,12 @@ class FrontEndActivity : ComponentActivity() {
}, steamSession = true)
}
private fun Intent.returnTo(returnHome: Boolean): Intent {
val task = taskId
return putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
}
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
val app = applicationContext
Thread({
@@ -573,7 +579,7 @@ class FrontEndActivity : ComponentActivity() {
}
com.droiddeck.launcher.session.NoSteamLaunch.remember(command)
val next = Intent(this, SessionActivity::class.java)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.returnTo(returnHome)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, command.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray())
@@ -582,7 +588,7 @@ class FrontEndActivity : ComponentActivity() {
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args ->
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.returnTo(returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
else -> pendingSwitch = next
}
@@ -1926,6 +1926,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.relaunch?.let { next ->
SessionState.relaunch = null
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
setIntent(next)
recreate()
return@runOnUiThread
@@ -3027,6 +3028,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return
}
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
if (!intent.hasExtra(EXTRA_LINK_TASK)) intent.putExtra(EXTRA_LINK_TASK, this.intent.getIntExtra(EXTRA_LINK_TASK, -1))
setIntent(intent)
if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
SessionState.steamVr = true
@@ -3549,17 +3551,33 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return
}
super.finish()
if (!closeAtOnce && intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) {
com.droiddeck.launcher.ui.QuitFlood.take()
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
closeLinkTasks()
if (!isTaskRoot) moveTaskToBack(true)
super.finishAndRemoveTask()
} else super.finish()
if (quitFlooded) overridePendingTransition(0, 0)
else overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
}
private fun closeLinkTasks() {
val linkTask = intent.getIntExtra(EXTRA_LINK_TASK, -1)
if (linkTask == -1) return
val tasks = runCatching { getSystemService(android.app.ActivityManager::class.java)?.appTasks }.getOrNull().orEmpty()
for (task in tasks) {
runCatching {
val info = task.taskInfo
@Suppress("DEPRECATION")
val id = if (android.os.Build.VERSION.SDK_INT >= 29) info.taskId else info.persistentId
val base = info.baseIntent
if (id == linkTask && base.component?.className == FrontEndActivity::class.java.name &&
com.droiddeck.launcher.frontend.GameLaunchIntent.accepts(base.action)) task.finishAndRemoveTask()
}
}
}
private fun completeLeave() {
if (isFinishing) return
val signal = com.droiddeck.launcher.ui.Themes.current(this).signal
@@ -3571,6 +3589,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
companion object {
const val EXTRA_RETURN_HOME = "returnHome"
const val EXTRA_LINK_TASK = "linkTask"
const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_REPAIR_RUNTIME = "repairRuntime"
private const val LEAVE_TIMEOUT_MS = 1_500L
@@ -1,27 +0,0 @@
package com.droiddeck.launcher.core
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SocNames
object CpuAllocationDefaults {
data class Allocation(val client: String, val game: String)
val device: Allocation? by lazy {
forDevice(SocNames.model(), GpuInfo.systemProperty("ro.board.platform"),
CpuCores.all.associateWith(CpuCores::maxGhz))
}
fun forDevice(model: String, platform: String, frequencies: Map<Int, Double?>): Allocation? {
val chip = model.trim().uppercase().substringBefore('-')
val gen2 = chip in setOf("SM8550", "QCS8550") ||
(chip.isEmpty() && platform.trim().equals("kalama", ignoreCase = true))
if (!gen2 || frequencies.size != 8 || frequencies.keys.any { it < 0 } ||
frequencies.values.any { it == null || !it.isFinite() || it <= 0.0 }) return null
val clusters = frequencies.entries.groupBy { it.value }.toSortedMap(compareBy { it ?: 0.0 }).values.toList()
if (clusters.map { it.size } != listOf(3, 4, 1)) return null
return Allocation(
client = CpuCores.format(clusters[2].map { it.key }.toSet()),
game = CpuCores.format(clusters[1].map { it.key }.toSet()),
)
}
}
@@ -152,13 +152,17 @@ object DeviceReport {
k("RAM total", FileUtils.sizeToString(mi.totalMem))
k("RAM available", FileUtils.sizeToString(mi.availMem))
}
runCatching {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) k("Thermal status", thermalStatusName(pm.currentThermalStatus))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
k("Thermal headroom (10 s)", pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) })
val pm = runCatching { context.getSystemService(Context.POWER_SERVICE) as? PowerManager }.getOrNull()
if (pm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
k("Thermal status", runCatching { thermalStatusName(pm.currentThermalStatus) }.getOrNull())
}
k("Power saver", pm.isPowerSaveMode)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
k("Thermal headroom (10 s)", runCatching {
pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) }
}.getOrNull())
}
k("Power saver", runCatching { pm.isPowerSaveMode }.getOrNull())
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val rate = runCatching { context.getSystemService(PerformanceHintManager::class.java)?.preferredUpdateRateNanos }.getOrNull()
@@ -387,11 +387,17 @@ object AddedGames {
}
}
private class LoginUser(val id: String, val mostRecent: Boolean, val autoLogin: Boolean, val timestamp: Long)
internal fun accountConfig(root: File): File? {
val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("")
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users)
.lastOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
val account = recent?.groupValues?.get(1)?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users).map {
val body = it.groupValues[2]
LoginUser(it.groupValues[1], Regex(""""MostRecent"\s*"1"""").containsMatchIn(body), Regex(""""AutoLogin"\s*"1"""").containsMatchIn(body),
Regex(""""timestamp"\s*"(\d+)"""").find(body)?.groupValues?.get(1)?.toLongOrNull() ?: 0L)
}.filter { it.mostRecent || it.autoLogin || it.timestamp > 0 }.toList().asReversed()
.maxWithOrNull(compareBy<LoginUser>({ it.mostRecent }, { it.autoLogin }, { it.timestamp }))
val account = recent?.id?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull()
return account?.let { File(root, "userdata/$it/config") }
}
@@ -46,12 +46,14 @@ object Library {
1054830,
1070560,
1113280,
1161040,
1245040,
1391110,
1420170,
1493710,
1580130,
1628350,
1826330,
1887720,
2180100,
228980,
@@ -301,15 +301,18 @@ class LinuxNetworkLinkComponent(
}
}
private fun seededMac(): String {
val id = Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) ?: "bannerlator"
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
val b0 = (bytes[0].toInt() and 0xfc) or 0x02
return listOf(b0, bytes[1].toInt(), bytes[2].toInt(), bytes[3].toInt(), bytes[4].toInt(), bytes[5].toInt())
.joinToString(":") { "%02x".format(it and 0xff) }
}
private fun seededMac(): String =
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
companion object {
internal fun seededMac(readId: () -> String?): String {
val id = runCatching(readId).getOrNull() ?: "bannerlator"
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
val b0 = (bytes[0].toInt() and 0xfc) or 0x02
return listOf(b0, bytes[1].toInt(), bytes[2].toInt(), bytes[3].toInt(), bytes[4].toInt(), bytes[5].toInt())
.joinToString(":") { "%02x".format(it and 0xff) }
}
private const val TAG = "LinuxNetworkLink"
private const val LINK_FILE = "etc/droiddeck-net"
private const val LINK_INDEX = 2
@@ -110,6 +110,11 @@ public final class LinuxRuntime {
File root = rootDir(context);
List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds);
if (sessionRoot != null) lastBinds = binds;
return commandWithBinds(context, root, binds, guestCommand);
}
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
List<String> guestCommand) {
List<String> cmd = prootPrefix(context, root, "/root");
for (String spec : binds) bind(cmd, spec);
cmd.addAll(guestCommand);
@@ -51,7 +51,7 @@ object BootMovie {
SessionPrefs.setBootMovieApplyNext(context, true)
BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}")
// Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later.
SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
fun customName(context: Context): String? =
@@ -167,10 +167,12 @@ object BootMovie {
* that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed.
*/
fun syncFromSteam(context: Context): Boolean {
val path = SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context)) ?: return false
if (path == SessionPrefs.bootMovieSteamSeen(context)) return false
SessionPrefs.setBootMovieSteamSeen(context, path)
if (path == SessionFiles.BOOT_MOVIE_PATH) return false
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
val seen = SessionPrefs.bootMovieSteamSeen(context)
if (named == seen) return false
SessionPrefs.setBootMovieSteamSeen(context, named)
if (named == SessionFiles.BOOT_MOVIE_PATH || (named.isEmpty() && seen == null)) return false
val path = named.ifEmpty { "/movies/steam_os_startup.webm" }
val prefix = "/uioverrides/movies/"
// The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder.
val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else {
@@ -79,8 +79,9 @@ object BootMovieLibrary {
return customMovieDirs(context).map { File(it, name) }.firstOrNull { it.isFile && it.length() > 0L }
}
private fun isMovie(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) &&
file.name !in STAGED && !file.name.startsWith(".")
private fun isMovie(file: File) = isWebm(file) && file.name !in STAGED
private fun isWebm(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) && !file.name.startsWith(".")
private fun readMeta(context: Context): JSONObject =
runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject())
@@ -136,7 +137,7 @@ object BootMovieLibrary {
}
val bought = HashMap<String, String>()
for (root in steamRoots(context)) {
File(root, "steamui/movies").listFiles { f -> isMovie(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
File(root, "steamui/movies").listFiles { f -> isWebm(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
.sortedBy { it.name.lowercase() }.forEach { steam.putIfAbsent(STEAM_PREFIX + "/movies/" + it.name, it) }
val scan = pointShopMovies(root)
bought.putAll(scan.titles)
@@ -144,8 +145,8 @@ object BootMovieLibrary {
}
val seen = HashSet<String>()
for ((id, file) in steam) {
if (file.name in STAGED || !seen.add(file.canonicalPath)) continue
val native = file.nameWithoutExtension.lowercase() in NATIVE
if ((file.name in STAGED && !native) || !seen.add(file.canonicalPath)) continue
// Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it.
val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension
out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false))
@@ -153,8 +154,11 @@ object BootMovieLibrary {
return out
}
/** The three startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf("deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup")
/** The four startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf(
"deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup",
"steam_os_startup" to "SteamOS startup",
)
private val skippedFolders = setOf("uioverrides", "steamapps", "librarycache", "httpcache", "logs", "compatdata", "shadercache")
@@ -721,13 +721,19 @@ object ComponentsManager {
class StoredOriginal(val protonId: String, val protonName: String?, val comp: String, val protonVersion: String, val size: Long, val kept: Boolean)
class Stored(val packages: List<StoredPackage>, val originals: List<StoredOriginal>)
private fun packagesInUse(state: JSONObject): Set<String> {
internal fun liveSelection(key: String, entry: JSONObject, proton: Proton?): Boolean =
proton != null && (key == "queued" || entry.optString("protonVersion") == proton.version)
private fun packagesInUse(state: JSONObject, installed: Map<String, Proton>): Set<String> {
val names = HashSet<String>()
for (key in listOf("active", "queued")) {
val byProton = state.optJSONObject(key) ?: continue
for (pid in byProton.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys()) comps.optJSONObject(comp)?.optString("file")?.takeIf { it.isNotEmpty() }?.let(names::add)
for (comp in comps.keys()) {
val entry = comps.optJSONObject(comp) ?: continue
if (liveSelection(key, entry, installed[pid])) entry.optString("file").takeIf { it.isNotEmpty() }?.let(names::add)
}
}
}
val profiles = state.optJSONObject("profiles")
@@ -747,8 +753,8 @@ object ComponentsManager {
fun stored(context: Context): Stored = synchronized(lock) {
val state = loadState(context)
val used = packagesInUse(state)
val installed = protons(context).associateBy { it.id }
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
val used = packagesInUse(state, installed)
val originals = originalsDir(context).listFiles()?.filter { it.isDirectory }?.flatMap { proton ->
proton.listFiles()?.filter { it.isDirectory }?.flatMap { version ->
COMPONENTS.mapNotNull { comp ->
@@ -777,24 +783,36 @@ object ComponentsManager {
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val queued = state.sub("queued")
for (pid in queued.keys()) {
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
val active = state.sub("active")
for (pid in active.keys()) {
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
val profiles = state.sub("profiles")
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) }
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
val byProton = state.sub(key)
for (pid in byProton.keys().asSequence().toList()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val entry = comps.optJSONObject(comp) ?: continue
if (entry.optString("file") != name) continue
check(!liveSelection(key, entry, installed[pid])) { context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid) }
comps.remove(comp)
changed = true
}
if (comps.length() == 0) byProton.remove(pid)
}
}
val f = File(packagesDir(context), name)
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
f.delete()
val profiles = state.sub("profiles")
for (scope in profiles.keys().asSequence().toList()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS.filter { profile.optString(it) == name }) {
rememberProfiledComponent(state, comp)
profile.remove(comp)
changed = true
}
if (profile.length() == 0) profiles.remove(scope)
}
check(f.delete()) { name }
if (changed) saveState(context, state)
context.getString(R.string.cmgr_deleted, name)
}
@@ -26,6 +26,7 @@ object GpuClockPin {
pinned = true
"gpu clock: held at its top"
} catch (t: Throwable) {
File(context.filesDir, MARKER).delete()
Log.w(TAG, "pin", t)
"gpu clock: pin failed"
}
@@ -87,11 +87,10 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
if (line.startsWith("== STEP ")) {
stepAt = at
stepText = line.substringAfter("== STEP ").substringAfter(' ')
val m = INSTALL_COUNT.find(line)
if (m != null) {
clientDownload(line)?.let { (what, percent) ->
clientDownloadAt = at
clientDownload = m.groupValues[1]
clientPercent = m.groupValues[2].toInt() * 100 / maxOf(1, m.groupValues[3].toInt())
clientDownload = what
clientPercent = percent
}
} else {
val m = UPDATE_PROGRESS.find(line)
@@ -132,6 +131,19 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
}
}
internal fun clientDownload(line: String): Pair<String, Int>? {
val count = INSTALL_COUNT.find(line) ?: return null
val mb = INSTALL_MEGABYTES.find(line.substring(count.range.last + 1))
val done = mb?.groupValues?.get(1)?.toLongOrNull()
val total = mb?.groupValues?.get(2)?.toLongOrNull()
if (done != null && total != null && total > 0) {
return "$done / $total MB" to (done * 100 / total).toInt().coerceIn(0, 100)
}
val part = count.groupValues[2].toIntOrNull() ?: return null
val all = count.groupValues[3].toIntOrNull() ?: return null
return count.groupValues[1] to (part.toLong() * 100 / maxOf(1, all)).coerceIn(0L, 100L).toInt()
}
internal fun readableScriptStep(scriptStep: String): Boolean {
val t = scriptStep.lowercase()
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
@@ -140,5 +152,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
}
}
@@ -390,10 +390,12 @@ object SessionFiles {
private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text)
/** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */
internal fun startupMoviePath(config: File): String? {
internal fun startupMoviePath(config: File): String? = startupMovieLocalPath(config)?.takeIf { it.isNotEmpty() }
internal fun startupMovieLocalPath(config: File): String? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val movie = activeStartupMovie(text) ?: return null
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")?.takeIf { it.isNotEmpty() }
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")
}
/** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */
@@ -4,7 +4,6 @@ import android.content.Context
import android.content.pm.ActivityInfo
import androidx.annotation.StringRes
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.gpu.Cardboard
@@ -50,9 +49,9 @@ object SessionPrefs {
)
fun orientation(context: Context): Int =
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
fun setOrientation(context: Context, orientation: Int) {
require(orientationOptions.any { it.first == orientation })
@@ -382,30 +381,19 @@ object SessionPrefs {
prefs(context).edit().putBoolean("wifiDiscoveryAsked", true).apply()
}
internal data class CoreAllocation(val clientOverride: Boolean, val clientCpus: String, val gameCpus: String)
internal fun coreAllocation(context: Context, defaults: CpuAllocationDefaults.Allocation? = CpuAllocationDefaults.device): CoreAllocation {
val saved = prefs(context)
return CoreAllocation(
saved.getBoolean("clientCpusOverride", defaults != null && !saved.contains("clientCpus")),
saved.getString("clientCpus", defaults?.client.orEmpty()).orEmpty(),
saved.getString("gameCpus", defaults?.game.orEmpty()).orEmpty(),
)
}
fun clientCpusOverride(context: Context): Boolean = coreAllocation(context).clientOverride
fun clientCpusOverride(context: Context): Boolean = prefs(context).getBoolean("clientCpusOverride", false)
fun setClientCpusOverride(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("clientCpusOverride", on).apply()
}
fun clientCpus(context: Context): String = coreAllocation(context).clientCpus
fun clientCpus(context: Context): String = prefs(context).getString("clientCpus", "").orEmpty()
fun setClientCpus(context: Context, list: String) {
prefs(context).edit().putString("clientCpus", list).apply()
}
fun gameCpus(context: Context): String = coreAllocation(context).gameCpus
fun gameCpus(context: Context): String = prefs(context).getString("gameCpus", "").orEmpty()
fun setGameCpus(context: Context, list: String) {
prefs(context).edit().putString("gameCpus", list).apply()
@@ -71,6 +71,7 @@ class SessionService : Service() {
private val steamDownloadMonitor = SteamDownloadMonitor()
private var downloadMonitorTask: Runnable? = null
private var downloadActive = false
private var clientInstallActive = false
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
private var suspendDownloadNow = false
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
@@ -321,6 +322,7 @@ class SessionService : Service() {
suspendDownloadNow = false
steamDownloadMonitor.reset()
downloadActive = false
clientInstallActive = false
steamSleepToken = null
completeNativeSleep()
suspendOperationPending = false
@@ -640,8 +642,8 @@ class SessionService : Service() {
}
},
)
mainHandler.post { updateSuspendPolicy() }
updateDownloadMonitoring()
mainHandler.post { updateSuspendPolicy() }
}
}
@@ -1413,8 +1415,7 @@ class SessionService : Service() {
private fun updateSuspendPolicy() {
if (!SessionState.running) return
val hidden = !hasVisibleSurface
val downloadsBlockingSuspend = steamDownloadsInBackground && SessionState.mode == MODE_STEAM &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER && hidden && downloadActive && !suspendDownloadNow
val downloadsBlockingSuspend = downloadsKeepAwake() && hidden && !suspendDownloadNow
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && hidden && !downloadsBlockingSuspend) {
manualPauseRequested = true
} else if (!hidden && !SessionState.suspended) {
@@ -1828,8 +1829,7 @@ class SessionService : Service() {
.setContentText(getString(
when {
SessionState.suspended -> R.string.session_notification_paused
downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER -> R.string.session_notification_downloads
downloadsKeepAwake() -> R.string.session_notification_downloads
else -> R.string.session_notification
}
))
@@ -1837,8 +1837,7 @@ class SessionService : Service() {
.apply {
if (SessionState.suspended) {
addAction(Notification.Action.Builder(null, getString(R.string.resume_session), resume).build())
} else if (downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER) {
} else if (downloadsKeepAwake()) {
val suspend = PendingIntent.getService(
this@SessionService, 3,
Intent(this@SessionService, SessionService::class.java).setAction(ACTION_SUSPEND_NOW),
@@ -1858,33 +1857,50 @@ class SessionService : Service() {
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification())
}
private fun downloadsKeepAwake(): Boolean =
downloadActive && (steamDownloadsInBackground || clientInstallActive) &&
SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER
private fun downloadWatchWanted(): Boolean =
SessionState.running && SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER &&
(steamDownloadsInBackground || !SessionState.firstFrameSeen)
private fun updateDownloadMonitoring() {
val enabled = SessionState.running && SessionState.mode == MODE_STEAM &&
steamDownloadsInBackground && suspendPolicy != SessionPrefs.SUSPEND_NEVER
if (!enabled) {
if (!downloadWatchWanted()) {
val wasActive = downloadActive
downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null
steamDownloadMonitor.reset()
downloadActive = false
if (clientInstallActive) SessionEvents.record("steam.client_download", mapOf("active" to false))
clientInstallActive = false
if (wasActive) refreshNotification()
return
}
if (downloadMonitorTask != null) return
val poll = object : Runnable {
override fun run() {
if (downloadMonitorTask !== this || !SessionState.running ||
SessionState.mode != MODE_STEAM || !steamDownloadsInBackground ||
suspendPolicy == SessionPrefs.SUSPEND_NEVER) {
if (downloadMonitorTask !== this) return
if (!downloadWatchWanted()) {
downloadMonitorTask = null
updateDownloadMonitoring()
updateSuspendPolicy()
return
}
val root = LinuxRuntime.rootDir(this@SessionService)
val wasActive = downloadActive
downloadActive = steamDownloadMonitor.poll(
LinuxRuntime.rootDir(this@SessionService),
val wasInstalling = clientInstallActive
clientInstallActive = !SessionState.firstFrameSeen &&
(clientInstallActive || SteamDownloadMonitor.clientInstallPending(root))
downloadActive = clientInstallActive || steamDownloadsInBackground && steamDownloadMonitor.poll(
root,
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
client = SessionState.steamClientArch,
mounts = steamLibraryMounts,
)
if (wasInstalling != clientInstallActive) {
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
}
if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy()
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
@@ -1,7 +1,7 @@
package com.droiddeck.launcher.session
import java.io.File
import java.io.RandomAccessFile
import java.io.FileInputStream
internal class SteamDownloadMonitor {
private data class ManifestState(
@@ -63,16 +63,17 @@ internal class SteamDownloadMonitor {
lastContentActivityAt = 0L
}
runCatching {
RandomAccessFile(log, "r").use { input ->
input.seek(contentLogOffset)
FileInputStream(log).use { input ->
input.channel.position(contentLogOffset)
val reader = input.bufferedReader(Charsets.ISO_8859_1)
while (true) {
val line = input.readLine() ?: break
val line = reader.readLine() ?: break
when {
"Client version:" in line -> {
activeContentUpdates.clear()
lastContentActivityAt = 0L
}
CONTENT_UPDATE.find(line)?.let { match ->
" update changed : " in line && CONTENT_UPDATE.find(line)?.let { match ->
val appId = match.groupValues[1]
val updateType = match.groupValues[2]
val state = match.groupValues[3]
@@ -85,14 +86,15 @@ internal class SteamDownloadMonitor {
}
true
} == true -> Unit
CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
"Current download rate: " in line &&
CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
lastContentActivityAt = now
"Downloading " in line && " chunks for depot " in line ->
lastContentActivityAt = now
}
if (activeContentUpdates.isNotEmpty()) lastContentActivityAt = now
}
contentLogOffset = input.filePointer
contentLogOffset = input.channel.position()
}
}
return activeContentUpdates.isNotEmpty() && lastContentActivityAt > 0L &&
@@ -138,13 +140,21 @@ internal class SteamDownloadMonitor {
private fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
private companion object {
const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
companion object {
fun clientInstallPending(runtimeRoot: File): Boolean {
val home = File(runtimeRoot, "root")
val steam = File(home, ".local/share/Steam")
val stamped = File(steam, "package/droiddeck-installed").isFile ||
File(steam, "package/bannerlator-installed").isFile
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists()
}
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
}
}
@@ -104,6 +104,29 @@ object StoreInstallRoot {
.map { it to guestFor(context, it) }
}
/** Xodus has its own PRoot mount table and cannot see the selected Steam library's SD bind. */
fun externalRootsForXodus(context: Context): List<Pair<File, String>> {
val roots = externalRoots(context).toMutableList()
val selectedLibrary = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
?.takeUnless { isInternal(context, it) }
if (selectedLibrary != null && roots.none { it.first.absolutePath == selectedLibrary.absolutePath }) {
roots += selectedLibrary to guestFor(context, selectedLibrary)
}
return roots
}
fun externalBindSpecs(context: Context): List<String> = externalBindSpecs(externalRoots(context), LinuxRuntime.rootDir(context))
fun externalBindSpecsForXodus(context: Context): List<String> =
externalBindSpecs(externalRootsForXodus(context), LinuxRuntime.rootDir(context))
internal fun externalBindSpecs(roots: List<Pair<File, String>>, guestRoot: File): List<String> =
roots.mapNotNull { (host, guest) ->
if (!host.isDirectory || !host.canRead()) return@mapNotNull null
val target = File(guestRoot, guest.removePrefix("/"))
if (target.isDirectory || target.mkdirs()) "${host.path}:$guest" else null
}
private fun guestFor(context: Context, root: File): String {
val sm = context.getSystemService(StorageManager::class.java)
val uuid = runCatching { sm?.getStorageVolume(root)?.uuid }.getOrNull()?.takeIf { it.isNotBlank() }?.replace(Regex("[^A-Za-z0-9-]"), "")
@@ -114,11 +137,21 @@ object StoreInstallRoot {
fun isInternal(context: Context, root: File): Boolean = root.absolutePath == internalRoot(context).absolutePath
fun externalGuestPath(context: Context, host: File): String? {
return externalGuestPath(host, externalRoots(context))
}
fun guestPath(context: Context, host: File): String = externalGuestPath(context, host) ?: host.path
fun guestPathForXodus(context: Context, host: File): String =
externalGuestPath(host, externalRootsForXodus(context)) ?: host.path
internal fun externalGuestPath(host: File, roots: List<Pair<File, String>>): String? {
val path = host.absolutePath
for ((root, guest) in externalRoots(context)) {
val dir = root.absolutePath
for ((root, guest) in roots.sortedByDescending { it.first.absolutePath.length }) {
val dir = root.absolutePath.trimEnd(File.separatorChar)
if (path == dir) return guest
if (path.startsWith("$dir/")) return guest + "/" + path.removePrefix("$dir/")
val prefix = dir + File.separator
if (path.startsWith(prefix)) return guest + "/" + path.removePrefix(prefix).replace(File.separatorChar, '/')
}
return null
}
@@ -251,7 +251,7 @@ internal object EpicClientLibrary {
SessionPrefs.addedGameStoredAppId(app, oldFolder.path)?.let { SteamLiveShortcuts.remove(app, it) }
changed = true
}
val next = StoreGameSidecar(
val next = withLaunchArgs(StoreGameSidecar(
Store.EPIC, appName, item.optString("DisplayName").ifEmpty { appName }, exe,
installVersion = item.optString("AppVersionString"), installedAt = existing?.installedAt?.takeIf { it > 0 } ?: folder.lastModified(),
cover = existing?.cover, hero = existing?.hero,
@@ -260,7 +260,7 @@ internal object EpicClientLibrary {
epic = existing?.epic ?: com.droiddeck.launcher.stores.EpicOptions(),
cloud = existing?.cloud ?: true,
launcher = StoreLaunch.LAUNCHER,
)
), commandArgs(item.optString("LaunchCommand")))
val sidecarChanged = existing?.toJson()?.toString(2) != next.toJson().toString(2)
val launcher = File(folder, StoreLaunch.LAUNCHER)
if (sidecarChanged || runCatching { launcher.readText() }.getOrNull() != StoreLaunch.launcherText(next)) {
@@ -328,6 +328,7 @@ internal object EpicClientLibrary {
.put("CatalogItemId", record.optString("itemId"))
.put("InstallLocation", dir)
.put("LaunchExecutable", record.optString("launchExecutable"))
.put("LaunchCommand", record.optString("launchCommand"))
.put("AppVersionString", record.optString("version"))
.put("SidecarDeploymentId", record.optJSONObject("sidecar")?.optString("deploymentId").orEmpty())
.put("DisplayName", title?.takeIf(String::isNotBlank) ?: dir.substringAfterLast('/'))
@@ -358,7 +359,11 @@ internal object EpicClientLibrary {
write(File(manifests, "$guid.item"), item(install, tags, ownership == true).toString(2))
runCatching { egstore(install, guid) { token } }.onFailure { Log.w(TAG, "${install.appName}: .egstore not written (${it.javaClass.simpleName})") }
after.put(install.appName, JSONObject().put("guid", guid).put("signature", install.signature).apply { if (ownership != null) put("ownership", ownership) })
StoreGameSidecar.read(install.folder)?.let { StoreLaunch.refreshLauncher(install.folder, it) }
StoreGameSidecar.read(install.folder)?.let { sidecar ->
val next = runCatching { manifestArgs(install, guid) }.getOrNull()?.let { withLaunchArgs(sidecar, it) } ?: sidecar
if (next !== sidecar) next.write(install.folder)
StoreLaunch.refreshLauncher(install.folder, next)
}
}
for (name in before.keys().asSequence().toList()) {
if (after.has(name)) continue
@@ -376,6 +381,33 @@ internal object EpicClientLibrary {
return changed
}
private const val LAUNCH_ARGS = "launchArgs"
private fun manifestArgs(install: Install, guid: String): List<String>? {
val manifest = File(install.folder, ".egstore/$guid.manifest").takeIf { it.isFile } ?: return null
val launch = EpicNative.inspect(manifest.readBytes(), JSONObject().put("op", "launch")) ?: return null
val build = launch.optString("buildVersion")
if (install.version.isNotEmpty() && build != install.version) return null
val args = launch.optJSONArray("args") ?: return null
return List(args.length()) { args.optString(it) }.filter { it.isNotEmpty() }
}
private fun commandArgs(command: String): List<String> {
if (command.isBlank()) return emptyList()
val args = EpicNative.call("launch.split", JSONObject().put("command", command))?.optJSONArray("args") ?: return emptyList()
return List(args.length()) { args.optString(it) }.filter { it.isNotEmpty() }
}
internal fun withLaunchArgs(sidecar: StoreGameSidecar, args: List<String>): StoreGameSidecar {
val previous = sidecar.extra[LAUNCH_ARGS]?.split('\n')?.filter { it.isNotEmpty() }.orEmpty()
val kept = sidecar.args.filterNot { it in previous }
val added = args.filterNot { it in kept }
val next = kept + added
val extra = LinkedHashMap(sidecar.extra).apply { if (added.isEmpty()) remove(LAUNCH_ARGS) else put(LAUNCH_ARGS, added.joinToString("\n")) }
if (next == sidecar.args && extra == sidecar.extra) return sidecar
return sidecar.copy(args = next, extra = extra)
}
private fun ownershipToken(token: String, install: Install): Boolean? =
runCatching { EpicApiClient.getCustomAttribute(token, install.namespace, install.catalogItemId, "OwnershipToken") }
.getOrNull()?.trim()?.lowercase()?.let { it == "true" }
@@ -39,8 +39,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
var sequence = -1L
try {
val source = if (content) selected else item.id
val guestFolder = StoreInstallRoot.guestPathForXodus(app, folder)
val selection = if (content) emptyList() else listOf("--selected-content-id", selected)
Xodus.start(app, listOf("streaming", source, folder.path, "--market", market,
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
"--progress-json", "--control-stdin") + selection).use { process ->
child = process
val diagnostics = Xodus.diagnostics(process)
@@ -46,7 +46,7 @@ internal object XboxRuntime {
val market = game.second.extra["market"]?.takeIf { it.matches(Regex("[A-Z]{2}")) } ?: Xodus.market()
val directory = views.create(app.filesDir)
val process = try {
Xodus.start(app, listOf("run", game.first.path, "droiddeck:prepare", "--exe", game.second.exe,
Xodus.start(app, listOf("run", StoreInstallRoot.guestPathForXodus(app, game.first), "droiddeck:prepare", "--exe", game.second.exe,
"--materialize-chain", "--market", market), launchDirectory = directory, credentialGeneration = credentials)
} catch (e: Exception) { XboxLaunchViews.remove(directory); throw e }
if (!launches.attach(token, process)) { process.close(); error("Xbox launch was cancelled") }
@@ -5,7 +5,9 @@ import android.os.Environment
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONObject
import java.io.Closeable
import java.io.File
@@ -79,10 +81,24 @@ internal object Xodus {
networkLink.publish()
networkLink.start()
val runtime = (runtimeDirectory ?: File(app.filesDir, "xbox-runtime")).apply { mkdirs() }
val command = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), listOf(
val root = LinuxRuntime.rootDir(app)
val external = Environment.getExternalStorageDirectory()
val extraBinds = StoreInstallRoot.externalBindSpecsForXodus(app)
val binds = LinuxRuntime.binds(app, null, null, external, extraBinds)
val fastPathPreloaded = runCatching {
File(root, "etc/ld.so.preload").useLines { lines -> lines.any { it.trim() == ProotFastPath.LIBRARY } }
}.getOrDefault(false)
val fastPathKey = if (ProotFastPath.enabled(app) && fastPathPreloaded &&
File(root, ProotFastPath.LIBRARY.removePrefix("/")).isFile) ProotFastPath.key(root, binds) else null
val guestCommand = mutableListOf(
"/usr/bin/env", "HOME=/root", "XODUS_LOG=off", "RUST_LOG=off",
"XDG_RUNTIME_DIR=${runtime.path}", "DROIDDECK_XBOX_CREDENTIAL_SOCKET=${credentials.name}", binary,
) + args)
)
fastPathKey?.let { key ->
guestCommand.addAll(guestCommand.lastIndex, ProotFastPath.guestEnv(root, binds, key))
}
guestCommand.addAll(args)
val command = LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)
val builder = ProcessBuilder(command).directory(LinuxRuntime.rootDir(app))
if (launchDirectory != null) builder.environment()["TMPDIR"] = launchDirectory.path
builder.environment().apply {
@@ -90,6 +106,7 @@ internal object Xodus {
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
val digest = java.security.MessageDigest.getInstance("SHA-256")
@@ -132,7 +132,7 @@ class FrontEndState(
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val showPhantomGate: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val launcherFullscreen: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
@@ -128,6 +128,7 @@ import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
@@ -173,6 +174,7 @@ private data class PaneKey(val chip: String, val tab: String, val signedIn: Bool
@Composable
internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
val ctx = LocalContext.current
val focusManager = LocalFocusManager.current
com.droiddeck.launcher.stores.xbox.XboxContent.plan?.let { content ->
androidx.compose.material3.AlertDialog(
onDismissRequest = { com.droiddeck.launcher.stores.xbox.XboxContent.dismiss() },
@@ -280,7 +282,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
val heroFocus = remember { androidx.compose.ui.focus.FocusRequester() }
var detailFocused by remember { mutableStateOf(false) }
fun move(kind: String) { focusMove = kind to (focusMove?.second ?: 0) + 1 }
fun open(key: String) { lastOpened = key; openGame = key; move("detail") }
fun open(key: String) { focusManager.clearFocus(force = true); lastOpened = key; openGame = key; move("detail") }
fun closeGame() { openGame = null; move("card") }
fun switchTab(to: String) { tab = to; move("first") }
val pickChip: (String) -> Unit = { id ->
@@ -478,7 +480,11 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
}
!k.signedIn -> Box(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { SignInCard(st, viewportH - 20.dp) }
else -> Storefront(st, k.tab, query, s, a, grids.getOrPut(k) { LazyGridState() }, onQuery = { query = it }, onOpen = { open(it) }, onTab = { switchTab(it) })
else -> Storefront(
st, k.tab, query, s, a, grids.getOrPut(k) { LazyGridState() },
clearSearchFocus = openGame != null,
onQuery = { query = it }, onOpen = { open(it) }, onTab = { switchTab(it) },
)
}
}
}
@@ -539,7 +545,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
seenActive.clear(); seenActive.addAll(activeKeys)
if (fresh.isNotEmpty()) StoresMotion.takeInstall()?.let { StoresMotion.fly(it) }
}
StoresState.pendingInstall?.let { item -> InstallWhere(item) }
StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
}
@Composable
@@ -938,6 +944,7 @@ internal fun StoreLogo(store: Store, size: Dp) {
private fun Storefront(
store: Store, tab: String, query: String, s: FrontEndState, a: FrontEndActions,
grid: LazyGridState,
clearSearchFocus: Boolean,
onQuery: (String) -> Unit, onOpen: (String) -> Unit, onTab: (String) -> Unit,
) {
val ctx = LocalContext.current
@@ -1082,6 +1089,7 @@ private fun Storefront(
libraryLabel,
query, onQuery,
placeholder = if (tab == "store") stringResource(R.string.stores_search_catalog, store.label) else stringResource(R.string.stores_search_library),
clearSearchFocus = clearSearchFocus,
lead = if (tabs.size < 2) null else { {
val labels = tabs.map { if (it == "store") stringResource(R.string.stores_tab_store) else libraryLabel }
HeaderTabs(labels, tabs.indexOf(tab).coerceAtLeast(0)) { onTab(tabs[it]) }
@@ -1185,6 +1193,7 @@ private fun HeaderTabs(labels: List<String>, selected: Int, onSelect: (Int) -> U
@Composable
internal fun ModeHeader(
title: String, query: String, onQuery: (String) -> Unit, placeholder: String,
clearSearchFocus: Boolean = false,
lead: (@Composable () -> Unit)? = null, trailing: @Composable () -> Unit,
) {
val colors = MaterialTheme.colorScheme
@@ -1206,6 +1215,7 @@ internal fun ModeHeader(
AdbTextField(
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = placeholder, compact = true, focusOnShow = focusOnOpen,
clearFocus = clearSearchFocus,
onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } },
)
}
@@ -356,6 +356,7 @@ internal fun AdbTextField(
placeholder: String? = null,
compact: Boolean = false,
onFocusChange: (Boolean) -> Unit = {},
clearFocus: Boolean = false,
onNext: (() -> Unit)? = null,
onDone: (() -> Unit)? = null,
focusOnShow: Boolean = false,
@@ -444,6 +445,11 @@ internal fun AdbTextField(
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
}
}
if (clearFocus && editText.hasFocus()) {
editText.clearFocus()
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.hideSoftInputFromWindow(editText.windowToken, 0)
}
editText.setTextColor(colors.onBackground.toArgb())
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
editText.hint = placeholder
+3 -1
View File
@@ -160,13 +160,15 @@ synchronous on the calling thread (network calls block: call them off the main t
| `cloud.list` | `accessToken`, `accountId`, `appName` | `files[]` of `name`, `modified` (ms, -1 unknown), `hash`, `readLink` |
| `cloud.writeLinks` | `accessToken`, `accountId`, `appName`, `names[]` | `links`: name → write link |
| `launch.args` | `displayName`, `accountId`, `namespace`, `locale`, `appName`, `deploymentId`, `additional` | `args[]` |
| `launch.split` | `command` | `args[]` |
| `locale` | `language`, `region` | `key`, `tags[]`, `launchLocale` |
`nativeFetch` ops: `manifest.download` (`info`, optional `cdns`) → the manifest bytes;
`cloud.read` (`url`) → the file. `null` = failed. `nativeSend` op: `cloud.write` (`url`) with the
body → `{"ok": true}` or an error. `nativeInspect` parses manifest bytes: `{"op":"summary"}` →
`buildVersion`, `launchExe`, `prereqName`, `prereqPath`, `prereqRead`, `files[]` (`path`, `size`,
`tags`); `{"op":"select","tags":[…]}` → `indices[]` of the files an install with those tags gets.
`tags`); `{"op":"select","tags":[…]}` → `indices[]` of the files an install with those tags gets;
`{"op":"launch"}` → the manifest's `buildVersion`, its `command` line and the `args[]` split from it.
### `nativeInstall`
@@ -39,10 +39,72 @@ pub fn arguments(d: &LaunchData) -> Vec<String> {
args
}
pub fn split_command(command: &str) -> Vec<String> {
let mut args = Vec::new();
let mut current = String::new();
let mut quoted = false;
let mut started = false;
let mut slashes = 0usize;
let mut chars = command.chars().map(|c| if c == '\t' { ' ' } else { c }).filter(|&c| c >= ' ' && c != '\u{7f}').peekable();
while let Some(c) = chars.next() {
if c == '\\' {
slashes += 1;
started = true;
continue;
}
if c == '"' {
current.extend(std::iter::repeat('\\').take(slashes / 2));
if slashes % 2 == 1 {
current.push('"');
} else if quoted && chars.peek() == Some(&'"') {
chars.next();
current.push('"');
} else {
quoted = !quoted;
}
slashes = 0;
started = true;
continue;
}
current.extend(std::iter::repeat('\\').take(slashes));
slashes = 0;
if c == ' ' && !quoted {
if started {
args.push(std::mem::take(&mut current));
started = false;
}
} else {
current.push(c);
started = true;
}
}
current.extend(std::iter::repeat('\\').take(slashes));
if started {
args.push(current);
}
args.retain(|a| !a.is_empty());
args
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn launch_command_splits_like_a_command_line() {
assert_eq!(split_command("-PCStore=EGS"), vec!["-PCStore=EGS"]);
assert_eq!(
split_command(" -a\t-b=\"c d\" \"-e f\" \"\" -g\r\n"),
vec!["-a", "-b=c d", "-e f", "-g"]
);
assert_eq!(
split_command(r#"-name="a\" b" -dir=C:\Games\ "-q=\\" -r"#),
vec![r#"-name=a" b"#, r"-dir=C:\Games\", r"-q=\", "-r"]
);
assert_eq!(split_command("-name=\"a\"\" b\" -s=\"\"\""), vec!["-name=a\" b", "-s=\""]);
assert!(split_command(" ").is_empty());
}
#[test]
fn arguments_in_order() {
let args = arguments(&LaunchData {
@@ -68,6 +68,7 @@ pub struct Manifest {
pub version: i64,
pub build_version: String,
pub launch_exe: String,
pub launch_command: String,
pub prereq_name: String,
pub prereq_path: String,
pub prereq_read: bool,
@@ -279,6 +280,7 @@ fn parse_binary(bytes: &[u8]) -> Result<Manifest, String> {
version,
build_version: meta.build_version,
launch_exe: meta.launch_exe,
launch_command: meta.launch_command,
prereq_name: meta.prereq_name,
prereq_path: meta.prereq_path,
prereq_read: meta.complete,
@@ -292,6 +294,7 @@ fn parse_binary(bytes: &[u8]) -> Result<Manifest, String> {
struct Meta {
build_version: String,
launch_exe: String,
launch_command: String,
prereq_name: String,
prereq_path: String,
complete: bool,
@@ -308,7 +311,7 @@ fn read_meta(data: &[u8]) -> Meta {
r.fstring()?;
meta.build_version = r.fstring()?;
meta.launch_exe = normalise_path(&r.fstring()?);
r.fstring()?;
meta.launch_command = r.fstring()?;
let ids = r.count(4)?;
for _ in 0..ids {
r.fstring()?;
@@ -548,6 +551,7 @@ fn parse_json(bytes: &[u8]) -> Result<Manifest, String> {
version,
build_version: str_field("BuildVersionString"),
launch_exe: normalise_path(launch),
launch_command: str_field("LaunchCommand"),
prereq_name: str_field("PrereqName"),
prereq_path: normalise_path(&str_field("PrereqPath")),
prereq_read: true,
@@ -611,7 +615,7 @@ pub mod testing {
fstring(&mut meta, "App");
fstring(&mut meta, &m.build);
fstring(&mut meta, &m.exe);
fstring(&mut meta, "");
fstring(&mut meta, "-PCStore=EGS \"-log=a b.txt\"");
if let Some((name, path)) = &m.prereq {
meta.extend_from_slice(&1i32.to_le_bytes());
fstring(&mut meta, "prereq-id");
@@ -763,6 +767,7 @@ mod tests {
assert_eq!(m.chunk_folder(), "ChunksV4");
assert_eq!(m.build_version, "1.2.3-CL-99");
assert_eq!(m.launch_exe, "Binaries/Win64/Game.exe");
assert_eq!(m.launch_command, "-PCStore=EGS \"-log=a b.txt\"");
assert_eq!(m.prereq_name, "UE4 Prerequisites (x64)");
assert_eq!(m.prereq_path, "Engine/Extras/UE4PrereqSetup_x64.exe");
assert!(m.prereq_read);
@@ -851,6 +856,7 @@ mod tests {
let doc = r#"{
"ManifestFileVersion": "013000000000",
"LaunchExeString": "Bin\\Game.exe",
"LaunchCommand": "-PCStore=EGS",
"BuildVersionString": "++Game+Release-1.0",
"PrereqName": "Redist", "PrereqPath": "Redist\\setup.exe",
"ChunkHashList": {
@@ -872,6 +878,7 @@ mod tests {
assert_eq!(m.version, 13);
assert_eq!(m.chunk_folder(), "ChunksV3");
assert_eq!(m.launch_exe, "Bin/Game.exe");
assert_eq!(m.launch_command, "-PCStore=EGS");
assert!(m.prereq_read);
assert_eq!(m.prereq_path, "Redist/setup.exe");
assert_eq!(m.chunks.len(), 2);
@@ -113,6 +113,7 @@ fn dispatch(op: &str, req: &Value) -> Value {
};
json!({ "args": launch::arguments(&data) })
}
"launch.split" => json!({ "args": launch::split_command(str_of(req, "command")) }),
"locale" => {
let key = locale::language_key(str_of(req, "language"), str_of(req, "region"));
json!({ "key": key, "tags": locale::tags_for_key(key), "launchLocale": locale::launch_locale(key) })
@@ -160,6 +161,11 @@ pub fn inspect(bytes: &[u8], request: &str) -> String {
.map(|a| a.iter().filter_map(|t| t.as_str()).map(str::to_string).collect());
json!({ "indices": locale::select(&m.files, tags.as_deref()) })
}
"launch" => json!({
"buildVersion": m.build_version,
"command": m.launch_command,
"args": launch::split_command(&m.launch_command),
}),
_ => json!({
"buildVersion": m.build_version,
"launchExe": m.launch_exe,
@@ -187,6 +193,8 @@ mod tests {
assert!(v["error"].is_string());
let v: Value = serde_json::from_str(&call("launch.args", r#"{"namespace":"ns","appName":"A"}"#)).unwrap();
assert_eq!(v["args"][0], "-EpicPortal");
let v: Value = serde_json::from_str(&call("launch.split", r#"{"command":"-PCStore=EGS \"-log=a b.txt\""}"#)).unwrap();
assert_eq!(v["args"], json!(["-PCStore=EGS", "-log=a b.txt"]));
}
#[test]
@@ -210,6 +218,10 @@ mod tests {
assert_eq!(v["files"].as_array().unwrap().len(), 2);
let v: Value = serde_json::from_str(&inspect(&bytes, r#"{"op":"select","tags":["English"]}"#)).unwrap();
assert_eq!(v["indices"], json!([0]));
let v: Value = serde_json::from_str(&inspect(&bytes, r#"{"op":"launch"}"#)).unwrap();
assert_eq!(v["buildVersion"], "b");
assert_eq!(v["command"], "-PCStore=EGS \"-log=a b.txt\"");
assert_eq!(v["args"], json!(["-PCStore=EGS", "-log=a b.txt"]));
let v: Value = serde_json::from_str(&inspect(b"nonsense", "{}")).unwrap();
assert!(v["error"].is_string());
}
@@ -1,42 +0,0 @@
package com.droiddeck.launcher.core
import org.junit.Assert.*
import org.junit.Test
class CpuAllocationDefaultsTest {
private val thor = (0..7).associateWith { when (it) { in 0..2 -> 2.016; in 3..6 -> 2.8032; else -> 3.1872 } }
@Test fun gen2UsesTheFourMiddleCoresAndOnePrime() {
for (model in listOf("SM8550", "QCS8550", "sm8550-ac")) {
assertEquals(CpuAllocationDefaults.Allocation("7", "3,4,5,6"), CpuAllocationDefaults.forDevice(model, "", thor))
}
assertEquals(CpuAllocationDefaults.Allocation("7", "3,4,5,6"), CpuAllocationDefaults.forDevice("", "kalama", thor))
}
@Test fun coreNumbersAndClockVariantsAreDetectedInsteadOfHardcoded() {
val reordered = mapOf(0 to 3.36, 1 to 2.0, 2 to 2.0, 3 to 2.0, 4 to 2.8, 5 to 2.8, 6 to 2.8, 7 to 2.8)
assertEquals(CpuAllocationDefaults.Allocation("0", "4,5,6,7"), CpuAllocationDefaults.forDevice("SM8550-AC", "kalama", reordered))
}
@Test fun anotherOrUnknownChipDoesNotAcquireThisDefault() {
assertNull(CpuAllocationDefaults.forDevice("SM8650", "pineapple", thor))
assertNull(CpuAllocationDefaults.forDevice("SM8650", "kalama", thor))
assertNull(CpuAllocationDefaults.forDevice("", "", thor))
}
@Test fun missingOrUnexpectedTopologyKeepsTheSchedulerDefault() {
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor - 7))
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to null)))
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to 0.0)))
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", thor + (7 to Double.NaN)))
assertNull(CpuAllocationDefaults.forDevice("SM8550", "kalama", (0..7).associateWith { 2.8 }))
}
@Test fun allCoreGamesUndoTheClientsInheritedRestriction() {
val all = CpuCores.listOrAll("")
assertEquals(all, CpuCores.gameLaunchList("", clientPinned = true))
assertEquals(all, CpuCores.gameLaunchList(all, clientPinned = true))
assertEquals("", CpuCores.gameLaunchList("", clientPinned = false))
assertEquals("0", CpuCores.gameLaunchList("0", clientPinned = true))
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.stores.CredentialCipher
import org.json.JSONArray
import org.json.JSONObject
@@ -92,8 +93,9 @@ class AddedGameArtLookupTest {
assertEquals("build", SteamGridDb.pick("", "build"))
assertEquals("build", SteamGridDb.pick(" ", "build"))
assertEquals("", SteamGridDb.pick("", ""))
assertEquals("", SteamGridDb.builtInKey())
assertEquals("", SteamGridDb.key(app))
val builtIn = SteamGridDb.builtInKey()
assertTrue(builtIn == BuildConfig.SGDB_API_KEY)
assertTrue(SteamGridDb.key(app) == builtIn.trim())
}
@Test fun theUsersKeyIsSealedOnDiskAndClears() {
@@ -106,7 +108,7 @@ class AddedGameArtLookupTest {
assertEquals("abcdef0123456789secretkey", SteamGridDb.key(app))
SteamGridDb.setUserKey(app, "")
assertFalse(file.exists())
assertEquals("", SteamGridDb.key(app))
assertTrue(SteamGridDb.key(app) == SteamGridDb.builtInKey().trim())
}
@Test fun aFailedLookupIsNotRememberedAsNoMatch() {
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.frontend
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class AddedGamesAccountTest {
@get:Rule val tmp = TemporaryFolder()
private fun steamRoot(vararg blocks: Pair<Long, Map<String, String>>): File = tmp.newFolder("Steam").also { root ->
File(root, "config").mkdirs()
File(root, "userdata/123/config").mkdirs()
File(root, "userdata/456/config").mkdirs()
val body = blocks.joinToString("") { (account, keys) ->
"\t\"${76561197960265728L + account}\"\n\t{\n" + keys.entries.joinToString("") { "\t\t\"${it.key}\"\t\t\"${it.value}\"\n" } + "\t}\n"
}
File(root, "config/loginusers.vdf").writeText("\"users\"\n{\n$body}\n")
}
@Test fun theAccountMarkedMostRecentIsUsed() {
val root = steamRoot(123L to mapOf("MostRecent" to "1", "AutoLogin" to "0", "timestamp" to "100"),
456L to mapOf("MostRecent" to "0", "AutoLogin" to "1", "timestamp" to "200"))
assertEquals(File(root, "userdata/123/config"), AddedGames.accountConfig(root))
}
@Test fun withoutMostRecentTheAccountThatSignsInIsUsed() {
val root = steamRoot(123L to mapOf("AutoLogin" to "1", "timestamp" to "100"), 456L to mapOf("AutoLogin" to "0", "timestamp" to "200"))
assertEquals(File(root, "userdata/123/config"), AddedGames.accountConfig(root))
}
@Test fun withoutEitherMarkTheAccountUsedLastIsUsed() {
val root = steamRoot(456L to mapOf("AutoLogin" to "0", "timestamp" to "100"), 123L to mapOf("AutoLogin" to "0", "timestamp" to "200"))
assertEquals(File(root, "userdata/123/config"), AddedGames.accountConfig(root))
}
@Test fun twoAccountsWithoutAnyMarkGiveNoAccount() {
val root = steamRoot(123L to mapOf("AccountName" to "a"), 456L to mapOf("AccountName" to "b"))
assertNull(AddedGames.accountConfig(root))
}
}
@@ -0,0 +1,21 @@
package com.droiddeck.launcher.runtime
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
class SeededMacTest {
@Test
fun theAndroidIdSeedsAStableLocalMac() {
val mac = LinuxNetworkLinkComponent.seededMac { "0123456789abcdef" }
assertEquals(mac, LinuxNetworkLinkComponent.seededMac { "0123456789abcdef" })
assertNotEquals(mac, LinuxNetworkLinkComponent.seededMac { null })
assertEquals(0x02, mac.substringBefore(':').toInt(16) and 0x03)
}
@Test
fun aRomThatThrowsOnTheAndroidIdReadFallsBackToTheDefaultSeed() {
val mac = LinuxNetworkLinkComponent.seededMac { throw IllegalArgumentException("Illegal char: - at offset 8") }
assertEquals(LinuxNetworkLinkComponent.seededMac { null }, mac)
}
}
@@ -178,17 +178,39 @@ class BootMovieLibraryTest {
assertNull(SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(app)))
}
@Test fun onlyTheThreeStartupMoviesOfSteamAreListed() {
listOf("deck_startup", "oled_startup", "startup_machine", "controller_generic_thumbstick_move").forEach {
@Test fun onlyTheStartupMoviesOfSteamAreListed() {
listOf("deck_startup", "oled_startup", "startup_machine", "steam_os_startup", "controller_generic_thumbstick_move").forEach {
File(BootMovieLibrary.steamRoot(app), "steamui/movies/$it.webm").also { f -> f.parentFile!!.mkdirs(); f.writeText("movie") }
}
val ids = BootMovieLibrary.list(app).map { it.id }.filter { it.startsWith("steam:") }
assertEquals(
listOf("steam:/movies/deck_startup.webm", "steam:/movies/oled_startup.webm", "steam:/movies/startup_machine.webm"),
listOf(
"steam:/movies/deck_startup.webm", "steam:/movies/oled_startup.webm", "steam:/movies/startup_machine.webm",
"steam:/movies/steam_os_startup.webm",
),
ids.sorted(),
)
}
@Test fun steamsDefaultPickIsTakenOverAsItsOwnStartupMovie() {
val native = File(BootMovieLibrary.steamRoot(app), "steamui/movies/steam_os_startup.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
movie("a.webm")
steamPicksAt(SessionFiles.BOOT_MOVIE_PATH)
BootMovie.select(app, "file:a.webm")
steamPicksAt("")
assertTrue(BootMovie.syncFromSteam(app))
assertEquals("steam:/movies/steam_os_startup.webm", BootMovie.choice(app))
assertEquals(native, BootMovie.currentFile(app))
assertFalse(BootMovie.syncFromSteam(app))
}
@Test fun anEmptySteamPickThatWasNeverSeenChangesNothing() {
File(BootMovieLibrary.steamRoot(app), "steamui/movies/steam_os_startup.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
steamPicksAt("")
assertFalse(BootMovie.syncFromSteam(app))
assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app))
}
@Test fun aMovieBoughtInThePointsShopIsListedAndAdopted() {
val file = File(BootMovieLibrary.steamRoot(app), "appcache/startupmovies/Bought.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") }
val entry = BootMovieLibrary.list(app).first { it.id == "steam:/appcache/startupmovies/Bought.webm" }
@@ -0,0 +1,32 @@
package com.droiddeck.launcher.session
import org.json.JSONObject
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.io.File
@RunWith(RobolectricTestRunner::class)
class ComponentsSelectionTest {
private val proton = ComponentsManager.Proton("DroidDeck-Proton_11-11.1", "DroidDeck-Proton 11-11.1", File("/p"), "/p", "DroidDeck-Proton-11-11.1", false)
private val entry = JSONObject().put("file", "dxvk-low-latency-arm64ec-3.1.1-2-linux.wcp").put("protonVersion", "DroidDeck-Proton-11-11.1")
@Test
fun `a package swapped into an installed Proton is in use`() {
assertTrue(ComponentsManager.liveSelection("active", entry, proton))
assertTrue(ComponentsManager.liveSelection("queued", JSONObject().put("file", "x.wcp"), proton))
}
@Test
fun `a package left on a removed Proton is not in use`() {
assertFalse(ComponentsManager.liveSelection("active", entry, null))
assertFalse(ComponentsManager.liveSelection("queued", entry, null))
}
@Test
fun `a package from before a Proton update is not in use`() {
assertFalse(ComponentsManager.liveSelection("active", JSONObject(entry.toString()).put("protonVersion", "DroidDeck-Proton-11-9.1"), proton))
}
}
@@ -1,7 +1,6 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.CpuAllocationDefaults
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -14,36 +13,22 @@ import org.robolectric.annotation.Config
@Config(sdk = [33])
class CoreAllocationPrefsTest {
private val app get() = RuntimeEnvironment.getApplication()
private val defaults = CpuAllocationDefaults.Allocation("7", "3,4,5,6")
private val saved get() = app.getSharedPreferences("session", Context.MODE_PRIVATE)
@Before fun clear() { saved.edit().clear().commit() }
@Test fun absentPreferencesUseTheDeviceDefaultWithoutWritingIt() {
assertEquals(SessionPrefs.CoreAllocation(true, "7", "3,4,5,6"), SessionPrefs.coreAllocation(app, defaults))
assertTrue(saved.all.isEmpty())
assertEquals(SessionPrefs.CoreAllocation(false, "", ""), SessionPrefs.coreAllocation(app, null))
@Test fun absentPreferencesLeaveEveryCoreToTheScheduler() {
assertFalse(SessionPrefs.clientCpusOverride(app))
assertEquals("", SessionPrefs.clientCpus(app))
assertEquals("", SessionPrefs.gameCpus(app))
}
@Test fun explicitDisableAndAllCoreChoicesSurviveAnUpdate() {
saved.edit().putBoolean("clientCpusOverride", false).putString("clientCpus", "").putString("gameCpus", "").commit()
assertEquals(SessionPrefs.CoreAllocation(false, "", ""), SessionPrefs.coreAllocation(app, defaults))
}
@Test fun existingCustomMasksArePreserved() {
saved.edit().putBoolean("clientCpusOverride", true).putString("clientCpus", "0,1").putString("gameCpus", "2,7").commit()
assertEquals(SessionPrefs.CoreAllocation(true, "0,1", "2,7"), SessionPrefs.coreAllocation(app, defaults))
}
@Test fun anOldClientMaskIsNotEnabledWithoutAnOverrideChoice() {
saved.edit().putString("clientCpus", "0,1").commit()
assertEquals(SessionPrefs.CoreAllocation(false, "0,1", "3,4,5,6"), SessionPrefs.coreAllocation(app, defaults))
}
@Test fun changingOneChoiceDoesNotReplaceTheOtherDefaults() {
SessionPrefs.setGameCpus(app, "0,1,2,3,4,5,6,7")
assertEquals(SessionPrefs.CoreAllocation(true, "7", "0,1,2,3,4,5,6,7"), SessionPrefs.coreAllocation(app, defaults))
SessionPrefs.setClientCpusOverride(app, false)
assertEquals(SessionPrefs.CoreAllocation(false, "7", "0,1,2,3,4,5,6,7"), SessionPrefs.coreAllocation(app, defaults))
@Test fun savedChoicesAreKept() {
SessionPrefs.setClientCpusOverride(app, true)
SessionPrefs.setClientCpus(app, "7")
SessionPrefs.setGameCpus(app, "3,4,5,6")
assertTrue(SessionPrefs.clientCpusOverride(app))
assertEquals("7", SessionPrefs.clientCpus(app))
assertEquals("3,4,5,6", SessionPrefs.gameCpus(app))
}
}
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class LoadingStateTest {
@Test fun clientDownloadCountsMegabytesWhenTheRuntimeSaysThem() {
assertEquals(
"45 / 360 MB" to 12,
LoadingState.clientDownload("== STEP 17:38:20 downloading Steam: bins_linuxarm64_linuxarm64 (2/17), 45 of 360 MB"),
)
}
@Test fun aStalledDownloadStillShowsWhereItIs() {
assertEquals(
"45 / 360 MB" to 12,
LoadingState.clientDownload(
"== STEP 17:39:20 downloading Steam: bins_linuxarm64_linuxarm64 (2/17), 45 of 360 MB" +
" - interrupted (curl exit 28), trying again in 5 s",
),
)
}
@Test fun anOlderRuntimeShowsThePartAndItsNumber() {
assertEquals(
"bins_linuxarm64_linuxarm64" to 11,
LoadingState.clientDownload("== STEP 17:38:17 downloading Steam: bins_linuxarm64_linuxarm64 (2/17)"),
)
assertEquals("a_all" to 50, LoadingState.clientDownload("== STEP 00:00:00 downloading Steam: a_all (1/2), 0 of 0 MB"))
}
@Test fun otherStepsAreNotClientDownloads() {
assertNull(LoadingState.clientDownload("== STEP 17:38:14 checking the Steam client (a first run downloads it)"))
}
}
@@ -20,7 +20,7 @@ class OrientationTest {
}
@Test fun landscapeChoicesPersistGloballyAndCanRestoreAutomaticRotation() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
for (value in listOf(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
@@ -34,7 +34,7 @@ class OrientationTest {
@Test fun invalidStoredOrientationFallsBackAndInvalidChoicePreservesTheSavedValue() {
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT).commit()
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
assertThrows(IllegalArgumentException::class.java) {
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
@@ -101,6 +101,28 @@ class SteamDownloadMonitorTest {
}
}
@Test fun aLongLogIsFollowedFromWhereTheLastPollStopped() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val contentLog = File(root, "root/.local/share/Steam/logs/content_log.txt").apply {
check(parentFile?.mkdirs() != false)
writeText(buildString {
repeat(5_000) { append("[2026-10-06 14:40:00] Detected write gap 64 MB in file \"data_$it.dat\"\r\n") }
append("[2026-10-06 14:44:17] AppID 44 App update changed : Running Update,Downloading,\r\n")
})
}
val monitor = SteamDownloadMonitor()
assertTrue(monitor.poll(root, now = 1_000L))
contentLog.appendText("[2026-10-06 14:45:03] AppID 44 App update changed : None\r\n")
assertFalse(monitor.poll(root, now = 2_000L))
contentLog.appendText("[2026-10-06 14:46:00] AppID 45 App update changed : Running Update,Downloading,\r\n")
assertTrue(monitor.poll(root, now = 3_000L))
} finally {
root.deleteRecursively()
}
}
@Test fun theOtherClientsLogIsReadFromItsStart() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
@@ -203,6 +225,38 @@ class SteamDownloadMonitorTest {
}
}
@Test fun theClientIsPendingUntilItIsInstalledAndStamped() {
val root = Files.createTempDirectory("droiddeck-steam-client-").toFile()
try {
val steam = File(root, "root/.local/share/Steam")
assertTrue(SteamDownloadMonitor.clientInstallPending(root))
File(steam, "steamrtarm64").mkdirs()
File(steam, "steamrtarm64/steam").writeText("client")
assertTrue(SteamDownloadMonitor.clientInstallPending(root))
File(steam, "package").mkdirs()
File(steam, "package/droiddeck-installed").writeText("1791686101\n")
assertFalse(SteamDownloadMonitor.clientInstallPending(root))
} finally {
root.deleteRecursively()
}
}
@Test fun anOlderStampCountsAndARepairRequestIsPending() {
val root = Files.createTempDirectory("droiddeck-steam-client-").toFile()
try {
val steam = File(root, "root/.local/share/Steam")
File(steam, "steamrtarm64").mkdirs()
File(steam, "steamrtarm64/steam").writeText("client")
File(steam, "package").mkdirs()
File(steam, "package/bannerlator-installed").writeText("1\n")
assertFalse(SteamDownloadMonitor.clientInstallPending(root))
File(root, "root/.bl-steam-repair").writeText("1\n")
assertTrue(SteamDownloadMonitor.clientInstallPending(root))
} finally {
root.deleteRecursively()
}
}
private fun manifest(root: File, appId: String, downloaded: Long, total: Long, flags: Int): File {
val file = File(root, "steamapps/appmanifest_$appId.acf")
check(file.parentFile?.mkdirs() != false)
@@ -38,6 +38,43 @@ class StoreInstallRootTest {
assertEquals(1, StoreInstallRoot.targets(app).size)
}
@Test fun externalStoreInstallPathsMapIntoTheirGuestMountWithoutPrefixCollisions() {
val cardRoot = File(app.filesDir, "card/Games").apply { mkdirs() }
val guestRoot = "/mnt/droiddeck-stores/card"
val roots = listOf(cardRoot to guestRoot)
assertEquals("$guestRoot/Stores/Xbox/Doom", StoreInstallRoot.externalGuestPath(
File(cardRoot, "Stores/Xbox/Doom"), roots))
assertEquals(null, StoreInstallRoot.externalGuestPath(
File(cardRoot.parentFile, "Games-old/Stores/Xbox/Doom"), roots))
}
@Test fun xodusMapsTheSelectedSteamLibraryOnAnExternalVolume() {
val library = File(app.filesDir, "card/steam").apply { mkdirs() }
val storeRoot = File(library, "Games").apply { mkdirs() }
SessionPrefs.setGameStorage(app, library.path, "Card")
val xodusRoot = StoreInstallRoot.externalRootsForXodus(app).single { it.first.absolutePath == storeRoot.absolutePath }
val gameFolder = File(storeRoot, "Xbox/Doom")
assertEquals("${xodusRoot.second}/Xbox/Doom", StoreInstallRoot.guestPathForXodus(app, gameFolder))
val bindSpecs = StoreInstallRoot.externalBindSpecsForXodus(app)
assertTrue(bindSpecs.contains("${storeRoot.path}:${xodusRoot.second}"))
assertTrue(File(LinuxRuntime.rootDir(app), xodusRoot.second.removePrefix("/")).isDirectory)
}
@Test fun externalStoreBindsCreateGuestTargetsAndSkipUnavailableVolumes() {
val host = File(app.filesDir, "card/Games").apply { mkdirs() }
val guestRoot = "/mnt/droiddeck-stores/card"
val guestFs = File(app.filesDir, "linuxfs").apply { mkdirs() }
val missing = File(app.filesDir, "missing/Games")
assertEquals(listOf("${host.path}:$guestRoot"), StoreInstallRoot.externalBindSpecs(
listOf(host to guestRoot, missing to "/mnt/droiddeck-stores/missing"), guestFs))
assertTrue(File(guestFs, "mnt/droiddeck-stores/card").isDirectory)
assertFalse(File(guestFs, "mnt/droiddeck-stores/missing").exists())
}
@Test fun anExistingInstallWinsOverAFreshFolderUnderTheChosenRoot() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val existing = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "Old Name").apply { mkdirs() }
@@ -285,6 +285,28 @@ class EpicClientTest {
assertTrue(EpicClient.loopback("http://localhost:5/launcher/authorized?code=1"))
}
@Test fun theManifestLaunchCommandJoinsTheGameArguments() {
val store = com.droiddeck.launcher.stores.Store.EPIC
val epicArgs = listOf("-EpicPortal", "-epicapp=Fig", "-epicenv=Prod")
val installed = com.droiddeck.launcher.stores.StoreGameSidecar(store, "Fig", "Fig Game", exe = "Fig.exe", args = epicArgs)
val first = EpicClientLibrary.withLaunchArgs(installed, listOf("-PCStore=EGS"))
assertEquals(epicArgs + "-PCStore=EGS", first.args)
assertTrue(EpicClientLibrary.withLaunchArgs(first, listOf("-PCStore=EGS")) === first)
val updated = EpicClientLibrary.withLaunchArgs(first, listOf("-PCStore=EGS", "-log=a b.txt"))
assertEquals(epicArgs + listOf("-PCStore=EGS", "-log=a b.txt"), updated.args)
val dropped = EpicClientLibrary.withLaunchArgs(updated, emptyList())
assertEquals(epicArgs, dropped.args)
assertFalse(dropped.extra.containsKey("launchArgs"))
val reinstalled = first.copy(args = epicArgs)
assertEquals(epicArgs + "-PCStore=EGS", EpicClientLibrary.withLaunchArgs(reinstalled, listOf("-PCStore=EGS")).args)
assertTrue(EpicClientLibrary.withLaunchArgs(installed, emptyList()) === installed)
val own = installed.copy(args = epicArgs + "-PCStore=EGS")
assertTrue(EpicClientLibrary.withLaunchArgs(own, listOf("-PCStore=EGS")) === own)
val ownUpdated = EpicClientLibrary.withLaunchArgs(own, listOf("-PCStore=EGS", "-log=a b.txt"))
assertEquals(epicArgs + listOf("-PCStore=EGS", "-log=a b.txt"), ownUpdated.args)
assertEquals(epicArgs + "-PCStore=EGS", EpicClientLibrary.withLaunchArgs(ownUpdated, emptyList()).args)
}
@Test fun itemsDescribeTheInstallForTheLauncher() {
val install = EpicClientLibrary.Install(
"Fig", "ns1", "item1", "Fig Game", "1.0.5", "Binaries/Win64/Fig.exe", "/root/Games/Stores/Epic/Fig Game",