Merge branch 'main' into fix/steam-client-download

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-23 10:16:19 -04:00
commit a25081df7c
123 files changed
+2637 -331

No files matched your search

@@ -80,7 +80,7 @@ import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
class MainActivity : ComponentActivity() {
class FrontEndActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -392,8 +392,6 @@ 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("")
@@ -699,7 +697,7 @@ class MainActivity : ComponentActivity() {
else {
switchPoll = null
switchingTo = null
android.widget.Toast.makeText(this@MainActivity, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
android.widget.Toast.makeText(this@FrontEndActivity, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
}
return
}
@@ -757,6 +755,7 @@ class MainActivity : ComponentActivity() {
downloadPrefix = DownloadSource.custom(this)
DownloadSource.probe()
animationsEnabled = SessionPrefs.animationsEnabled(this)
LauncherIcon.repair(this, intent?.component)
launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
@@ -1037,7 +1036,7 @@ class MainActivity : ComponentActivity() {
onWirelessAdbPair = { host, port, code, complete ->
Thread({
val result = runCatching {
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@FrontEndActivity, host, port, code) }
}
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_pair_failed) }
ui.post { complete(error) }
@@ -1045,13 +1044,13 @@ class MainActivity : ComponentActivity() {
},
onFindWirelessAdbPort = { host, complete ->
Thread({
val port = WirelessAdbFix.findConnectPort(this@MainActivity, host)
val port = WirelessAdbFix.findConnectPort(this@FrontEndActivity, host)
ui.post { complete(port) }
}, "wireless-adb-discovery").start()
},
onWirelessAdbApply = { host, port, enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@FrontEndActivity, host, port, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_command_failed) }
ui.post {
if (error == null) refreshPhantomStatus()
@@ -1061,7 +1060,7 @@ class MainActivity : ComponentActivity() {
},
onSetPhantomProcessLimit = { enabled, complete ->
Thread({
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@FrontEndActivity, enabled) }
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_unavailable) }
ui.post {
if (error == null) refreshPhantomStatus()
@@ -1117,7 +1116,7 @@ class MainActivity : ComponentActivity() {
showNonAdreno?.let { release ->
ConfirmDialog(
title = androidx.compose.ui.res.stringResource(R.string.main_non_adreno_title),
text = androidx.compose.ui.res.stringResource(R.string.main_non_adreno_text, com.droiddeck.launcher.core.DeviceSupport.gpuName(this@MainActivity), release.size / 1e6),
text = androidx.compose.ui.res.stringResource(R.string.main_non_adreno_text, com.droiddeck.launcher.core.DeviceSupport.gpuName(this@FrontEndActivity), release.size / 1e6),
confirm = androidx.compose.ui.res.stringResource(R.string.main_install_anyway),
onConfirm = { showNonAdreno = null; install(release) },
onDismiss = { showNonAdreno = null },
@@ -1616,8 +1615,6 @@ 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 &&
@@ -1686,7 +1683,6 @@ 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 },
onUnfoldedControlsWithController = { on ->
@@ -1918,9 +1914,6 @@ class MainActivity : ComponentActivity() {
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
settingsMode = mode
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
@@ -2037,7 +2030,7 @@ class MainActivity : ComponentActivity() {
steamGamesX64 = scannedX64
steamGames = all.map { g ->
val newer = current[g.appId]
if (newer != null && g.library != Library.ADDED && steamArtRefreshes[g.appId] != artRefreshesAtStart[g.appId]) g.withArt(newer.art, newer.hero, newer.icon) else g
if (newer != null && g.library != Library.ADDED && steamArtRefreshes[g.appId] != artRefreshesAtStart[g.appId]) g.withArt(newer.art, newer.hero, newer.icon, newer.logo) else g
}
shortcutLibraryScanning = false
handleGameLink(all)
@@ -23,7 +23,7 @@ class HomeActivity : Activity() {
.setAction(SessionService.ACTION_HOME_GUIDE)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
} else {
Intent(this, MainActivity::class.java)
Intent(this, FrontEndActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
startActivity(destination)
@@ -8,7 +8,7 @@ object LauncherIcon {
const val DARK = "dark"
const val LIGHT = "light"
private val aliases = linkedMapOf(DARK to "com.droiddeck.launcher.LauncherDark", LIGHT to "com.droiddeck.launcher.LauncherLight")
private val aliases = linkedMapOf(DARK to "com.droiddeck.launcher.MainActivity", LIGHT to "com.droiddeck.launcher.LauncherLight")
val options: List<Pair<String, Int>> = listOf(
DARK to R.string.setup_launcher_icon_dark,
@@ -29,6 +29,12 @@ object LauncherIcon {
fun activity(context: Context): ComponentName = component(context, current(context))
fun repair(context: Context, launchedFrom: ComponentName?) {
if (!enabled(context, DARK) || !enabled(context, LIGHT) || launchedFrom == component(context, DARK)) return
context.packageManager.setComponentEnabledSetting(component(context, DARK),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)
}
fun set(context: Context, style: String) {
if (style !in aliases || style == current(context)) return
val pm = context.packageManager
@@ -17,6 +17,8 @@ public class DirectAudioRelayComponent extends SessionPart {
private File logFile;
private final File micFifoPath;
private volatile int pid = -1;
private final Object micLock = new Object();
private boolean micHot;
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
this.socketPath = socketPath;
@@ -30,6 +32,9 @@ public class DirectAudioRelayComponent extends SessionPart {
@Override
public void start() {
stop();
synchronized (micLock) {
micHot = false;
}
File binary = new File(app().getApplicationInfo().nativeLibraryDir, BINARY);
if (!binary.isFile()) {
Log.w(TAG, "helper missing at " + binary + "; DirectAudio will report itself unavailable");
@@ -79,12 +84,40 @@ public class DirectAudioRelayComponent extends SessionPart {
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
trackMic(line);
if (log != null) synchronized (log) { log.println(line); log.flush(); }
});
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
+ (micFifoPath != null ? " mic=" + micFifoPath : " (no microphone)"));
}
private void trackMic(String line) {
boolean start = line.startsWith("DA-Relay: mic start ");
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
synchronized (micLock) {
micHot = start;
micLock.notifyAll();
}
}
// Android keeps the input stream's wake lock while a frozen helper still has it started.
public boolean awaitMicReleased(long timeoutMs) {
long deadline = System.currentTimeMillis() + timeoutMs;
synchronized (micLock) {
while (micHot) {
long left = deadline - System.currentTimeMillis();
if (left <= 0) return false;
try {
micLock.wait(left);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
return true;
}
}
@Override
public void stop() {
if (pid != -1) {
@@ -20,6 +20,7 @@ import java.util.concurrent.TimeUnit;
public class PulseAudioComponent extends SessionPart {
private static final String TAG = "PulseAudio";
public static final String SOCKET_NAME = "PS0";
private static final String MIC_SOURCE = "DirectAudioMic";
private static final String BUNDLE_STAMP = "2026-10-08-pa13-directaudio-native";
@@ -97,9 +98,9 @@ public class PulseAudioComponent extends SessionPart {
config.add("set-default-sink DirectAudio");
config.add(".fail");
if (micFifoPath != null && !micFifoPath.isEmpty()) {
config.add("load-module module-pipe-source source_name=DirectAudioMic file=\""
config.add("load-module module-pipe-source source_name=" + MIC_SOURCE + " file=\""
+ micFifoPath + "\" format=s16le rate=48000 channels=1");
config.add("set-default-source DirectAudioMic");
config.add("set-default-source " + MIC_SOURCE);
}
FileUtils.writeString(new File(workingDir, "default.pa"), String.join("\n", config));
@@ -202,16 +203,24 @@ public class PulseAudioComponent extends SessionPart {
}
public boolean setSinkSuspended(boolean suspended) {
return suspend("sink", "@DEFAULT_SINK@", suspended);
}
public boolean setMicSuspended(boolean suspended) {
return micFifoPath == null || micFifoPath.isEmpty() || suspend("source", MIC_SOURCE, suspended);
}
private boolean suspend(String kind, String name, boolean suspended) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || pid <= 1) {
Log.w(TAG, "cannot change sink state: PulseAudio control client or server unavailable");
Log.w(TAG, "cannot change " + kind + " state: PulseAudio control client or server unavailable");
return false;
}
java.lang.Process process = null;
try {
File modules = new File(workingDir, "modules/arm64");
ProcessBuilder builder = new ProcessBuilder(
pactl.getAbsolutePath(), "suspend-sink", "@DEFAULT_SINK@", Boolean.toString(suspended));
pactl.getAbsolutePath(), "suspend-" + kind, name, Boolean.toString(suspended));
builder.directory(workingDir);
builder.redirectErrorStream(true);
builder.redirectOutput(new File("/dev/null"));
@@ -222,18 +231,18 @@ public class PulseAudioComponent extends SessionPart {
process = builder.start();
if (!process.waitFor(5, TimeUnit.SECONDS)) {
process.destroyForcibly();
Log.w(TAG, "timed out changing sink state to suspended=" + suspended);
Log.w(TAG, "timed out changing " + kind + " state to suspended=" + suspended);
return false;
}
int status = process.exitValue();
if (status != 0) Log.w(TAG, "sink state change failed with exit " + status);
if (status != 0) Log.w(TAG, kind + " state change failed with exit " + status);
return status == 0;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Log.w(TAG, "interrupted changing sink state", e);
Log.w(TAG, "interrupted changing " + kind + " state", e);
return false;
} catch (Exception e) {
Log.w(TAG, "could not change sink state", e);
Log.w(TAG, "could not change " + kind + " state", e);
return false;
} finally {
if (process != null && process.isAlive()) process.destroyForcibly();
@@ -14,7 +14,7 @@ import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import com.droiddeck.launcher.MainActivity
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -185,7 +185,7 @@ class WirelessAdbPairingService : Service() {
enableVibration(false)
})
val open = PendingIntent.getActivity(this, 0,
Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE)
val cancel = PendingIntent.getService(this, 1,
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
@@ -1,26 +1,10 @@
package com.droiddeck.launcher.core
import android.app.ActivityManager
import android.content.Context
import android.os.Build
import java.io.File
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()
@@ -5,6 +5,8 @@ import android.graphics.Bitmap
import android.util.Log
import com.droiddeck.launcher.files.PeIconExtractor
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreArt
import com.droiddeck.launcher.stores.StoreGameSidecar
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
@@ -228,41 +230,93 @@ object AddedGameArt {
return if (tmp.renameTo(png)) png else null
}
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean {
internal class Sources(
val storeLogo: (AddedGames.Game) -> Boolean,
val steamSearch: (String) -> Int?,
val steam: (String, File, Set<Slot>) -> Boolean,
val sgdbGame: (String, Int?, String) -> Int?,
val sgdb: (String, Int, File, Set<Slot>) -> Boolean,
)
private val network = Sources(
storeLogo = ::storeLogo,
steamSearch = { name -> search(name)?.toIntOrNull() },
steam = ::download,
sgdbGame = SteamGridDb::gameId,
sgdb = SteamGridDb::download,
)
private val EXTRAS = setOf(Slot.LOGO, Slot.ICON)
private val STEAM_SLOTS = setOf(Slot.COVER, Slot.WIDE, Slot.BACKGROUND, Slot.LOGO)
internal const val EXTRAS_TRIED = "extras-tried"
internal fun missing(context: Context, game: AddedGames.Game): Set<Slot> {
val own = local(game)
val cache = cacheDir(context, game)
fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile
return Slot.values().filterNot { slot ->
when (slot) {
Slot.COVER -> has(slot, own.portrait, "p.jpg")
Slot.WIDE -> has(slot, own.header, "header.jpg")
Slot.BACKGROUND -> has(slot, own.hero, "hero.jpg")
Slot.LOGO -> has(slot, own.logo, "logo.png")
Slot.ICON -> has(slot, own.icon, "icon-sgdb.png")
}
}.toSet()
}
private fun storeLogo(game: AddedGames.Game): Boolean {
val url = StoreGameSidecar.read(game.folder)?.logo ?: return false
return StoreArt.fetchLogo(game.folder, url)
}
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean =
fetchMissing(context, games, SteamGridDb.key(context), network)
internal fun fetchMissing(context: Context, games: List<AddedGames.Game>, sgdbKey: String, sources: Sources): Boolean {
if (!SessionPrefs.addedGamesArt(context)) return false
val sgdbKey = SteamGridDb.key(context)
val keyChangedAt = SteamGridDb.keyChangedAt(context)
var sgdbDown = false
var changed = false
for (game in games) {
if (local(game).portrait != null) continue
val start = missing(context, game)
val full = Slot.COVER in start
val allowed = if (full) Slot.values().toSet() else EXTRAS
var need = start intersect allowed
if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue
val cache = cacheDir(context, game)
if (File(cache, "p.jpg").isFile) continue
val tried = File(cache, EXTRAS_TRIED)
if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
cache.mkdirs()
val match = steamMatch(context, game) { name ->
runCatching { search(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()?.toIntOrNull()
if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) {
changed = true
need = need - Slot.LOGO
}
val appId = match.appId?.takeIf { match.certainty == SteamMatch.Certainty.FILES }
val id = match.appId?.toString()
if (id != null && download(id, cache)) changed = true
if (File(cache, "p.jpg").isFile || sgdbKey.isEmpty() || sgdbDown) continue
val stored: String? = try {
remembered(File(cache, "sgdb-id"), keyChangedAt) {
SteamGridDb.gameId(sgdbKey, appId ?: id?.toIntOrNull(), game.name)?.toString()
val match by lazy {
steamMatch(context, game) { name ->
runCatching { sources.steamSearch(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()
}
} catch (e: Exception) {
Log.w(TAG, "${game.name}: SteamGridDB lookup failed (${e.javaClass.simpleName}); not asking again this pass")
sgdbDown = true
null
}
val gridId = stored?.toIntOrNull() ?: continue
val grabbed = try {
SteamGridDb.download(sgdbKey, gridId, cache)
} catch (e: Exception) {
sgdbDown = true
false
val steamWant = need intersect STEAM_SLOTS
if (steamWant.isNotEmpty()) {
val id = match.appId?.toString()
if (id != null && sources.steam(id, cache, steamWant)) changed = true
need = missing(context, game) intersect allowed
}
if (grabbed) changed = true
var asked = true
if (need.isNotEmpty() && sgdbKey.isNotEmpty()) {
if (sgdbDown) asked = false else try {
val gridId = remembered(File(cache, "sgdb-id"), keyChangedAt) {
sources.sgdbGame(sgdbKey, match.appId, game.name)?.toString()
}?.toIntOrNull()
if (gridId != null && sources.sgdb(sgdbKey, gridId, cache, need)) changed = true
} catch (e: Exception) {
Log.w(TAG, "${game.name}: SteamGridDB failed (${e.javaClass.simpleName}); not asking again this pass")
sgdbDown = true
asked = false
}
}
if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
}
return changed
}
@@ -314,11 +368,13 @@ object AddedGameArt {
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
}
private fun download(id: String, cache: File): Boolean {
private fun download(id: String, cache: File, slots: Set<Slot>): Boolean {
var got = false
for ((remote, localName) in listOf(
"library_600x900.jpg" to "p.jpg", "header.jpg" to "header.jpg", "library_hero.jpg" to "hero.jpg", "logo.png" to "logo.png",
for ((slot, remote, localName) in listOf(
Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"),
Triple(Slot.BACKGROUND, "library_hero.jpg", "hero.jpg"), Triple(Slot.LOGO, "logo.png", "logo.png"),
)) {
if (slot !in slots) continue
val dst = File(cache, localName)
if (dst.isFile) continue
val bytes = get("$CDN$id/$remote") ?: steamAssetUrl(id, remote)?.let { get(it) } ?: continue
@@ -11,13 +11,13 @@ import android.graphics.drawable.Icon
import android.net.Uri
import android.widget.Toast
import com.droiddeck.launcher.LauncherIcon
import com.droiddeck.launcher.MainActivity
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
import java.io.File
object GameShortcuts {
fun launchIntent(context: Context, gameId: String) = Intent(Intent.ACTION_VIEW,
Uri.parse(GameLaunchLink.uri(gameId)), context, MainActivity::class.java)
Uri.parse(GameLaunchLink.uri(gameId)), context, FrontEndActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
private fun info(context: Context, game: Library.SteamGame): ShortcutInfo {
@@ -16,9 +16,10 @@ object Library {
val icon: File? = null,
val source: String = SOURCE_STEAM,
val storeId: String? = null,
val logo: File? = null,
) {
fun withArt(art: File?, hero: File?, icon: File?) =
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId)
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo)
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
@@ -68,6 +69,7 @@ object Library {
)
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
private val STEAM_HEROES = listOf("library_hero.jpg")
internal val STEAM_LOGOS = listOf("logo.png")
private val STEAM_ICON = Regex("[a-fA-F0-9]{40}\\.(jpg|png)")
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
@@ -131,6 +133,7 @@ object Library {
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
icon = steamCacheImage(cache, appId, listOf("icon.jpg", "icon.png"))
?: File(cache, appId.toString()).listFiles()?.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) },
logo = steamCacheImage(cache, appId, STEAM_LOGOS),
))
}
}
@@ -203,6 +206,7 @@ object Library {
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
source = g.source, storeId = g.storeId,
logo = art.logo,
)
}
@@ -27,6 +27,7 @@ object LibraryCache {
icon = o.file("icon"),
source = o.optString("source").ifEmpty { if (o.getString("library") == Library.ADDED) Library.ADDED else Library.SOURCE_STEAM },
storeId = o.optString("storeId").ifEmpty { null },
logo = o.file("logo"),
)
} to x64
}.getOrElse { e -> Log.w(TAG, "unreadable, ignored: ${e.message}"); Pair(emptyList(), false) }
@@ -44,7 +45,7 @@ object LibraryCache {
for (g in games) array.put(
JSONObject().put("appId", g.appId).put("name", g.name).put("library", g.library).put("gameId", g.gameId)
.put("lastPlayed", g.lastPlayed).putFile("art", g.art).putFile("hero", g.hero)
.putFile("gameFiles", g.gameFiles).putFile("protonPrefix", g.protonPrefix).putFile("icon", g.icon)
.putFile("gameFiles", g.gameFiles).putFile("protonPrefix", g.protonPrefix).putFile("icon", g.icon).putFile("logo", g.logo)
.put("source", g.source).apply { g.storeId?.let { put("storeId", it) } },
)
val f = file(context)
@@ -22,10 +22,12 @@ object SteamGameArt {
val cover = chosenFile(context, game.appId, AddedGameArt.Slot.COVER)
val hero = chosenFile(context, game.appId, AddedGameArt.Slot.BACKGROUND)
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
if (cover == null && hero == null && icon == null) return game
val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO)
if (cover == null && hero == null && icon == null && logo == null) return game
return Library.SteamGame(
game.appId, game.name, cover ?: game.art, game.library, game.gameId,
hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId,
logo ?: game.logo,
)
}
@@ -84,18 +84,23 @@ object SteamGridDb {
.filter { it.second > 0 && it.first > 0 }
.maxByOrNull { it.second }?.first
fun download(key: String, id: Int, cache: File): Boolean {
internal fun cacheName(slot: AddedGameArt.Slot): String =
when (slot) {
AddedGameArt.Slot.COVER -> "p.jpg"
AddedGameArt.Slot.WIDE -> "header.jpg"
AddedGameArt.Slot.BACKGROUND -> "hero.jpg"
AddedGameArt.Slot.LOGO -> "logo.png"
AddedGameArt.Slot.ICON -> "icon-sgdb.png"
}
fun download(key: String, id: Int, cache: File, slots: Set<AddedGameArt.Slot> = AddedGameArt.Slot.values().toSet()): Boolean {
var got = false
for ((path, local) in listOf(
"grids/game/$id?dimensions=600x900&$QUERY" to "p.jpg",
"grids/game/$id?dimensions=460x215,920x430&$QUERY" to "header.jpg",
"heroes/game/$id?$QUERY" to "hero.jpg",
"logos/game/$id?$QUERY" to "logo.png",
"icons/game/$id?$QUERY" to "icon-sgdb.png",
)) {
for (slot in AddedGameArt.Slot.values()) {
if (slot !in slots) continue
val local = cacheName(slot)
val dst = File(cache, local)
if (dst.isFile) continue
val items = json(key, "$API/$path")?.optJSONArray("data") ?: continue
val items = json(key, "$API/${path(id, slot)}")?.optJSONArray("data") ?: continue
val url = best(items, local.endsWith(".png")) ?: continue
val bytes = AddedGameArt.get(url) ?: continue
val tmp = File(cache, "$local.tmp")
@@ -9,7 +9,7 @@ import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.droiddeck.launcher.MainActivity
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
class RuntimeInstallService : Service() {
@@ -75,7 +75,7 @@ class RuntimeInstallService : Service() {
enableVibration(false)
})
val open = PendingIntent.getActivity(this, 0,
Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE)
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.session
import android.os.SystemClock
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.runtime.LinuxRuntime
@@ -23,11 +24,16 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
}
fun prepare(): Boolean {
if (!File(KGSL).exists() || MANGOHUD_FILES.none { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }) return false
if (!File(KGSL).exists()) return false
val unreadable = MANGOHUD_FILES.any { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }
if (!unreadable && !File(GPUBUSY).canRead()) return false
return try {
dir.mkdirs()
dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) }
feeds.clear()
PASSTHROUGH_FILES.forEach { name ->
runCatching { File(dir, name).writeText(File(KGSL, name).readText()) }
}
loadFeed()?.let { load ->
feeds.add(load)
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
@@ -37,7 +43,7 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n"))
}
pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
feeds.forEach { feed -> feed.read()?.let { write(feed, it) } }
refresh()
Log.i(TAG, "hud: kgsl stats from the session's own: " + MANGOHUD_FILES.joinToString { name ->
"$name " + (feeds.firstOrNull { it.file.name == name }?.source ?: "none")
})
@@ -55,11 +61,20 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (!running) break
for (feed in feeds) feed.read()?.let { write(feed, it) }
refresh()
}
}, "gpu-stats").apply { isDaemon = true; start() }
}
// kgsl's gpubusy can read 0 0 straight after a read, so feeds that share a reader share one read.
private fun refresh() {
val values = HashMap<() -> Long?, Long?>()
for (feed in feeds) {
if (feed.read !in values) values[feed.read] = feed.read()
values[feed.read]?.let { write(feed, it) }
}
}
override fun stop() {
running = false
thread?.interrupt()
@@ -67,16 +82,30 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
}
private fun loadFeed(): Feed? {
pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }?.let { return it }
val gpubusy = "$KGSL/gpubusy"
val read = {
runCatching {
val parts = File(gpubusy).readText().trim().split(Regex("\\s+"))
val total = parts[1].toLong()
if (total > 0) (parts[0].toLong() * 100 / total).coerceIn(0, 100) else 0L
latchedBusyFeed()?.let { return it }
return pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }
}
// kgsl publishes busy/total once per ~1 s of GPU-on time and zeroes it on any read while the GPU is
// power-collapsed, so direct pollers mostly see 0; latch each published window instead.
private fun latchedBusyFeed(): Feed? {
var load = 0L
var windowAt = 0L
val read = read@{
val parts = runCatching {
File(GPUBUSY).readText().trim().split(Regex("\\s+")).map { it.toLong() }
}.getOrNull()
if (parts == null || parts.size < 2) return@read null
val now = SystemClock.elapsedRealtime()
if (parts[1] > 0) {
load = (parts[0] * 100 / parts[1]).coerceIn(0, 100)
windowAt = now
} else if (now - windowAt > LOAD_HOLD_MS) {
load = 0
}
load
}
return if (read() != null) Feed(File(dir, "gpu_busy_percentage"), gpubusy, read, "%3d %%\n") else null
return if (read() != null) Feed(File(dir, "gpu_busy_percentage"), GPUBUSY, read, "%3d %%\n") else null
}
private fun pick(name: String, sources: List<String>, format: String, unit: (Long) -> Long?): Feed? {
@@ -100,8 +129,11 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
const val KGSL = "/sys/class/kgsl/kgsl-3d0"
const val MSM_LOAD = "/sys/kernel/debug/dri/0/perf_now"
const val MSM_CLOCK = "/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"
private const val GPUBUSY = "$KGSL/gpubusy"
private const val PERIOD_MS = 500L
private const val LOAD_HOLD_MS = 5_000L
private val MANGOHUD_FILES = listOf("gpu_busy_percentage", "clock_mhz", "temp")
private val PASSTHROUGH_FILES = listOf("gpu_model", "gpu_chipid")
private const val QCOM_GPU = "/sys/kernel/gpu"
private val LOAD_SOURCES = listOf(
"$KGSL/gpu_busy_percentage", "$KGSL/devfreq/gpu_load", "$KGSL/gpuload", "$QCOM_GPU/gpu_busy",
@@ -7,7 +7,6 @@ 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
@@ -1051,15 +1050,6 @@ object SessionPrefs {
}.apply()
}
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()
}
fun gameStorage(context: Context): String = prefs(context).getString("gameStorage", "") ?: ""
@@ -104,6 +104,8 @@ class SessionService : Service() {
private var suspendOperationPending = false
private var pipTask = false
private var suspendAttemptFailed = false
private var freezePending = false
private var freezeCancelled = false
private var pendingSteamGameId: String? = null
private var pendingSteamGameGeneration = -1
// Bumped to cancel a running game-exit watch (a new launch, or the session ending).
@@ -329,6 +331,7 @@ class SessionService : Service() {
steamSleepToken = null
completeNativeSleep()
suspendOperationPending = false
freezePending = false
suspendAttemptFailed = false
suspendController = null
SessionState.suspended = false
@@ -619,9 +622,26 @@ class SessionService : Service() {
helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } },
suspendAudio = {
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
if (!pulse.setMicSuspended(true)) Log.w(TAG, "could not suspend microphone source")
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
if (relay != null && !relay.awaitMicReleased(MIC_RELEASE_TIMEOUT_MS)) {
Log.w(TAG, "microphone still open after ${MIC_RELEASE_TIMEOUT_MS} ms; suspending anyway")
}
},
resumeAudio = {
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
if (!pulse.setMicSuspended(false)) Log.w(TAG, "could not resume microphone source")
},
zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-zram"),
pagedOut = { processes, unacknowledged, residentKb, swapKb, swapBeforeKb, millis ->
Log.i(TAG, "paged out $processes processes ($unacknowledged unacknowledged) in $millis ms: " +
"resident ${residentKb / 1024} MB, zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
mainHandler.post {
SessionEvents.record("session.paged_out", mapOf(
"processes" to processes, "unacknowledged" to unacknowledged, "residentMb" to residentKb / 1024,
"swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024, "ms" to millis,
))
}
},
)
// Watching first: a first run's client download must be known before anything is paused.
@@ -704,8 +724,7 @@ class SessionService : Service() {
guest.add("BL_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0"))
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
if (SessionState.mode == MODE_STEAM && SessionPrefs.zramCompression(this) &&
com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
if (com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + com.droiddeck.launcher.agent.AgentEnv.beginSession(this)
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
@@ -1420,6 +1439,10 @@ class SessionService : Service() {
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend
else -> false
}
if (freezePending && !shouldSuspend && !freezeCancelled) {
freezeCancelled = true
controller.cancelFreeze()
}
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
val gen = sessionGen
suspendOperationPending = true
@@ -1430,20 +1453,31 @@ class SessionService : Service() {
"nativeSleep" to (nativeSleepToken != null),
))
if (shouldSuspend) {
controller.freeze { success ->
freezePending = true
freezeCancelled = false
val freezeSteamToken = steamSleepToken
val freezeNativeToken = nativeSleepToken
controller.freeze(
pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn,
) { success ->
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
suspendOperationPending = false
freezePending = false
if (success) {
SessionState.suspended = true
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
releaseLocks()
refreshNotification()
} else {
completeNativeSleep()
completeSteamSleep()
suspendAttemptFailed = true
Log.w(TAG, "could not confirm that the session stopped")
if (nativeSleepToken == freezeNativeToken) completeNativeSleep()
if (steamSleepToken == freezeSteamToken) completeSteamSleep()
if (freezeCancelled) {
SessionEvents.record("session.suspend_cancelled")
} else {
suspendAttemptFailed = true
Log.w(TAG, "could not confirm that the session stopped")
}
}
updateSuspendPolicy()
}
@@ -1614,6 +1648,7 @@ class SessionService : Service() {
GameThreadHints.stop()
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
suspendOperationPending = false
freezePending = false
launchWatcher?.stopWatching()
launchWatcher = null
syncWatcher?.stopWatching()
@@ -1880,6 +1915,7 @@ class SessionService : Service() {
companion object {
private const val TAG = "SessionService"
private const val TRACER_NICE = -6
private const val MIC_RELEASE_TIMEOUT_MS = 5_000L
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
private const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env"
@@ -18,6 +18,9 @@ internal class SessionSuspendController(
private val sleep: (Long) -> Unit = Thread::sleep,
private val nowMillis: () -> Long = { System.nanoTime() / 1_000_000 },
private val executor: ExecutorService = Executors.newSingleThreadExecutor(),
private val zramControl: File? = null,
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _, _ -> },
) {
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
@@ -38,9 +41,11 @@ internal class SessionSuspendController(
private data class TaskIdentity(val process: ProcessRecord, val tid: Int, val started: Long)
@Volatile private var closing = false
@Volatile private var cancelled = false
private var frozen = emptyList<ProcessRecord>()
fun freeze(completion: (Boolean) -> Unit) {
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
cancelled = false
submit({
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
var complete = false
@@ -59,17 +64,18 @@ internal class SessionSuspendController(
records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT)
}
}
if (pageOut) pageOut(records, root.pid, helpers)
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
var previous: Map<TaskIdentity, Long>? = null
for (pass in 0 until FREEZE_MAX_PASSES) {
if (closing || nowMillis() >= deadline) break
if (closing || cancelled || nowMillis() >= deadline) break
try {
if (readProcess(root.pid)?.started != root.started) break
addSnapshot(records, root.pid, helpers)
if (readProcess(root.pid)?.started != root.started) break
stop(records.values.toList())
sleep(if (pass == 0) 70L else 35L)
if (closing || nowMillis() >= deadline) break
if (closing || cancelled || nowMillis() >= deadline) break
val current = stoppedSnapshot(records.values.toList(), root)
if (current != null && current == previous) {
complete = true
@@ -97,6 +103,11 @@ internal class SessionSuspendController(
}, { completion(false) })
}
// A freeze still queued or paging out stops before its next SIGSTOP pass and rolls back.
fun cancelFreeze() {
cancelled = true
}
fun resume(completion: (Boolean) -> Unit) {
submit({
val records = frozen
@@ -233,6 +244,65 @@ internal class SessionSuspendController(
return tasks.takeIf { stopped && it.isNotEmpty() }
}
// A stopped process cannot run libblsession's SIGURG handler, so the page-out has to finish
// before the stop. Android's low-memory killer otherwise finds the frozen game resident in RAM
// with most of zram still free.
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
val control = zramControl?.takeIf { it.isFile } ?: return
try {
addSnapshot(records, root, helpers)
control.writeText("1")
} catch (_: IOException) {
return
}
val targets = records.values.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libblsession.so") } }
} catch (_: IOException) {
false
}
}
if (targets.isEmpty()) return
val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") }
acks.values.forEach { it.delete() }
val start = nowMillis()
val before = memoryKb(targets)
for (record in targets) send(record, SIGURG)
// A program can replace libblsession's SIGURG handler (PyInstaller's bootloader, the Go runtime);
// such a process never creates its ack and is not waited for once the start window has passed.
val waiting = targets.toMutableList()
while (!closing && !cancelled && nowMillis() - start < PAGE_OUT_TIMEOUT_MS) {
val started = nowMillis() - start >= PAGE_OUT_START_MS
waiting.removeAll { val ack = acks.getValue(it); ack.length() > 0 || (started && !ack.exists()) || isGone(it) }
if (waiting.isEmpty()) break
sleep(PAGE_OUT_POLL_MS)
}
val unacknowledged = targets.count { acks.getValue(it).length() == 0L && !isGone(it) }
acks.values.forEach { it.delete() }
val after = memoryKb(targets)
pagedOut(targets.size, unacknowledged, after.first, after.second, before.second, nowMillis() - start)
}
private fun isGone(record: ProcessRecord): Boolean =
try { readProcess(record.pid)?.started != record.started } catch (_: Exception) { false }
private fun memoryKb(records: List<ProcessRecord>): Pair<Long, Long> {
var resident = 0L
var swap = 0L
for (record in records) {
try {
File(procRoot, "${record.pid}/status").useLines { lines ->
for (line in lines) {
val kb = line.substringAfter(':').trim().substringBefore(' ').toLongOrNull() ?: continue
if (line.startsWith("VmRSS:")) resident += kb else if (line.startsWith("VmSwap:")) swap += kb
}
}
} catch (_: IOException) {
}
}
return resident to swap
}
// PRoot traces every guest. A stop sent while it runs becomes a group stop that it restarts
// thread by thread; once it is stopped, each thread that takes a SIGSTOP stays parked in its
// signal-delivery stop. So the roots stop first and every guest thread gets its own SIGSTOP.
@@ -310,6 +380,10 @@ internal class SessionSuspendController(
private companion object {
const val SIGSTOP = 19
const val SIGCONT = 18
const val SIGURG = 23
const val PAGE_OUT_POLL_MS = 100L
const val PAGE_OUT_START_MS = 2_000L
const val PAGE_OUT_TIMEOUT_MS = 12_000L
const val RESTORE_CHECKS = 80
const val FREEZE_TIMEOUT_MS = 8_000L
const val FREEZE_MAX_PASSES = 256
@@ -94,6 +94,20 @@ object StoreAccounts {
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
}
/** The name the Stores page shows. Xbox shows the gamertag, else the sign-in email with its name part masked. */
fun displayName(context: Context, store: Store): String? {
if (store != Store.XBOX) return signedInAs(context, store)
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
val signedIn = json.optString("username").takeIf { it.isNotBlank() } ?: return null
json.optString("gamertag").takeIf { it.isNotBlank() }?.let { return it }
return maskEmail(signedIn)
}
internal fun maskEmail(name: String): String {
val at = name.indexOf('@')
return if (at <= 0) name.take(1) + "•••" else name.take(1) + "•••" + name.substring(at)
}
private fun seal(f: File, json: JSONObject, retry: Boolean = false): File? {
if (keystoreFailed && !retry) return null
val text = json.toString()
@@ -14,13 +14,45 @@ object StoreArt {
fun fetchInto(folder: File, sidecar: StoreGameSidecar) {
sidecar.cover?.let { place(it, File(folder, "cover.jpg")) }
val wide = sidecar.hero ?: return
if (place(wide, File(folder, "hero.jpg"))) {
val header = File(folder, "header.jpg")
if (!header.isFile) runCatching { File(folder, "hero.jpg").copyTo(header, overwrite = true) }
sidecar.hero?.let { wide ->
if (place(wide, File(folder, "hero.jpg"))) {
val header = File(folder, "header.jpg")
if (!header.isFile) runCatching { File(folder, "hero.jpg").copyTo(header, overwrite = true) }
}
}
sidecar.logo?.let { fetchLogo(folder, it) }
}
fun fetchLogo(folder: File, url: String): Boolean {
val dst = File(folder, LOGO)
if (dst.isFile && dst.length() > 0) return true
return writeLogo(get(url) ?: return false, dst)
}
/** A logo is drawn over the hero, so it stays a PNG with its transparency instead of going through [place]. */
internal fun writeLogo(bytes: ByteArray, dst: File): Boolean {
if (dst.isFile && dst.length() > 0) return true
val bitmap = runCatching { BitmapFactory.decodeByteArray(bytes, 0, bytes.size) }.getOrNull() ?: return false
val tmp = File(dst.path + ".tmp")
return try {
if (bitmap.width <= 0 || bitmap.height <= 0) return false
if (isPng(bytes)) tmp.writeBytes(bytes) else tmp.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
tmp.renameTo(dst)
} catch (e: Exception) {
Log.w(TAG, "${dst.name}: ${e.javaClass.simpleName}")
false
} finally {
tmp.delete()
bitmap.recycle()
}
}
private val PNG_MAGIC = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
private fun isPng(bytes: ByteArray): Boolean = bytes.size > PNG_MAGIC.size && PNG_MAGIC.indices.all { bytes[it] == PNG_MAGIC[it] }
const val LOGO = "logo.png"
private fun place(url: String, dst: File): Boolean {
if (dst.isFile && dst.length() > 0) return true
val bytes = get(url) ?: return false
@@ -23,6 +23,7 @@ data class CatalogItem(
val mature: Boolean = false,
val subscription: Boolean = false,
val includedWith: String = "",
val logoUrl: String? = null,
) {
val accessible: Boolean get() = owned || subscription
/** Licensed now, or a supported package the account's subscription can install. */
@@ -22,6 +22,7 @@ class StoreGameSidecar(
val epic: EpicOptions = EpicOptions(),
val cloud: Boolean = true,
val achievements: Boolean = true,
val logo: String? = null,
) {
val isInstalled: Boolean get() = state == STATE_INSTALLED
@@ -33,7 +34,8 @@ class StoreGameSidecar(
env: Map<String, String> = this.env, installVersion: String = this.installVersion,
installedAt: Long = this.installedAt, cover: String? = this.cover, hero: String? = this.hero,
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic, cloud: Boolean = this.cloud, achievements: Boolean = this.achievements,
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements)
logo: String? = this.logo,
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements, logo)
fun toJson(): JSONObject = JSONObject().apply {
put("version", VERSION)
@@ -52,6 +54,7 @@ class StoreGameSidecar(
if (installedAt > 0L) put("installedAt", installedAt)
if (!cover.isNullOrEmpty()) put("cover", cover)
if (!hero.isNullOrEmpty()) put("hero", hero)
if (!logo.isNullOrEmpty()) put("logo", logo)
if (extra.isNotEmpty()) put("extra", JSONObject(extra as Map<*, *>))
}
@@ -129,6 +132,7 @@ class StoreGameSidecar(
epic = o.optJSONObject("epic")?.let { e -> EpicOptions(eos = e.optBoolean("eos", true), offline = e.optBoolean("offline", false)) } ?: EpicOptions(),
cloud = o.optBoolean("cloud", true),
achievements = o.optBoolean("achievements", true),
logo = o.optString("logo", "").ifEmpty { null },
)
}
@@ -40,7 +40,7 @@ object StoreInstalls {
val app = context.applicationContext
onStep?.invoke(0, STEPS)
val before = StoreGameSidecar.read(folder)
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = before?.epic ?: sidecar.epic, cloud = before?.cloud ?: sidecar.cloud, achievements = before?.achievements ?: sidecar.achievements))
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = before?.epic ?: sidecar.epic, cloud = before?.cloud ?: sidecar.cloud, achievements = before?.achievements ?: sidecar.achievements, logo = sidecar.logo ?: before?.logo))
finished.write(folder)
if (StoreGameSidecar.read(folder)?.isInstalled != true) throw java.io.IOException("the install record could not be written in ${folder.name}")
onStep?.invoke(1, STEPS)
@@ -24,6 +24,11 @@ object StoreLogFiles {
Thread({ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); r.run() }, "store-log-flush").apply { isDaemon = true }
}
private val CLOCK = SimpleDateFormat("HH:mm:ss.SSS", Locale.US)
/** Appends [text] with a time stamp. Works in any of the app's processes. */
fun stamped(context: Context, text: String) = append(context, "${synchronized(CLOCK) { CLOCK.format(Date()) }} $text")
fun append(context: Context, line: String) {
val app = context.applicationContext
pending.add(line)
@@ -10,9 +10,6 @@ import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.stores.download.DownloadEntry
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
object StoresState {
private const val TAG = "Stores"
@@ -79,7 +76,7 @@ object StoresState {
val app = context.applicationContext
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
background("stores-refresh") {
val found = Store.entries.mapNotNull { store -> StoreAccounts.signedInAs(app, store)?.let { store to it } }
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled }?.let { InstalledStoreGame(it, folder) }
}
@@ -262,7 +259,7 @@ object StoresState {
val text = StoreLog.redactLine(raw)
Log.i(TAG, text)
val app = appContext ?: return
StoreLogFiles.append(app, "${synchronized(CLOCK) { CLOCK.format(Date()) }} $text")
StoreLogFiles.stamped(app, text)
}
private var appContext: Context? = null
@@ -295,8 +292,6 @@ object StoresState {
}
}, name).start()
}
private val CLOCK = SimpleDateFormat("HH:mm:ss.SSS", Locale.US)
}
interface StoreBackend {
@@ -124,6 +124,7 @@ internal class AmazonInstaller(
installVersion = versionId, installedAt = System.currentTimeMillis(),
cover = cover, hero = item.imageUrl,
extra = mapOf("entitlementId" to entitlementId, "sku" to sku),
logo = item.logoUrl,
)
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
return folder.path
@@ -24,6 +24,7 @@ data class AmazonGame(
val publisher: String = "",
val productSku: String = "",
val versionId: String = "",
val logoUrl: String = "",
)
object AmazonLibrary {
@@ -42,7 +43,8 @@ object AmazonLibrary {
JSONObject()
.put("productId", g.productId).put("entitlementId", g.entitlementId).put("title", g.title)
.put("artUrl", g.artUrl).put("heroUrl", g.heroUrl).put("developer", g.developer)
.put("publisher", g.publisher).put("productSku", g.productSku).put("versionId", g.versionId),
.put("publisher", g.publisher).put("productSku", g.productSku).put("versionId", g.versionId)
.apply { if (g.logoUrl.isNotEmpty()) put("logoUrl", g.logoUrl) },
)
}.toString()
@@ -60,6 +62,7 @@ object AmazonLibrary {
publisher = o.optString("publisher", ""),
productSku = o.optString("productSku", ""),
versionId = o.optString("versionId", ""),
logoUrl = o.optString("logoUrl", ""),
)
}
return tidy(games)
@@ -94,6 +97,7 @@ object AmazonLibrary {
sizeBytes = prefs.getLong("size_${game.productId}", 0L).takeIf { it > 0 } ?: 0L,
storeUrl = STORE_URL,
extra = mapOf("entitlementId" to game.entitlementId, "sku" to game.productSku, "version" to ""),
logoUrl = game.logoUrl.ifEmpty { null },
)
}
@@ -106,7 +110,7 @@ object AmazonLibrary {
}
}
private fun gameFrom(o: JSONObject, before: AmazonGame?): AmazonGame = AmazonGame(
internal fun gameFrom(o: JSONObject, before: AmazonGame?): AmazonGame = AmazonGame(
productId = o.optString("productId"),
entitlementId = o.optString("entitlementId"),
title = o.optString("title"),
@@ -116,6 +120,7 @@ object AmazonLibrary {
publisher = o.optString("publisher"),
productSku = o.optString("sku"),
versionId = before?.versionId.orEmpty(),
logoUrl = o.optString("logo").ifEmpty { before?.logoUrl.orEmpty() },
)
private fun backfillPosters(app: Context, games: List<AmazonGame>) {
@@ -77,6 +77,7 @@ object SavedQueue {
private fun itemJson(i: CatalogItem) = JSONObject().apply {
put("store", i.store.id); put("id", i.id); put("title", i.title)
put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "")
i.logoUrl?.let { put("logo", it) }
put("tags", i.tags); put("developer", i.developer); put("description", i.description)
put("size", i.sizeBytes); put("owned", i.owned); put("subscription", i.subscription)
put("extra", JSONObject(i.extra))
@@ -91,6 +92,7 @@ object SavedQueue {
tags = o.optString("tags"), developer = o.optString("developer"), description = o.optString("description"),
owned = o.optBoolean("owned", true), subscription = o.optBoolean("subscription"), sizeBytes = o.optLong("size"),
extra = extra?.keys()?.asSequence()?.associateWith { extra.getString(it) } ?: emptyMap(),
logoUrl = o.optString("logo").ifEmpty { null },
)
}
}
@@ -15,7 +15,7 @@ import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
import android.util.Log
import com.droiddeck.launcher.MainActivity
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.stores.StoresState
@@ -189,7 +189,7 @@ class StoreDownloadService : Service() {
}
private fun openPage(context: Context, nav: String, code: Int): PendingIntent =
PendingIntent.getActivity(context, code, Intent(context, MainActivity::class.java).putExtra(EXTRA_NAV, nav)
PendingIntent.getActivity(context, code, Intent(context, FrontEndActivity::class.java).putExtra(EXTRA_NAV, nav)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
private fun openDownloads(context: Context, code: Int) = openPage(context, "stores:downloads", code)
@@ -133,7 +133,7 @@ internal class EpicInstaller(
val sidecar = StoreGameSidecar(
Store.EPIC, item.id, item.title, exe = picked.ifEmpty { "game.exe" }, args = args,
installVersion = result.optString("buildVersion"), installedAt = System.currentTimeMillis(),
cover = cover, hero = item.imageUrl, extra = extra,
cover = cover, hero = item.imageUrl, extra = extra, logo = item.logoUrl,
)
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
val disk = result.optLong("diskBytes", 0L)
@@ -25,6 +25,7 @@ data class EpicGame(
val releaseDate: String = "",
val publisher: String = "",
val isDlc: Boolean = false,
val artLogo: String = "",
)
object EpicLibrary {
@@ -50,7 +51,8 @@ object EpicLibrary {
.put("title", g.title).put("artCover", g.artCover).put("artSquare", g.artSquare)
.put("developer", g.developer).put("description", g.description).put("version", g.version)
.put("installSize", g.installSize).put("canRunOffline", g.canRunOffline)
.put("releaseDate", g.releaseDate).put("publisher", g.publisher),
.put("releaseDate", g.releaseDate).put("publisher", g.publisher)
.apply { if (g.artLogo.isNotEmpty()) put("artLogo", g.artLogo) },
)
}.toString()
@@ -73,6 +75,7 @@ object EpicLibrary {
canRunOffline = o.optBoolean("canRunOffline", true),
releaseDate = o.optString("releaseDate", ""),
publisher = o.optString("publisher", ""),
artLogo = o.optString("artLogo", ""),
)
}
return tidy(games)
@@ -106,6 +109,7 @@ object EpicLibrary {
sizeBytes = prefs.getLong("size_${game.appName}", 0L).takeIf { it > 0 } ?: game.installSize,
storeUrl = "https://store.epicgames.com/en-US/browse?q=" + URLEncoder.encode(title, "UTF-8"),
extra = mapOf("namespace" to game.namespace, "catalogItemId" to game.catalogItemId, "version" to game.version),
logoUrl = game.artLogo.ifEmpty { null },
)
}
@@ -128,6 +132,7 @@ object EpicLibrary {
releaseDate = pick("releaseDate", before?.releaseDate.orEmpty()),
publisher = pick("publisher", before?.publisher.orEmpty()),
isDlc = d.optBoolean("dlc", false),
artLogo = pick("logo", before?.artLogo.orEmpty()),
)
}
@@ -11,10 +11,12 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONObject
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
@@ -85,6 +87,13 @@ object GogBackend : StoreBackend {
override fun uninstall(context: Context, game: InstalledStoreGame) {}
private fun fetchLogo(id: String): String? =
runCatching { StoreNet.get("https://api.gog.com/v2/games/$id?locale=en-US")?.let { logoOf(JSONObject(it)) } }.getOrNull()
/** `images.logo2x` from the products API is an opaque banner, not a logo; the v2 `logo` link is a transparent PNG. */
internal fun logoOf(v2: JSONObject): String? =
GogStoreCatalog.absolutize(v2.optJSONObject("_links")?.optJSONObject("logo")?.optString("href")).takeIf { it.startsWith("https://") }
private class InstallJob(val app: Context, val game: GogGame, val item: CatalogItem, val folder: File) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
@@ -118,6 +127,7 @@ object GogBackend : StoreBackend {
Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" },
installVersion = result.buildId, installedAt = System.currentTimeMillis(),
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
logo = item.logoUrl ?: fetchLogo(game.gameId),
extra = mapOf(com.droiddeck.launcher.frontend.WinCompSources.GOG_DEPENDENCIES to result.dependencies.joinToString(","))
+ (if (result.dependenciesRead) mapOf(com.droiddeck.launcher.frontend.WinCompSources.LIST_READ to "1") else emptyMap())
+ mapOf(StoreLanguage.EXTRA to installedLanguage),
@@ -53,7 +53,7 @@ object XboxBackend : StoreBackend {
else StoresState.status.remove(store)
}
}
if (cached != null && !cached.needsRefresh(force)) return@Thread
if (cached != null && !cached.needsRefresh(force)) { XboxGamertag.ensure(app); return@Thread }
val response = Xodus.run(app, listOf("library", "--json", "--market", market))
val licenses = XboxCatalog.access(response, account, market, report = { StoresState.logLine("Xbox: $it") })
val products = XboxCatalog.rawProducts(licenses.keys.toList(), market)
@@ -73,6 +73,7 @@ object XboxBackend : StoreBackend {
StoresState.problems.remove(store)
}
}
if (current == generation) XboxGamertag.ensure(app)
} catch (e: Exception) {
StoresState.post {
if (current == generation) {
@@ -29,10 +29,16 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
}
private fun rejected(reason: String): Boolean {
android.util.Log.w("XboxCredentials", "Rejected credential peer: $reason")
note("Rejected credential peer: $reason")
return false
}
/** Also written to the stores log: sign-in runs in its own process, where only that file reaches a shared log. */
private fun note(text: String) {
android.util.Log.w("XboxCredentials", text)
com.droiddeck.launcher.stores.StoreLogFiles.stamped(app, "Xbox credentials: $text")
}
private fun authorized(pid: Int): Boolean {
if (!bound.await(5, java.util.concurrent.TimeUnit.SECONDS) || closed) return rejected("unbound")
val process = backend ?: return rejected("missing-child")
@@ -88,7 +94,7 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
answer(request)
}
}.getOrElse {
android.util.Log.w("XboxCredentials", "Credential request rejected: ${it.javaClass.simpleName}")
note("Credential request rejected: ${it.javaClass.simpleName}")
JSONObject().put("ok", false)
}
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
@@ -0,0 +1,51 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoresState
/** Keeps the account's Xbox gamertag in its record so the Stores page can show it instead of the sign-in email. */
internal object XboxGamertag {
/** `xodus-cli profile` allows itself 45 s, and starting it through PRoot adds to that. */
private const val TIMEOUT_SECONDS = 75L
private val triedGeneration = java.util.concurrent.atomic.AtomicReference<String?>(null)
internal fun valid(value: String): Boolean = value.isNotEmpty() && value.length <= 64 && value.none { it.isISOControl() }
/** Reads the gamertag with `xodus-cli profile` and stores it; false when Xbox didn't return one. */
fun refresh(app: Context, credentialGeneration: String? = null): Boolean = try {
val gamertag = Xodus.run(app, listOf("profile", "--json"), timeout = TIMEOUT_SECONDS, credentialGeneration = credentialGeneration)
.optString("gamertag").trim()
require(valid(gamertag))
XboxCredentials.lifecycle(app, credentialGeneration) {
val record = StoreAccounts.read(app, Store.XBOX) ?: error("Xbox credentials missing")
record.put("gamertag", gamertag)
StoreAccounts.write(app, Store.XBOX, record)
}
StoresState.logLine("Xbox: gamertag read")
true
} catch (e: Exception) {
StoresState.logLine("Xbox: gamertag unavailable (${XboxLoginActivity.failure(e)})")
false
}
/** Fetches a missing gamertag once per signed-in account, on its own thread so it never holds up a library sync. */
fun ensure(app: Context) {
Thread({
runCatching {
val generation = XboxCredentials.lifecycle(app) { it }
if (!StoreAccounts.read(app, Store.XBOX)?.optString("gamertag").isNullOrBlank()) return@runCatching
if (!shouldTryRefresh(generation)) return@runCatching
if (refresh(app, generation)) StoresState.refresh(app)
}.onFailure { StoresState.logLine("Xbox: gamertag check failed (${it.javaClass.simpleName})") }
}, "xbox-gamertag").start()
}
internal fun shouldTryRefresh(generation: String): Boolean {
while (true) {
val previous = triedGeneration.get()
if (previous == generation) return false
if (triedGeneration.compareAndSet(previous, generation)) return true
}
}
}
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.webkit.CookieManager
import android.webkit.WebResourceRequest
import android.webkit.WebView
@@ -14,8 +15,11 @@ import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoreLogFiles
import com.droiddeck.launcher.stores.StoreLog
import org.json.JSONObject
import java.util.concurrent.TimeUnit
@@ -26,6 +30,7 @@ class XboxLoginActivity : ComponentActivity() {
@Volatile private var child: Xodus.Child? = null
@Volatile private var session = 0L
@Volatile private var closed = false
@Volatile private var step = "starting"
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
@@ -49,10 +54,18 @@ class XboxLoginActivity : ComponentActivity() {
if (closed) return@Thread
try {
val accountGeneration = XboxCredentials.lifecycle(applicationContext) { it }
progress("downloading the Xbox components", "Downloading Xbox components…")
check(AddonPack.XBOX.await(applicationContext, { !closed }) { state ->
if (state is AddonPack.State.Downloading) show("Downloading Xbox components… ${(state.progress * 100).toInt()}%")
}) { "Couldn't download the Xbox components. Check your connection and try again." }
if (closed) return@Thread
progress("starting the Xbox helper", "Starting the Xbox helper…")
Xodus.start(applicationContext, listOf("--external-webview-stdio", "login"), credentialGeneration = accountGeneration).use { process ->
child = process
if (closed) return@use
Xodus.diagnostics(process)
// StoresState.logLine writes no file in this process, so the reason would miss the shared log.
Xodus.diagnostics(process) { logStep(it) }
progress("waiting for the Xbox helper", "Waiting for the Xbox helper…")
val timer = Thread({
runCatching { if (!process.process.waitFor(10, TimeUnit.MINUTES)) process.process.destroy() }
}, "xbox-login-timeout").apply { start() }
@@ -68,16 +81,19 @@ class XboxLoginActivity : ComponentActivity() {
check(!ready && frame.getInt("version") == 1)
ready = true
process.send(JSONObject().put("type", "hello").put("version", 1))
progress("waiting for Microsoft's sign-in page", "Opening Microsoft sign-in…")
}
"open" -> {
val next = frame.getLong("session")
check(ready && next > latest && next <= 32 && trusted(frame.getString("url")))
latest = next; session = next
step = "loading Microsoft's sign-in page"
runOnUiThread { if (!closed) open(frame) }
}
"close" -> {
check(frame.getLong("session") == session)
session = 0L
step = "completing the sign-in"
runOnUiThread { disposeView(); status.text = "Completing Microsoft sign-in…" }
}
"context" -> {
@@ -95,26 +111,52 @@ class XboxLoginActivity : ComponentActivity() {
else -> error("Unsupported Xbox sign-in response")
}
}
check(process.process.waitFor(5, TimeUnit.SECONDS) && process.process.exitValue() == 0 && ready && latest > 0 && session == 0L)
if (closed) return@use
check(process.process.waitFor(5, TimeUnit.SECONDS)) { "the Xbox helper did not exit" }
val exit = process.process.exitValue()
check(exit == 0) { "the Xbox helper stopped with exit code $exit" }
check(ready) { "the Xbox helper never became ready" }
check(latest > 0) { "Microsoft's sign-in page was never requested" }
check(session == 0L) { "the sign-in page was closed before Microsoft finished" }
timer.interrupt()
}
child = null
if (closed) return@Thread
step = "saving the account"
val account = Xodus.run(applicationContext, listOf("account", "--json"), credentialGeneration = accountGeneration)
check(account.optBoolean("stored"))
check(account.optBoolean("stored")) { "Xbox did not save the account" }
XboxCredentials.lifecycle(this, accountGeneration) {
val record = StoreAccounts.read(this, Store.XBOX) ?: error("Xbox credentials missing")
record.put("username", account.getString("username"))
StoreAccounts.write(this, Store.XBOX, record)
}
logStep("signed in")
runOnUiThread { finish() }
} catch (e: Exception) {
child = null
if (!closed) runOnUiThread { disposeView(); status.text = "Microsoft sign-in did not complete. Close this window and try again." }
if (closed) return@Thread
val failed = step
val reason = failure(e)
logStep("failed while $failed: $reason")
runOnUiThread {
disposeView()
status.text = "Microsoft sign-in did not complete.\nFailed while $failed: $reason\nClose this window and try again."
}
}
}, "xbox-login").start()
}
private fun show(text: String) = runOnUiThread { if (!closed && view == null) status.text = text }
private fun progress(name: String, text: String) { step = name; show(text) }
/** Written to the stores log, which the shared log zip carries; the main process's log helpers don't run in this process. */
private fun logStep(line: String) {
val text = StoreLog.redactLine("Xbox sign-in: $line")
Log.i(TAG, text)
StoreLogFiles.stamped(applicationContext, text)
}
@SuppressLint("SetJavaScriptEnabled")
private fun open(frame: JSONObject) {
disposeView()
@@ -172,6 +214,15 @@ class XboxLoginActivity : ComponentActivity() {
}
companion object {
private const val TAG = "XboxLogin"
/** Our own check messages are safe to show; anything else is named by its type, never its text, which may hold sign-in data. */
internal fun failure(e: Exception): String {
val message = e.message.orEmpty()
return if (e is IllegalStateException && message.isNotBlank() && message != "Check failed." && message.length <= 160) message
else e.javaClass.simpleName.ifBlank { "error" }
}
private val hosts = setOf("login.live.com", "account.live.com", "login.microsoftonline.com", "login.microsoft.com", "account.microsoft.com", "sisu.xboxlive.com")
private val origins = hosts.map { "https://$it" }.toSet()
private val allowedHeaders = setOf("cxh-capabilities", "cxh-correlationid", "cxh-msabinaryversion", "cxh-identityclientbinaryversion", "cxh-osversioninfo", "cxh-platform", "cxh-protocol", "cxh-source", "hostapp")
@@ -133,11 +133,12 @@ internal object Xodus {
}
}
fun diagnostics(child: Child): Thread = Thread({
/** Passes the backend's known stderr diagnostics to [report]; other stderr text never leaves the process. */
fun diagnostics(child: Child, report: (String) -> Unit = { com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $it") }): Thread = Thread({
runCatching {
child.process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line ->
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.")))
com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $line")
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.")))
report(line)
} }
}
}, "xbox-diagnostics").apply { start() }
@@ -27,6 +27,7 @@ import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
@@ -341,11 +342,24 @@ private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.c
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
Text(
GameTitle(g, titleSize)
Spacer(Modifier.height(8.dp))
}
@Composable
private fun GameTitle(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
val logo = g.logo
var failed by remember(logo) { androidx.compose.runtime.mutableStateOf(false) }
if (logo != null && !failed) {
AsyncImage(
model = logo, contentDescription = g.name, contentScale = ContentScale.Fit, alignment = Alignment.CenterStart,
onError = { failed = true },
modifier = Modifier.padding(vertical = 4.dp).height((titleSize.value * 2.2f).dp).widthIn(max = (titleSize.value * 9f).dp).testTag("game-logo"),
)
} else Text(
g.name, fontSize = titleSize, lineHeight = titleSize * 1.15f, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(8.dp))
}
@Composable
@@ -65,8 +65,6 @@ class ModeSettings(
val touchMode: String,
val suspendPolicy: String,
val steamDownloadsInBackground: Boolean = false,
val zramCompression: Boolean? = null,
val zramSupported: Boolean? = null,
val pipSupported: Boolean = false,
val pipAutoEnter: Boolean = false,
val oscMode: String?,
@@ -121,7 +119,6 @@ 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 = {},
@@ -333,12 +330,6 @@ 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.syncBackend != null) ChoiceRow(
host, "sync", stringResource(R.string.sync_backend_title), stringResource(R.string.sync_backend_hint),
listOf(