feat: Battle.net on the desktop with its games and store, plus memory options (#979)

This commit is contained in:
Charles DuBose authored and GitHub committed 2026-10-25 12:49:27 -04:00
1 parent 6918fd9308
commit c4df7e9b3d
82 files changed
+4750 -53

No files matched your search

@@ -53,6 +53,7 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
}
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
@@ -139,6 +139,7 @@ class FrontEndActivity : ComponentActivity() {
private var pkgPercent by mutableIntStateOf(-1)
private var desktopInstalled by mutableStateOf(false)
private var desktopPresent by mutableStateOf(false)
private var battleNetInstalled by mutableStateOf(false)
private var offlineAccount by mutableStateOf<String?>(null)
private var offline by mutableStateOf(false)
private var showPerformance by mutableStateOf(false)
@@ -414,6 +415,10 @@ class FrontEndActivity : ComponentActivity() {
private var logsEnabled by mutableStateOf(true)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
private var clearCachedApps by mutableStateOf(false)
private var adbPaired by mutableStateOf(false)
private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF)
private var backgroundAppLimit by mutableStateOf(com.droiddeck.launcher.core.BackgroundAppLimit.OFF)
private var showRoms by mutableStateOf(false)
private var homeAppSelected by mutableStateOf(false)
private var homeScreenEnabled by mutableStateOf(false)
@@ -594,6 +599,7 @@ class FrontEndActivity : ComponentActivity() {
when {
!SessionState.running -> startSessionOrWait(next)
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
command.program == com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET && handToBattleNet(command.args, returnHome) { pendingSwitch = next } -> {}
SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args ->
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.returnTo(returnHome)
@@ -691,7 +697,8 @@ class FrontEndActivity : ComponentActivity() {
}
private fun startSessionOrWait(next: Intent): Boolean {
val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL))
val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL) ||
next.getStringExtra(SessionService.EXTRA_PROGRAM) in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET))
if (!started && (busy || LinuxRuntimeInstaller.isBusy())) android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return started
}
@@ -756,6 +763,7 @@ class FrontEndActivity : ComponentActivity() {
gameSyncFolder = GameFileSync.folder(this)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
if (!SessionState.running) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
theme = SessionPrefs.theme(this)
frameGenLabel = getString(R.string.frame_gen_off)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
@@ -805,6 +813,7 @@ class FrontEndActivity : ComponentActivity() {
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this),
lossless = lossless,
@@ -823,6 +832,7 @@ class FrontEndActivity : ComponentActivity() {
packageStage = pkgStage,
packagePercent = pkgPercent,
sessionRunning = SessionState.running,
battleNetInstalled = battleNetInstalled,
backActionsInverted = backActionsInverted,
buildLabel = BuildConfig.BUILD_LABEL,
oscMode = oscMode,
@@ -911,6 +921,7 @@ class FrontEndActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_PROGRAM, app.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray()))
},
onBattleNet = { openBattleNet() },
onFlatpakApp = { id, name ->
Library.flatpakNames[id] = name
startActivity(Intent(this, SessionActivity::class.java)
@@ -965,6 +976,12 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
},
onClearCachedApps = { on -> SessionPrefs.setClearCachedApps(this, on); clearCachedApps = on },
onMemoryHud = { value -> SessionPrefs.setMemoryHud(this, value); memoryHud = value },
onBackgroundAppLimit = { limit ->
SessionPrefs.setBackgroundAppLimit(this, limit); backgroundAppLimit = limit
if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
},
onShareLogs = {
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
@@ -1322,6 +1339,7 @@ class FrontEndActivity : ComponentActivity() {
refreshWifiDiscovery()
com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.Ambient.poke()
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
@@ -1389,6 +1407,7 @@ class FrontEndActivity : ComponentActivity() {
unregisterReceiver(mediaReceiver)
ui.removeCallbacks(mediaRefresh)
com.droiddeck.launcher.stores.StoresState.libraryListener = null
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
flood = null
returning = null
@@ -1582,6 +1601,50 @@ class FrontEndActivity : ComponentActivity() {
desktopPresent = DesktopCatalog.desktopPresent(this)
}
private fun openBattleNet(args: List<String> = emptyList()) {
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return
}
val app = applicationContext
Thread({
val full = if (args.firstOrNull() == "--library") args else com.droiddeck.launcher.stores.battlenet.BattleNetClient.library(app) + args
ui.post {
if (isDestroyed) return@post
val next = Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, full.toTypedArray())
when {
!SessionState.running -> startSessionOrWait(next)
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
handToBattleNet(full) { pendingSwitch = next } -> {}
else -> pendingSwitch = next
}
}
}, "battlenet-open").start()
}
private fun handToBattleNet(args: List<String>, returnHome: Boolean = false, otherwise: () -> Unit): Boolean {
if (SessionState.mode != SessionService.MODE_RUN || SessionState.program != com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET) return false
val library = args.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
val sessionLibrary = SessionState.programArgs.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
if (library != null && sessionLibrary != null && library != sessionLibrary) return false
val request = if (library != null) args.drop(2) else args
val app = applicationContext
Thread({
val handed = request.isEmpty() || com.droiddeck.launcher.stores.battlenet.BattleNetClient.request(LinuxRuntime.sessionRoot(app), request)
ui.post {
if (isDestroyed) return@post
if (!handed) otherwise()
else startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.returnTo(returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
}
}, "battlenet-request").start()
return true
}
private fun launchProgram(path: String) {
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
@@ -2044,6 +2107,7 @@ class FrontEndActivity : ComponentActivity() {
addedGamesArt = SessionPrefs.addedGamesArt(this)
desktopInstalled = DesktopCatalog.desktopInstalled(this)
desktopPresent = DesktopCatalog.desktopPresent(this)
battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this)
offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this)
installed = LinuxRuntimeInstaller.installedVersion(this)
@@ -2054,6 +2118,10 @@ class FrontEndActivity : ComponentActivity() {
logsEnabled = SessionPrefs.logsEnabled(this)
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
clearCachedApps = SessionPrefs.clearCachedApps(this)
adbPaired = WirelessAdbFix.hasSavedPairing(this)
memoryHud = SessionPrefs.memoryHud(this)
backgroundAppLimit = SessionPrefs.backgroundAppLimit(this)
runningLabel = if (SessionState.running) when (SessionState.mode) {
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
@@ -2151,6 +2219,7 @@ class FrontEndActivity : ComponentActivity() {
private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(this)
adbPaired = WirelessAdbFix.hasSavedPairing(this)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
getString(
R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus),
@@ -155,6 +155,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState
private lateinit var hud: PerfHud
private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud
private var padBridge: PadBridge? = null
private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null
private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null
@@ -572,17 +573,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val needResume = !needRuntime && com.droiddeck.launcher.runtime.DesktopCatalog.interrupted(this).isNotEmpty()
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
(repair || !com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this))
val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM &&
com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
val protonUser = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM ||
program == com.droiddeck.launcher.runtime.BattleNet.PROGRAM || program == com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN
val needProton = protonUser && com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume)
}
hud = PerfHud(this)
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
hud.onPresentingWindowChanged = {
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
}
if (SessionState.running && SessionState.firstFrameSeen) {
loading.visible = false
hud.start()
memoryHud.start()
}
readPrefs()
@@ -677,7 +682,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (hud.text.isNotEmpty() || hud.graph.size >= 2) HudText(hud.text, hud.graph, hudColor, hudOpacity)
val hudLines = listOf(hud.text, memoryHud.text).filter { it.isNotEmpty() }
if (hudLines.isNotEmpty() || hud.graph.size >= 2)
HudText(hudLines.joinToString("\n"), hud.graph, hudColor, hudOpacity)
val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen
if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking)
if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) {
@@ -3056,6 +3063,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!SessionState.suspended) pausedFrame = null
com.droiddeck.launcher.ui.Motion.refresh(this)
refreshHomeApp()
if (::memoryHud.isInitialized && SessionState.running && SessionState.firstFrameSeen) memoryHud.refresh()
if (intent?.action == SessionService.ACTION_RESUME) {
intent.action = null
SessionService.resume(this)
@@ -3501,8 +3509,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionEvents.firstFrame()
if (SessionState.mode == SessionService.MODE_STEAM) SteamRepair.clientShown(this)
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
loading.visible = false
hud.start()
memoryHud.start()
}
}
@@ -3520,6 +3530,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } }
headTracker?.stop()
if (::hud.isInitialized) hud.stop()
if (::memoryHud.isInitialized) memoryHud.stop()
joyConVr?.close()
joyConVr = null
handCamera?.stop()
@@ -0,0 +1,59 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.util.Log
import java.util.concurrent.Executors
object BackgroundAppLimit {
private const val TAG = "BackgroundAppLimit"
const val OFF = -1
val CHOICES = listOf(OFF, 4, 1, 0)
private const val KEY = "max_cached_processes"
private const val STATE = "background-app-limit"
private const val APPLIED = "applied"
private const val PREVIOUS = "previous"
private val worker = Executors.newSingleThreadExecutor { Thread(it, "background-app-limit").apply { isDaemon = true } }
internal fun readCommand() = "device_config get activity_manager $KEY"
internal fun setCommand(limit: Int): String {
require(limit in 0..1024)
return "device_config put activity_manager $KEY $limit"
}
internal fun restoreCommand(previous: String?) =
if (previous == null) "device_config delete activity_manager $KEY" else "device_config put activity_manager $KEY $previous"
internal fun parse(output: String): String? = output.trim().takeIf { it.toIntOrNull() != null }
private fun state(context: Context) = context.applicationContext.getSharedPreferences(STATE, Context.MODE_PRIVATE)
fun applied(context: Context): Boolean = state(context).getBoolean(APPLIED, false)
fun applyAsync(context: Context, limit: Int) {
val app = context.applicationContext
worker.execute {
runCatching {
if (!applied(app)) {
val previous = parse(WirelessAdbFix.shell(app, readCommand()))
check(state(app).edit().putBoolean(APPLIED, true).putString(PREVIOUS, previous).commit()) { "previous value not saved" }
}
WirelessAdbFix.shell(app, setCommand(limit))
}.onSuccess { Log.i(TAG, "at most $limit cached app(s) while the session runs") }
.onFailure { Log.w(TAG, "limit not set: ${it.message}") }
}
}
fun restoreAsync(context: Context) {
val app = context.applicationContext
worker.execute {
if (!applied(app)) return@execute
val previous = state(app).getString(PREVIOUS, null)
runCatching { WirelessAdbFix.shell(app, restoreCommand(previous)) }
.onSuccess {
state(app).edit().putBoolean(APPLIED, false).remove(PREVIOUS).commit()
Log.i(TAG, "cached-app limit put back (${previous ?: "Android's own"})")
}
.onFailure { Log.w(TAG, "limit not put back yet: ${it.message}") }
}
}
}
@@ -182,25 +182,47 @@ object WirelessAdbFix {
}
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
withSavedPairing(context) { appContext, host, port -> setChildProcessLimit(appContext, host, port, enabled) }
}
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
fun clearCachedApps(context: Context) {
shell(context, "am kill-all")
}
fun shell(context: Context, command: String): String {
var output = ""
withSavedPairing(context) { appContext, host, port ->
loadOrCreateIdentity(appContext)
Kadb.create(host, port).use { adb ->
val result = adb.shell(command)
check(result.exitCode == 0) { result.allOutput.ifBlank { appContext.getString(R.string.adbfix_command_failed, result.exitCode) } }
output = result.output
}
saveConnection(appContext, host, port)
}
return output
}
private fun withSavedPairing(context: Context, action: (Context, String, Int) -> Unit) {
val appContext = context.applicationContext
val saved = savedConnection(appContext)
?: error(appContext.getString(R.string.adbfix_no_pairing))
val cachedPort = saved.port
if (cachedPort != null) {
val cachedResult = runCatching {
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
}
val cachedResult = runCatching { action(appContext, saved.host, cachedPort) }
if (cachedResult.isSuccess) return
val discoveredPort = findConnectPort(appContext, saved.host)
if (discoveredPort != null && discoveredPort != cachedPort) {
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
action(appContext, saved.host, discoveredPort)
} else {
cachedResult.getOrThrow()
}
} else {
val discoveredPort = findConnectPort(appContext, saved.host)
?: error(appContext.getString(R.string.adbfix_enter_address))
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
action(appContext, saved.host, discoveredPort)
}
}
}
@@ -4,7 +4,9 @@ import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import com.droiddeck.launcher.files.PeIconExtractor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreArt
import com.droiddeck.launcher.stores.StoreGameSidecar
import org.json.JSONObject
@@ -75,14 +77,18 @@ object AddedGameArt {
)
}
private fun storeArt(context: Context, game: AddedGames.Game): BattleNet.Art? =
if (game.source != Store.BATTLENET.id) null else game.storeId?.let(BattleNet::title)?.let { BattleNet.art(context, it) }
fun resolve(context: Context, game: AddedGames.Game): Art {
val own = local(game)
val cache = cacheDir(context, game)
val store = storeArt(context, game)
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
return Art(
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
header = chosen(cache, Slot.WIDE) ?: own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"),
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: store?.cover ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
header = chosen(cache, Slot.WIDE) ?: own.header ?: store?.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: store?.header ?: cached("hero.jpg"),
logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"),
icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game),
)
@@ -91,15 +97,16 @@ object AddedGameArt {
fun describe(context: Context, game: AddedGames.Game): List<SlotState> {
val own = local(game)
val cache = cacheDir(context, game)
val store = storeArt(context, game)
fun cached(name: String): Pair<File, String>? = File(cache, name).takeIf { it.isFile }?.let { f ->
f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM)
}
return Slot.values().map { slot ->
chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) }
val auto: Pair<File, String>? = when (slot) {
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
Slot.WIDE -> own.header?.let { it to FOLDER } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg")
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: store?.cover?.let { it to AUTO } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
Slot.WIDE -> own.header?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("hero.jpg")
Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png")
Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB }
?: exeIcon(context, game)?.let { it to EXE }
@@ -253,12 +260,13 @@ object AddedGameArt {
internal fun missing(context: Context, game: AddedGames.Game): Set<Slot> {
val own = local(game)
val cache = cacheDir(context, game)
val store = storeArt(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.COVER -> has(slot, own.portrait ?: store?.cover, "p.jpg")
Slot.WIDE -> has(slot, own.header ?: store?.header, "header.jpg")
Slot.BACKGROUND -> has(slot, own.hero ?: store?.header, "hero.jpg")
Slot.LOGO -> has(slot, own.logo, "logo.png")
Slot.ICON -> has(slot, own.icon, "icon-sgdb.png")
}
@@ -322,6 +330,10 @@ object AddedGameArt {
}
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
if (game.source == Store.BATTLENET.id) {
val id = game.storeId?.let(BattleNet::title)?.steam
return SteamMatch.Match(id, if (id == null) SteamMatch.Certainty.NONE else SteamMatch.Certainty.FILES, Store.BATTLENET.id, System.currentTimeMillis())
}
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
return match
@@ -361,14 +373,14 @@ object AddedGameArt {
.filter { it.second > 0 && it.first.isNotEmpty() }
.maxByOrNull { it.second }?.first
private fun search(name: String): String? {
internal fun search(name: String): String? {
val term = name.replace(EDITION, " ").trim().ifEmpty { name }
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
val items = JSONObject(json).optJSONArray("items") ?: return null
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, slots: Set<Slot>): Boolean {
internal fun download(id: String, cache: File, slots: Set<Slot> = Slot.entries.toSet()): Boolean {
var got = false
for ((slot, remote, localName) in listOf(
Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"),
@@ -79,6 +79,18 @@ object AddedGames {
return null
}
fun hostPath(context: Context, guest: String): File? {
if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null
val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) +
listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) +
(android.os.Environment.getExternalStorageDirectory() to "/root/Storage")
for ((host, root) in mapped.sortedByDescending { it.second.length }) {
if (guest == root) return host
if (guest.startsWith("$root/")) return File(host, guest.removePrefix("$root/"))
}
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
}
fun candidates(folder: File): List<File> = rank(folder).exes
fun rank(folder: File): GameExePicker.Ranking {
@@ -177,6 +189,9 @@ object AddedGames {
scanGame(context, folder, out, single = entry)
}
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
}
return out.distinctBy { it.folder.canonicalPath }
}
@@ -11,7 +11,7 @@ object GameRemoval {
enum class Kind { STORE, SHORTCUT, LAUNCHER }
fun kind(game: Library.SteamGame): Kind = when {
game.library == Library.EPIC_LAUNCHER -> Kind.LAUNCHER
game.library == Library.EPIC_LAUNCHER || game.library == Library.BATTLENET_LAUNCHER -> Kind.LAUNCHER
game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT
else -> Kind.STORE
}
@@ -22,11 +22,16 @@ object Library {
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()
val profileKey: String get() = when {
source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
library == ADDED -> java.lang.Integer.toUnsignedString(appId)
else -> appId.toString()
}
}
const val ADDED = "added"
const val EPIC_LAUNCHER = "epic-launcher"
const val EPIC_LAUNCHER_NAME = "Epic Games Launcher"
const val BATTLENET_LAUNCHER = "battlenet-launcher"
const val XBOX_CLOUD = "xbox-cloud"
const val SOURCE_STEAM = "steam"
@@ -238,7 +243,8 @@ object Library {
SteamGame(
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, lastPlayed = lastPlayed, gameFiles = g.folder,
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory }
else 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,
@@ -0,0 +1,410 @@
package com.droiddeck.launcher.runtime
import android.app.ActivityManager
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.GameEnvironmentStore
import java.io.File
object BattleNet {
private const val TAG = "BattleNet"
const val APP_ID = 2596113170L
const val FEX_REQUEST = "battlenet-fex.request"
const val FEX_RESULT = "battlenet-fex.result"
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null)
internal val TITLES = listOf(
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight"),
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades"),
Title("wow_classic_era", "World of Warcraft Classic", "WoWC"),
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC"),
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii"),
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii"),
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered"),
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone"),
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm"),
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch"),
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged"),
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4"),
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare"),
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered"),
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war"),
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard"),
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii"),
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii"),
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4"),
Title("osi", "Diablo II: Resurrected", "OSI"),
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection"),
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal"),
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
Title("d1", "Diablo", "D1", shop = "diablo"),
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans"),
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition"),
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered"),
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered"),
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble"),
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages"),
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves"),
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2"),
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710),
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed"),
)
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
fun notInstalled(title: Title, installedIds: Collection<String?>) =
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
private const val COVER_RETRY_MS = 24 * 3600_000L
private fun coverDir(context: Context, title: Title) =
File(context.filesDir, "battlenet-art/${(TITLES.firstOrNull { it.code == title.code } ?: title).uid}")
fun cover(context: Context, title: Title): File? = art(context, title).cover
private val coverLock = Any()
fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" }): Boolean = synchronized(coverLock) {
val art = com.droiddeck.launcher.frontend.AddedGameArt
val key = com.droiddeck.launcher.frontend.SteamGridDb.key(context)
var got = false
for (title in titles) {
val dir = coverDir(context, title)
val tried = File(dir, ".tried")
val wide = File(dir, BLIZZARD)
val done = File(dir, "p.jpg").isFile && (title.shop == null || wide.isFile)
if (done || System.currentTimeMillis() - tried.lastModified() < COVER_RETRY_MS) continue
dir.mkdirs()
if (title.steam != null && runCatching { art.download(title.steam.toString(), dir) }.getOrDefault(false)) got = true
if (title.shop != null && !wide.isFile) {
val cover = File(dir, BLIZZARD_COVER).takeUnless { File(dir, "p.jpg").isFile }
if (runCatching { com.droiddeck.launcher.stores.battlenet.BlizzardArt.fetch(title.shop, wide, cover) }
.onFailure { Log.w(TAG, "Blizzard art for ${title.uid}: ${it.javaClass.simpleName}") }.getOrDefault(false)) got = true
}
if (!File(dir, "p.jpg").isFile && !File(dir, BLIZZARD_COVER).isFile && key.isNotEmpty()) {
val id = runCatching { com.droiddeck.launcher.frontend.SteamGridDb.gameId(key, title.steam, title.name) }.getOrNull()
if (id != null && runCatching { com.droiddeck.launcher.frontend.SteamGridDb.download(key, id, dir) }.getOrDefault(false)) got = true
}
runCatching { tried.writeText("") ; tried.setLastModified(System.currentTimeMillis()) }
}
got
}
private val LOCALES = setOf(
"enus", "engb", "dede", "eses", "esmx", "frfr", "itit", "kokr", "plpl", "ptbr", "ptpt", "ruru", "zhcn", "zhtw", "jajp", "thth", "trtr", "arsa",
)
private val NOT_GAMES = setOf("agent", "bna", "battle.net")
class Game(val uid: String, val name: String, val code: String, val folder: File) {
val title: Title get() = title(uid) ?: Title(uid, name, code)
}
class Art(val cover: File?, val header: File?)
private const val BLIZZARD = "blizzard.jpg"
private const val BLIZZARD_COVER = "p-blizzard.jpg"
fun art(context: Context, title: Title): Art {
val dir = coverDir(context, title)
fun first(vararg names: String) = names.map { File(dir, it) }.firstOrNull { it.isFile }
return Art(first("p.jpg", BLIZZARD_COVER), first(BLIZZARD, "header.jpg"))
}
fun prefix(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/compatdata/$APP_ID")
fun client(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe")
fun installed(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe").isFile
fun profile(context: Context): Pair<String, String>? =
(APP_ID.toString() to context.getString(com.droiddeck.launcher.R.string.bnet_name)).takeIf { installed(context) }
fun icon(context: Context): File? {
val out = File(context.filesDir, "battlenet-art/launcher/icon.png")
if (out.isFile) return out
val exe = client(context).takeIf { it.isFile } ?: return null
val bitmap = runCatching { com.droiddeck.launcher.files.PeIconExtractor.extract(exe) }.getOrNull() ?: return null
return runCatching {
out.parentFile?.mkdirs()
val tmp = File(out.path + ".tmp")
tmp.outputStream().use { check(bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it)) }
check(tmp.renameTo(out))
out
}.getOrNull()
}
fun launcherEntry(installed: Boolean, art: File? = null): com.droiddeck.launcher.frontend.Library.SteamGame? =
if (!installed) null
else com.droiddeck.launcher.frontend.Library.SteamGame(
appId = APP_ID.toInt(), name = com.droiddeck.launcher.stores.Store.BATTLENET.label, art = art,
library = com.droiddeck.launcher.frontend.Library.BATTLENET_LAUNCHER, gameId = APP_ID,
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
)
fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"]
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
val base = id.substringBeforeLast('_', "")
return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null
}
fun games(context: Context): List<Game> {
val pfx = File(prefix(context), "pfx")
val entries = runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()) +
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrDefault(emptyList())
val found = LinkedHashMap<String, Game>()
for ((uid, path) in entries) {
val title = title(uid)
if (title == null) {
if (uid.lowercase() !in NOT_GAMES) Log.i(TAG, "not listed: $uid (no launch code known)")
continue
}
if (title.code in found) continue
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
found[title.code] = Game(title.uid, title.name, title.code, folder)
}
return found.values.toList()
}
internal fun hostFolder(context: Context, path: String): File? {
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
if (relative.isEmpty() || relative.split('/').any { it == ".." }) return null
return if (drive.groupValues[1].equals("c", ignoreCase = true)) File(prefix(context), "pfx/drive_c/$relative")
else com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "/$relative")
}
private val KEY = Regex("""^\[(.+)\](?:\s+\d+)?\s*$""")
private val UNINSTALL = Regex("""(?i)\\CurrentVersion\\Uninstall\\[^\\]+$""")
private val VALUE = Regex("""^"((?:[^"\\]|\\.)*)"=(?:str\(\d+\):)?"((?:[^"\\]|\\.)*)"\s*$""")
private val UID = Regex("""--uid=([A-Za-z0-9_.-]+)""")
internal fun uninstallEntries(lines: Sequence<String>): List<Pair<String, String>> {
val out = ArrayList<Pair<String, String>>()
var inside = false
var uid: String? = null
var location: String? = null
fun flush() {
val u = uid
val l = location
if (u != null && l != null) out.add(u to l)
uid = null
location = null
}
for (line in lines) {
if (line.startsWith("[")) {
flush()
inside = KEY.matchEntire(line)?.groupValues?.get(1)?.let { UNINSTALL.containsMatchIn(unescape(it)) } == true
continue
}
if (!inside) continue
val value = VALUE.matchEntire(line) ?: continue
val text = unescape(value.groupValues[2])
when (unescape(value.groupValues[1]).lowercase()) {
"uninstallstring" -> if (text.contains("battle.net", ignoreCase = true)) uid = UID.find(text)?.groupValues?.get(1)
"installlocation" -> location = text
}
}
flush()
return out
}
private fun unescape(s: String): String {
val out = StringBuilder(s.length)
var i = 0
while (i < s.length) {
val c = s[i++]
if (c != '\\' || i >= s.length) { out.append(c); continue }
when (val e = s[i++]) {
'n' -> out.append('\n')
'r' -> out.append('\r')
't' -> out.append('\t')
'0' -> out.append('\u0000')
'x' -> {
var end = i
while (end < s.length && end - i < 4 && s[end].lowercaseChar() in "0123456789abcdef") end++
if (end > i) { out.append(s.substring(i, end).toInt(16).toChar()); i = end } else out.append('x')
}
else -> out.append(e)
}
}
return out.toString()
}
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>> {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrDefault(emptyList()).filter { it.first == 1 }
return installs.mapNotNull { (_, start, end) ->
runCatching {
val install = fields(bytes, start, end)
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { String(bytes, it.second, it.third - it.second) }
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { s -> varints(bytes, s.second, s.third)[1] }
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
}.getOrNull()
}
}
private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> }
private fun varints(bytes: ByteArray, from: Int, to: Int): Map<Int, Long> =
HashMap<Int, Long>().also { found -> walk(bytes, from, to) { field, value -> found.putIfAbsent(field, value) } }
private fun walk(bytes: ByteArray, from: Int, to: Int, varint: (Int, Long) -> Unit): List<Triple<Int, Int, Int>> {
val out = ArrayList<Triple<Int, Int, Int>>()
var i = from
fun next(): Long {
var value = 0L
var shift = 0
while (true) {
require(i < to && shift < 64) { "truncated" }
val b = bytes[i++].toInt() and 0xff
value = value or ((b and 0x7f).toLong() shl shift)
if (b < 0x80) return value
shift += 7
}
}
while (i < to) {
val key = next()
when ((key and 7).toInt()) {
0 -> varint((key ushr 3).toInt(), next())
1 -> { require(to - i >= 8) { "truncated" }; i += 8 }
2 -> {
val n = next()
require(n in 0..(to - i).toLong()) { "truncated" }
out.add(Triple((key ushr 3).toInt(), i, i + n.toInt()))
i += n.toInt()
}
5 -> { require(to - i >= 4) { "truncated" }; i += 4 }
else -> error("wire type ${key and 7}")
}
}
return out
}
fun shortcut(context: Context, game: Game): com.droiddeck.launcher.frontend.AddedGames.Game? {
val added = com.droiddeck.launcher.frontend.AddedGames
val client = client(context)
val guestExe = added.guestPath(context, client) ?: return null
val guestDir = added.guestPath(context, client.parentFile ?: return null) ?: return null
val guestPrefix = added.guestPath(context, prefix(context)) ?: return null
val crc = java.util.zip.CRC32().apply { update("\"$guestExe\"${game.name}".toByteArray()) }.value
val appId = com.droiddeck.launcher.session.SessionPrefs.addedGameAppId(context, game.folder.path, crc or 0x80000000L)
val exe = added.candidates(game.folder).firstOrNull() ?: client
return com.droiddeck.launcher.frontend.AddedGames.Game(
game.folder, game.name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, listOf(exe),
source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = game.uid,
launchOptions = "STEAM_COMPAT_DATA_PATH=$guestPrefix %command% --exec=\"launch ${game.code}\"",
)
}
fun remove(context: Context) {
val root = LinuxRuntime.rootDir(context)
com.droiddeck.launcher.core.FileUtils.delete(prefix(context))
File(root, "usr/local/share/applications/droiddeck-battlenet.desktop").delete()
com.droiddeck.launcher.core.FileUtils.delete(File(root, "root/.cache/droiddeck/battlenet"))
ComponentsManager.clearGameComponents(context, APP_ID.toString())
Log.i(TAG, "removed")
}
private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""")
private const val LISTING_MAX_AGE = 6 * 3600L
private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b ->
for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i])
if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second)
}
internal fun d2rfix(file: String): Pair<List<Long>, Long>? {
val m = D2RFIX.matchEntire(file) ?: return null
val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
return version to (m.groupValues[2].toLongOrNull() ?: return null)
}
internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? =
items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } }
.maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first
fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items }
@Synchronized
internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String {
val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing")
val file = ComponentsManager.safeName(item.file)
if (ComponentsManager.packages(context).none { it.file == file }) {
Log.i(TAG, "downloading ${item.file}")
ComponentsManager.download(context, item) {}
}
val scope = APP_ID.toString()
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
ComponentsManager.setGameComponent(context, scope, "fex", file)
Log.i(TAG, "FEX for the Battle.net prefix: $file")
}
return file
}
private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> {
val cached = ComponentsManager.catalog(context, false)
val age = System.currentTimeMillis() / 1000 - cached.fetchedAt
if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items
val fetched = runCatching { refresh(context) }
.onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty()
return if (newestD2rFix(fetched) != null) fetched else cached.items
}
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
internal fun videoMemoryOptions(megabytes: Int): String =
"dxgi.maxDeviceMemory = $megabytes; dxgi.maxSharedMemory = $megabytes; d3d9.maxAvailableMemory = $megabytes"
fun ensureVideoMemory(context: Context): Boolean {
val memory = ActivityManager.MemoryInfo()
context.getSystemService(ActivityManager::class.java)?.getMemoryInfo(memory) ?: return false
if (memory.totalMem <= 0) return false
val options = videoMemoryOptions(videoMemory(memory.totalMem / (1024 * 1024)))
val set = GameEnvironmentStore.setDefault(context, APP_ID.toString(), DXVK_CONFIG, options)
if (set) Log.i(TAG, "DXVK_CONFIG for the Battle.net profile: $options")
return set
}
private const val DXVK_CONFIG = "DXVK_CONFIG"
fun ensureNoSteam(context: Context): Boolean {
if (com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context)) return false
GameEnvironmentStore.setGameNoSteam(context, APP_ID.toString(), true)
com.droiddeck.launcher.session.SessionPrefs.setBattleNetNoSteamSet(context)
Log.i(TAG, "Start without Steam for the Battle.net profile")
return true
}
fun answerFexRequest(context: Context, dir: File) {
val app = context.applicationContext
Thread({
runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
val answer = try {
"ok " + ensureFex(app)
} catch (e: Exception) {
Log.w(TAG, "FEX for the Battle.net prefix", e)
"error " + (e.message ?: e.javaClass.simpleName)
}
Log.i(TAG, "FEX request: $answer")
val result = File(dir, FEX_RESULT)
val partial = File(dir, "$FEX_RESULT.tmp")
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
}, "battlenet-fex").start()
}
}
@@ -900,6 +900,7 @@ object ComponentsManager {
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
}
}
if (items.length() == 0 && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000)
val tmp = File(cache.parentFile, cache.name + ".tmp")
tmp.writeText(out.toString()); tmp.renameTo(cache)
@@ -78,6 +78,14 @@ object GameEnvironmentStore {
return config
}
@Synchronized
fun setDefault(context: Context, scope: String, name: String, value: String): Boolean {
val config = read(context)
if (GameEnvironment.hasOverride(config, scope, name)) return false
save(context, GameEnvironment.withScopeValue(config, scope, name, value))
return true
}
@Synchronized
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
@@ -0,0 +1,175 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import java.io.File
import java.util.Locale
internal object MemoryReadout {
data class Device(val totalKb: Long, val availableKb: Long, val swapTotalKb: Long, val swapFreeKb: Long) {
val usedKb get() = (totalKb - availableKb).coerceAtLeast(0)
val swapUsedKb get() = (swapTotalKb - swapFreeKb).coerceAtLeast(0)
}
data class Split(val gameKb: Long, val droiddeckKb: Long, val gpuKb: Long?)
fun parseMeminfo(text: String): Device? {
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(text)?.groupValues?.get(1)?.toLongOrNull()
val total = field("MemTotal") ?: return null
val available = field("MemAvailable") ?: return null
return Device(total, available, field("SwapTotal") ?: 0, field("SwapFree") ?: 0)
}
fun residentKb(status: String): Long {
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(status)?.groupValues?.get(1)?.toLongOrNull() ?: 0
return field("RssAnon") + field("RssShmem")
}
fun inWinePrefix(environ: ByteArray): Boolean {
var start = 0
val key = "WINEPREFIX=".toByteArray()
for (i in 0..environ.size) {
if (i == environ.size || environ[i] == 0.toByte()) {
if (i - start >= key.size && (key.indices).all { environ[start + it] == key[it] }) return true
start = i + 1
}
}
return false
}
fun androidKb(device: Device, split: Split): Long =
(device.usedKb - split.gameKb - split.droiddeckKb - (split.gpuKb ?: 0)).coerceAtLeast(0)
fun gb(kb: Long): String = String.format(Locale.US, "%.1f", kb / (1024.0 * 1024.0))
fun availableMb(): Long? = runCatching { parseMeminfo(File("/proc/meminfo").readText())?.availableKb?.div(1024) }.getOrNull()
fun device(): Device? = runCatching { parseMeminfo(File("/proc/meminfo").readText()) }.getOrNull()
fun split(root: Int = android.os.Process.myPid()): Split {
val parents = HashMap<Int, Int>()
File("/proc").listFiles()?.forEach { entry ->
val pid = entry.name.toIntOrNull() ?: return@forEach
parentOf(pid)?.let { parents[pid] = it }
}
val children = parents.entries.groupBy({ it.value }, { it.key })
var game = 0L
var droiddeck = 0L
val queue = ArrayDeque<Int>().apply { add(root) }
val seen = HashSet<Int>()
while (queue.isNotEmpty()) {
val pid = queue.removeFirst()
if (!seen.add(pid)) continue
val status = runCatching { File("/proc/$pid/status").readText() }.getOrNull()
if (status != null) {
val kb = residentKb(status)
val windows = pid != root && runCatching { inWinePrefix(File("/proc/$pid/environ").readBytes()) }.getOrDefault(false)
if (windows) game += kb else droiddeck += kb
}
children[pid]?.let(queue::addAll)
}
return Split(game, droiddeck, gpuKb())
}
private fun parentOf(pid: Int): Int? {
val stat = runCatching { File("/proc/$pid/stat").readText() }.getOrNull() ?: return null
val close = stat.lastIndexOf(')')
if (close < 0 || close + 2 >= stat.length) return null
return stat.substring(close + 2).split(' ').getOrNull(1)?.toIntOrNull()
}
private fun gpuKb(): Long? = runCatching {
File("/sys/class/kgsl/kgsl/page_alloc").readText().trim().split(Regex("\\s+"))[0].toLong() / 1024
}.getOrNull()
}
object MemoryLog {
private const val TAG = "Memory"
private const val PERIOD_MS = 10_000L
@Volatile private var thread: Thread? = null
internal fun line(device: MemoryReadout.Device, split: MemoryReadout.Split): String =
"used ${device.usedKb / 1024}/${device.totalKb / 1024} MB, available ${device.availableKb / 1024} MB, " +
"swap ${device.swapUsedKb / 1024}/${device.swapTotalKb / 1024} MB | game ${split.gameKb / 1024}, " +
"droiddeck ${split.droiddeckKb / 1024}, android ${MemoryReadout.androidKb(device, split) / 1024}, " +
"gpu ${split.gpuKb?.div(1024) ?: "?"} MB"
@Synchronized
fun start() {
if (thread != null) return
thread = Thread({
while (!Thread.currentThread().isInterrupted) {
runCatching { MemoryReadout.device()?.let { android.util.Log.i(TAG, line(it, MemoryReadout.split())) } }
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}, "memory-log").apply { isDaemon = true; start() }
}
@Synchronized
fun stop() {
thread?.interrupt()
thread = null
}
}
class MemoryHud(context: Context) {
var text by mutableStateOf("")
private set
private val context = context.applicationContext
private val handler = Handler(Looper.getMainLooper())
@Volatile private var running = false
@Volatile private var generation = 0
private var thread: Thread? = null
fun refresh() {
if (SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) stop() else start()
}
fun start() {
if (running || SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) return
running = true
val token = ++generation
thread = Thread({
while (running && generation == token) {
val line = runCatching { sample() }.getOrDefault("")
handler.post { if (running && generation == token) text = line }
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}, "memory-hud").apply { isDaemon = true; start() }
}
fun stop() {
running = false
generation++
thread?.interrupt()
thread = null
text = ""
}
private fun sample(): String {
val device = MemoryReadout.device() ?: return ""
val memory = context.getString(
R.string.memory_hud_simple,
MemoryReadout.gb(device.usedKb), MemoryReadout.gb(device.totalKb),
MemoryReadout.gb(device.swapUsedKb), MemoryReadout.gb(device.swapTotalKb),
)
if (SessionPrefs.memoryHud(context) != SessionPrefs.MEMORY_HUD_ADVANCED) return memory
val split = MemoryReadout.split()
val parts = context.getString(
R.string.memory_hud_split,
MemoryReadout.gb(split.gameKb), MemoryReadout.gb(split.droiddeckKb), MemoryReadout.gb(MemoryReadout.androidKb(device, split)),
)
val gpu = split.gpuKb?.let { context.getString(R.string.memory_hud_gpu, MemoryReadout.gb(it)) }
return listOfNotNull(memory, parts, gpu).joinToString("\n")
}
private companion object {
const val PERIOD_MS = 2000L
}
}
@@ -9,11 +9,13 @@ import com.droiddeck.launcher.stores.epic.EpicClient
object NoSteamLaunch {
const val PROTON_RUN = "/usr/local/bin/droiddeck-proton-run"
const val EPIC = "/usr/local/bin/droiddeck-epic"
const val BATTLENET = com.droiddeck.launcher.runtime.BattleNet.PROGRAM
class Command(val program: String, val args: List<String>, val name: String)
fun scope(game: Library.SteamGame): String? = when {
game.library == Library.EPIC_LAUNCHER -> EpicClient.shortcutAppId.toString()
game.library == Library.BATTLENET_LAUNCHER -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
game.library == Library.ADDED || game.appId > 0 -> game.profileKey
else -> null
}?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) }
@@ -30,6 +32,8 @@ object NoSteamLaunch {
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id ->
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) }
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
else -> null
@@ -52,6 +56,7 @@ object NoSteamLaunch {
fun nameFor(program: String?, args: List<String>): String? = when (program) {
EPIC -> Library.EPIC_LAUNCHER_NAME
BATTLENET -> args.getOrNull(args.indexOf("launch") + 1)?.takeIf { args.contains("launch") }?.let { names[it] } ?: com.droiddeck.launcher.stores.Store.BATTLENET.label
PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") }?.let { names[it] }
else -> null
}
@@ -60,5 +65,6 @@ object NoSteamLaunch {
fun remember(command: Command) {
if (command.program == PROTON_RUN) command.args.getOrNull(command.args.indexOf("--app") + 1)?.let { names[it] = command.name }
if (command.program == BATTLENET) command.args.getOrNull(command.args.indexOf("launch") + 1)?.takeIf { command.args.contains("launch") }?.let { names[it] = command.name }
}
}
@@ -74,6 +74,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
"usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url",
@@ -566,6 +566,32 @@ object SessionPrefs {
prefs(context).edit().putBoolean("logs", on).apply()
}
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
fun clearCachedApps(context: Context): Boolean = prefs(context).getBoolean("clearCachedApps", false)
fun setClearCachedApps(context: Context, on: Boolean) { prefs(context).edit().putBoolean("clearCachedApps", on).apply() }
fun backgroundAppLimit(context: Context): Int =
prefs(context).getInt("backgroundAppLimit", com.droiddeck.launcher.core.BackgroundAppLimit.OFF)
.takeIf { it in com.droiddeck.launcher.core.BackgroundAppLimit.CHOICES } ?: com.droiddeck.launcher.core.BackgroundAppLimit.OFF
fun setBackgroundAppLimit(context: Context, limit: Int) {
require(limit in com.droiddeck.launcher.core.BackgroundAppLimit.CHOICES)
prefs(context).edit().putInt("backgroundAppLimit", limit).apply()
}
const val MEMORY_HUD_OFF = "off"
const val MEMORY_HUD_SIMPLE = "simple"
const val MEMORY_HUD_ADVANCED = "advanced"
fun memoryHud(context: Context): String =
prefs(context).getString("memoryHud", MEMORY_HUD_OFF)
?.takeIf { it == MEMORY_HUD_SIMPLE || it == MEMORY_HUD_ADVANCED } ?: MEMORY_HUD_OFF
fun setMemoryHud(context: Context, value: String) {
require(value == MEMORY_HUD_OFF || value == MEMORY_HUD_SIMPLE || value == MEMORY_HUD_ADVANCED)
prefs(context).edit().putString("memoryHud", value).apply()
}
fun storageDiagnosticsEnabled(context: Context): Boolean =
prefs(context).getBoolean("storageDiagnostics", false)
@@ -351,6 +351,7 @@ class SessionService : Service() {
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
@@ -365,6 +366,9 @@ class SessionService : Service() {
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
com.droiddeck.launcher.wayland.CompositorHost.newSession()
val gen = ++sessionGen
SessionPrefs.backgroundAppLimit(this).takeIf { it != com.droiddeck.launcher.core.BackgroundAppLimit.OFF }
?.let { com.droiddeck.launcher.core.BackgroundAppLimit.applyAsync(this, it) }
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
cancelQueuedSteamGame(clearMailbox = false)
clearSteamGameMailbox()
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl
@@ -671,6 +675,7 @@ class SessionService : Service() {
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
SessionLogCapture.start(File(sessionDir, "app.log"))
MemoryLog.start()
return sessionDir
}
@@ -757,7 +762,7 @@ class SessionService : Service() {
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC)
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
@@ -1057,6 +1062,7 @@ class SessionService : Service() {
if (!stillSameProcess()) return
val tree = descendants(prootPid)
if (!stillSameProcess()) return
saveWineRegistries(tree)
android.os.Process.sendSignal(prootPid, 15)
if (!waitForExit(prootPid, GRACE_MS)) {
if (!stillSameProcess()) return
@@ -1073,6 +1079,31 @@ class SessionService : Service() {
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
}
private fun clearCachedApps() {
val app = applicationContext
Thread({
val before = MemoryReadout.availableMb()
val result = runCatching { com.droiddeck.launcher.core.WirelessAdbFix.clearCachedApps(app) }
val after = MemoryReadout.availableMb()
result.onSuccess { Log.i(TAG, "cached apps closed: available memory $before -> $after MB") }
.onFailure { Log.w(TAG, "cached apps not closed: ${it.message}") }
}, "clear-cached-apps").start()
}
private fun saveWineRegistries(tree: List<Pair<Int, Long>>) {
val servers = tree.filter { (pid, started) ->
readStat(pid)?.second == started && WineProcesses.isWineserver(
runCatching { File("/proc/$pid/cmdline").readBytes() }.getOrNull(),
runCatching { File("/proc/$pid/comm").readText() }.getOrNull(),
)
}
if (servers.isEmpty()) return
servers.forEach { (pid, _) -> android.os.Process.sendSignal(pid, 15) }
val deadline = System.currentTimeMillis() + WINE_SAVE_MS
val saved = servers.count { (pid, _) -> waitForExit(pid, (deadline - System.currentTimeMillis()).coerceAtLeast(0)) }
Log.i(TAG, "wineserver registry save: $saved of ${servers.size} exited after SIGTERM")
}
private fun descendants(root: Int): List<Pair<Int, Long>> {
val started = HashMap<Int, Long>()
val children = HashMap<Int, MutableList<Int>>()
@@ -1352,6 +1383,11 @@ class SessionService : Service() {
}
return
}
if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) {
File(dir, path).delete()
com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir)
return
}
if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) {
val request = File(dir, path)
val text = runCatching { request.readText() }.getOrNull() ?: return
@@ -1635,6 +1671,8 @@ class SessionService : Service() {
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks()
MemoryLog.stop()
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else {
@@ -1688,7 +1726,8 @@ class SessionService : Service() {
updateDownloadMonitoring()
val stoppedGen = sessionGen
val stoppedSession = SessionState.sessionId
val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC
val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC ||
SessionState.program == NoSteamLaunch.BATTLENET
SessionState.stopRequested = false
GpuClockPin.stop(this)
GameThreadHints.stop()
@@ -1748,6 +1787,9 @@ class SessionService : Service() {
private fun importLauncherGames() {
runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.importClientGames(this) }
.onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") }
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(this) }
.onFailure { Log.w(TAG, "Battle.net sign-in check failed: ${it.javaClass.simpleName}") }
com.droiddeck.launcher.stores.StoresState.notifyLibraryChanged(this)
}
override fun onTaskRemoved(rootIntent: Intent?) {
@@ -1995,6 +2037,7 @@ class SessionService : Service() {
private val STRAGGLERS = listOf("droiddeck-session", "gamescope", "Xwayland", "steamrtarm64",
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
private const val GRACE_MS = 1200L
private const val WINE_SAVE_MS = 3000L
private const val STEAM_PICKUP_MS = 1500L
private const val STEAM_EXIT_MS = 10_000L
private const val GAME_LAUNCH_RETRY_MS = 250L
@@ -0,0 +1,13 @@
package com.droiddeck.launcher.session
internal object WineProcesses {
private const val WINESERVER = "wineserver"
fun isWineserver(cmdline: ByteArray?, comm: String?): Boolean {
val program = cmdline?.let { bytes ->
val end = bytes.indexOf(0.toByte()).let { if (it < 0) bytes.size else it }
String(bytes, 0, end, Charsets.UTF_8).substringAfterLast('/')
}
return program == WINESERVER || comm?.trim() == WINESERVER
}
}
@@ -58,7 +58,7 @@ object CloudSaves {
val item = sidecar.extra["catalogItemId"].orEmpty()
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
}
Store.AMAZON, Store.ITCH, Store.XBOX -> ""
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> ""
} ?: return null
p.edit().putString("cloud_template_$id", fetched).apply()
Log.i(TAG, "cloud ${store.id} $id template ${if (fetched.isEmpty()) "none" else "found"}")
@@ -96,7 +96,7 @@ object CloudSaves {
val dir = when (store) {
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
Store.AMAZON, Store.ITCH, Store.XBOX -> null
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null
}
return dir to (if (dir == null) "unresolved" else "ok")
}
@@ -121,7 +121,7 @@ object CloudSaves {
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
}
Store.AMAZON, Store.ITCH, Store.XBOX -> null
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -12,7 +12,7 @@ internal object LoginFlows {
Store.GOG -> GogFlow(state, browserUserAgent)
Store.EPIC -> epicFlow()
Store.AMAZON -> amazonFlow()
Store.ITCH, Store.XBOX -> null
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
}
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
@@ -23,14 +23,14 @@ object SteamLiveShortcuts {
val wanted = games.filter(include)
if (wanted.isEmpty() || !clientRunning()) return
val list = JSONArray()
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL))
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL).put("launch", g.launchOptions))
val js = """
(async () => {
const want = ${list};
let added = 0;
for (const w of want) {
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))})) added++;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++;
}
return added;
})()
@@ -164,8 +164,8 @@ object SteamLiveShortcuts {
private fun compatTool(context: Context): String =
com.droiddeck.launcher.session.ProtonDefault.state(context).default ?: COMPAT_TOOL
private val ADD = """(async (name, exe, dir, compat, tool) => {
const id = await SteamClient.Apps.AddShortcut(name, exe, dir, "");
private val ADD = """(async (name, exe, dir, compat, tool, launch) => {
const id = await SteamClient.Apps.AddShortcut(name, exe, dir, launch || "");
if (!id) return 0;
try { SteamClient.Apps.SetShortcutName(id, name); } catch (e) {}
try { SteamClient.Apps.AddUserTagToApps([id], ${JSONObject.quote(TAG_NAME)}); } catch (e) {}
@@ -5,7 +5,8 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
EPIC("epic", "Epic Games", "Epic"),
AMAZON("amazon", "Amazon Games", "Amazon"),
XBOX("xbox", "Xbox", "Xbox"),
ITCH("itch", "itch.io", "itch");
ITCH("itch", "itch.io", "itch"),
BATTLENET("battlenet", "Battle.net", "Battle.net");
companion object {
fun byId(id: String?): Store? = entries.firstOrNull { it.id == id }
@@ -90,6 +90,7 @@ object StoreAccounts {
fun signedInAs(context: Context, store: Store): String? {
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
if (store == Store.XBOX) return json.optString("username").takeIf { it.isNotBlank() }
if (store == Store.BATTLENET) return json.optString("display_name").takeIf { it.isNotBlank() }
if (json.optString("access_token", "").isEmpty()) return null
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
}
@@ -91,6 +91,8 @@ object StoreInstallRoot {
fun installRoot(context: Context): File = internalRoot(context)
fun libraryRoot(context: Context): File? = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
fun roots(context: Context): List<File> {
val cards = GameStorage.options(context).map { File(it.path, ON_VOLUME) }
val library = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
@@ -187,7 +189,7 @@ object StoreInstallRoot {
fun isFinished(folder: File): Boolean = StoreGameSidecar.read(folder)?.isInstalled == true
fun unfinished(context: Context): List<Unfinished> = roots(context).flatMap { root ->
Store.entries.flatMap { store ->
Store.entries.filter { it != Store.BATTLENET }.flatMap { store ->
storeDir(root, store).listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { folder ->
val sidecar = StoreGameSidecar.read(folder)
when {
@@ -55,7 +55,7 @@ object StoreSizes {
Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.ITCH -> {}
Store.GOG, Store.XBOX -> {}
Store.GOG, Store.XBOX, Store.BATTLENET -> {}
}
}
}, pool).exceptionally { error ->
@@ -111,7 +111,7 @@ object StoreSizes {
val bytes = AmazonApiClient.getBytes(AmazonApiClient.appendPath(spec.downloadUrl, "manifest.proto"), token) ?: return 0L
AmazonManifest.parse(bytes).totalInstallSize
}
Store.GOG, Store.XBOX -> 0L
Store.GOG, Store.XBOX, Store.BATTLENET -> 0L
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
} }
}
@@ -77,10 +77,11 @@ object StoresState {
val app = context.applicationContext
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
background("stores-refresh") {
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
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) }
}
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
val partial = StoreInstallRoot.unfinished(app)
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
main.post {
@@ -225,6 +226,10 @@ object StoresState {
fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) {
val app = context.applicationContext
if (item.store == Store.BATTLENET) {
backends[item.store]?.install(app, item, root ?: StoreInstallRoot.installRoot(app))
return
}
val folder = StoreInstallRoot.folderFor(app, item.store, item.id, item.title, root ?: StoreInstallRoot.installRoot(app))
val target = folder.parentFile!!.parentFile!!
val code = language?.takeIf { it.isNotBlank() } ?: StoreLanguage.preferredCode(app)
@@ -258,6 +263,10 @@ object StoresState {
uninstalling[key] = 0f
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
if (game.sidecar.store == Store.BATTLENET) {
main.post { uninstalling.remove(key); onDone() }
return@background
}
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
main.post {
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
@@ -0,0 +1,294 @@
package com.droiddeck.launcher.stores.battlenet
import android.content.Context
import android.net.Uri
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoreBackend
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreShelves
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.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
object BattleNetClient {
private const val TAG = "BattleNetClient"
const val DOWNLOAD_ID = "battlenet-client"
const val DOWNLOAD_KEY = "battlenet:$DOWNLOAD_ID"
const val REQUEST = "battlenet-request"
internal const val INSTALLER_URL = "https://downloader.battle.net/download/getInstallerForGame?os=win&gameProgram=BATTLENET_APP&version=Live"
private const val SETUP = "root/.cache/droiddeck/battlenet/Battle.net-Setup.exe"
private const val CONFIG = "pfx/drive_c/users/steamuser/AppData/Roaming/Battle.net/Battle.net.config"
internal const val MIN_SETUP = 1L shl 20
private val work = Executors.newSingleThreadExecutor { r -> Thread(r, "battlenet-client") }
private val sequence = AtomicLong()
@Volatile var opener: ((List<String>) -> Unit)? = null
fun setup(context: Context): File = File(LinuxRuntime.rootDir(context), SETUP)
internal fun setupReady(file: File): Boolean = runCatching {
file.length() >= MIN_SETUP && file.inputStream().use { input ->
val head = ByteArray(2)
input.read(head) == 2 && head[0] == 'M'.code.toByte() && head[1] == 'Z'.code.toByte()
}
}.getOrDefault(false)
internal fun account(config: String?): String? {
val client = runCatching { JSONObject(config ?: return null).optJSONObject("Client") }.getOrNull() ?: return null
if (client.optString("AutoLogin") != "true") return null
return client.optString("SavedAccountNames").split(',').map { it.trim() }.firstOrNull { it.isNotEmpty() }
}
private fun config(context: Context) = File(BattleNet.prefix(context), CONFIG)
fun signedInAs(context: Context): String? =
if (!BattleNet.installed(context)) null
else account(runCatching { config(context).readText() }.getOrNull())?.let(StoreAccounts::maskEmail)
fun syncAccount(context: Context): Boolean {
val name = signedInAs(context)
if (name == StoreAccounts.signedInAs(context, Store.BATTLENET)) return false
if (name == null) StoreAccounts.clear(context, Store.BATTLENET)
else StoreAccounts.write(context, Store.BATTLENET, JSONObject().put("display_name", name))
Log.i(TAG, if (name == null) "Battle.net is signed out" else "Battle.net is signed in")
return true
}
fun refresh(context: Context) {
val app = context.applicationContext
work.execute {
if (runCatching { syncAccount(app) }.getOrDefault(false)) StoresState.notifyLibraryChanged(app)
}
}
fun signIn(context: Context) {
val app = context.applicationContext
work.execute {
if (BattleNet.installed(app) || setupReady(setup(app))) {
open(emptyList())
return@execute
}
StoresState.post {
if (DownloadQueue.isActive(DOWNLOAD_KEY)) return@post
val entry = DownloadEntry(
Store.BATTLENET, DOWNLOAD_ID, app.getString(R.string.bnet_name),
location = StoreInstallRoot.labelFor(app, setup(app)),
)
DownloadQueue.enqueue(app, entry) { SetupDownload(app) }
StoresState.openDownloads = true
}
}
}
fun signOut(context: Context) {
val file = config(context)
runCatching {
val json = JSONObject(file.readText())
json.optJSONObject("Client")?.put("AutoLogin", "false") ?: return@runCatching
val staged = File(file.path + ".droiddeck")
staged.writeText(json.toString(4))
check(staged.renameTo(file))
Log.i(TAG, "Battle.net will ask for a sign-in at its next start")
}.onFailure { Log.w(TAG, "Battle.net's sign-in kept: ${it.javaClass.simpleName}") }
}
fun request(sessionRoot: File, args: List<String>): Boolean = runCatching {
require(args.none { '\n' in it })
val now = System.nanoTime()
val name = "$REQUEST.%020d".format(java.util.Locale.ROOT, sequence.updateAndGet { maxOf(it + 1, now) })
val staged = File(sessionRoot, "$name.tmp")
staged.writeText(args.joinToString("\n") + "\n")
check(staged.renameTo(File(sessionRoot, name)))
Log.i(TAG, "handed ${args.firstOrNull()} to the open Battle.net")
}.onFailure { Log.w(TAG, "Battle.net request not left: ${it.javaClass.simpleName}") }.isSuccess
fun clearRequests(sessionRoot: File) {
sessionRoot.listFiles { file -> file.name == REQUEST || file.name.startsWith("$REQUEST.") }?.forEach { it.delete() }
}
fun open(args: List<String>) {
StoresState.post { opener?.invoke(args) }
}
fun library(context: Context, root: File = preferred(context)): List<String> =
AddedGames.guestPath(context, StoreInstallRoot.storeDir(root, Store.BATTLENET))?.let { listOf("--library", it) }.orEmpty()
internal fun preferred(context: Context): File {
val second = StoreInstallRoot.libraryRoot(context)?.absolutePath
return StoreInstallRoot.targets(context).firstOrNull { it.root.absolutePath == second && (it.root.isDirectory || it.root.mkdirs()) }?.root
?: StoreInstallRoot.internalRoot(context)
}
fun installGame(context: Context, uid: String, root: File) {
val app = context.applicationContext
work.execute { open(library(app, root) + listOf("install-game", uid)) }
}
internal fun downloaded(context: Context) {
Log.i(TAG, "Battle.net's installer downloaded from Blizzard")
open(emptyList())
StoresState.post { StoresState.notifyLibraryChanged(context) }
}
}
object BattleNetBackend : StoreBackend {
override val store: Store = Store.BATTLENET
override fun signIn(context: Context) = BattleNetClient.signIn(context)
override fun signOut(context: Context) {
BattleNetClient.signOut(context)
StoresState.post { StoresState.shelves.remove(store); StoresState.found.remove(store) }
}
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
Thread({
val items = runCatching { installed(app).map { item(app, it.title, owned = true) } }.getOrDefault(emptyList())
StoresState.post { StoresState.library[store] = items }
}, "battlenet-library").start()
}
override fun loadShelves(context: Context, force: Boolean) {
val app = context.applicationContext
Thread({
val known = shelves(app)
StoresState.post { StoresState.shelves[store] = known }
if (runCatching { BattleNet.fetchCovers(app) }.getOrDefault(false)) {
val covered = shelves(app)
val items = runCatching { installed(app).map { item(app, it.title, owned = true) } }.getOrDefault(emptyList())
StoresState.post {
StoresState.shelves[store] = covered
StoresState.library[store] = items
StoresState.notifyLibraryChanged(app)
}
}
}, "battlenet-shelves").start()
}
override fun search(context: Context, query: String): List<CatalogItem> =
BattleNet.STORE.filter { it.name.contains(query, ignoreCase = true) }.map { item(context, it) }
override fun install(context: Context, item: CatalogItem, root: File) = BattleNetClient.installGame(context, item.id, root)
override fun uninstall(context: Context, game: InstalledStoreGame) = BattleNetClient.open(emptyList())
fun installed(context: Context): List<BattleNet.Game> = if (BattleNet.installed(context)) BattleNet.games(context) else emptyList()
fun installedGames(context: Context): List<InstalledStoreGame> = installed(context).map { game ->
val art = BattleNet.art(context, game.title)
val cover = art.cover?.let { Uri.fromFile(it).toString() }
InstalledStoreGame(StoreGameSidecar(store, game.title.uid, game.name, "", cover = cover, hero = art.header?.let { Uri.fromFile(it).toString() } ?: cover), game.folder)
}
private fun shelves(context: Context): StoreShelves {
val items = BattleNet.STORE.map { item(context, it) }
return StoreShelves(trending = items, art = items.mapNotNull { it.tallImageUrl })
}
private fun item(context: Context, title: BattleNet.Title, owned: Boolean = false): CatalogItem {
val art = BattleNet.art(context, title)
return CatalogItem(
store, title.uid, title.name,
imageUrl = (art.header ?: art.cover)?.let { Uri.fromFile(it).toString() },
tallImageUrl = art.cover?.let { Uri.fromFile(it).toString() },
owned = owned,
)
}
}
internal class SetupDownload(private val app: Context) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
@Volatile private var connection: HttpURLConnection? = null
override fun run(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.DOWNLOAD)
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.epic_client_no_runtime))
val file = BattleNetClient.setup(app)
val partial = File(file.path + ".part")
file.parentFile?.mkdirs()
var attempt = 0
while (!cancelled.get()) {
try {
fetch(partial, handle)
if (cancelled.get()) break
if (!BattleNetClient.setupReady(partial)) throw IOException("not a Windows program")
if (!partial.renameTo(file)) throw IOException("could not keep the installer")
BattleNetClient.downloaded(app)
return file.absolutePath
} catch (e: IOException) {
partial.delete()
if (cancelled.get()) break
attempt++
handle.log("Battle.net installer attempt $attempt: ${e.message ?: e.javaClass.simpleName}")
if (attempt >= ATTEMPTS) throw IllegalStateException(app.getString(R.string.epic_client_download_failed, e.message ?: e.javaClass.simpleName))
val until = System.currentTimeMillis() + (2_000L shl (attempt - 1))
while (System.currentTimeMillis() < until && !cancelled.get()) Thread.sleep(100)
}
}
partial.delete()
return null
}
private fun fetch(partial: File, handle: DownloadQueue.JobHandle) {
val conn = (URL(BattleNetClient.INSTALLER_URL).openConnection() as HttpURLConnection).apply {
connectTimeout = 20_000
readTimeout = 30_000
instanceFollowRedirects = true
setRequestProperty("User-Agent", "DroidDeck")
}
connection = conn
try {
if (conn.responseCode != 200) throw IOException("HTTP ${conn.responseCode}")
if (conn.url.protocol != "https") throw IOException("not served over HTTPS")
val total = conn.contentLengthLong
var done = 0L
conn.inputStream.use { input ->
FileOutputStream(partial).use { out ->
val buf = ByteArray(64 * 1024)
while (!cancelled.get()) {
val n = input.read(buf)
if (n < 0) break
out.write(buf, 0, n)
done += n
handle.progress(done, total)
}
out.fd.sync()
}
}
if (!cancelled.get() && total > 0 && done != total) throw IOException("the download ended early")
} finally {
connection = null
runCatching { conn.disconnect() }
}
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
runCatching { connection?.disconnect() }
}
private companion object {
const val ATTEMPTS = 4
}
}
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.stores.battlenet
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.File
import java.io.IOException
import java.net.CookieManager
import java.net.CookiePolicy
import java.net.HttpURLConnection
import java.net.URL
internal object BlizzardArt {
private const val SHOP = "https://us.shop.battle.net/en-us/product/"
private const val MAX_PAGE = 16 shl 20
private const val MAX_IMAGE = 12 shl 20
private const val WIDE = 1280
private val OG = Regex("""<meta property="og:image" content="(https://[^"]+)"""")
private val THUMB = Regex("""\\?"imageUrl\\?":\\?"(//catalog\.blzstatic\.com/[^"\\]+)""")
private val HOSTS = listOf(".blzstatic.com", ".blz-contentstack.com", "blz-contentstack-images.akamaized.net")
internal fun imageUrl(page: String): String? {
val og = OG.find(page)?.groupValues?.get(1)?.takeUnless { "youtube" in it || "maxresdefault" in it }
val thumbs = THUMB.findAll(page).map { it.groupValues[1] }.filter { "_bundle" !in it }.map { "https:$it" }
return (sequenceOf(og) + thumbs).filterNotNull().firstOrNull(::allowed)
}
private fun allowed(url: String): Boolean {
val host = runCatching { URL(url).host }.getOrNull() ?: return false
return HOSTS.any { h -> host == h.trimStart('.') || host.endsWith(h) }
}
fun fetch(slug: String, wide: File, cover: File?): Boolean {
val page = get(URL(SHOP + slug), MAX_PAGE, true)?.toString(Charsets.UTF_8) ?: return false
val url = imageUrl(page) ?: return false
val bytes = get(URL(url.substringBefore('?') + "?imwidth=$WIDE"), MAX_IMAGE, false) ?: return false
val art = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return false
try {
val scaled = if (art.width > WIDE) Bitmap.createScaledBitmap(art, WIDE, art.height * WIDE / art.width, true) else art
save(scaled, wide)
if (cover != null) {
val w = minOf(scaled.width, scaled.height * 2 / 3)
val crop = Bitmap.createBitmap(scaled, (scaled.width - w) / 2, 0, w, w * 3 / 2)
save(Bitmap.createScaledBitmap(crop, 600, 900, true), cover)
}
return true
} finally {
art.recycle()
}
}
private fun save(bitmap: Bitmap, file: File) {
val tmp = File(file.path + ".tmp")
tmp.outputStream().use { if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)) throw IOException("not saved") }
if (!tmp.renameTo(file)) throw IOException("not kept")
}
private fun get(start: URL, limit: Int, follow: Boolean): ByteArray? {
val cookies = CookieManager(null, CookiePolicy.ACCEPT_ALL)
var url = start
repeat(8) {
if (url.protocol != "https") return null
val conn = (url.openConnection() as HttpURLConnection).apply {
instanceFollowRedirects = false
connectTimeout = 15_000
readTimeout = 20_000
setRequestProperty("User-Agent", "DroidDeck")
cookies.get(url.toURI(), emptyMap()).forEach { (k, v) -> if (v.isNotEmpty()) setRequestProperty(k, v.joinToString("; ")) }
}
try {
val code = conn.responseCode
cookies.put(url.toURI(), conn.headerFields)
when {
code == 200 -> return conn.inputStream.use { input ->
val out = java.io.ByteArrayOutputStream()
val buf = ByteArray(64 * 1024)
while (true) {
val n = input.read(buf)
if (n < 0) break
out.write(buf, 0, n)
if (out.size() > limit) return null
}
out.toByteArray()
}
follow && code in 301..308 -> url = URL(url, conn.getHeaderField("Location") ?: return null)
else -> return null
}
} finally {
conn.disconnect()
}
}
return null
}
}
@@ -100,6 +100,10 @@ class FrontEndState(
val logsEnabled: Boolean,
val vacDiagnostics: Boolean = false,
val agentCommands: Boolean = false,
val clearCachedApps: Boolean = false,
val adbPaired: Boolean = false,
val backgroundAppLimit: Int = -1,
val memoryHud: String = "off",
val steamGames: List<Library.SteamGame>,
val steamGamesX64: Boolean = false,
val emulators: List<Library.Emulator>,
@@ -124,6 +128,7 @@ class FrontEndState(
val packageStage: String? = null,
val packagePercent: Int = -1,
val sessionRunning: Boolean = false,
val battleNetInstalled: Boolean = false,
val removalPending: Boolean = false,
val runtimeActionsBlocked: Boolean = false,
val backActionsInverted: Boolean = false,
@@ -176,6 +181,7 @@ class FrontEndActions(
val onEmulator: (Library.Emulator) -> Unit,
val onFlatpakApp: (String, String) -> Unit = { _, _ -> },
val onUserApp: (com.droiddeck.launcher.runtime.UserApps.App) -> Unit = {},
val onBattleNet: () -> Unit = {},
val onRom: (Library.Rom) -> Unit,
val onResume: () -> Unit,
val onSteamSettings: () -> Unit,
@@ -200,6 +206,9 @@ class FrontEndActions(
val onLogs: () -> Unit,
val onVacDiagnostics: () -> Unit = {},
val onAgentCommands: () -> Unit = {},
val onClearCachedApps: (Boolean) -> Unit = {},
val onMemoryHud: (String) -> Unit = {},
val onBackgroundAppLimit: (Int) -> Unit = {},
val onShareLogs: () -> Unit = {},
val onClearLogs: () -> Unit = {},
val onResetSettings: () -> Unit = {},
@@ -470,6 +470,38 @@ internal fun SetupPanel(
ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint),
stringResource(R.string.setup_reset_settings_button), a.onResetSettings)
}
SettingsGroup(stringResource(R.string.setup_group_memory)) {
ToggleRow(
host, "clear-cached-apps", stringResource(R.string.setup_clear_cached),
stringResource(if (s.adbPaired) R.string.setup_clear_cached_hint else R.string.setup_clear_cached_unpaired),
s.clearCachedApps, enabled = s.adbPaired || s.clearCachedApps,
) { a.onClearCachedApps(it) }
ChoiceRow(
host, "background-app-limit", stringResource(R.string.setup_bg_limit),
stringResource(if (s.adbPaired) R.string.setup_bg_limit_hint else R.string.setup_clear_cached_unpaired),
listOf(
com.droiddeck.launcher.core.BackgroundAppLimit.OFF to stringResource(R.string.game_env_off),
4 to stringResource(R.string.setup_bg_limit_4),
1 to stringResource(R.string.setup_bg_limit_1),
0 to stringResource(R.string.setup_bg_limit_0),
),
s.backgroundAppLimit, enabled = s.adbPaired || s.backgroundAppLimit != com.droiddeck.launcher.core.BackgroundAppLimit.OFF,
onPick = a.onBackgroundAppLimit,
)
ChoiceRow(
host, "memory-hud", stringResource(R.string.setup_memory_hud), stringResource(R.string.setup_memory_hud_hint),
listOf(
com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_OFF to stringResource(R.string.game_env_off),
com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_SIMPLE to stringResource(R.string.setup_memory_hud_simple),
com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_ADVANCED to stringResource(R.string.setup_memory_hud_advanced),
),
s.memoryHud, onPick = a.onMemoryHud,
)
if (!s.adbPaired) ActionRow(
stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint),
stringResource(R.string.setup_adb_pair_button), { onRequestWirelessAdb(false) },
)
}
}
GLASSES_TAB -> GlassesSetupPanel()
}
@@ -364,6 +364,7 @@ private fun GameActions(
}
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
}
if (store == Store.BATTLENET) SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
@@ -378,6 +379,7 @@ private fun GameActions(
}
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
}
store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> {
XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
XboxLibraryButton(item.id, item)
@@ -521,6 +523,7 @@ private fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, la
private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id) return
if (installed != null) {
val key = installed.key
val gone = StoresState.uninstalling[key]
@@ -101,7 +101,8 @@ internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", on
LaunchedEffect(Unit) {
runCatching {
withContext(Dispatchers.IO) {
GameEnvironmentStore.read(context) to Library.steamGames(context).map { it.appId.toString() to it.name }
GameEnvironmentStore.read(context) to Library.steamGames(context).map { it.appId.toString() to it.name } +
listOfNotNull(com.droiddeck.launcher.runtime.BattleNet.profile(context))
}
}.onSuccess { (settings, installed) -> config = settings; games = installed }
.onFailure { error = true }
@@ -31,6 +31,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
Store.AMAZON.id -> SourceColours(Color(0xFF3A2A0A), Color(0xFFFFC266), Color(0xFFFF9900))
Store.XBOX.id -> SourceColours(Color(0xFF17381B), Color(0xFFC6EDC2), Color(0xFF70C850))
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
@@ -44,6 +45,7 @@ internal fun sourceLabel(source: String): String = when (source) {
Store.AMAZON.id -> Store.AMAZON.label
Store.XBOX.id -> Store.XBOX.label
Store.ITCH.id -> Store.ITCH.label
Store.BATTLENET.id -> Store.BATTLENET.label
else -> stringResource(R.string.source_added)
}
@@ -221,7 +221,7 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions,
ArtStrip(d.cover, d.name) {
StripLabel(d.name, d.store.id, stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), Color.White.copy(alpha = 0.72f))
if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else launchStoreGame(ctx, d.store, d.id, s, a) }
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(ctx, d.store, d.id, s, a) }
}
}
}
@@ -372,7 +372,7 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
CancelAction { DownloadQueue.clear(ctx, d.key) }
}
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else launchStoreGame(ctx, d.store, d.id, s, a) }
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(ctx, d.store, d.id, s, a) }
}
DownloadState.CANCELLED -> {}
}
@@ -235,6 +235,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
LaunchedEffect(Unit) { StoresState.refresh(ctx) }
val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
LaunchedEffect(chip) {
if (chip == Store.BATTLENET.id) {
while (true) {
if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) com.droiddeck.launcher.stores.battlenet.BattleNetClient.refresh(ctx)
delay(5_000)
}
}
if (chip == Store.EPIC.id) {
EpicClient.ensure(ctx)
while (true) {
@@ -919,7 +925,7 @@ private fun Storefront(
Shelf(stringResource(R.string.stores_shelf_new), shelf(shelves?.whatsNew), card)
Shelf(stringResource(R.string.stores_shelf_deals), shelf(shelves?.deals), card)
Shelf(stringResource(R.string.stores_shelf_free), shelf(shelves?.free), card)
Shelf(stringResource(R.string.stores_shelf_trending), shelf(shelves?.trending), card)
Shelf(stringResource(if (store == Store.BATTLENET) R.string.bnet_store else R.string.stores_shelf_trending), shelf(shelves?.trending), card)
if (shelves == null) Rise(4) { Box(Modifier.padding(top = 8.dp)) { Note(stringResource(R.string.stores_shelves_loading)) } }
else if (shelves.isEmpty && store == Store.AMAZON) Rise(4) { Box(Modifier.padding(top = 8.dp)) { Note(stringResource(R.string.stores_amazon_no_catalog)) } }
}
@@ -965,6 +971,39 @@ private fun ProfileStrip(store: Store, owned: Int, loaded: Boolean, s: FrontEndS
}
}
if (store == Store.EPIC) EpicLauncherRow(s, a)
if (store == Store.BATTLENET) BattleNetLauncherRow(s, a)
}
}
@Composable
private fun BattleNetLauncherRow(s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val title = stringResource(R.string.bnet_name)
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().testTag("stores-battlenet-launcher")) {
val icon by androidx.compose.runtime.produceState<java.io.File?>(null, s.battleNetInstalled) {
value = if (!s.battleNetInstalled) null
else kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.runtime.BattleNet.icon(ctx) }
}
if (icon != null) AsyncImage(model = icon, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.size(36.dp).clip(RoundedCornerShape(8.dp)))
Text(title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Actions {
SecondaryButton(stringResource(R.string.bnet_open), enabled = !s.busy, compact = true) { a.onBattleNet() }
val entry = remember(s.battleNetInstalled) { com.droiddeck.launcher.runtime.BattleNet.launcherEntry(s.battleNetInstalled) }
val scope = entry?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) }
if (entry != null && scope != null) {
val host = rememberMenuHost()
val settings = rememberGameSettings(scope)
Box {
SecondaryButton(stringResource(R.string.game_settings_card), compact = true) {
host.open = if (host.open == GAME_SETTINGS_MENU) null else GAME_SETTINGS_MENU
}
GameSettingsMenus(host, entry, settings)
}
}
}
}
}
@@ -1066,6 +1105,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
Store.AMAZON -> Color(0xFFFF9900) to Color(0xFFE07800)
Store.XBOX -> Color(0xFF70C850) to Color(0xFF107C10)
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
null -> return base
}
val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White