fix(input): reconcile the second-screen picker

This commit is contained in:
Kurt Himebauch committed 2026-11-20 07:30:42 -05:00
commit ec1d5126c4
197 files changed
+12209 -3764

No files matched your search

@@ -99,6 +99,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
this, ui,
idle = { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null },
onInstalled = { if (!OfflineMode.enabled(this)) components.checkComponentUpdates(force = false) },
onRemoved = { components.refreshComponents() },
)
private var installed by mutableStateOf<String?>(null)
@@ -180,10 +181,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var ramCapMb by mutableStateOf(0)
private var zramClient by mutableStateOf(true)
private var zramIdle by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
@@ -279,6 +276,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) }
}
private val pickExperimentalProton = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { zip ->
protons.installExperimental { progress -> com.droiddeck.launcher.session.ExperimentalProtons.installFromFile(this, zip, progress) }
}
}
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
@@ -873,7 +875,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
}, "components-restore").start()
}
private var pendingGameLink: String? = null
private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null
private var gameLinkReading = false
private var gameLinkTried = false
private var gameSyncFolder by mutableStateOf<String?>(null)
@@ -945,12 +947,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
val copy = Intent(request)
Thread({
val id = GameLaunchIntent.read(this, copy)
val game = GameLaunchIntent.read(this, copy)
ui.post {
if (intent === request && !isDestroyed) {
gameLinkReading = false
pendingGameLink = id
if (id == null) {
pendingGameLink = game
if (game == null) {
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
} else {
@@ -1200,16 +1202,16 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val id = pendingGameLink ?: return
if (!scanned && games.none { it.gameIdString == id }) return
val request = pendingGameLink ?: return
val game = request.find(games, byTitle = scanned)
if (!scanned && game == null) return
gameLinkTried = true
ui.postDelayed({
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
}, LINK_PANEL_MS)
val game = games.firstOrNull { it.gameIdString == id }
val link = intent
fun consume() {
if (intent !== link || pendingGameLink != id) return
if (intent !== link || pendingGameLink !== request) return
pendingGameLink = null
link.data = null
link.action = Intent.ACTION_MAIN
@@ -1218,7 +1220,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (game == null) {
consume()
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
android.widget.Toast.makeText(this,
if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing,
android.widget.Toast.LENGTH_LONG).show()
} else launchGame(game, returnHome = true, onSettled = ::consume)
}
@@ -1513,7 +1517,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onComponents = { focusContent -> openComponents(focusContent) },
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(this@FrontEndActivity, sg) } },
onAddonImport = { sg, target -> importAddons(sg.name, target) },
onAddonDelete = { target, name ->
saveAction(getString(R.string.main_addons_deleting, name)) {
@@ -1521,7 +1525,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
getString(R.string.main_addons_deleted, name)
}
},
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(this@FrontEndActivity, sg) } },
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
performancePanel = { PerformanceHost(embedded = true) },
onRoms = { showRoms = true },
@@ -2431,13 +2435,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
),
protons = com.droiddeck.launcher.ui.ProtonsState(
rows = protons.protonRows, busyId = protons.protonBusyId, stage = protons.protonStage, percent = protons.protonPercent,
runtimeReady = ready && !busy, sessionRunning = SessionState.running,
runtimeReady = ready && !busy, sessionRunning = SessionState.running, experimental = protons.experimentalDirs,
experimentalReleases = protons.experimentalReleases,
),
protonActions = com.droiddeck.launcher.ui.ProtonsActions(
onInstall = { id -> protons.installProton(id) },
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
onRemove = { id, dir -> protons.removeProton(id, dir) },
onRemoveOlder = { id -> protons.removeProton(id, older = true) },
onExperimentalFile = {
pickExperimentalProton.launch(InAppFilePicker.buildIntent(this, EXPERIMENTAL_PROTON_EXT, getString(R.string.xproton_install_file),
android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path))
},
onExperimentalRelease = { release -> protons.installExperimentalRelease(release) },
onRemoveExperimental = { dir -> protons.removeExperimental(dir) },
),
protonOptions = {
com.droiddeck.launcher.ui.ProtonOptions(
@@ -2745,10 +2756,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, zramIdle = zramIdle,
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
@@ -2763,10 +2770,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
onZramIdle = { on -> SessionPrefs.setZramIdle(this, on); zramIdle = on },
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
@@ -3065,10 +3068,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
ramCapMb = SessionPrefs.ramCapMb(this)
zramClient = SessionPrefs.zramClient(this)
zramIdle = SessionPrefs.zramIdle(this)
vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
@@ -3418,6 +3417,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val ZIP_EXT = listOf("zip")
private val EXPERIMENTAL_PROTON_EXT = listOf("zip", "7z", "tar", "gz", "xz", "zst", "bz2", "tgz", "txz", "tbz2", "tzst")
private val WCP_EXT = listOf("wcp")
}
}
@@ -7,6 +7,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
@@ -19,6 +20,7 @@ internal class ProtonMenu(
private val activity: android.app.Activity,
private val ui: Handler,
private val onInstalled: () -> Unit = {},
private val onRemoved: () -> Unit = {},
private val idle: () -> Boolean = { true },
) {
private object Operation {
@@ -27,13 +29,23 @@ internal class ProtonMenu(
val stage = mutableStateOf<String?>(null)
val percent = mutableIntStateOf(-1)
val problem = mutableStateOf<String?>(null)
val experimental = mutableStateOf<List<String>>(emptyList())
val experimentalReleases = mutableStateOf<List<ExperimentalProtons.Release>>(emptyList())
var fetchedReleases = emptyList<ExperimentalProtons.Release>()
val checking = java.util.concurrent.atomic.AtomicBoolean(false)
}
var protonRows by Operation.rows
var protonBusyId by Operation.busyId
var protonStage by Operation.stage
var protonPercent by Operation.percent
var protonProblem by Operation.problem
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
var experimentalDirs by Operation.experimental
var experimentalReleases by Operation.experimentalReleases
companion object {
const val EXPERIMENTAL = "experimental"
}
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
@@ -86,7 +98,57 @@ internal class ProtonMenu(
}, "remove-proton-$id").start()
}
fun installExperimental(work: ((String, Int) -> Unit) -> String?) {
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
protonBusyId = EXPERIMENTAL
protonProblem = null
protonStage = activity.getString(R.string.store_starting)
protonPercent = -1
Thread({
val problem = runCatching {
work { label, value -> ui.post { protonStage = label; protonPercent = value } }
}.getOrElse { it.message ?: it.javaClass.simpleName }
ui.post {
protonProblem = problem
protonBusyId = null
protonStage = null
protonPercent = -1
refreshProtons()
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.xproton_installed), android.widget.Toast.LENGTH_LONG).show()
if (problem == null) onInstalled()
}
}, "install-proton-experimental").start()
}
fun installExperimentalRelease(release: ExperimentalProtons.Release) {
installExperimental { progress -> ExperimentalProtons.installRelease(activity, release, progress) }
}
fun removeExperimental(dir: String) {
if (protonBusyId != null || SessionState.running) return
protonBusyId = EXPERIMENTAL
protonProblem = null
protonStage = activity.getString(R.string.main_removing_named, dir)
protonPercent = -1
Thread({
val removed = runCatching { ExperimentalProtons.remove(activity, dir) }.getOrDefault(false)
ui.post {
protonBusyId = null
protonStage = null
refreshProtons()
if (!removed) android.widget.Toast.makeText(activity, activity.getString(R.string.xproton_remove_failed, dir), android.widget.Toast.LENGTH_LONG).show()
}
}, "remove-proton-experimental").start()
}
private fun refreshExperimental() {
val installed = ExperimentalProtons.installed(activity)
experimentalDirs = installed.map { it.dir }
experimentalReleases = ExperimentalProtons.available(Operation.fetchedReleases, installed)
}
fun refreshProtons() {
refreshExperimental()
protonRows = ProtonExtras.tools.map {
val all = ProtonExtras.installedAll(activity, it)
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
@@ -94,13 +156,22 @@ internal class ProtonMenu(
}
fun checkUpdates(force: Boolean = false) {
if (!checking.compareAndSet(false, true)) return
if (!Operation.checking.compareAndSet(false, true)) return
Thread({
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
ui.post {
if (asked) refreshProtons()
val asked = runCatching { latestCheck(force) }.getOrDefault(false)
val experimental = runCatching { experimentalRefresh() }.getOrNull()
val published = ui.post {
try {
val before = experimentalDirs
Operation.fetchedReleases = experimental ?: emptyList()
if (asked) refreshProtons() else refreshExperimental()
if (!experimentalDirs.containsAll(before)) onRemoved()
} finally {
Operation.checking.set(false)
}
ensureAutoUpdates()
}
if (!published) Operation.checking.set(false)
}, "proton-updates").start()
}
@@ -115,6 +115,7 @@ import com.droiddeck.launcher.hud.DroidDeckHudHost
import com.droiddeck.launcher.session.PerfMode
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.session.GpuClockPin
import com.droiddeck.launcher.session.GameProfileFollowState
import com.droiddeck.launcher.session.GameProfileInventoryCache
import com.droiddeck.launcher.session.GameProfileRefreshState
@@ -549,6 +550,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
private var achievementsOpen by mutableStateOf(false)
private var hudOn by mutableStateOf(true)
private var gpuClockPin by mutableStateOf(false)
private var hudConfig by mutableStateOf<Map<String, String>>(emptyMap())
private var hudColor by mutableStateOf(SessionPrefs.HUD_COLOR_MINT)
private var hudOpacity by mutableStateOf(SessionPrefs.HUD_OPACITY_DEFAULT)
@@ -1034,7 +1036,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
kotlinx.coroutines.delay(2000)
}
}
pip = com.droiddeck.launcher.session.SessionPipController(this, ::pipBounds, ::showPipUi)
pip = com.droiddeck.launcher.session.SessionPipController(this, ::pipBounds, ::showPipUi) {
intent.getBooleanExtra(EXTRA_RETURN_HOME, false)
}
surfaceView.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> pip.refresh() }
pip.refresh()
handleHomeGuideIntent(intent)
@@ -1423,6 +1427,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
androidApps = androidApps,
hudOn = hudOn,
hudConfig = hudConfig,
gpuClockPin = gpuClockPin,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
effects = effects,
screenEffectsTarget = screenEffectsTarget,
@@ -1471,6 +1476,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onGpuClockPin = { on ->
SessionPrefs.setGpuClockPin(this@SessionActivity, on)
gpuClockPin = on
Thread {
synchronized(GpuClockPin) { GpuClockPin.sync(applicationContext)?.let { Log.i(TAG, it) } }
runOnUiThread { gpuClockPin = gpuClockHeld() }
}.start()
},
onHudSetting = { key, value -> hudConfig = DroidDeckHudConfig.set(this@SessionActivity, key, value); hud.applyConfig() },
onHudOrder = { switches, order -> hudConfig = DroidDeckHudConfig.choose(this@SessionActivity, switches, order); hud.applyConfig() },
onHudReset = { hudConfig = DroidDeckHudConfig.reset(this@SessionActivity); hud.applyConfig() },
@@ -1764,10 +1777,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = { mode ->
if (docked) drawerOpen = false
typingReturnMode = null
automaticPanel = false
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this@SessionActivity, desktopSession, mode.id)
selectSecondScreenMode(mode)
pickSecondScreenMode(mode)
},
onSecondScreenDisplay = ::selectSecondScreenDisplay,
onLaunchAndroidApp = { app, displayId ->
@@ -2485,6 +2495,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
.show()
}
private fun gpuClockHeld() = SessionPrefs.gpuClockPin(this) && !GpuClockPin.failed
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -2492,6 +2504,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
picturePosition = SessionPrefs.picturePosition(this)
integerScaling = SessionPrefs.integerScaling(this)
hudOn = SessionPrefs.hudEnabled(this)
gpuClockPin = gpuClockHeld()
blackFrameInsertion = SessionPrefs.blackFrameInsertion(this)
hudConfig = DroidDeckHudConfig.load(this)
hudColor = SessionPrefs.hudColor(this)
@@ -3497,7 +3510,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (drawerOpen) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
drawerPage = sessionDrawerPages(secondScreenDisplays.isNotEmpty(), glasses.present)
drawerPage = sessionDrawerPages(glasses.present)
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection()
}
@@ -4232,6 +4245,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
private fun pickSecondScreenMode(mode: SecondScreenMode) {
typingReturnMode = null
automaticPanel = false
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
selectSecondScreenMode(mode)
}
private fun bottomScreenPicker(mode: SecondScreenMode) = com.droiddeck.launcher.ui.ScreenPicker(
com.droiddeck.launcher.ui.secondScreenModes(false, SessionState.deckPad, bottomPages().isNotEmpty(),
com.droiddeck.launcher.session.BottomDesktop.available()),
mode, ::pickSecondScreenMode, onMenu = { drawerOpen = true },
)
private fun secondScreenPresentation(target: Display) = SecondScreenPresentation(
this, target,
onSteamMenu = ::tapSteamButton,
@@ -4240,6 +4266,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pad = padBridge,
onKeyboardClosed = ::bottomKeyboardClosed,
onMenu = { drawerOpen = true },
picker = ::bottomScreenPicker,
onMenuTouched = {
if (drawerPinned) {
drawerPinned = false
@@ -5667,6 +5694,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
super.onPictureInPictureModeChanged(inPip, newConfig)
if (inPip) {
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
}
if (::pip.isInitialized) pip.changed(inPip)
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
applyUnfoldedControls()
@@ -5709,6 +5741,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onStop() {
if (lightPause.stopped()) departureCleanup()
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
if (runtimeRemovalBlocked) { super.onStop(); return }
started = false
if (::hud.isInitialized) hud.setBackgrounded(true)
@@ -5738,6 +5773,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
if (!intent.hasExtra(EXTRA_LINK_TASK)) intent.putExtra(EXTRA_LINK_TASK, this.intent.getIntExtra(EXTRA_LINK_TASK, -1))
setIntent(intent)
if (::pip.isInitialized) pip.refresh(true)
if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
SessionState.steamVr = true
steamVrAutoTried = false
@@ -5752,6 +5788,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onResume() {
super.onResume()
com.droiddeck.launcher.session.KeepTopActivity.onYield = onGuardYield
uiHandler.removeCallbacks(lightPauseCheck)
when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) {
com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return
@@ -5835,6 +5872,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
// A touch that removed a guard while the session kept the top spot did not move focus to that
// display, so the guard comes back unless the user carries on there.
private val rearmAfterYield = Runnable {
if (topResumed && !isFinishing) {
com.droiddeck.launcher.session.KeepTopActivity.rearm()
guardOtherDisplays()
}
}
private val onGuardYield: () -> Unit = {
uiHandler.removeCallbacks(rearmAfterYield)
uiHandler.postDelayed(rearmAfterYield, com.droiddeck.launcher.session.KeepTopActivity.YIELD_GRACE_MS)
}
// RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up
// as soon as a running session is on top.
override fun onTrimMemory(level: Int) {
@@ -5848,13 +5898,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
super.onTopResumedActivityChanged(isTopResumedActivity)
topResumed = isTopResumedActivity
uiHandler.removeCallbacks(guardWhenRunning)
if (isTopResumedActivity) uiHandler.post(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
if (isTopResumedActivity) {
com.droiddeck.launcher.session.KeepTopActivity.rearm()
uiHandler.post(guardWhenRunning)
}
else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim(
android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays()
}
private fun guardOtherDisplays() {
if (!SessionState.running || isFinishing) return
if (!SessionState.running || isFinishing || isInPictureInPictureMode) return
val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)
val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY)
if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) {
@@ -6536,6 +6590,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onDestroy() {
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
if (com.droiddeck.launcher.session.KeepTopActivity.onYield === onGuardYield) com.droiddeck.launcher.session.KeepTopActivity.onYield = null
com.droiddeck.launcher.session.KeepTopActivity.release()
synchronized(frameGenGlobalLock) {
frameGenActivityActive = false
@@ -76,6 +76,9 @@ class AgentBridgeProvider : ContentProvider() {
"stop" -> stop(context)
"resume" -> resume(context)
"launch" -> launch(context, request)
"library" -> AgentStores.library(context, request)
"xodus" -> AgentStores.xodus(context, request)
"cloud" -> AgentStores.cloud(context, request)
"focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000)
"quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId"))
.put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000))
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.agent
import android.content.Context
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
/** The text typed in the Agent tab and not yet sent, kept across leaving the tab and restarts. */
object AgentDraft {
private const val KEY = "draft"
private var state: MutableState<String>? = null
fun state(context: Context): MutableState<String> = state ?: run {
val prefs = AgentHost.prefs(context.applicationContext)
val backing = mutableStateOf(prefs.getString(KEY, "") ?: "")
object : MutableState<String> {
override var value: String
get() = backing.value
set(text) {
if (text == backing.value) return
backing.value = text
prefs.edit().apply { if (text.isEmpty()) remove(KEY) else putString(KEY, text) }.apply()
}
override fun component1() = value
override fun component2(): (String) -> Unit = { value = it }
}.also { state = it }
}
}
@@ -141,8 +141,11 @@ object AgentSetup {
Step.CONNECTION -> return
Step.INSTALL -> {
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
"dpkg --configure -a; apt-get update || echo 'Some package sources could not be refreshed; continuing'; apt-get -f install -y; " +
"apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " +
"for i in 1 2 3; do apt update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
"apt -f install -y --fix-missing; " +
"apt install -y --fix-missing --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
}
Step.SIGN_IN -> harness.signIn
Step.GITHUB -> listOf("dd-gh-login")
@@ -0,0 +1,91 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.frontend.LibraryCache
import com.droiddeck.launcher.stores.CloudSaves
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.xbox.Xodus
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.concurrent.TimeUnit
import org.json.JSONArray
import org.json.JSONObject
internal object AgentStores {
private const val OUTPUT_CAP = 160 * 1024
fun library(context: Context, request: JSONObject): JSONObject {
val query = request.optString("query").trim()
val source = request.optString("source").trim()
val games = JSONArray()
LibraryCache.load(context)
.filter { (query.isEmpty() || it.name.contains(query, ignoreCase = true)) && (source.isEmpty() || it.source.equals(source, ignoreCase = true)) }
.forEach {
games.put(JSONObject().put("id", it.gameIdString).put("name", it.name).put("source", it.source)
.put("storeId", it.storeId ?: JSONObject.NULL).put("folder", it.gameFiles?.path ?: JSONObject.NULL))
}
return JSONObject().put("ok", true).put("command", "library").put("games", games)
}
fun xodus(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val list = request.optJSONArray("args")
val args = if (list == null) emptyList() else List(list.length()) { list.optString(it) }
if (args.isEmpty() || args.any { it.isEmpty() }) throw AgentException("INVALID_REQUEST", "xodus needs its arguments")
val timeoutMs = (request.optDouble("timeout", 120.0) * 1000).toLong().coerceIn(1_000L, 900_000L)
return Xodus.start(context.applicationContext, args).use { child ->
val out = Tail(child.process.inputStream)
val err = Tail(child.process.errorStream)
val finished = child.process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)
if (!finished) child.close()
JSONObject().put("ok", true).put("command", "xodus").put("timedOut", !finished)
.put("exit", if (finished) child.process.exitValue() else JSONObject.NULL)
.put("stdout", out.text()).put("stderr", err.text())
}
}
fun cloud(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val store = Store.byId(request.optString("store"))?.takeIf(CloudSaves::supports)
?: throw AgentException("INVALID_REQUEST", "store must be one with cloud saves")
val id = request.optString("id").ifEmpty { throw AgentException("INVALID_REQUEST", "cloud needs a game id") }
val force = request.optBoolean("force")
val result = when (val direction = request.optString("direction")) {
"down" -> CloudSaves.download(context.applicationContext, store, id, force)
"up" -> CloudSaves.upload(context.applicationContext, store, id, force)
else -> throw AgentException("INVALID_REQUEST", "direction '$direction' is not down or up")
}
return JSONObject().put("ok", true).put("command", "cloud").put("result", result.result).put("files", result.files)
.put("bytes", result.bytes).put("reason", result.reason).put("conflicts", result.conflicts).put("detail", result.detail)
}
private class Tail(stream: InputStream) {
private val kept = ByteArrayOutputStream()
private var dropped = false
private val reader = Thread({
val buffer = ByteArray(8192)
stream.use { input ->
while (true) {
val n = runCatching { input.read(buffer) }.getOrDefault(-1)
if (n < 0) break
synchronized(kept) {
kept.write(buffer, 0, n)
if (kept.size() > OUTPUT_CAP * 2) {
val bytes = kept.toByteArray()
kept.reset()
kept.write(bytes, bytes.size - OUTPUT_CAP, OUTPUT_CAP)
dropped = true
}
}
}
}
}, "agent-xodus-output").apply { isDaemon = true; start() }
fun text(): String {
reader.join(2_000)
val bytes = synchronized(kept) { kept.toByteArray() }
val tail = if (bytes.size > OUTPUT_CAP) bytes.copyOfRange(bytes.size - OUTPUT_CAP, bytes.size) else bytes
return (if (dropped || bytes.size > OUTPUT_CAP) "...\n" else "") + String(tail, Charsets.UTF_8)
}
}
}
@@ -281,9 +281,6 @@ object DeviceReport {
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context))
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
@@ -122,6 +122,12 @@ public final class Downloader {
return null;
}
public static Boolean gone(String url) {
Fetch fetch = fetch(url);
if (fetch.body != null) return Boolean.FALSE;
return fetch.fatal ? Boolean.TRUE : null;
}
public static String downloadDirect(String url) {
LAST_FAILURE.remove();
return fetch(url).body;
@@ -2,6 +2,9 @@ package com.droiddeck.launcher.frontend
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import android.util.AtomicFile
import com.droiddeck.launcher.R
import androidx.core.util.readText
@@ -13,27 +16,65 @@ import java.io.InputStream
object GameFiles {
const val EXTENSION = "steam"
private const val MAX_BYTES = 128
private const val MAX_BYTES = 4096
private const val MAX_NAME_BYTES = 200
private const val INVENTORY = ".droiddeck-sync.json"
private const val FORMAT = "droiddeck-game-files-v1"
fun readIntent(context: Context, request: Intent): String? = runCatching {
fun readIntent(context: Context, request: Intent): GameRequest? = runCatching {
if (request.action != Intent.ACTION_VIEW) return null
val uri = request.data ?: return null
GameLaunchLink.parse(uri.toString())?.let { return it }
GameRequest.link(uri.toString())?.let { return GameRequest(it) }
val name = displayName(context, uri)
val extension = name?.substringAfterLast('.', "").orEmpty()
if (extension.lowercase(java.util.Locale.ROOT) in GameRequest.PROGRAMS) {
val program = localFile(context, uri)?.takeIf { it.isFile } ?: return null
return GameRequest(title = name?.substringBeforeLast('.'), program = program.canonicalFile)
}
val stream = when (uri.scheme) {
"content" -> context.contentResolver.openInputStream(uri)
"file" -> {
if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) return null
File(uri.path ?: return null).inputStream()
}
null -> File(uri.toString()).takeIf { it.isAbsolute }?.inputStream()
"content" -> runCatching { context.contentResolver.openInputStream(uri) }.getOrNull()
?: localFile(context, uri)?.takeIf { it.isFile }?.inputStream()
"file", null -> localFile(context, uri)?.inputStream()
else -> null
} ?: return null
stream.use(::read)
val id = stream.use(::read) ?: return null
GameRequest(id, GameRequest.sourceOf(extension), name?.substringBeforeLast('.'))
}.getOrNull()
private fun displayName(context: Context, uri: Uri): String? = when (uri.scheme) {
"content" -> runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
}
}.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/')?.substringAfterLast(':')
"file" -> uri.path?.let { File(it).name }
null -> File(uri.toString()).name
else -> null
}?.takeIf { it.isNotEmpty() }
private fun localFile(context: Context, uri: Uri): File? = when (uri.scheme) {
"file" -> {
if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) null
else uri.path?.let(::File)
}
null -> File(uri.toString()).takeIf { it.isAbsolute }
"content" -> storageDocument(context, uri) ?: uri.pathSegments.let { parts ->
(0..1).asSequence().map { File("/" + parts.drop(it).joinToString("/")) }.firstOrNull { it.isFile }
}
else -> null
}
// Frontends pass SAF document URIs or FileProvider URIs whose path mirrors shared storage.
private fun storageDocument(context: Context, uri: Uri): File? {
if (uri.authority != "com.android.externalstorage.documents" || !DocumentsContract.isDocumentUri(context, uri)) return null
val id = DocumentsContract.getDocumentId(uri)
val volume = id.substringBefore(':')
val path = id.substringAfter(':', "")
val root = if (volume.equals("primary", ignoreCase = true)) android.os.Environment.getExternalStorageDirectory()
else File("/storage", volume)
return File(root, path)
}
fun read(stream: InputStream): String? {
val bytes = ByteArray(MAX_BYTES + 1)
var count = 0
@@ -44,8 +85,7 @@ object GameFiles {
count += n
}
if (count > MAX_BYTES) return null
val text = String(bytes, 0, count, Charsets.UTF_8).trim()
return text.takeIf(GameLaunchLink::validId)
return GameRequest.parse(String(bytes, 0, count, Charsets.UTF_8))
}
fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String {
@@ -61,7 +101,7 @@ object GameFiles {
}
val title = String(points, 0, end).trimEnd { it.isWhitespace() || it == '.' }.ifBlank { "Game" }
val suffix = if (disambiguate) " (${game.gameIdString})" else ""
return "$title$suffix.$EXTENSION"
return "$title$suffix.${GameRequest.extension(game)}"
}
private fun contents(id: String): String {
@@ -130,7 +170,7 @@ object GameFiles {
}
for (name in previous.keys()) {
val id = previous.getString(name)
if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) {
if (!next.has(name) && ours(name) && GameLaunchLink.validId(id)) {
val file = child(context, folder, name)
if (matches(file, contents(id))) {
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
@@ -141,6 +181,9 @@ object GameFiles {
if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString())
}
private fun ours(name: String) = name.substringAfterLast('.', "").lowercase(java.util.Locale.ROOT)
.let { it == EXTENSION || it in GameRequest.extensions }
private fun inventoryOwns(context: Context, folder: File, record: JSONObject, file: File, id: String): Boolean {
if (record.optString(file.name) == id) return true
if (!file.exists()) return false
@@ -11,22 +11,26 @@ object GameLaunchIntent {
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
fun read(context: Context, intent: Intent): String? = when (intent.action) {
fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) {
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
ACTION, GAMENATIVE_ACTION -> readId(intent)
ACTION, GAMENATIVE_ACTION -> readExtras(intent)
else -> null
}
@Suppress("DEPRECATION")
internal fun readId(intent: Intent): String? = runCatching {
internal fun readExtras(intent: Intent): GameRequest? = runCatching {
if (intent.action != ACTION && intent.action != GAMENATIVE_ACTION) return null
val source = intent.extras?.get(EXTRA_GAME_SOURCE)
if (source != null && (source !is String || !source.equals("STEAM", ignoreCase = true))) return null
val source = when (val value = intent.extras?.get(EXTRA_GAME_SOURCE)) {
null -> Library.SOURCE_STEAM
is String -> GameRequest.sourceNamed(value) ?: return null
else -> return null
}
val id = when (val value = intent.extras?.get(EXTRA_APP_ID)) {
is Int -> value.takeIf { it > 0 }?.toString()
is Long -> value.takeIf { it != 0L }?.let(java.lang.Long::toUnsignedString)
is String -> value.takeIf(GameLaunchLink::validId)
else -> null
}
id
} ?: return null
GameRequest(id, source)
}.getOrNull()
}
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.stores.Store
import java.io.File
import java.util.Locale
class GameRequest(
val id: String? = null,
val source: String = Library.SOURCE_STEAM,
val title: String? = null,
val program: File? = null,
) {
fun find(games: List<Library.SteamGame>, byTitle: Boolean = true): Library.SteamGame? {
program?.let { return owner(games, it) }
val exact = id?.let { id -> games.firstOrNull { it.gameIdString == id } }
if (source == Library.SOURCE_STEAM) return exact ?: games.firstOrNull { it.appId > 0 && it.appId.toString() == id }
exact?.takeIf { it.source == source }?.let { return it }
id?.let { id -> games.firstOrNull { it.source == source && it.storeId == id } }?.let { return it }
if (!byTitle) return null
val key = title?.let(::titleKey)?.takeIf { it.isNotEmpty() } ?: return null
return games.firstOrNull { it.source == source && titleKey(it.name) == key }
}
private fun owner(games: List<Library.SteamGame>, program: File): Library.SteamGame? {
val path = program.path
return games.mapNotNull { game ->
val folder = game.gameFiles ?: return@mapNotNull null
val dir = folder.absolutePath.takeIf { inside(path, it) }
?: runCatching { folder.canonicalPath }.getOrNull()?.takeIf { inside(path, it) }
dir?.let { game to it.length }
}.maxByOrNull { it.second }?.first
}
companion object {
val PROGRAMS = setOf("exe", "bat")
private const val CUSTOM_GAME = "CUSTOM_GAME"
private const val CUSTOM_EXTENSION = "pcgame"
private val DAIJISHOU = setOf("# Daijishou Player Template", "# DST")
private val daijishouId = Regex("""(?i)\[steamappid]\s*([0-9]+)""")
private val steamLink = Regex("steam://rungameid/([1-9][0-9]{0,19})")
val extensions: Set<String> = Store.entries.map { it.id }.toSet() + CUSTOM_EXTENSION
fun extension(game: Library.SteamGame): String = Store.byId(game.source)?.id ?: GameFiles.EXTENSION
fun sourceNamed(value: String): String? = when {
value.equals(Library.SOURCE_STEAM, ignoreCase = true) -> Library.SOURCE_STEAM
value.equals(CUSTOM_GAME, ignoreCase = true) -> Library.ADDED
else -> Store.entries.firstOrNull { it.name.equals(value, ignoreCase = true) }?.id
}
fun sourceOf(extension: String): String = when (val ext = extension.lowercase(Locale.ROOT)) {
CUSTOM_EXTENSION -> Library.ADDED
else -> Store.byId(ext)?.id ?: Library.SOURCE_STEAM
}
fun link(text: String): String? = text.takeIf(GameLaunchLink::validId)
?: GameLaunchLink.parse(text)
?: steamLink.matchEntire(text)?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId)
fun parse(text: String): String? {
link(text.trim())?.let { return it }
val lines = text.lines().map { it.trim() }.filter { it.isNotEmpty() }
val header = lines.firstOrNull() ?: return null
return when {
DAIJISHOU.any { header.equals(it, ignoreCase = true) } -> lines.firstNotNullOfOrNull { daijishouId.matchEntire(it) }
?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId)
header.equals("[InternetShortcut]", ignoreCase = true) -> lines.firstOrNull { it.startsWith("URL=", ignoreCase = true) }
?.substring(4)?.trim()?.takeIf { !GameLaunchLink.validId(it) }?.let(::link)
else -> null
}
}
internal fun titleKey(name: String): String = name.lowercase(Locale.ROOT).filter { it.isLetterOrDigit() }
private fun inside(path: String, dir: String) = path.startsWith(dir.trimEnd(File.separatorChar) + File.separator)
}
}
@@ -293,6 +293,7 @@ object Library {
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, lastPlayed = maxOf(lastPlayed, recordedPlay(context, g.gameId)), gameFiles = g.folder,
protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory }
else if (g.source == com.droiddeck.launcher.stores.Store.UBISOFT.id) File(com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.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,
@@ -37,22 +37,22 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList()
val gpuCandidates = gpuSources()
val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null }
val stepSources = GpuLimits.stepSources()
val maxSources = GpuLimits.maxSources()
val minSources = GpuLimits.minSources()
val steps = GpuLimits.first(stepSources)
var ceiling = ceilingSource(maxSources)
val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager
val time = SimpleDateFormat("HH:mm:ss", Locale.US)
try {
FileWriter(logFile, true).use { w ->
w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n")
w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n")
for (source in gpuCandidates) {
val f = File(source)
val state = when {
!f.exists() -> continue
firstNumber(source) != null -> "readable"
else -> "refused"
}
w.write("gpu source $source: $state\n")
}
probeLines("gpu source", gpuCandidates).forEach { w.write(it + "\n") }
w.write("gpu clock from: ${gpu ?: "nothing readable"}\n")
(probeLines("gpu limit", stepSources, ::firstStep) + probeLines("gpu limit", maxSources, ::limit) +
probeLines("gpu limit", minSources, ::firstStep)).distinct().forEach { w.write(it + "\n") }
limitLines(steps, ceiling, GpuLimits.first(minSources)).forEach { w.write(it + "\n") }
w.flush()
while (running && logFile.length() < MAX_BYTES) {
val line = StringBuilder(time.format(Date()))
@@ -63,7 +63,8 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
}
gpu?.let { line.append(" | gpu ${mhz(firstNumber(it))} MHz") }
if (ceiling == null) ceiling = ceilingSource(maxSources)?.also { w.write("gpu ceiling from: $it\n") }
line.append(gpuField(gpu, ceiling, steps?.mhz?.last()))
if (power != null && Build.VERSION.SDK_INT >= 29) {
line.append(" | thermal ${power.currentThermalStatus}")
if (Build.VERSION.SDK_INT >= 30) {
@@ -109,16 +110,41 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
return list.distinct()
}
internal fun probeLines(label: String, sources: List<String>, read: (String) -> Long? = ::firstNumber): List<String> = sources.mapNotNull { source ->
when {
!File(source).exists() -> null
read(source) != null -> "$label $source: readable"
else -> "$label $source: refused"
}
}
internal fun limitLines(steps: GpuLimits.Found?, ceiling: String?, floor: GpuLimits.Found?): List<String> = listOf(
"gpu steps: " + (steps?.let { "${it.mhz.joinToString(" ")} MHz from ${it.path}" } ?: "nothing readable"),
"gpu ceiling from: " + (ceiling ?: "nothing readable"),
"gpu floor: " + (floor?.let { "${it.mhz.first()} MHz from ${it.path}" } ?: "nothing readable"),
)
internal fun gpuField(clock: String?, ceiling: String?, top: Long?): String {
if (clock == null && ceiling == null) return ""
val field = StringBuilder(" | gpu ").append(mhz(clock?.let(::firstNumber)))
ceiling?.let(::limit)?.let { max ->
field.append('/').append(mhz(max))
if (top != null && GpuLimits.mhz(max) < top) field.append("(of $top)")
}
return field.append(" MHz").toString()
}
private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull()
private fun firstNumber(path: String): Long? =
runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
private fun mhz(raw: Long?): String = when {
raw == null -> "?"
raw > 10_000_000 -> (raw / 1_000_000).toString()
raw > 10_000 -> (raw / 1_000).toString()
else -> raw.toString()
}
internal fun limit(path: String): Long? = firstNumber(path)?.takeIf { it > 0 }
internal fun firstStep(path: String): Long? = GpuLimits.read(path).firstOrNull()
internal fun ceilingSource(sources: List<String>): String? = sources.firstOrNull { limit(it) != null }
private fun mhz(raw: Long?): String = raw?.let { GpuLimits.mhz(it).toString() } ?: "?"
}
}
@@ -87,20 +87,10 @@ object DeviceInfo {
private fun ghz(khz: Long) = String.format(Locale.US, "%.2f GHz", khz / 1e6)
private fun gpuRange(): String? {
fun mhz(hz: Long) = "${hz / 1_000_000} MHz"
val kgsl = read("/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies")
?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
if (kgsl.isNotEmpty()) return "${mhz(kgsl.min())}–${mhz(kgsl.max())} (${kgsl.size} steps)"
read("/sys/class/kgsl/kgsl-3d0/max_gpuclk")?.toLongOrNull()?.let { return "up to ${mhz(it)}" }
val node = File("/sys/class/devfreq").listFiles()?.firstOrNull { f ->
val n = f.name.lowercase()
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
} ?: return null
val steps = read("${node.path}/available_frequencies")?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
if (steps.isNotEmpty()) return "${mhz(steps.min())}–${mhz(steps.max())} (${steps.size} steps)"
val min = read("${node.path}/min_freq")?.toLongOrNull()
val max = read("${node.path}/max_freq")?.toLongOrNull() ?: return null
return (if (min != null) "${mhz(min)}–" else "up to ") + mhz(max)
GpuLimits.first(GpuLimits.stepSources())?.mhz?.let { return "${it.first()} MHz–${it.last()} MHz (${it.size} steps)" }
val max = GpuLimits.first(GpuLimits.maxSources())?.mhz?.last() ?: return null
val min = GpuLimits.first(GpuLimits.minSources())?.mhz?.first()
return (if (min != null) "$min MHz–" else "up to ") + "$max MHz"
}
private fun memory(context: Context) = Section("Memory", buildList<Pair<String, String>> {
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.gpu
import java.io.File
object GpuLimits {
class Found(val path: String, val mhz: List<Long>)
private const val KGSL = "/sys/class/kgsl/kgsl-3d0"
private const val QCOM_GPU = "/sys/kernel/gpu"
fun stepSources(): List<String> = listOf(
"$KGSL/gpu_available_frequencies", "$KGSL/freq_table_mhz", "$KGSL/devfreq/available_frequencies", "$QCOM_GPU/gpu_freq_table",
) + devfreq("available_frequencies")
fun maxSources(): List<String> = listOf(
"$KGSL/max_gpuclk", "$KGSL/max_clock_mhz", "$KGSL/devfreq/max_freq", "$QCOM_GPU/gpu_max_clock",
) + devfreq("max_freq")
fun minSources(): List<String> = listOf(
"$KGSL/min_clock_mhz", "$KGSL/devfreq/min_freq", "$QCOM_GPU/gpu_min_clock",
) + devfreq("min_freq")
fun first(sources: List<String>): Found? =
sources.firstNotNullOfOrNull { path -> read(path).takeIf { it.isNotEmpty() }?.let { Found(path, it) } }
fun read(path: String): List<Long> = runCatching {
Regex("\\d+").findAll(File(path).readText()).map { mhz(it.value.toLong()) }.filter { it > 0 }.distinct().sorted().toList()
}.getOrDefault(emptyList())
fun mhz(raw: Long): Long = when {
raw > 10_000_000 -> raw / 1_000_000
raw > 10_000 -> raw / 1_000
else -> raw
}
private fun devfreq(file: String): List<String> =
File("/sys/class/devfreq").listFiles()?.filter { f ->
val n = f.name.lowercase()
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
}?.sortedBy { it.name }?.map { "${it.path}/$file" }.orEmpty()
}
@@ -282,6 +282,8 @@ object ComponentsManager {
if (parts.size > 1) parts[1] else parts.firstOrNull()?.ifEmpty { null } ?: "unknown"
}.getOrDefault("unknown")
internal fun isProtonTree(dir: File): Boolean = File(dir, WINE).isDirectory && File(dir, "proton").isFile
fun protons(context: Context): List<Proton> {
val found = LinkedHashMap<String, Proton>()
val bases = listOf(File(steam(context), "compatibilitytools.d") to false) +
@@ -290,7 +292,7 @@ object ComponentsManager {
for ((base, valve) in bases) {
val entries = base.listFiles()?.sortedBy { it.name } ?: continue
for (dir in entries) {
if (!File(dir, WINE).isDirectory || !File(dir, "proton").isFile) continue
if (!isProtonTree(dir)) continue
val real = runCatching { dir.canonicalPath }.getOrDefault(dir.path)
if (found.containsKey(real)) continue
val guest = if (dir.absolutePath.startsWith(rootPath)) dir.absolutePath.removePrefix(rootPath) else dir.absolutePath
@@ -900,15 +902,26 @@ object ComponentsManager {
}
}
fun forgetProton(context: Context, dirName: String) {
synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
if (selected && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return
File(originalsDir(context), id).deleteRecursively()
}
fun forgetProton(context: Context, dirName: String): Boolean = synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return true
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
val published = File(launchDir(context), "desired.tsv")
val listed = published.takeIf { it.isFile }
?.useLines { rows -> rows.any { it.split('\t').getOrNull(1) == dirName } } == true
if ((selected || listed) && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return false
val originals = File(originalsDir(context), id)
val store = File(launchDir(context), "store")
val used = published.takeIf { it.isFile }?.useLines { rows ->
rows.mapNotNull { it.substringAfterLast('\t').substringAfter("/store/", "").substringBefore('/').ifEmpty { null } }.toSet()
}.orEmpty()
val unpacked = originals.listFiles().orEmpty().flatMap { version ->
version.listFiles().orEmpty().map { File(store, "original-$id-${version.name}-${it.name.removeSuffix(".wcp")}") }
}.filter { it.name !in used }
if (unpacked.any { File(it, ".complete").delete(); !it.deleteRecursively() && it.exists() }) return false
originals.deleteRecursively()
true
}
private fun storePackage(context: Context, part: File, dest: File) {
@@ -708,10 +708,10 @@ internal object EnhancedSessionLogShare {
}
val logs = LinuxRuntime.logDir(context)
for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) {
val scan = directFiles(root, remaining(maxFiles, out.size))
val scan = directFiles(root, STORE_LOG_SCAN)
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) }
scan.files.filter { recent(it) }.sortedByDescending { it.lastModified() }.take(remaining(maxFiles, out.size))
.forEach { add(it, root, "$name/${it.name}", name) }
}
if (legacy) {
@@ -965,6 +965,7 @@ internal object EnhancedSessionLogShare {
"events.jsonl", "memory.csv", "capture.json", "crash.log",
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val STORE_LOG_SCAN = 512
private const val COPY_BUFFER_BYTES = 64 * 1024
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
@@ -0,0 +1,412 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.StatFs
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermission
import java.security.DigestOutputStream
import java.security.MessageDigest
import java.util.zip.ZipFile
import org.apache.commons.compress.archivers.sevenz.SevenZFile
import org.apache.commons.compress.archivers.zip.ZipFile as CommonsZipFile
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.deleteRecursively
import org.json.JSONArray
import org.json.JSONObject
object ExperimentalProtons {
private const val TAG = "ExperimentalProtons"
const val PREFIX = "Experimental-"
private const val MARKER = ".droiddeck-experimental.json"
private const val STAGING = ".droiddeck-experimental"
private const val BACKUPS = ".droiddeck-experimental-old"
private const val INCOMING = ".droiddeck-experimental-new"
private const val REMOVED = ".droiddeck-experimental-gone"
private const val GUEST_TOOLS = "/root/.local/share/Steam/compatibilitytools.d"
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
private const val USER_SETTINGS = "user_settings.py"
internal val TARBALL = Regex("(?i)\\.tar(\\.(gz|xz|zst|bz2))?$")
internal val FOREIGN_ARCH = Regex("(?i)(^|[^a-z0-9])(x86|x64|amd64|i[3-6]86)([^a-z0-9]|$)")
private val DOWNLOAD_PREFIX = "droiddeck-"
data class Installed(val dir: String, val label: String, val source: String, val releaseTag: String? = null)
data class Release(val tag: String, val asset: String, val url: String, val sha512: String?, val size: Long, val name: String = tag)
enum class ArchiveType { ZIP, SEVEN_Z, TAR, UNKNOWN }
private fun toolsDir(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_TOOLS.removePrefix("/"))
fun installed(context: Context): List<Installed> =
toolsDir(context).listFiles()
?.filter { it.isDirectory && File(it, MARKER).isFile }
?.map { dir ->
val info = runCatching { JSONObject(File(dir, MARKER).readText()) }.getOrDefault(JSONObject())
Installed(dir.name, info.optString("label").ifEmpty { dir.name }, info.optString("source"), info.optString("releaseTag").ifEmpty { null })
}
?.sortedBy { it.dir }
?: emptyList()
fun remove(context: Context, dir: String): Boolean {
val tools = toolsDir(context)
val target = File(tools, dir)
if (!File(target, MARKER).isFile) return false
val doomed = File(File(tools, REMOVED).apply { mkdirs() }, dir)
if (!deleteTree(doomed)) return false
val detached = synchronized(SessionState.startLock) { !SessionState.running && target.renameTo(doomed) }
if (!detached) return false
ComponentsManager.forgetProton(context, dir)
deleteTree(doomed)
deleteTree(File(File(tools, BACKUPS), dir))
deleteTree(File(File(tools, INCOMING), dir))
return true
}
internal fun dirName(tree: String, label: String?): String {
val base = ComponentsManager.safeName(tree)
val tag = label?.let(ComponentsManager::safeName)?.takeIf { it != "unnamed" && !base.contains(it, ignoreCase = true) }
return PREFIX + base + (tag?.let { "-$it" } ?: "")
}
fun refresh(context: Context): List<Release>? {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
if (!SessionState.running) {
reconcile(context, fetched)
if (fetched.complete) removeStaleDownloads(context, fetched.releases.tags())
}
return rows
}
private fun JSONArray.tags(): Set<String> = (0 until length()).mapNotNull { optJSONObject(it)?.optString("tag_name")?.takeIf(String::isNotEmpty) }.toSet()
internal fun removeStaleDownloads(context: Context, availableTags: Set<String>) {
val downloads = File(context.filesDir, "proton-downloads")
downloads.listFiles()?.filter { file ->
file.isFile && file.name.startsWith(DOWNLOAD_PREFIX) && availableTags.none { tag -> file.name.startsWith("$DOWNLOAD_PREFIX${ComponentsManager.safeName(tag)}-") }
}?.forEach { it.delete() }
}
internal fun available(releases: List<Release>, installed: List<Installed>): List<Release> =
releases.filter { release -> installed.none { it.releaseTag == release.tag } }
internal fun shouldRemove(installedReleaseTag: String?, fetched: ProtonExtras.ReleaseFetch, gone: (String) -> Boolean): Boolean {
val tag = installedReleaseTag ?: return false
val release = (0 until fetched.releases.length()).asSequence()
.mapNotNull { fetched.releases.optJSONObject(it) }
.firstOrNull { it.optString("tag_name") == tag }
return if (release != null) !release.optBoolean("prerelease", false) else fetched.complete && gone(tag)
}
internal fun reconcile(
context: Context,
fetched: ProtonExtras.ReleaseFetch,
gone: (String) -> Boolean = { tag -> ProtonExtras.releaseGone(ProtonExtras.tools.first { it.id == ProtonExtras.OWN }, tag) },
) {
for (build in installed(context)) {
if (SessionState.running) return
if (shouldRemove(build.releaseTag, fetched, gone)) remove(context, build.dir)
}
}
internal fun compatVdf(name: String): String = """"compatibilitytools"
{
"compat_tools"
{
"$name"
{
"install_path" "."
"display_name" "$name"
"from_oslist" "windows"
"to_oslist" "linux"
}
}
}
"""
fun installFromFile(context: Context, file: File, onProgress: (String, Int) -> Unit): String? {
preflight(context)?.let { return it }
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + file.length()) {
return context.getString(R.string.xproton_no_space)
}
return install(context, file, fileLabel(file.name), file.name, null, onProgress, false)
}
internal fun fileLabel(name: String): String =
if (TARBALL.containsMatchIn(name)) name.replace(TARBALL, "") else name.substringBeforeLast('.')
fun installRelease(context: Context, release: Release, onProgress: (String, Int) -> Unit): String? {
preflight(context)?.let { return it }
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "droiddeck-${ComponentsManager.safeName(release.tag)}-${release.asset}")
if (release.size > 0 && archive.length() > release.size) archive.delete()
val missing = (release.size - archive.length()).coerceAtLeast(0L)
val copyBytes = if (sameFileStore(archive, toolsDir(context))) 0L else release.size
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing + copyBytes) return context.getString(R.string.xproton_no_space)
val title = context.getString(R.string.pextra_downloading, "Proton", release.tag)
onProgress(title, 0)
if (!Downloader.downloadFile(release.url, archive, true) { fraction ->
onProgress(title, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
}) return context.getString(R.string.pextra_download_failed)
if (release.size > 0 && archive.length() != release.size) return context.getString(R.string.pextra_incomplete)
if (release.sha512 != null) {
val expected = Downloader.downloadDirect(release.sha512)?.let(::checksumIn)
?: return context.getString(R.string.pextra_checksum_unreadable)
if (!expected.equals(Hashes.sha512(archive), true)) {
archive.delete()
return context.getString(R.string.pextra_checksum_mismatch)
}
}
return try { install(context, archive, release.tag, release.tag, release.tag, onProgress, true) }
finally { archive.delete() }
}
private fun sameFileStore(file: File, directory: File): Boolean = runCatching {
directory.mkdirs()
Files.getFileStore((file.takeIf(File::exists) ?: file.parentFile).toPath()) == Files.getFileStore(directory.toPath())
}.getOrDefault(false)
private fun preflight(context: Context): String? = when {
SessionState.running -> context.getString(R.string.pextra_stop_session)
!LinuxRuntime.isInstalled(context) -> context.getString(R.string.user_apps_runtime_required)
else -> null
}
private fun install(context: Context, archive: File, label: String, source: String, releaseTag: String?, onProgress: (String, Int) -> Unit, downloaded: Boolean): String? {
val tools = toolsDir(context).apply { mkdirs() }
val staging = File(tools, STAGING)
val forget = { name: String -> ComponentsManager.forgetProton(context, name) }
restoreInterrupted(tools, forget)
deleteTree(staging)
staging.mkdirs()
try {
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, LinuxRuntime.rootDir(context))
onProgress(context.getString(R.string.xproton_unpacking), -1)
val unpacked = File(staging, "unpacked").apply { mkdirs() }
val type = archiveType(archive)
if (SessionState.running) return context.getString(R.string.pextra_session_started)
onProgress(context.getString(R.string.xproton_unpacking), -1)
when (type) {
ArchiveType.ZIP -> {
val tarball = extractTarball(archive, staging)
if (tarball == null) {
extractDirect(archive, unpacked, ArchiveType.ZIP)
} else {
val status = runGuest(context, listOf("tar", "-xf", "$GUEST_TOOLS/$STAGING/${tarball.name}", "-C", "$GUEST_TOOLS/$STAGING/unpacked"))
tarball.delete()
if (status != 0) return context.getString(R.string.xproton_untar_failed, status)
}
}
ArchiveType.SEVEN_Z -> extractDirect(archive, unpacked, ArchiveType.SEVEN_Z)
ArchiveType.TAR -> {
val stagedArchive = File(staging, archive.name)
if (!archive.canonicalFile.equals(stagedArchive.canonicalFile) && !(downloaded && archive.renameTo(stagedArchive))) {
archive.copyTo(stagedArchive, overwrite = true)
}
val status = runGuest(context, listOf("tar", "-xf", "$GUEST_TOOLS/$STAGING/${stagedArchive.name}", "-C", "$GUEST_TOOLS/$STAGING/unpacked"))
if (status != 0) return context.getString(R.string.xproton_untar_failed, status)
}
ArchiveType.UNKNOWN -> return context.getString(R.string.xproton_archive_invalid)
}
val tree = buildTree(unpacked) ?: return context.getString(R.string.xproton_no_tree)
val name = dirName(tree.name, label)
ownFile(tree, "compatibilitytool.vdf").writeText(compatVdf(name))
ownFile(tree, MARKER).writeText(
JSONObject().put("label", name).put("source", source).putOpt("releaseTag", releaseTag).put("at", System.currentTimeMillis() / 1000).toString(),
)
val final = File(tools, name)
val settings = File(final, USER_SETTINGS)
if (Files.isRegularFile(settings.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
settings.copyTo(ownFile(tree, USER_SETTINGS))
}
if (!placeTree(tree, tools, name, forget)) return context.getString(R.string.xproton_place_failed)
onProgress(context.getString(R.string.pextra_installing, name), -1)
runGuest(context, listOf("steam-compatibility", "/root/.local/share/Steam"))
return null
} catch (e: Exception) {
Log.e(TAG, "install $source", e)
return if (e is UnsafeArchiveException) context.getString(R.string.xproton_archive_unsafe) else context.getString(R.string.xproton_archive_invalid)
} finally {
deleteTree(staging)
}
}
internal fun buildTree(unpacked: File): File? {
val root = unpacked.canonicalFile
return unpacked.listFiles()?.sortedBy { it.name }?.firstOrNull {
!Files.isSymbolicLink(it.toPath()) && it.isDirectory && it.canonicalFile.parentFile == root &&
Files.isRegularFile(File(it, "toolmanifest.vdf").toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS) &&
ComponentsManager.isProtonTree(it)
}
}
@OptIn(ExperimentalPathApi::class)
internal fun deleteTree(dir: File): Boolean =
runCatching { dir.toPath().deleteRecursively() }.onFailure { Log.w(TAG, "delete $dir", it) }.isSuccess && !Files.exists(dir.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)
internal fun ownFile(tree: File, name: String): File {
val file = File(tree, name)
Files.deleteIfExists(file.toPath())
return file
}
internal fun placeTree(tree: File, tools: File, name: String, forget: (String) -> Boolean): Boolean {
val incoming = File(File(tools, INCOMING).apply { mkdirs() }, name)
if (!deleteTree(incoming) || !tree.renameTo(incoming)) return false
return finishPlacing(tools, name, forget)
}
private fun finishPlacing(tools: File, name: String, forget: (String) -> Boolean): Boolean {
val incoming = File(File(tools, INCOMING), name)
val final = File(tools, name)
val backup = File(File(tools, BACKUPS).apply { mkdirs() }, name)
val moved = !final.exists() || (deleteTree(backup) && final.renameTo(backup))
val placed = moved && (!backup.exists() || forget(name)) && incoming.renameTo(final)
if (!placed) {
if (!final.exists()) backup.renameTo(final)
deleteTree(incoming)
}
if (final.exists()) deleteTree(backup)
return placed
}
internal fun restoreInterrupted(tools: File, forget: (String) -> Boolean) {
deleteTree(File(tools, REMOVED))
File(tools, INCOMING).listFiles()?.forEach { finishPlacing(tools, it.name, forget) }
File(tools, BACKUPS).listFiles()?.forEach { if (File(tools, it.name).exists()) deleteTree(it) else it.renameTo(File(tools, it.name)) }
}
internal fun archiveType(file: File): ArchiveType {
val head = runCatching { file.inputStream().use { ByteArray(300).also { b -> it.read(b) } } }.getOrNull() ?: return ArchiveType.UNKNOWN
fun at(i: Int, vararg bytes: Int) = bytes.indices.all { head.getOrNull(i + it) == bytes[it].toByte() }
return when {
at(0, 0x50, 0x4B) -> ArchiveType.ZIP
at(0, 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C) -> ArchiveType.SEVEN_Z
at(0, 0x1F, 0x8B) || at(0, 0x42, 0x5A, 0x68) || at(0, 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00) || at(0, 0x28, 0xB5, 0x2F, 0xFD) || at(257, 0x75, 0x73, 0x74, 0x61, 0x72) -> ArchiveType.TAR
else -> ArchiveType.UNKNOWN
}
}
private fun extractTarball(zip: File, into: File): File? = ZipFile(zip).use { z ->
val entries = z.entries().toList().filter { !it.isDirectory }
val entry = entries.filter { TARBALL.containsMatchIn(it.name) }.maxByOrNull { it.size } ?: return null
val name = File(entry.name).name
val sums = checksumEntry(entries.map { it.name }, name)?.let { checksumName -> entries.first { it.name == checksumName } }
val expected = sums?.let { e ->
z.getInputStream(e).use { checksumIn(it.readBytes().decodeToString()) }
?: throw IllegalStateException("${File(e.name).name} holds no SHA-512 checksum")
}
val out = File(into, name)
val digest = MessageDigest.getInstance("SHA-512")
z.getInputStream(entry).use { input -> DigestOutputStream(FileOutputStream(out), digest).use { input.copyTo(it, 1 shl 16) } }
if (expected != null && !expected.equals(digest.digest().joinToString("") { "%02x".format(it) }, ignoreCase = true)) {
out.delete()
throw IllegalStateException("Checksum mismatch in $name")
}
out
}
internal class UnsafeArchiveException : Exception()
internal fun extractDirect(archive: File, into: File, type: ArchiveType) {
val root = into.toPath().toAbsolutePath().normalize()
fun target(name: String): File {
val clean = name.replace('\\', '/')
val parts = clean.split('/')
if (clean.startsWith('/') || parts.any { it == ".." }) throw UnsafeArchiveException()
val path = root.resolve(clean).normalize()
if (!path.startsWith(root)) throw UnsafeArchiveException()
var parent = path.parent
while (parent != null && parent.startsWith(root) && parent != root) {
if (Files.isSymbolicLink(parent)) throw UnsafeArchiveException()
parent = parent.parent
}
return path.toFile()
}
fun applyMode(file: File, mode: Int) {
val permissions = mutableSetOf<PosixFilePermission>()
if (mode and 0x100 != 0) permissions += PosixFilePermission.OWNER_READ
if (mode and 0x80 != 0) permissions += PosixFilePermission.OWNER_WRITE
if (mode and 0x40 != 0) permissions += PosixFilePermission.OWNER_EXECUTE
if (mode and 0x20 != 0) permissions += PosixFilePermission.GROUP_READ
if (mode and 0x10 != 0) permissions += PosixFilePermission.GROUP_WRITE
if (mode and 0x08 != 0) permissions += PosixFilePermission.GROUP_EXECUTE
if (mode and 0x04 != 0) permissions += PosixFilePermission.OTHERS_READ
if (mode and 0x02 != 0) permissions += PosixFilePermission.OTHERS_WRITE
if (mode and 0x01 != 0) permissions += PosixFilePermission.OTHERS_EXECUTE
if (permissions.isNotEmpty()) Files.setPosixFilePermissions(file.toPath(), permissions)
}
val directoryModes = mutableListOf<Pair<File, Int>>()
fun place(name: String, mode: Int, directory: Boolean, content: () -> InputStream) {
val file = target(name)
when {
mode and 0xF000 == 0xA000 -> {
val link = content().use { it.readBytes().decodeToString() }
val parent = file.parentFile ?: throw UnsafeArchiveException()
val climbsLater = link.split('/').filter { it != "." }.dropWhile { it == ".." }.any { it == ".." }
if (link.startsWith('/') || climbsLater || !parent.toPath().resolve(link).normalize().startsWith(root)) throw UnsafeArchiveException()
parent.mkdirs()
Files.deleteIfExists(file.toPath())
Files.createSymbolicLink(file.toPath(), java.nio.file.Paths.get(link))
}
directory -> {
file.mkdirs()
directoryModes += file to mode
}
else -> {
if (Files.isSymbolicLink(file.toPath())) throw UnsafeArchiveException()
file.parentFile?.mkdirs()
content().use { input -> file.outputStream().use { output -> input.copyTo(output, 1 shl 16) } }
applyMode(file, mode)
}
}
}
when (type) {
ArchiveType.ZIP -> CommonsZipFile.builder().setFile(archive).get().use { zip ->
for (entry in zip.entries) place(entry.name, entry.unixMode, entry.isDirectory) { zip.getInputStream(entry) }
}
ArchiveType.SEVEN_Z -> Files.newByteChannel(archive.toPath()).use { channel ->
SevenZFile.builder().setSeekableByteChannel(channel).get().use { seven ->
for (entry in seven.entries) {
val unix = entry.hasWindowsAttributes && entry.windowsAttributes and 0x8000 != 0
place(entry.name, if (unix) entry.windowsAttributes ushr 16 else 0, entry.isDirectory) { seven.getInputStream(entry) }
}
}
}
else -> error("Unsupported direct archive")
}
directoryModes.sortedByDescending { it.first.path.length }.forEach { (directory, mode) -> applyMode(directory, mode) }
}
internal fun checksumIn(text: String): String? = Regex("(?i)\\b[0-9a-f]{128}\\b").find(text)?.value
internal fun checksumEntry(entries: List<String>, tarball: String): String? {
val stem = tarball.substringBefore(".tar")
return entries.firstOrNull {
val name = File(it).name
!TARBALL.containsMatchIn(name) && (name.startsWith("$tarball.") || name.startsWith("$stem.")) && name.contains("sha512", true)
}
}
private fun runGuest(context: Context, command: List<String>): Int {
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
) + command
val child = ProtonExtras.guestProcess(context, guest).start()
child.inputStream.bufferedReader().useLines { lines -> lines.forEach { Log.i(TAG, it) } }
return child.waitFor()
}
}
@@ -25,7 +25,7 @@ object GameSaves {
fun label(context: Context): String = context.getString(R.string.saves_layout_zip, app)
}
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>) {
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>, val root: String? = null) {
val launched get() = prefix?.let { File(it, "drive_c").isDirectory } == true
}
@@ -36,7 +36,28 @@ object GameSaves {
fun savesDir(): File = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck/Saves")
private fun backupsDir(): File = File(savesDir(), "backups")
fun game(game: Library.SteamGame): Game = Game(game, game.protonPrefix, game.protonPrefix?.let { locate(it, game) } ?: emptyList())
fun game(context: Context, game: Library.SteamGame): Game {
val root = if (ubisoft(game)) ubisoftRoot(context, game) else null
val saves = game.protonPrefix?.let { prefix -> if (ubisoft(game)) root?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game) }.orEmpty()
return Game(game, game.protonPrefix, saves, root)
}
fun saves(context: Context, prefix: File, game: Library.SteamGame): List<SaveDir> =
if (ubisoft(game)) ubisoftRoot(context, game)?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game)
private fun ubisoftRoot(context: Context, game: Library.SteamGame): String? {
val product = game.gameFiles?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it) }?.extra?.get("productId")?.toLongOrNull() ?: return null
val user = com.droiddeck.launcher.stores.ubisoft.UbisoftAuth.load(context)?.userId
if (user.isNullOrEmpty() || user.contains('/') || user.contains("..")) return null
return "Saved Games/Ubisoft/$user/$product"
}
private fun ubisoft(game: Library.SteamGame) = game.source == com.droiddeck.launcher.stores.Store.UBISOFT.id
private fun ubisoftSaves(prefix: File, rel: String): List<SaveDir> {
val files = File(profile(prefix), rel).walkTopDown().filter { it.isFile }.toList()
return if (files.isEmpty()) emptyList() else listOf(SaveDir(rel, files.size, files.sumOf { it.length() }))
}
private val SAVE_ROOTS = listOf("Documents/My Games", "Saved Games", "AppData/Roaming", "Documents", "AppData/Local", "AppData/LocalLow")
@@ -109,9 +130,11 @@ object GameSaves {
fun export(context: Context, game: Game, layout: Layout, dir: File): Pair<File, Int> {
val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name))
val roots = game.saves.map { it.relPath }
if (roots.isEmpty() && ubisoft(game.game)) error(context.getString(R.string.saves_none_found, game.game.name))
dir.mkdirs()
val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip")
val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out)
val count = zipProfile(profile(prefix), roots.ifEmpty { null }, layout, out)
if (count == 0) { out.delete(); error(context.getString(R.string.saves_none_found, game.game.name)) }
return out to count
}
@@ -142,12 +165,21 @@ object GameSaves {
if (!driveC.isDirectory) error(context.getString(R.string.saves_not_launched, game.game.name))
if (!looksLikeSaveZip(zip)) error(context.getString(R.string.saves_not_save_zip, zip.name))
val scoped = if (ubisoft(game.game)) game.root ?: error(context.getString(R.string.saves_none_found, game.game.name)) else null
if (scoped != null) {
val base = File(profile(prefix), scoped).canonicalFile
val eligible = ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
generateSequence { zis.nextEntry }.any { e -> !e.isDirectory && remap(e.name)?.let { File(driveC, it).canonicalFile.path.startsWith(base.path + File.separator) } == true }
}
if (!eligible) error(context.getString(R.string.saves_not_save_zip, zip.name))
}
backupsDir().mkdirs()
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip")
val backedUp = zipProfile(profile(prefix), null, Layout.GAMEHUB, backup)
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}_${System.currentTimeMillis()}.zip")
val backedUp = if (scoped != null && File(profile(prefix), scoped).walkTopDown().none { it.isFile }) 0
else zipProfile(profile(prefix), scoped?.let(::listOf), Layout.GAMEHUB, backup)
if (backedUp == 0) backup.delete()
val base = driveC.canonicalFile
val base = (if (scoped != null) File(profile(prefix), scoped) else driveC).canonicalFile
var written = 0
ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
var e = zis.nextEntry
@@ -14,10 +14,22 @@ object GpuClockPin {
@Volatile
private var pinned = false
private val supported: Boolean by lazy { File(KGSL_NODE).exists() }
@Volatile
var failed = false
private set
val supported: Boolean by lazy { File(KGSL_NODE).exists() }
private var live = false
@Synchronized
fun start(context: Context): String {
live = true
return hold(context)
}
private fun hold(context: Context): String {
failed = false
if (!SessionPrefs.gpuClockPin(context)) return "gpu clock: governed"
if (!supported) return "gpu clock: no $KGSL_NODE, left governed"
return try {
@@ -28,12 +40,21 @@ object GpuClockPin {
} catch (t: Throwable) {
File(context.filesDir, MARKER).delete()
Log.w(TAG, "pin", t)
failed = true
"gpu clock: pin failed"
}
}
@Synchronized
fun sync(context: Context): String? {
if (!live) return null
if (!SessionPrefs.gpuClockPin(context) && pinned) clear(context)
return hold(context)
}
@Synchronized
fun stop(context: Context) {
live = false
if (pinned) clear(context)
}
@@ -9,11 +9,15 @@ import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.Display
import android.view.MotionEvent
import android.view.WindowManager
// While a session runs, sits invisibly on top of every other display until it ends, so
// that display's home launcher is not its top activity. lmkd kills the launcher first; restarted as a
// top activity it takes focus from the session, which then drops to adj 50 and is killed next.
// While a session is on screen, sits invisibly on top of every other display, so that display's
// home launcher is not its top activity. lmkd kills the launcher first; restarted as a top activity
// it takes focus from the session, which then drops to adj 50 and is killed next.
// Android gives a translucent activity alone in its task an input sink that eats every touch on the
// display whatever its window flags say, so a touch makes the guard leave that display until the
// session is back on top.
class KeepTopActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -27,13 +31,28 @@ class KeepTopActivity : Activity() {
finishAndRemoveTask()
return
}
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
val id = display?.displayId ?: Display.INVALID_DISPLAY
starting.remove(id)
if (id in yielded) {
finishAndRemoveTask()
return
}
guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
guards[id] = this
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) {
val id = display?.displayId ?: Display.INVALID_DISPLAY
yielded.add(id)
Log.i(TAG, "display $id touched, leaving it to the app below")
finishAndRemoveTask()
onYield?.invoke()
}
return true
}
override fun onDestroy() {
guards.values.remove(this)
super.onDestroy()
@@ -49,13 +68,18 @@ class KeepTopActivity : Activity() {
private val guards = HashMap<Int, KeepTopActivity>()
private const val START_TIMEOUT_MS = 2_000L
private val starting = HashMap<Int, Long>()
private val yielded = HashSet<Int>()
const val YIELD_GRACE_MS = 5_000L
var onYield: (() -> Unit)? = null
fun rearm() = yielded.clear()
fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean {
val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false
var started = false
for (display in displays) {
val id = display.displayId
if (id == sessionDisplay || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
if (id == sessionDisplay || id in yielded || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue
runCatching {
launch(context, id, bounce = false)
@@ -73,13 +97,18 @@ class KeepTopActivity : Activity() {
const val RETRY_MS = START_TIMEOUT_MS + 250
fun release() {
fun stepAside() {
generation++
guards.values.toList().forEach { it.finishAndRemoveTask() }
guards.clear()
starting.clear()
}
fun release() {
stepAside()
yielded.clear()
}
private fun launch(context: Context, displayId: Int, bounce: Boolean) {
val intent = Intent(context, KeepTopActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
@@ -5,6 +5,11 @@ object PipPolicy {
running && frameSeen && phase in setOf(SessionPhase.READY, SessionPhase.SUSPENDED) &&
(!automatic || !suspended)
// A front end or shortcut that launched the game brings it back by moving its task to the
// front, which Android ignores for a task in picture in picture, and draws its resume controls
// where the picture would sit. Going home suspends the game for it instead.
fun autoEnter(enabled: Boolean, launchedByAnotherApp: Boolean): Boolean = enabled && !launchedByAnotherApp
fun aspect(width: Int, height: Int): Pair<Int, Int> = when {
width <= 0 || height <= 0 -> 16 to 9
width.toDouble() / height > 2.39 -> 239 to 100
@@ -9,13 +9,17 @@ import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.Locale
import org.json.JSONArray
import org.json.JSONObject
object ProtonExtras {
private const val TAG = "ProtonExtras"
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
private const val RELEASE_PAGE_SIZE = 15
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=$RELEASE_PAGE_SIZE&page=%d"
private const val RELEASE_PAGES = 5
private const val RELEASE_TAG = "https://api.github.com/repos/%s/releases/tags/%s"
const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile
var installInProgress = false
@@ -26,7 +30,8 @@ object ProtonExtras {
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null)
val sha256: String? = null, val releaseName: String = tag)
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
const val OWN = "droiddeck"
@@ -120,22 +125,25 @@ object ProtonExtras {
if (due.isEmpty() || !force && (now - lastAttempt) in 0 until RETRY_MS) return false
lastAttempt = now
for (tool in due) {
val tag = findLatestAsset(tool)?.tag ?: continue
cache.put(tool.id, JSONObject().put("tag", tag).put("at", now))
updateLatest(cache, tool, releases(tool), now)
}
runCatching { file.writeText(cache.toString()) }
return true
}
}
internal fun recordLatest(latest: JSONObject, tool: Tool, tag: String, now: Long): Boolean {
val entry = latest.optJSONObject(tool.id)
val known = entry?.optString("tag")
if (!known.isNullOrEmpty() && compareVersions(tag, known) < 0) return false
latest.put(tool.id, JSONObject().put("tag", tag).put("at", now))
return true
}
private fun record(context: Context, tool: Tool, dir: String?, tag: String) {
runCatching {
val latest = readJson(latestFile(context))
val known = latest.optJSONObject(tool.id)?.optString("tag")
if (known.isNullOrEmpty() || compareVersions(tag, known) >= 0) {
latest.put(tool.id, JSONObject().put("tag", tag).put("at", System.currentTimeMillis()))
latestFile(context).writeText(latest.toString())
}
if (recordLatest(latest, tool, tag, System.currentTimeMillis())) latestFile(context).writeText(latest.toString())
if (dir != null) {
val releases = readJson(releasesFile(context))
val present = toolsDir(context).list()?.toSet() ?: emptySet()
@@ -218,7 +226,7 @@ object ProtonExtras {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = findLatestAsset(tool) ?: return context.getString(R.string.pextra_no_release, tool.name)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
@@ -277,26 +285,12 @@ object ProtonExtras {
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
"/usr/local/bin/droiddeck-proton-extra", "/root/.local/share/Steam", archive.absolutePath,
)
val process = if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
} else {
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
.directory(root)
.redirectErrorStream(true)
.also { builder ->
val hostEnv = builder.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
}
}
val process = guestProcess(context, guest)
val child = process.start()
var placed: String? = null
child.inputStream.bufferedReader().useLines { lines ->
@@ -331,36 +325,106 @@ object ProtonExtras {
}
}
private fun findLatestAsset(tool: Tool): Asset? {
val releases = Downloader.downloadString(RELEASES.format(tool.repo)) ?: return null
return try {
pickAsset(tool, JSONArray(releases))
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
internal fun guestProcess(context: Context, guest: List<String>): ProcessBuilder {
val root = LinuxRuntime.rootDir(context)
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
return if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
} else {
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
.directory(root)
.redirectErrorStream(true)
.also { builder ->
val hostEnv = builder.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
}
}
}
internal fun releases(tool: Tool): JSONArray? = releases(tool) { page ->
Downloader.downloadString(RELEASES.format(Locale.ROOT, tool.repo, page))?.let { body ->
try {
JSONArray(body)
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
}
}
}
internal fun releases(tool: Tool, fetch: (Int) -> JSONArray?): JSONArray? {
return releasesResult(tool, fetch, stopAtStable = true)?.releases
}
internal fun releasesForRemoval(tool: Tool, fetch: (Int) -> JSONArray? = { page ->
Downloader.downloadString(RELEASES.format(Locale.ROOT, tool.repo, page))?.let { body ->
runCatching { JSONArray(body) }.getOrNull()
}
}): ReleaseFetch? = releasesResult(tool, fetch, stopAtStable = false)
internal fun releaseGone(tool: Tool, tag: String): Boolean =
Downloader.gone(RELEASE_TAG.format(Locale.ROOT, tool.repo, java.net.URLEncoder.encode(tag, "UTF-8").replace("+", "%20"))) == true
private fun releasesResult(tool: Tool, fetch: (Int) -> JSONArray?, stopAtStable: Boolean): ReleaseFetch? {
val all = fetch(1) ?: return null
var page = 1
var last = all.length()
var complete = last < RELEASE_PAGE_SIZE
while (!complete && page < RELEASE_PAGES && (!stopAtStable || pickAsset(tool, all) == null)) {
val next = fetch(++page) ?: return null
for (i in 0 until next.length()) all.put(next.opt(i))
last = next.length()
complete = last < RELEASE_PAGE_SIZE
}
return ReleaseFetch(all, complete)
}
internal fun assets(tool: Tool, array: JSONArray, prerelease: Boolean): List<Asset> {
val releases = (0 until array.length()).mapNotNull { array.optJSONObject(it) }.filter { !it.optBoolean("draft", false) }
val stableAt = releases.filter { !it.optBoolean("prerelease", false) }.maxOfOrNull { it.optString("published_at") }.orEmpty()
return releases
.filter { it.optBoolean("prerelease", false) == prerelease && (!prerelease || it.optString("published_at") > stableAt) }
.mapNotNull { assetOf(tool, it, experimental = prerelease) }
}
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
for (i in 0 until array.length()) {
val release = array.getJSONObject(i)
if (release.optBoolean("draft", false) || release.optBoolean("prerelease", false)) continue
val assets = release.optJSONArray("assets") ?: continue
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
val candidates = (0 until array.length()).asSequence()
.mapNotNull { array.optJSONObject(it) }
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
}
internal fun updateLatest(cache: JSONObject, tool: Tool, array: JSONArray?, now: Long) {
if (array == null) return
val tag = pickAsset(tool, array)?.tag
if (tag == null) {
return
}
cache.put(tool.id, JSONObject().put("tag", tag).put("at", now))
}
internal fun assetOf(tool: Tool, release: JSONObject, requireChecksum: Boolean = false, experimental: Boolean = false): Asset? = try {
val assets = release.optJSONArray("assets")
val entries = assets?.let { list -> (0 until list.length()).mapNotNull { list.optJSONObject(it) } }.orEmpty()
entries.sortedBy { it.optString("name") }.filter {
val name = it.optString("name")
if (experimental && tool.id == OWN) name.startsWith(release.optString("tag_name")) && ExperimentalProtons.TARBALL.containsMatchIn(name) && !ExperimentalProtons.FOREIGN_ARCH.containsMatchIn(name) else tool.assetPattern.containsMatchIn(name)
}.mapNotNull { archive ->
val name = archive.optString("name")
val stem = name.substringBefore(".tar")
val checksum = entries.firstOrNull {
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
return Asset(
release.optString("tag_name"), name,
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
archive.optLong("size", 0L),
Hashes.githubSha256(archive.optString("digest")),
)
}
return null
archive.optString("browser_download_url").takeIf { it.startsWith("http") }?.let { url ->
Asset(release.optString("tag_name"), name, url, checksum, archive.optLong("size", 0L), Hashes.githubSha256(archive.optString("digest")), release.optString("name").ifEmpty { release.optString("tag_name") })
}
}.let { found -> if (requireChecksum) found.firstOrNull { it.sha256 != null || it.sha512 != null } else found.firstOrNull() }
} catch (e: Exception) {
Log.w(TAG, "release metadata for ${tool.id}", e)
null
}
private fun requestLines(context: Context): List<String> =
@@ -234,8 +234,6 @@ object SessionFiles {
val gpuLoad = listOf(
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_vram_cap.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json",
)
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libddsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
@@ -282,6 +280,8 @@ object SessionFiles {
if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
}
File(root, "usr/local/bin/bannerlator-steam-compat").delete()
File(root, "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so").delete()
File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete()
LegacyNames.migrateRootfs(root)
ComponentsManager.migrateLaunchDir(context)
EsyncPacks.stageBundled(context, root)
@@ -16,6 +16,7 @@ class SessionPipController(
private val activity: SessionActivity,
private val bounds: () -> Rect,
private val showPipUi: (Boolean) -> Unit,
private val launchedByAnotherApp: () -> Boolean = { false },
) {
var transitioning = false
private set
@@ -29,7 +30,8 @@ class SessionPipController(
PipPolicy.eligible(SessionState.running, SessionState.firstFrameSeen, SessionState.phase,
SessionState.suspended, automatic)
fun automatic() = !suppressAuto && SessionPrefs.pipAutoEnter(activity) && eligible(true)
fun automatic() = !suppressAuto && PipPolicy.autoEnter(SessionPrefs.pipAutoEnter(activity), launchedByAnotherApp()) &&
eligible(true)
fun refresh(force: Boolean = false) {
if (!supported(activity)) return
@@ -280,6 +280,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("developerTools", on).apply()
}
fun previewShortcuts(context: Context): Boolean = prefs(context).getBoolean("previewShortcuts", false)
fun setPreviewShortcuts(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("previewShortcuts", on).apply()
}
fun fpsLimitKey(mode: String?, game: String?): String? = when (mode) {
SessionService.MODE_RUN -> game?.trim()?.takeIf(com.droiddeck.launcher.frontend.GameLaunchLink::validId)?.let { "fpsLimit.game.$it" }
SessionService.MODE_DESKTOP -> "fpsLimit.desktop"
@@ -352,6 +358,25 @@ object SessionPrefs {
prefs(context).edit().putString("storesTabOrder", order.joinToString(",")).apply()
}
/**
* Where the Library's own tabs (Favorites, Steam, Custom games) sit among the store tabs, as "tab=the tab it follows" pairs in
* strip order ("" follows nothing, i.e. first). Null until arranged.
*/
fun libraryTabPlaces(context: Context): List<Pair<String, String>>? =
prefs(context).getString("libraryTabPlaces", null)?.split(',')?.mapNotNull { pair ->
pair.split('=', limit = 2).takeIf { it.size == 2 && it[0].isNotEmpty() }?.let { it[0] to it[1] }
}
fun setLibraryTabPlaces(context: Context, places: List<Pair<String, String>>) {
prefs(context).edit().putString("libraryTabPlaces", places.joinToString(",") { "${it.first}=${it.second}" }).apply()
}
fun libraryTabsHidden(context: Context): Set<String> = idList(prefs(context).getString("libraryTabsHidden", null)).toSet()
fun setLibraryTabsHidden(context: Context, hidden: Set<String>) {
prefs(context).edit().putString("libraryTabsHidden", hidden.joinToString(",")).apply()
}
fun storesTabHidden(context: Context): Set<String> = idList(prefs(context).getString("storesTabHidden", null)).toSet()
fun setStoresTabHidden(context: Context, hidden: Set<String>) {
@@ -787,7 +812,7 @@ object SessionPrefs {
val prefs = prefs(context)
if (!prefs.contains("shaderPrecache")) {
if (steamConfig(context).exists()) return null
prefs.edit().putBoolean("shaderPrecache", false).apply()
prefs.edit().putBoolean("shaderPrecache", true).apply()
}
val on = prefs.getBoolean("shaderPrecache", true)
val applied = shaderPrecacheApplied(context)
@@ -947,29 +972,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("gamescopeRealtime", on).apply()
}
fun ramCapMb(context: Context): Int = prefs(context).getInt("ramCapMb", 0).coerceAtLeast(0)
fun setRamCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("ramCapMb", mb.coerceAtLeast(0)).apply()
}
fun zramClient(context: Context): Boolean = prefs(context).getBoolean("zramClient", true)
fun setZramClient(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramClient", on).apply()
}
fun zramIdle(context: Context): Boolean = prefs(context).getBoolean("zramIdle", true)
fun setZramIdle(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramIdle", on).apply()
}
fun vramCapMb(context: Context): Int = prefs(context).getInt("vramCapMb", 0).coerceAtLeast(0)
fun setVramCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("vramCapMb", mb.coerceAtLeast(0)).apply()
}
fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false)
@@ -1499,6 +1501,8 @@ object SessionPrefs {
(id and 0xFFFFFFFFL) to key.removePrefix("addedAppId:")
}.toMap()
fun storeGameFolder(context: Context, key: String): String? = prefs(context).getString("storeFolder:$key", null)
fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) {
val p = prefs(context)
val previous = p.getString("storeFolder:$key", null)
@@ -1570,6 +1574,45 @@ object SessionPrefs {
prefs(context).edit().putInt("gradientPrimary", primary).putInt("gradientSecondary", secondary).apply()
}
fun customThemeColors(context: Context): com.droiddeck.launcher.ui.CustomThemeColors =
prefs(context).let { p ->
val defaults = com.droiddeck.launcher.ui.CustomThemeColors()
com.droiddeck.launcher.ui.CustomThemeColors(
background = p.getInt("customThemeBackground", defaults.background),
surface = p.getInt("customThemeSurface", defaults.surface),
surfaceVariant = p.getInt("customThemeSurfaceVariant", defaults.surfaceVariant),
line = p.getInt("customThemeLine", defaults.line),
line2 = p.getInt("customThemeLine2", defaults.line2),
onBackground = p.getInt("customThemeOnBackground", defaults.onBackground),
onSurfaceVariant = p.getInt("customThemeOnSurfaceVariant", defaults.onSurfaceVariant),
primary = p.getInt("customThemePrimary", defaults.primary),
onPrimary = p.getInt("customThemeOnPrimary", defaults.onPrimary),
signal = p.getInt("customThemeSignal", defaults.signal),
good = p.getInt("customThemeGood", defaults.good),
error = p.getInt("customThemeError", defaults.error),
)
}
fun setCustomThemeColors(
context: Context,
colors: com.droiddeck.launcher.ui.CustomThemeColors,
) {
prefs(context).edit()
.putInt("customThemeBackground", colors.background)
.putInt("customThemeSurface", colors.surface)
.putInt("customThemeSurfaceVariant", colors.surfaceVariant)
.putInt("customThemeLine", colors.line)
.putInt("customThemeLine2", colors.line2)
.putInt("customThemeOnBackground", colors.onBackground)
.putInt("customThemeOnSurfaceVariant", colors.onSurfaceVariant)
.putInt("customThemePrimary", colors.primary)
.putInt("customThemeOnPrimary", colors.onPrimary)
.putInt("customThemeSignal", colors.signal)
.putInt("customThemeGood", colors.good)
.putInt("customThemeError", colors.error)
.apply()
}
fun trueBlackHighlight(context: Context): Int =
prefs(context).getInt("trueBlackHighlight", com.droiddeck.launcher.ui.Themes.DEFAULT_HIGHLIGHT)
@@ -417,10 +417,12 @@ class SessionService : Service() {
SessionPrefs.screenEffectsProfileId(SessionState.mode, resolvedGameId, SessionState.program),
)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
val gen = synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
++sessionGen
val gen = synchronized(SessionState.startLock) {
synchronized(stopLock) {
SessionState.steamClientArch = null
SessionState.running = true
++sessionGen
}
}
if (SessionState.stopRequested) {
stopSession(0)
@@ -911,10 +913,9 @@ class SessionService : Service() {
))
}
},
readBackAllowed = { SessionPrefs.ramCapMb(this) == 0 },
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
if (processes == 0) {
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (RAM cap, or ${availableKb / 1024} MB available is too little)")
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (${availableKb / 1024} MB available is too little)")
} else {
Log.i(TAG, "read back $processes processes in $millis ms: zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
}
@@ -1085,11 +1086,7 @@ class SessionService : Service() {
relativeMouseForSession().takeIf { it != 0 }?.let { guest.add("gamescope_relative_mouse=$it") }
if (com.droiddeck.launcher.core.ZramSupport.supported()) {
guest.add("DD_ZRAM=1")
if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("DD_RAM_CAP_MB=$it") }
if (!SessionPrefs.zramClient(this)) guest.add("DD_ZRAM_CLIENT=0")
if (!SessionPrefs.zramIdle(this)) guest.add("DD_ZRAM_IDLE=0")
}
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("DD_VRAM_MB=$it") }
guest.add("AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
@@ -43,6 +43,8 @@ object SessionState {
@Volatile
var stopRequested = false
val startLock = Any()
@Volatile
var running = false
@Volatile
@@ -27,7 +27,6 @@ internal class SessionSuspendController(
private val nowNanos: () -> Long = System::nanoTime,
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _, _ -> },
private val readBackAllowed: () -> Boolean = { true },
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _ -> },
) {
@@ -278,12 +277,21 @@ internal class SessionSuspendController(
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
val control = zramControl?.takeIf { it.isFile } ?: return
val hold = holdFile(control)
try {
addSnapshot(records, root, helpers)
control.writeText("1")
hold.writeText(PAGE_OUT_REQUEST)
sleep(PAGE_OUT_POLL_MS)
pageOut(control, records, root, helpers)
} catch (_: IOException) {
return
} finally {
hold.delete()
}
}
private fun holdFile(control: File) = File(control.parentFile, "${control.name}.hold")
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
addSnapshot(records, root, helpers)
val targets = records.values.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
@@ -301,16 +309,22 @@ internal class SessionSuspendController(
val waiting = targets.toMutableList()
while (!closing && !cancelled && nowMillis() - start < PAGE_OUT_TIMEOUT_MS) {
val started = nowMillis() - start >= PAGE_OUT_START_MS
waiting.removeAll { val ack = acks.getValue(it); ack.length() > 0 || (started && !ack.exists()) || isGone(it) }
waiting.removeAll { val ack = acks.getValue(it); pagedOut(ack) || (started && !ack.exists()) || isGone(it) }
if (waiting.isEmpty()) break
sleep(PAGE_OUT_POLL_MS)
}
val unacknowledged = targets.count { acks.getValue(it).length() == 0L && !isGone(it) }
val unacknowledged = targets.count { !pagedOut(acks.getValue(it)) && !isGone(it) }
acks.values.forEach { it.delete() }
val after = memoryKb(targets)
pagedOut(targets.size, unacknowledged, after.first, after.second, before.second, nowMillis() - start)
}
private fun pagedOut(ack: File): Boolean = try {
ack.readText().trim() == PAGE_OUT_ACK
} catch (_: IOException) {
false
}
private fun readBack() {
val targets = pagedOutTargets.filterNot { isGone(it) }
pagedOutTargets = emptyList()
@@ -318,13 +332,15 @@ internal class SessionSuspendController(
if (targets.isEmpty() || closing) return
val before = memoryKb(targets).second
val (total, available) = meminfoKb()
if (!readBackAllowed() || !canTake(before, total, available)) {
if (!canTake(before, total, available)) {
pagedIn(0, before, before, available, 0)
return
}
val hold = holdFile(control)
try {
control.writeText("0")
hold.writeText(READ_BACK_REQUEST)
} catch (_: IOException) {
hold.delete()
return
}
val start = nowMillis()
@@ -341,6 +357,8 @@ internal class SessionSuspendController(
}
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
} finally {
hold.delete()
}
pagedIn(targets.size, swap, before, available, nowMillis() - start)
}
@@ -456,6 +474,9 @@ internal class SessionSuspendController(
const val SIGSTOP = 19
const val SIGCONT = 18
const val SIGURG = 23
const val PAGE_OUT_ACK = "1"
const val PAGE_OUT_REQUEST = "1"
const val READ_BACK_REQUEST = "0"
const val PAGE_OUT_POLL_MS = 100L
const val PAGE_OUT_START_MS = 2_000L
const val PAGE_OUT_TIMEOUT_MS = 12_000L
@@ -20,7 +20,7 @@ object SettingsReset {
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient", "zramIdle",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
@@ -71,7 +71,10 @@ class StorageReport(
val kept: List<KeptPrefix>,
val leftoversChecked: Boolean,
val storeGames: List<StoreGameUsage> = emptyList(),
val systemCaches: List<SystemCacheUsage> = emptyList(),
val checkouts: List<CheckoutUsage> = emptyList(),
) {
val systemCacheBytes: Long get() = systemCaches.sumOf { it.bytes }
val otherPrefixes: Long get() = kept.sumOf { it.bytes }
val droiddeck: Long get() = buckets.values.sum()
val installedShaders: Long get() = games.sumOf { it.shaders }
@@ -358,6 +361,9 @@ object StorageScan {
val stores = m(File(rootfs, "root/Games"))
val flatpak = m(File(rootfs, "root/.local/share/flatpak"))
val rootfsBytes = m(rootfs)
val systemCaches = SystemCaches.find(rootfs, clientRoots, System.currentTimeMillis())
.map { (kind, found) -> SystemCacheUsage(kind, found, found.sumOf { walker.measure(it) }) }.filter { it.bytes > 0 }
val checkouts = SystemCaches.checkouts(rootfs).map { CheckoutUsage(it, walker.measure(it)) }.sortedByDescending { it.bytes }
val privateBytes = privateRoots.sumOf { m(it) }
val system = rootfsBytes - installs - inApps("compatdata") - inApps("shadercache") - workshop -
compatTools - stores - flatpak
@@ -381,7 +387,7 @@ object StorageScan {
),
prefixes, shaders, workshop, flatpak,
games.sortedByDescending { it.total }, tools.values.toList(), leftovers, logs, logBytes,
components, flatpakApps, flatpakRuntimes, kept, everyLibraryRead, storeGames,
components, flatpakApps, flatpakRuntimes, kept, everyLibraryRead, storeGames, systemCaches, checkouts,
)
}
}
@@ -15,7 +15,7 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoreGameSidecar
enum class CleanItem { OLD_TOOLS, LEFTOVERS, LEFTOVERS_UNSURE, LOGS, UNUSED_CUSTOM, UNUSED_COMPONENTS, SHADERS }
enum class CleanItem { OLD_TOOLS, LEFTOVERS, LEFTOVERS_UNSURE, LOGS, SYSTEM_CACHES, UNUSED_CUSTOM, UNUSED_COMPONENTS, SHADERS }
object StorageState {
private const val TAG = "StorageState"
@@ -61,8 +61,17 @@ object StorageState {
}, "storage-store-sizes").start()
}
/** The last scan's overview from disk, shown until this run's first scan lands. */
var saved by mutableStateOf<StorageSummary?>(null)
private set
private fun publish(app: Context, result: StorageReport) {
report = result
val summary = StorageSummary.of(result)
saved = summary
Thread({
runCatching { StorageSummary.file(app.filesDir).writeText(summary.toJson()) }.onFailure { Log.w(TAG, "could not keep the storage summary", it) }
}, "storage-summary").start()
val live = result.storeGames.mapTo(HashSet()) { sizeKey(it) }
storeSizes.keys.retainAll(live)
measureStoreGames(app)
@@ -88,6 +97,9 @@ object StorageState {
fun refresh(context: Context, force: Boolean = false) {
val current = report
if (current == null && saved == null) {
saved = runCatching { StorageSummary.fromJson(StorageSummary.file(context.applicationContext.filesDir).readText()) }.getOrNull()
}
if (scanning || cleaning) {
if (force) refreshAgain = true
return
@@ -122,9 +134,10 @@ object StorageState {
CleanItem.UNUSED_CUSTOM -> report.unusedTools.filter { it.reason == ToolReason.CUSTOM }.sumOf { it.bytes }
CleanItem.UNUSED_COMPONENTS -> report.unusedComponents.sumOf { it.bytes }
CleanItem.SHADERS -> report.installedShaders
CleanItem.SYSTEM_CACHES -> report.systemCacheBytes
}
val SAFE = setOf(CleanItem.OLD_TOOLS, CleanItem.LEFTOVERS, CleanItem.LOGS)
val SAFE = setOf(CleanItem.OLD_TOOLS, CleanItem.LEFTOVERS, CleanItem.LOGS, CleanItem.SYSTEM_CACHES)
fun safeBytes(report: StorageReport): Long = SAFE.sumOf { bytes(report, it) }
@@ -200,10 +213,19 @@ object StorageState {
true
})
/**
* Whether a kept prefix may be removed. A store app's prefix can go, as Wine makes a new one and the app can be set up
* again, but not while a store game is installed inside it, as Battle.net does on drive C, or while a download may write to it.
*/
internal fun keptRemovable(report: StorageReport, prefix: KeptPrefix): Boolean =
prefix.owner != PrefixOwner.LAUNCHER || (report.storeGames.none { it.game.folder.path.startsWith(prefix.dir.path + "/") } &&
!com.droiddeck.launcher.stores.download.DownloadQueue.anyActive())
fun resetKept(context: Context, prefix: KeptPrefix) = act(context, "kept-${prefix.dir.name}", { _, fresh ->
val dir = fresh.kept.firstOrNull { it.dir.path == prefix.dir.path && it.owner == prefix.owner }
?.takeIf { it.owner == PrefixOwner.SHARED || it.owner == PrefixOwner.GAME }?.dir ?: return@act false
check(FileOps.delete(dir)) { "cannot delete $dir" }
val kept = fresh.kept.firstOrNull { it.dir.path == prefix.dir.path && it.owner == prefix.owner }
?.takeIf { keptRemovable(fresh, it) } ?: return@act false
val reset = kept.owner == PrefixOwner.SHARED || kept.owner == PrefixOwner.GAME
(listOf(kept.dir) + listOfNotNull(kept.shaders?.takeUnless { reset })).forEach { check(FileOps.delete(it)) { "cannot delete $it" } }
true
})
@@ -225,9 +247,25 @@ object StorageState {
com.droiddeck.launcher.stores.StoresState.uninstall(app, next.game) { uninstallNext(app, rest.drop(1)) }
}
/** Clears one cache, as found by a fresh scan, so a file that became busy since stays. */
fun clearSystemCache(context: Context, kind: SystemCache) = act(context, "cache-$kind", { _, fresh ->
val files = fresh.systemCaches.firstOrNull { it.kind == kind }?.files.orEmpty()
files.forEach { FileOps.delete(it) }
files.isNotEmpty()
})
/** Deletes a checkout the fresh scan still lists, and the main repository's record of it if it was a worktree. */
fun removeCheckout(context: Context, dir: java.io.File) = act(context, "checkout-${dir.name}", { app, fresh ->
val checkout = fresh.checkouts.firstOrNull { it.dir.path == dir.path } ?: return@act false
val record = SystemCaches.worktreeRecord(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), checkout.dir)
check(FileOps.delete(checkout.dir)) { "cannot delete ${checkout.dir}" }
record?.let { FileOps.delete(it) }
true
})
fun removeDirs(context: Context, dirs: List<java.io.File>) = act(context, "remove-${dirs.size}", { _, fresh ->
val allowed = (fresh.games.flatMap { it.shaderDirs + listOfNotNull(it.prefixDir) } + fresh.leftovers.flatMap { listOfNotNull(it.prefix, it.shaders) } +
fresh.kept.filter { it.owner == PrefixOwner.SHARED || it.owner == PrefixOwner.GAME }.flatMap { listOfNotNull(it.dir, it.shaders) }).mapTo(HashSet()) { it.path }
fresh.kept.filter { keptRemovable(fresh, it) }.flatMap { listOfNotNull(it.dir, it.shaders) }).mapTo(HashSet()) { it.path }
val wanted = dirs.distinctBy { it.path }
val targets = wanted.filter { it.path in allowed }
if (targets.size < wanted.size) Log.w(TAG, "kept ${wanted.size - targets.size} folders that are no longer safe to remove")
@@ -283,6 +321,7 @@ object StorageState {
CleanItem.LEFTOVERS_UNSURE -> report.leftovers.filter { !it.safe }.forEach(::deleteLeftover)
CleanItem.LOGS -> report.logs.forEach { FileOps.delete(it) }
CleanItem.SHADERS -> report.games.flatMap { it.shaderDirs }.forEach { FileOps.delete(it) }
CleanItem.SYSTEM_CACHES -> report.systemCaches.flatMap { it.files }.forEach { FileOps.delete(it) }
}
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.storage
import org.json.JSONObject
import java.io.File
/**
* What the Storage overview shows, kept on disk so the page opens at once after DroidDeck restarts, as it does on
* every update, while a fresh scan of the whole userland runs behind it.
*/
class StorageSummary(
val at: Long, val total: Long, val free: Long, val buckets: Map<Bucket, Long>, val safe: Long,
val games: Int, val gamesOnSd: Int, val prefixes: Long, val workshop: Long, val shaders: Long,
val tools: Int, val unusedTools: Long, val components: Int, val unusedComponents: Long,
val storeGames: Int, val flatpakApps: Int, val flatpakShared: Long, val logBytes: Long, val systemClearable: Long,
) {
val droiddeck: Long get() = buckets.values.sum()
fun toJson(): String = JSONObject().apply {
put("v", VERSION)
put("at", at); put("total", total); put("free", free); put("safe", safe)
put("buckets", JSONObject().apply { buckets.forEach { (b, v) -> put(b.name, v) } })
put("games", games); put("gamesOnSd", gamesOnSd); put("prefixes", prefixes); put("workshop", workshop); put("shaders", shaders)
put("tools", tools); put("unusedTools", unusedTools); put("components", components); put("unusedComponents", unusedComponents)
put("storeGames", storeGames); put("flatpakApps", flatpakApps); put("flatpakShared", flatpakShared)
put("logBytes", logBytes); put("systemClearable", systemClearable)
}.toString()
companion object {
private const val VERSION = 1
fun of(r: StorageReport) = StorageSummary(
r.at, r.total, r.free, r.buckets, StorageState.safeBytes(r),
r.games.size, r.gamesOnSd, r.prefixes, r.workshop, r.shaders,
r.tools.size, r.unusedTools.sumOf { it.bytes }, r.components.size, r.unusedComponents.sumOf { it.bytes },
r.storeGames.size, r.flatpakApps.size, r.flatpakRuntimes + r.flatpakCache, r.logBytes,
r.systemCacheBytes + r.checkouts.sumOf { it.bytes },
)
/** A summary another version wrote, or a damaged file, reads as none, so the page measures as before. */
fun fromJson(text: String): StorageSummary? = runCatching {
val o = JSONObject(text)
if (o.optInt("v") != VERSION) return null
val b = o.getJSONObject("buckets")
StorageSummary(
o.getLong("at"), o.getLong("total"), o.getLong("free"), Bucket.entries.associateWith { b.optLong(it.name) }, o.getLong("safe"),
o.getInt("games"), o.getInt("gamesOnSd"), o.getLong("prefixes"), o.getLong("workshop"), o.getLong("shaders"),
o.getInt("tools"), o.getLong("unusedTools"), o.getInt("components"), o.getLong("unusedComponents"),
o.getInt("storeGames"), o.getInt("flatpakApps"), o.getLong("flatpakShared"), o.getLong("logBytes"), o.getLong("systemClearable"),
)
}.getOrNull()
fun file(filesDir: File) = File(filesDir, "storage-summary.json")
}
}
@@ -0,0 +1,58 @@
package com.droiddeck.launcher.storage
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.attribute.BasicFileAttributes
/** Parts of the Linux userland that the system and Steam make again when needed, so clearing them loses nothing. */
enum class SystemCache { TEMP, PACKAGES, STEAM_WEB, STEAM_CORRUPT }
class SystemCacheUsage(val kind: SystemCache, val files: List<File>, val bytes: Long)
/** A git checkout in the home folder, such as one the agent made with `git worktree add`. */
class CheckoutUsage(val dir: File, val bytes: Long)
object SystemCaches {
/** Temporary files nothing has touched for a day belong to no program still running. */
const val TEMP_IDLE_MS = 24L * 60 * 60 * 1000
/**
* What each cache would delete. In /tmp, hidden entries (X11, ICE and other sockets' folders) stay, as does
* anything changed within [TEMP_IDLE_MS] or holding a socket or pipe. apt keeps only its downloaded packages
* here, and Steam's web cache and the download chunks it set aside as corrupt come back or are not needed.
*/
fun find(rootfs: File, steamRoots: List<File>, now: Long): Map<SystemCache, List<File>> = linkedMapOf(
SystemCache.TEMP to File(rootfs, "tmp").listFiles().orEmpty().filter { !it.name.startsWith(".") && idle(it, now) },
SystemCache.PACKAGES to File(rootfs, "var/cache/apt/archives").let { dir ->
dir.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".deb") } + File(dir, "partial").listFiles().orEmpty()
},
SystemCache.STEAM_WEB to steamRoots.map { File(it, "config/htmlcache") }.filter { it.isDirectory },
SystemCache.STEAM_CORRUPT to steamRoots.map { File(it, "steamapps/corrupt") }.filter { it.isDirectory },
)
/** The home folder's git checkouts but the DroidDeck source, which the Agent tab's own entry covers. */
fun checkouts(rootfs: File): List<File> = File(rootfs, "root").listFiles().orEmpty()
.filter { it.isDirectory && it.name != "DroidDeck" && File(it, ".git").exists() }
/**
* The main repository's record of a worktree, which `git worktree prune` would drop once the folder is gone.
* Only a path inside some `.git/worktrees/` under [rootfs] counts.
*/
fun worktreeRecord(rootfs: File, checkout: File): File? {
val link = File(checkout, ".git").takeIf { it.isFile } ?: return null
val path = runCatching { link.readText() }.getOrNull()?.lineSequence()?.firstOrNull { it.startsWith("gitdir:") }
?.removePrefix("gitdir:")?.trim()?.takeIf { it.startsWith("/") && "/.git/worktrees/" in it && "/../" !in it } ?: return null
return File(rootfs, path.removePrefix("/")).takeIf { it.isDirectory }
}
/** Nothing inside changed for [TEMP_IDLE_MS] and nothing is a socket or pipe; links are not followed. */
internal fun idle(file: File, now: Long): Boolean = runCatching {
Files.walk(file.toPath()).use { paths ->
paths.allMatch { p ->
val a = Files.readAttributes(p, BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS)
!a.isOther && now - a.lastModifiedTime().toMillis() >= TEMP_IDLE_MS
}
}
}.getOrDefault(false)
}
@@ -5,11 +5,20 @@ import android.content.SharedPreferences
import android.util.Log
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.ea.EaAuth
import com.droiddeck.launcher.stores.ea.EaCloud
import com.droiddeck.launcher.stores.ea.EaLibrary
import com.droiddeck.launcher.stores.ea.EaPrefs
import com.droiddeck.launcher.stores.ea.EaSaveRules
import com.droiddeck.launcher.stores.epic.EpicApiClient
import com.droiddeck.launcher.stores.epic.EpicCredentialStore
import com.droiddeck.launcher.stores.epic.EpicPrefs
import com.droiddeck.launcher.stores.gog.GogAuth
import com.droiddeck.launcher.stores.gog.GogPrefs
import com.droiddeck.launcher.stores.ubisoft.UbisoftAuth
import com.droiddeck.launcher.stores.ubisoft.UbisoftCloud
import com.droiddeck.launcher.stores.ubisoft.UbisoftCloudTransport
import com.droiddeck.launcher.stores.ubisoft.UbisoftConnect
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
@@ -32,19 +41,27 @@ object CloudSaves {
if (detail.isNotEmpty()) " detail=\"$detail\"" else ""
}
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList())
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList(), val signedIn: Boolean = true)
private fun game(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? =
StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull { f ->
StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it }
}
private fun game(context: Context, store: Store, id: String): Pair<File, StoreGameSidecar>? {
fun match(f: File) = StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it }
return StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull(::match)
?: if (store != Store.UBISOFT) null
else com.droiddeck.launcher.session.SessionPrefs.storeGameFolder(context, "${store.id}:$id")?.let { match(File(it)) }
}
fun supports(store: Store?): Boolean = store == Store.GOG || store == Store.EPIC || store == Store.EA || store == Store.UBISOFT
fun prefix(context: Context, folder: File): File? {
val appId = AddedGames.scan(context).firstOrNull { it.folder.absolutePath == folder.absolutePath }?.appId ?: return null
return Library.protonPrefix(context, appId and 0xFFFFFFFFL)
}
private fun prefs(context: Context, store: Store) = if (store == Store.GOG) GogPrefs.get(context) else EpicPrefs.get(context)
private fun prefs(context: Context, store: Store) = when (store) {
Store.GOG -> GogPrefs.get(context)
Store.EA -> EaPrefs.get(context)
else -> EpicPrefs.get(context)
}
fun lastSync(context: Context, store: Store, id: String): Long = prefs(context, store).getLong("cloud_sync_$id", 0L)
@@ -52,6 +69,7 @@ object CloudSaves {
private const val TEMPLATE_NONE = "none"
private const val UBISOFT_TEMPLATE = "ubisoft"
internal const val TEMPLATE_NONE_TTL_MS = 24 * 60 * 60 * 1000L
internal fun noneTemplateIsCurrent(storedAtMs: Long, nowMs: Long) =
@@ -64,6 +82,10 @@ object CloudSaves {
fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? {
val p = prefs(context, store)
if (store == Store.EA) eaRules(context, id)?.let { fresh ->
if (fresh.isEmpty()) rememberNoCloud(p, id) else p.edit().putString("cloud_template_$id", fresh).remove("cloud_template_at_$id").apply()
return fresh
}
var retryNone = false
if (p.contains("cloud_template_$id")) {
val cached = p.getString("cloud_template_$id", "") ?: ""
@@ -89,7 +111,9 @@ 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.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> ""
Store.UBISOFT -> UBISOFT_TEMPLATE
Store.EA -> eaRules(context, id) ?: return null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> ""
} ?: return null
p.edit()
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
@@ -146,18 +170,25 @@ object CloudSaves {
val (folder, sidecar) = game(context, store, id) ?: return null to "not-installed"
val template = template(context, store, id, folder, sidecar) ?: return null to "store-unreachable"
if (template.isEmpty()) return null to "no-cloud-saves"
if (store == Store.UBISOFT) {
val user = UbisoftAuth.load(context)?.userId?.takeIf { it.isNotEmpty() } ?: return null to "not-signed-in"
val product = sidecar.extra["productId"]?.toLongOrNull() ?: return null to "unresolved"
return File(UbisoftConnect.prefix(context), "pfx/drive_c/users/steamuser/Saved Games/Ubisoft/$user/$product") to "ok"
}
val pfx = prefix(context, folder) ?: return null to "no-prefix"
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.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
Store.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null
else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) }
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> null
}
return dir to (if (dir == null) "unresolved" else "ok")
}
fun status(context: Context, store: Store, id: String): Status {
val (dir, reason) = saveFolder(context, store, id)
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id))
return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id, dir), signedIn(context, store))
}
@@ -175,7 +206,33 @@ 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.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null
Store.UBISOFT -> {
val session = UbisoftAuth.current(context)
val product = StoreGameSidecar.read(folder)?.extra?.get("productId")?.toLongOrNull()
if (session == null || product == null) null else UbisoftCloudTransport(UbisoftCloud(session, product), session.userId)
}
Store.EA -> {
val sidecar = StoreGameSidecar.read(folder)
val rules = sidecar?.let { template(context, store, id, folder, it) }?.let(EaSaveRules::parse)
val base = rules?.base()
val token = EaAuth.accessToken(context)
val uid = EaAuth.load(context)?.userId.orEmpty()
val master = sidecar?.extra?.get("masterTitleId").orEmpty()
if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null
else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first)
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> null
}
private fun signedIn(context: Context, store: Store): Boolean = when (store) {
Store.EA -> EaAuth.signedIn(context)
else -> true
}
private fun eaRules(context: Context, id: String): String? {
val games = EaLibrary.cached(context)
if (games.isEmpty()) return null
return games.firstOrNull { it.offerId == id }?.cloudSaves.orEmpty()
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -184,11 +241,15 @@ object CloudSaves {
}
private fun baseline(context: Context, store: Store, id: String): Map<String, CloudPlan.Entry>? =
CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$id", null))
/** Ubisoft saves belong to an account and product, so their sync state is kept per save folder. */
internal fun scope(store: Store, id: String, dir: File): String =
if (store == Store.UBISOFT) "$id:${dir.parentFile?.name.orEmpty()}:${dir.name}" else id
private fun saveBaseline(context: Context, store: Store, id: String, b: Map<String, CloudPlan.Entry>) =
prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply()
internal fun baseline(context: Context, store: Store, key: String): Map<String, CloudPlan.Entry>? =
CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$key", null))
private fun saveBaseline(context: Context, store: Store, key: String, b: Map<String, CloudPlan.Entry>) =
prefs(context, store).edit().putString("cloud_baseline_$key", CloudPlan.toJson(b)).apply()
internal class Migration(val baseline: Map<String, CloudPlan.Entry>, val moved: Int, val cleaned: Int, val failed: Int)
@@ -260,30 +321,45 @@ object CloudSaves {
if (result == null || result.failed == 0) p.edit().putInt("cloud_layout_$id", CLOUD_LAYOUT).apply()
}
fun conflicts(context: Context, store: Store, id: String): List<String> =
prefs(context, store).getString("cloud_conflicts_$id", "").orEmpty().split('\n').filter { it.isNotEmpty() }
fun conflicts(context: Context, store: Store, id: String, dir: File? = null): List<String> =
if (store == Store.UBISOFT && dir == null) emptyList() else savedConflicts(context, store, dir?.let { scope(store, id, it) } ?: id)
private fun saveConflicts(context: Context, store: Store, id: String, names: Collection<String>) =
prefs(context, store).edit().putString("cloud_conflicts_$id", names.joinToString("\n")).apply()
private fun savedConflicts(context: Context, store: Store, key: String): List<String> =
prefs(context, store).getString("cloud_conflicts_$key", "").orEmpty().split('\n').filter { it.isNotEmpty() }
fun download(context: Context, store: Store, id: String, force: Boolean = false): Result =
sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force) }
private fun saveConflicts(context: Context, store: Store, key: String, names: Collection<String>) =
prefs(context, store).edit().putString("cloud_conflicts_$key", names.joinToString("\n")).apply()
private fun alike(cloud: CloudTransport, conflicts: List<String>, local: Map<String, CloudPlan.Local>, remote: Map<String, CloudFile>): List<String> =
if (cloud.contentDigests) emptyList()
else conflicts.filter { name ->
val r = remote[name] ?: return@filter false
val l = local[name] ?: return@filter false
runCatching { md5(cloud.get(r).first) }.getOrNull()?.equals(l.md5, ignoreCase = true) == true
}
private fun settled(plan: CloudPlan.Plan, alike: List<String>): CloudPlan.Plan =
if (alike.isEmpty()) plan else CloudPlan.Plan(plan.transfer, plan.conflicts - alike.toSet(), plan.same + alike, plan.refused)
fun download(context: Context, store: Store, id: String, force: Boolean = false, claim: () -> Boolean = { true }): Result =
sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force, claim) }
fun upload(context: Context, store: Store, id: String, force: Boolean = false): Result =
sync(context, store, id, "up") { dir, cloud -> upWith(context, store, id, dir, cloud, force) }
fun downloadOrDefer(context: Context, store: Store, id: String): Result =
downloadOrDefer(context, store, id, Executor { Thread(it, "cloud-deferred").start() })
fun downloadOrDefer(context: Context, store: Store, id: String, claim: () -> Boolean): Result =
downloadOrDefer(context, store, id, Executor { Thread(it, "cloud-deferred").start() }, claim)
internal fun downloadOrDefer(context: Context, store: Store, id: String, executor: Executor): Result {
internal fun downloadOrDefer(context: Context, store: Store, id: String, executor: Executor, claim: () -> Boolean = { true }): Result {
val app = context.applicationContext
val g = game(app, store, id) ?: return done(store, id, "down", Result("skipped", 0, 0, "not-installed"))
if (!g.second.cloud) return done(store, id, "down", Result("skipped", 0, 0, "off"))
if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) return download(app, store, id)
val ready = { (if (store == Store.UBISOFT) File(UbisoftConnect.prefix(app), "pfx") else prefix(app, g.first))?.let { CloudSavePaths.profile(it).isDirectory } == true }
if (ready()) return download(app, store, id, claim = claim)
executor.execute {
val end = System.currentTimeMillis() + PREFIX_WAIT_MS
while (System.currentTimeMillis() < end) {
if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) { download(app, store, id); return@execute }
if (ready()) { download(app, store, id); return@execute }
Thread.sleep(2000)
}
done(store, id, "down", Result("skipped", 0, 0, "no-prefix"))
@@ -304,8 +380,12 @@ object CloudSaves {
if (dir != null && store == Store.GOG) migrateGogNested(context, id, g.first, dir)
val cloud = if (dir != null) transport(context, store, id, g.first) else null
when {
cloud is UbisoftCloudTransport && dir?.parentFile?.name != cloud.user -> Result("skipped", 0, 0, "account-changed")
dir == null -> Result("skipped", 0, 0, reason)
cloud == null && store == Store.EA && signedIn(context, store) -> Result("failed", 0, 0, "sign-in-unreachable")
cloud == null -> Result("skipped", 0, 0, "not-signed-in")
cloud is EaCloud && cloud.localDir?.canonicalPath != dir.canonicalPath -> Result("skipped", 0, 0, "rules-changed")
cloud is EaCloud && caseCollision(localFiles(dir).keys, cloud::wants) -> Result("failed", 0, 0, "case-collision")
else -> body(dir, cloud).also { if (it.result == "ok") markSynced(context, store, id) }
}
}
@@ -319,15 +399,32 @@ object CloudSaves {
return done(store, id, way, result)
}
internal fun caseCollision(names: Collection<String>, wants: (String) -> Boolean): Boolean =
names.filter(wants).groupBy { it.lowercase() }.any { it.value.size > 1 }
private fun done(store: Store, id: String, way: String, r: Result): Result {
Log.i(TAG, "cloud ${store.id} $id $way ${r.line}")
StoresState.logLine("cloud ${store.id} $id $way ${r.line}")
return r
}
private fun localFiles(dir: File): Map<String, File> =
if (!dir.isDirectory) emptyMap()
else dir.walkTopDown().filter { it.isFile }.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') }
private fun localFiles(dir: File): Map<String, File> {
if (!dir.isDirectory) return emptyMap()
val root = runCatching { dir.toPath().toRealPath() }.getOrNull() ?: return emptyMap()
val found = LinkedHashMap<String, File>()
fun walk(d: File, prefix: String, ancestry: Set<java.nio.file.Path>) {
for (child in d.listFiles().orEmpty()) {
val real = runCatching { child.toPath().toRealPath() }.getOrNull() ?: continue
if (!real.startsWith(root)) continue
val name = prefix + child.name
if (child.isDirectory) {
if (real !in ancestry) walk(child, "$name/", ancestry + real)
} else if (child.isFile) found[name] = child
}
}
walk(dir, "", setOf(root))
return found
}
internal fun md5(f: File): String = md5(f.readBytes())
@@ -341,46 +438,85 @@ object CloudSaves {
return files.associateBy { it.name }
}
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
val files = localFiles(dir)
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result {
val files = localFiles(dir).filterKeys(cloud::wants)
val remote = remote(cloud) { it in files }
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val base = baseline(context, store, id)
val plan = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val take = if (force) plan.transfer + plan.conflicts else plan.transfer
if (take.isNotEmpty() && files.isNotEmpty()) backup(context, store, id, dir, "local")
val key = scope(store, id, dir)
val base = baseline(context, store, key)
val planned = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val alike = alike(cloud, planned.conflicts, local, remote)
val plan = settled(planned, alike)
val saved = savedConflicts(context, store, key).filter { it in remote && it !in alike && it !in plan.same }
val take = if (force) (plan.transfer + plan.conflicts + saved).distinct() else plan.transfer
val next = HashMap(base.orEmpty())
var bytes = 0L
val written = HashSet<String>()
val changed = ArrayList<String>()
val blocked = ArrayList<String>()
val fetched = LinkedHashMap<String, Pair<CloudFile, Pair<ByteArray, Long>>>()
for (name in take) {
val f = remote[name] ?: continue
val (data, modified) = cloud.get(f)
if (!File(dir, name).canonicalPath.startsWith(dir.canonicalPath + File.separator)) { blocked += name; continue }
fetched[name] = f to cloud.get(f)
}
if (fetched.isNotEmpty() && !claim()) return Result("skipped", 0, 0, "launch-moved-on")
val replaced = fetched.keys.mapNotNull { name -> files[name] ?: File(dir, name).takeIf { it.isFile } }
if (!backupReplaced(context, store, id, dir, replaced)) return Result("failed", 0, 0, "backup-failed")
for ((name, got) in fetched) {
val (f, content) = got
val (data, modified) = content
val dest = File(dir, name)
if (!dest.canonicalPath.startsWith(dir.canonicalPath + File.separator)) continue
if ((if (dest.isFile) md5(dest) else null) != local[name]?.md5) { changed += name; continue }
dest.parentFile?.mkdirs()
dest.writeBytes(data)
if (modified > 0) dest.setLastModified(modified)
bytes += data.size
written += name
next[name] = CloudPlan.Entry(md5(data), f.md5, if (modified > 0) modified else f.modifiedMs)
}
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
saveBaseline(context, store, id, next)
val left = if (force) emptyList() else plan.conflicts
saveConflicts(context, store, id, left)
return Result("ok", take.size, bytes, if (take.isEmpty()) "up-to-date" else "downloaded", left.size)
saveBaseline(context, store, key, next)
val left = (if (force) take.filter { it !in written } else plan.conflicts + saved.filter { it !in written } + changed)
.filter { it !in blocked }.distinct()
saveConflicts(context, store, key, left)
val reason = when {
take.isEmpty() -> "up-to-date"
changed.isNotEmpty() -> "changed-locally"
blocked.isNotEmpty() -> "blocked-path"
else -> "downloaded"
}
val detail = listOfNotNull(
changed.takeIf { it.isNotEmpty() }?.joinToString(prefix = "changed locally: "),
blocked.takeIf { it.isNotEmpty() }?.joinToString(prefix = "outside the save folder: "),
).joinToString("; ")
return Result(if (written.size < take.size) "partial" else "ok", written.size, bytes, reason, left.size, detail)
}
internal fun upWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result {
val base = baseline(context, store, id) ?: return Result("skipped", 0, 0, "no-baseline")
val files = localFiles(dir)
val key = scope(store, id, dir)
val base = baseline(context, store, key) ?: return Result("skipped", 0, 0, "no-baseline")
val files = localFiles(dir).filterKeys(cloud::wants).let { all -> if (cloud is UbisoftCloudTransport) all.filterValues(::markUbisoftSave) else all }
if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local")
val remote = remote(cloud) { it in files }
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val plan = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys)
val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val alike = alike(cloud, planned.conflicts, local, remote)
val plan = settled(planned, alike)
val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same }
var send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys)
val next = HashMap(base)
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
var drifted = emptyList<String>()
var raced = emptyList<String>()
if (send.isNotEmpty()) {
val copies = backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
if (cloud is UbisoftCloudTransport && !force) {
drifted = send.filter { name -> val synced = base[name]?.localMd5; synced != null && copies[name]?.let { it != synced } == true }
send = send - drifted.toSet()
}
}
if (send.isNotEmpty()) {
backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
val stamped = HashMap<String, Long>()
val sentMd5 = HashMap<String, String>()
if (cloud is GogCloud) {
@@ -394,19 +530,40 @@ object CloudSaves {
} else {
val data = send.associateWith { files.getValue(it).readBytes() }
for ((name, bytes) in data) sentMd5[name] = md5(bytes)
stamped += cloud.put(data, send.associateWith { files.getValue(it).lastModified() })
stamped += try {
cloud.put(data, send.associateWith { files.getValue(it).lastModified() })
} catch (e: CloudChanged) {
raced = e.unsent
e.sent
} catch (e: Exception) {
val kept = send.mapNotNull { name -> cloud.committed(name)?.let { name to it } }
if (kept.isNotEmpty()) {
for ((name, r) in kept) next[name] = CloudPlan.Entry(sentMd5.getValue(name), r.md5, r.modifiedMs)
saveBaseline(context, store, key, next)
saveConflicts(context, store, key, saved - kept.map { it.first }.toSet())
}
throw e
}
send = send.filter { it in stamped }
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
}
val after = remote(cloud) { it in send }
val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }
for (name in send) {
val r = after[name]
val r = cloud.committed(name) ?: after[name]
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
}
}
saveBaseline(context, store, id, next)
val left = if (force) emptyList() else plan.conflicts
saveConflicts(context, store, id, left)
return Result("ok", send.size, send.sumOf { files.getValue(it).length() }, if (send.isEmpty()) "up-to-date" else "uploaded", left.size)
saveBaseline(context, store, key, next)
val left = (if (force) (plan.conflicts + saved).filter { it !in send } + raced
else plan.conflicts + drifted + raced + saved.filter { it !in send && it in files }).distinct()
saveConflicts(context, store, key, left)
val reason = when {
raced.isNotEmpty() -> "changed-in-cloud"
send.isEmpty() -> "up-to-date"
else -> "uploaded"
}
return Result(if (raced.isEmpty()) "ok" else "partial", send.size, send.sumOf { files.getValue(it).length() }, reason, left.size,
if (raced.isEmpty()) "" else raced.joinToString(prefix = "changed in the cloud: "))
}
@@ -441,23 +598,59 @@ object CloudSaves {
private fun backupRoot(context: Context, store: Store, id: String) =
File(context.filesDir, "stores/cloud-backups/${store.id}-${id.replace(Regex("[^A-Za-z0-9._-]"), "_")}")
private fun backup(context: Context, store: Store, id: String, dir: File, kind: String) {
val root = backupRoot(context, store, id)
runCatching { dir.copyRecursively(File(root, "$kind-${System.currentTimeMillis()}"), overwrite = true) }
prune(root, kind)
private fun markUbisoftSave(file: File): Boolean {
val head = ByteArray(40)
var filled = 0
file.inputStream().use { input ->
while (filled < head.size) {
val n = input.read(head, filled, head.size - filled)
if (n < 0) break
filled += n
}
}
if (filled < head.size) return false
if (UbisoftCloud.mark(head) != null) return true
if (head.copyOfRange(8, 40).any { it != 0.toByte() }) return false
java.io.RandomAccessFile(file, "rw").use { it.seek(8); it.write(UbisoftCloud.freshMark().toByteArray(Charsets.ISO_8859_1)) }
return true
}
private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List<CloudFile>) {
if (files.isEmpty()) return
private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List<CloudFile>): Map<String, String> {
if (files.isEmpty()) return emptyMap()
val root = backupRoot(context, store, id)
val target = File(root, "cloud-${System.currentTimeMillis()}")
val copies = HashMap<String, String>()
for (f in files) {
val dest = File(target, f.name)
if (!dest.canonicalPath.startsWith(target.canonicalPath + File.separator)) continue
dest.parentFile?.mkdirs()
dest.writeBytes(cloud.get(f).first)
val data = cloud.get(f).first
dest.writeBytes(data)
copies[f.name] = md5(data)
}
prune(root, "cloud")
return copies
}
private fun backupReplaced(context: Context, store: Store, id: String, dir: File, replaced: List<File>): Boolean {
if (replaced.isEmpty()) return true
val base = runCatching { dir.canonicalPath + File.separator }.getOrNull() ?: return false
val root = backupRoot(context, store, id)
val stamp = "${System.currentTimeMillis()}-${java.util.UUID.randomUUID().toString().take(8)}"
val staging = File(root, "staging-$stamp")
val copied = runCatching {
for (f in replaced) {
check(f.canonicalPath.startsWith(base))
f.copyTo(File(staging, f.relativeTo(dir).path), overwrite = true)
}
check(staging.renameTo(File(root, "local-$stamp")))
}.isSuccess
if (!copied) {
staging.deleteRecursively()
return false
}
prune(root, "local")
return true
}
private fun prune(root: File, kind: String) {
@@ -27,6 +27,10 @@ class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null,
class CloudPut(val modifiedMs: Long, val md5: String?)
interface CloudTransport {
/** False when [CloudFile.md5] is a version the service assigns rather than a digest of the content. */
val contentDigests: Boolean get() = true
fun committed(name: String): CloudFile? = null
fun wants(name: String): Boolean = true
fun list(): List<CloudFile>
fun details(file: CloudFile) {}
fun get(file: CloudFile): Pair<ByteArray, Long>
@@ -182,6 +186,8 @@ internal fun isoDate(s: String?): Long {
class NoCloudSaves : Exception("no cloud saves")
class CloudChanged(val sent: Map<String, Long>, val unsent: List<String>) : Exception("cloud saves changed since they were read")
internal fun splitGogName(name: String): Pair<String?, String> {
val slash = name.indexOf('/')
return if (slash <= 0 || slash == name.length - 1) null to name
@@ -46,11 +46,18 @@ object StoreLaunchRequests {
}
private fun answer(app: Context, file: File) {
val resp = File(dir(app), "resp").apply { mkdirs() }
val rid = file.name.removeSuffix(".json")
val taken = File(resp, "$rid.taken")
val writing = File(resp, "$rid.writing")
if (!file.renameTo(taken)) return
val request = try {
JSONObject(file.readText()).also { file.delete() }
JSONObject(taken.readText())
} catch (e: Exception) {
taken.delete()
return
}
val claim = { taken.renameTo(writing) }
val reply = when (request.optString("op")) {
"xbox-released" -> {
com.droiddeck.launcher.stores.xbox.XboxRuntime.released(request.optString("lease"))
@@ -108,7 +115,7 @@ object StoreLaunchRequests {
else {
lastLaunched = store to id
CloudSaves.markDirty(app, store, id)
CloudSaves.downloadOrDefer(app, store, id).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) }
CloudSaves.downloadOrDefer(app, store, id, claim).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) }
}
}
"cloud-up" -> {
@@ -167,12 +174,14 @@ object StoreLaunchRequests {
else -> JSONObject().put("ok", false).put("reason", "unknown-op")
}
try {
val resp = File(dir(app), "resp").apply { mkdirs() }
val tmp = File(resp, file.name + ".tmp")
tmp.writeText(reply.toString())
tmp.renameTo(File(resp, file.name))
} catch (e: Exception) {
Log.w(TAG, "could not answer ${file.name}: ${e.message}")
} finally {
taken.delete()
writing.delete()
}
}
@@ -46,6 +46,26 @@ data class DownloadEntry(
stageItemsTotal > 0 -> (stageItems.toFloat() / stageItemsTotal).coerceIn(0f, 1f)
else -> -1f
}
val downloadFraction: Float get() = if (bytesTotal > 0L) (bytesDone.toDouble() / bytesTotal).toFloat().coerceIn(0f, 1f) else -1f
val installFraction: Float get() = when {
stage != DownloadStage.DOWNLOAD && stage != DownloadStage.INSTALL -> -1f
stageTotal > 0L -> (stageDone.toDouble() / stageTotal).toFloat().coerceIn(0f, 1f)
stageItemsTotal > 0 -> (stageItems.toFloat() / stageItemsTotal).coerceIn(0f, 1f)
else -> -1f
}
val streaming: Boolean get() = state == DownloadState.RUNNING && bytesTotal > 0L && bytesDone < bytesTotal && installFraction >= 0f &&
(stage == DownloadStage.INSTALL || (stage == DownloadStage.DOWNLOAD && passed(DownloadStage.INSTALL)))
/** Whole job as one bar: downloading fills the first 90%, installing the rest, also when they run together. */
val overallFraction: Float get() {
if (state == DownloadState.INSTALLED || stage == DownloadStage.DONE) return 1f
val downloaded = when {
bytesTotal > 0L -> downloadFraction
passed(DownloadStage.DOWNLOAD) -> 1f
else -> 0f
}
val installed = if (stage == DownloadStage.INSTALL || (stage == DownloadStage.DOWNLOAD && passed(DownloadStage.INSTALL))) installFraction.coerceAtLeast(0f) else 0f
return (0.9f * downloaded + 0.1f * installed).coerceIn(0f, 1f)
}
val fraction: Float get() = stageFraction.coerceAtLeast(0f)
val percent: Int get() = (fraction * 100).toInt()
}
@@ -45,13 +45,18 @@ object DownloadQueue {
val e = item.entry
if (e.stage == stage) return
item.speedAt = 0L; item.speedBytes = 0L; item.speedEwma = 0.0
item.entry = e.copy(
stage = stage, stagesPassed = e.stagesPassed or (1 shl e.stage.ordinal), speedBps = 0, etaSeconds = -1,
val passed = e.stagesPassed or (1 shl e.stage.ordinal)
// Streaming installers (GOG) alternate between DOWNLOAD and INSTALL; the install count lives on across the swaps.
val streaming = e.stage in STREAMED && stage in STREAMED && (passed and (1 shl DownloadStage.INSTALL.ordinal)) != 0
item.entry = if (streaming) e.copy(stage = stage, stagesPassed = passed, speedBps = 0, etaSeconds = -1)
else e.copy(
stage = stage, stagesPassed = passed, speedBps = 0, etaSeconds = -1,
stageDone = 0, stageTotal = 0, stageItems = 0, stageItemsTotal = 0,
)
}
private const val SPEED_WINDOW_MS = 3000.0
private val STREAMED = setOf(DownloadStage.DOWNLOAD, DownloadStage.INSTALL)
private fun stageCount(key: String, done: Long, total: Long, files: Int, filesTotal: Int, bytes: Boolean) {
synchronized(lock) {
@@ -178,6 +183,8 @@ object DownloadQueue {
fun isActive(key: String): Boolean = entry(key)?.isActive == true
fun anyActive(): Boolean = synchronized(lock) { items.values.any { it.entry.isActive } }
fun enqueue(context: Context, entry: DownloadEntry, factory: () -> DownloadJob) {
val app = context.applicationContext
synchronized(lock) {
@@ -17,7 +17,7 @@ object EaAuth {
const val CLIENT_ID = "JUNO_PC_CLIENT"
private const val CLIENT_SECRET = "4mRLtYMb6vq9qglomWEaT4ChxsXWcyqbQpuBNfMPOYOiDmYYQmjuaBsF2Zp0RyVeWkfqhE9TuGgAw7te"
const val AUTH_URL = "https://accounts.ea.com/connect/auth"
private const val TOKEN_URL = "https://accounts.ea.com/connect/token"
internal var tokenUrl = "https://accounts.ea.com/connect/token"
const val REDIRECT = "qrc:///html/login_successful.html"
private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L
private val refreshLock = Any()
@@ -41,8 +41,11 @@ object EaAuth {
val personaId: String,
val displayName: String,
val eaId: String,
val rejected: Boolean = false,
)
private class Rejected(message: String) : IllegalStateException(message)
class Pending(val url: String, val verifier: String)
internal fun fromJson(o: JSONObject): Account? {
@@ -55,6 +58,7 @@ object EaAuth {
personaId = o.optString("persona_id"),
displayName = o.optString("display_name"),
eaId = o.optString("ea_id"),
rejected = o.optBoolean("refresh_rejected"),
)
}
@@ -122,14 +126,15 @@ object EaAuth {
private fun tokenCall(values: List<Pair<String, String>>): JSONObject {
val reply = EaHttp.request(
TOKEN_URL, "POST",
tokenUrl, "POST",
mapOf("Content-Type" to "application/x-www-form-urlencoded"),
EaHttp.form(values + listOf("client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET)).toByteArray(),
follow = false,
)
val json = runCatching { JSONObject(reply.text) }.getOrNull()
if (!reply.ok || json == null || json.optString("access_token").isEmpty()) {
throw IllegalStateException("EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}")
val message = "EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}"
throw if (json?.optString("error") == "invalid_grant") Rejected(message) else IllegalStateException(message)
}
return json
}
@@ -162,6 +167,7 @@ object EaAuth {
tokenCall(listOf("grant_type" to "refresh_token", "refresh_token" to a.refreshToken))
} catch (e: Exception) {
Log.w(TAG, "refresh: ${e.message}")
if (e is Rejected) markRejected(context, a.refreshToken)
return null
}
val access = token.getString("access_token")
@@ -176,11 +182,24 @@ object EaAuth {
val record = StoreAccounts.read(app, Store.EA) ?: return false
record.put("access_token", access).put("expires_at", System.currentTimeMillis() + expiresIn * 1000)
refresh.takeIf { it.isNotEmpty() }?.let { record.put("refresh_token", it) }
record.remove("refresh_rejected")
player?.let { record.put("user_id", it.userId).put("persona_id", it.personaId).put("display_name", it.displayName).put("ea_id", it.eaId) }
StoreAccounts.write(app, Store.EA, record)
true
}
private fun markRejected(context: Context, refresh: String) = synchronized(refreshLock) {
val app = context.applicationContext
val record = StoreAccounts.read(app, Store.EA) ?: return@synchronized
if (record.optString("refresh_token") != refresh) return@synchronized
StoreAccounts.write(app, Store.EA, record.put("refresh_rejected", true))
}
fun signedIn(context: Context): Boolean {
val a = load(context) ?: return false
return a.userId.isNotEmpty() && !(a.rejected && a.expiresAt <= System.currentTimeMillis())
}
fun accessToken(context: Context): String? {
val current = load(context) ?: return null
if (fresh(current)) return current.accessToken
@@ -0,0 +1,265 @@
package com.droiddeck.launcher.stores.ea
import android.util.Base64
import android.util.Xml
import com.droiddeck.launcher.stores.CloudFile
import com.droiddeck.launcher.stores.CloudTransport
import java.io.File
import java.io.StringReader
import java.security.MessageDigest
import java.time.Instant
import org.xmlpull.v1.XmlPullParser
internal class EaCloud(
private val token: String,
private val uid: String,
private val keys: List<String>,
private val base: String,
private val rules: EaSaveRules,
val localDir: File? = null,
) : CloudTransport {
class Entry(val size: Long, val href: String, val md5: String, val created: String, val modified: String, val localName: String)
class Manifest(val lineage: String, val files: List<Entry>, val snapshots: List<String>)
private class Signed(val url: String, val headers: Map<String, String>)
private class Request(val verb: String, val resource: String, val md5: String? = null, val type: String? = null)
private var key: String? = null
private var found = false
private var listed: Map<String, String?>? = null
private val committed = HashMap<String, CloudFile>()
override fun wants(name: String): Boolean = rules.matches(base + name)
override fun committed(name: String): CloudFile? = committed[name]
override fun list(): List<CloudFile> {
val manifest = pick()
val files = manifest?.files.orEmpty().mapNotNull { e ->
val path = EaSaveRules.normalize(e.localName)
if (!path.startsWith(base, ignoreCase = true) || !rules.matches(path)) return@mapNotNull null
val md5 = hex(e.md5) ?: error("EA listed ${path.substring(base.length)} without a valid checksum")
CloudFile(localName(path.substring(base.length)), parseTime(e.modified), md5, readLink = e.href)
}
val twins = files.groupBy { it.name.lowercase() }.values.firstOrNull { it.size > 1 }
check(twins == null) { "EA lists more than one save named ${twins!!.first().name} in different cases" }
listed = files.associate { it.name.lowercase() to it.md5 }
return files
}
private fun localName(name: String): String {
var dir = localDir ?: return name
val parts = name.split('/')
val out = ArrayList<String>()
for (part in parts) {
val match = dir.listFiles()?.filter { it.name.equals(part, ignoreCase = true) }.orEmpty()
check(match.size <= 1) { "The save folder holds more than one file named $part in different cases" }
val pick = match.singleOrNull()
if (pick == null) return (out + parts.drop(out.size)).joinToString("/")
out += pick.name
dir = pick
}
return out.joinToString("/")
}
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val href = file.readLink ?: error("EA has no data for ${file.name}")
return locked("read", key ?: keys.first()) { lock, _ ->
val signed = authorize(lock, listOf(Request("GET", href))).single()
val reply = EaHttp.request(signed.url, headers = signed.headers)
check(reply.ok) { "EA cloud save download answered ${reply.status}" }
val want = file.md5 ?: error("EA listed ${file.name} without a valid checksum")
check(hex(b64(md5(reply.body))) == want) { "EA cloud save ${file.name} failed its checksum" }
reply.body to file.modifiedMs
}
}
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> {
if (key == null) pick()
check(found || keys.size == 1) { "EA has no cloud save record for this game yet; play it once in the EA app" }
val target = key ?: keys.first()
val seen = listed
return locked("write", target) { lock, body ->
val locked = manifestUrl(body)?.let { fetchManifest(it) }
check(locked != null || !found) { "EA's cloud save record disappeared" }
val current = locked ?: Manifest("{00000000-0000-0000-0000-000000000000}", emptyList(), emptyList())
if (seen != null) for (name in files.keys) {
val entry = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }
val now = entry?.let { hex(it.md5) ?: error("EA lists $name without a valid checksum") }
check(now == seen[name.lowercase()]) { "EA's cloud saves changed since they were read" }
}
val now = System.currentTimeMillis()
val added = files.map { (name, data) ->
val sum = md5(data)
val stamp = stamp(modifiedMs[name]?.takeIf { it > 0 } ?: now)
val old = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) }
Entry(data.size.toLong(), "content/${data.size}-${hexOf(sum)}", b64(sum), old?.created ?: stamp, stamp, base + name) to data
}
val names = added.map { it.first.localName.lowercase() }.toSet()
val next = Manifest(current.lineage, current.files.filter { EaSaveRules.normalize(it.localName).lowercase() !in names } + added.map { it.first }, current.snapshots)
val xml = write(next).toByteArray()
val xmlMd5 = b64(md5(xml))
val requests = added.map { Request("PUT", it.first.href, it.first.md5, "application/octet-stream") } + Request("PUT", "manifest.xml", xmlMd5, "text/xml")
val signed = authorize(lock, requests)
for ((i, pair) in added.withIndex()) upload(signed[i], pair.second)
upload(signed.last(), xml)
found = true
for ((entry, _) in added) {
val name = entry.localName.substring(base.length)
committed[name] = CloudFile(name, parseTime(entry.modified), hex(entry.md5), readLink = entry.href)
}
listed = null
files.mapValues { (name, _) -> modifiedMs[name]?.takeIf { it > 0 } ?: now }
}
}
private fun pick(): Manifest? {
for (candidate in keys) {
val manifest = locked("read", candidate, missing = { null }) { _, body -> manifestUrl(body)?.let { fetchManifest(it) } }
if (manifest != null) {
key = candidate
found = true
return manifest
}
}
key = keys.first()
found = false
return null
}
private fun upload(signed: Signed, data: ByteArray) {
val reply = EaHttp.request(signed.url, "PUT", signed.headers, data)
check(reply.ok) { "EA cloud save upload answered ${reply.status}" }
}
private fun fetchManifest(url: String): Manifest? {
val reply = EaHttp.request(url)
if (reply.status == 404) return null
check(reply.ok) { "EA cloud save manifest answered ${reply.status}" }
return parse(reply.text)
}
private fun <T> locked(kind: String, key: String, missing: (() -> T)? = null, body: (String, String) -> T): T {
val reply = EaHttp.request("$HOST/lock/$kind/$uid/$key", "POST", mapOf(AUTH to token, "Content-Type" to "application/xml"), ByteArray(0))
if (reply.status == 404 && missing != null) return missing()
check(reply.ok) { "EA cloud saves answered ${reply.status}" }
val lock = reply.header(LOCK) ?: error("EA did not grant a cloud save lock")
try {
return body(lock, reply.text)
} finally {
runCatching { EaHttp.request("$HOST/lock/delete/$uid", "DELETE", mapOf(AUTH to token, LOCK to lock)) }
}
}
private fun authorize(lock: String, requests: List<Request>): List<Signed> {
val body = buildString {
append("<requests>")
for ((i, r) in requests.withIndex()) {
append("<request id=\"").append(i).append("\"><verb>").append(r.verb).append("</verb><resource>").append(escape(r.resource)).append("</resource>")
r.md5?.let { append("<md5>").append(it).append("</md5>") }
r.type?.let { append("<content-type>").append(it).append("</content-type>") }
append("</request>")
}
append("</requests>")
}
val reply = EaHttp.request("$HOST/lock/authorize/$uid", "PUT", mapOf(AUTH to token, LOCK to lock, "Content-Type" to "application/xml"), body.toByteArray())
check(reply.ok) { "EA cloud saves refused the transfer (${reply.status})" }
return signedRequests(reply.text, requests.size)
}
companion object {
private const val HOST = "https://cloudsync.juno.ea.com"
private const val AUTH = "X-Origin-AuthToken"
private const val LOCK = "X-Origin-Sync-Lock"
private val REQUEST = Regex("<request\\b[^>]*\\bid=\"(\\d+)\"[^>]*>(.*?)</request>", RegexOption.DOT_MATCHES_ALL)
private val HEADER = Regex("<header\\b([^>]*)/?>")
fun keys(masterTitleId: String, multiplayerId: String): List<String> =
if (multiplayerId.isNotEmpty()) listOf("${masterTitleId}_$multiplayerId") else listOf(masterTitleId, "${masterTitleId}_$masterTitleId")
fun manifestUrl(lockBody: String): String? = Regex("<manifest>([^<]+)</manifest>").find(lockBody)?.groupValues?.get(1)?.let(::unescape)
fun parse(xml: String): Manifest {
val p = Xml.newPullParser().apply { setInput(StringReader(xml)) }
var root: String? = null
var lineage: String? = null
var depth = 0
var closed = false
val files = ArrayList<Entry>()
val snapshots = ArrayList<String>()
var file: Array<String>? = null
var local: Entry? = null
runCatching {
while (p.next() != XmlPullParser.END_DOCUMENT) when (p.eventType) {
XmlPullParser.START_TAG -> {
depth++
val at = { name: String -> p.getAttributeValue(null, name).orEmpty() }
when {
root == null -> { root = p.name; lineage = p.getAttributeValue(null, "lineage") }
depth == 2 && p.name == "file" -> { file = arrayOf(at("size"), at("href"), at("md5")); local = null }
depth == 3 && p.name == "localName" && file != null -> {
val f = file!!
val created = at("created")
val modified = at("lastModified")
local = Entry(f[0].toLongOrNull() ?: 0, f[1], f[2], created, modified, p.nextText())
depth--
}
depth == 2 && p.name == "snapshot" -> { snapshots += p.nextText(); depth-- }
}
}
XmlPullParser.END_TAG -> {
if (depth == 2 && p.name == "file") { local?.let(files::add); file = null }
depth--
if (depth == 0) closed = true
}
}
}.onFailure { error("EA sent an incomplete cloud save manifest") }
check(root == "manifest" && depth == 0 && closed) { "EA sent an incomplete cloud save manifest" }
return Manifest(lineage ?: "{00000000-0000-0000-0000-000000000000}", files, snapshots)
}
fun write(m: Manifest): String = buildString {
append("<manifest xmlns=\"http://origin.com/cloudsaves/manifest\" lineage=\"").append(escape(m.lineage)).append("\">\n")
for (f in m.files) {
append(" <file size=\"").append(f.size).append("\" href=\"").append(escape(f.href)).append("\" md5=\"").append(escape(f.md5)).append("\">\n")
append(" <localName created=\"").append(escape(f.created)).append("\" lastModified=\"").append(escape(f.modified)).append("\">")
append(escape(f.localName)).append("</localName>\n </file>\n")
}
for (s in m.snapshots) append(" <snapshot>").append(escape(s)).append("</snapshot>\n")
append("</manifest>\n")
}
private fun signedRequests(xml: String, count: Int): List<Signed> {
val byId = REQUEST.findAll(xml).associate { m ->
val inner = m.groupValues[2]
val url = Regex("<url>([^<]+)</url>").find(inner)?.groupValues?.get(1)?.let(::unescape) ?: error("EA sent no transfer URL")
val headers = HEADER.findAll(inner).mapNotNull { h ->
val k = attr(h.groupValues[1], "key") ?: return@mapNotNull null
k to (attr(h.groupValues[1], "value") ?: "")
}.toMap()
m.groupValues[1].toInt() to Signed(url, headers)
}
return (0 until count).map { byId[it] ?: error("EA signed ${byId.size} of $count cloud save transfers") }
}
fun stamp(ms: Long): String = Instant.ofEpochMilli(ms / 1000 * 1000).toString() + "Z"
fun parseTime(s: String): Long = runCatching { Instant.parse(s.trimEnd('Z') + "Z").toEpochMilli() }.getOrDefault(-1L)
private fun attr(attrs: String, name: String): String? = Regex("\\b$name=\"([^\"]*)\"").find(attrs)?.groupValues?.get(1)?.let(::unescape)
private fun md5(data: ByteArray) = MessageDigest.getInstance("MD5").digest(data)
private fun b64(sum: ByteArray) = Base64.encodeToString(sum, Base64.NO_WRAP)
private fun hexOf(sum: ByteArray) = sum.joinToString("") { "%02x".format(it) }
fun hex(b64: String): String? = runCatching { hexOf(Base64.decode(b64, Base64.DEFAULT)) }.getOrNull()?.takeIf { it.length == 32 }
private fun escape(s: String) = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
private fun unescape(s: String) = EaSaveRules.unescape(s)
}
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.stores.ea
internal class EaSaveRules(private val rules: List<Pair<Boolean, String>>) {
val includes get() = rules.filter { it.first }.map { it.second }
val excludes get() = rules.filterNot { it.first }.map { it.second }
fun base(): String? {
val dirs = includes.filterNot(::bare).map { pattern ->
val wild = pattern.indexOfFirst { it == '*' || it == '?' }
val fixed = if (wild < 0) pattern else pattern.substring(0, wild)
if (fixed.endsWith('/')) fixed else fixed.substringBeforeLast('/', "") + "/"
}
val parts = dirs.map { it.trimEnd('/').split('/') }
if (parts.isEmpty()) return null
val common = ArrayList<String>()
for (i in parts.minOf { it.size }.let { 0 until it }) {
val seg = parts[0][i]
if (parts.all { it[i].equals(seg, ignoreCase = true) }) common += seg else break
}
if (common.isEmpty() || !VARIABLE.matches(common[0])) return null
return common.joinToString("/") + "/"
}
fun matches(path: String): Boolean {
val p = normalize(path)
val inside = base()?.let { p.startsWith(it, ignoreCase = true) } ?: false
return rules.firstOrNull { (_, pattern) -> if (bare(pattern)) inside && hit(pattern, p.substringAfterLast('/')) else hit(pattern, p) }?.first ?: false
}
private fun bare(pattern: String) = !pattern.startsWith('%') && '/' !in pattern
private fun hit(pattern: String, path: String): Boolean = when {
pattern.endsWith('/') -> path.startsWith(pattern, ignoreCase = true)
pattern.any { it == '*' || it == '?' } -> glob(pattern).matches(path)
else -> path.equals(pattern, ignoreCase = true)
}
private fun glob(pattern: String): Regex = Regex(
pattern.split('*').joinToString("[^/]*") { part -> part.split('?').joinToString("[^/]") { Regex.escape(it) } },
RegexOption.IGNORE_CASE,
)
companion object {
private val VARIABLE = Regex("%[A-Za-z]+%")
private val RULE = Regex("<(include|exclude)\\b([^>]*)>([^<]*)</\\1>", RegexOption.IGNORE_CASE)
private val ORDER = Regex("\\border\\s*=\\s*[\"']?(\\d+)")
private val TOKENS = mapOf(
"documents" to "%DOCUMENTS%", "savedgames" to "%SAVED_GAMES%", "appdata" to "%APPDATA%",
"localappdata" to "%LOCALAPPDATA%", "programdata" to "%PROGRAMDATA%", "userprofile" to "%USERPROFILE%",
"locallowappdata" to "%APPLICATION_DATA_LOCAL_LOW%", "installdir" to "%INSTALL%",
)
private val COMMENT = Regex("<!--.*?-->", RegexOption.DOT_MATCHES_ALL)
private val ENTITY = Regex("&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|quot|apos|amp);")
fun normalize(path: String) = path.replace('\\', '/')
fun parse(xml: String): EaSaveRules? {
val rules = RULE.findAll(COMMENT.replace(xml, "")).mapIndexed { index, rule ->
val order = ORDER.find(rule.groupValues[2])?.groupValues?.get(1)?.toIntOrNull() ?: index
Triple(order, rule.groupValues[1].equals("include", true), normalize(unescape(rule.groupValues[3]).trim()))
}.filter { it.third.isNotEmpty() }.sortedBy { it.first }.map { it.second to it.third }.toList()
if (rules.none { it.first }) return null
return EaSaveRules(rules)
}
fun template(base: String): String? {
val variable = VARIABLE.find(base)?.takeIf { it.range.first == 0 } ?: return null
val token = TOKENS[variable.value.trim('%').lowercase()] ?: return null
return token + base.substring(variable.value.length)
}
fun unescape(s: String): String = ENTITY.replace(s) { m ->
when (val e = m.groupValues[1]) {
"lt" -> "<"
"gt" -> ">"
"quot" -> "\""
"apos" -> "'"
"amp" -> "&"
else -> runCatching { String(Character.toChars(if (e.startsWith("#x")) e.substring(2).toInt(16) else e.substring(1).toInt())) }.getOrDefault(m.value)
}
}
}
}
@@ -129,8 +129,6 @@ internal object ItchBrowseState {
private var next = 1
private var generation = 0
val active: Boolean get() = !query.isDefault
fun choose(context: Context, wanted: BrowseQuery) {
if (wanted == query) return
generation++
@@ -140,11 +138,11 @@ internal object ItchBrowseState {
failed = false
loading = false
next = 1
if (active) more(context)
more(context)
}
fun more(context: Context, retry: Boolean = false) {
if (loading || ended || !active || (failed && !retry)) return
if (loading || ended || (failed && !retry)) return
loading = true
failed = false
val app = context.applicationContext
@@ -15,23 +15,44 @@ object UbisoftActivation {
private const val POLL_MS = 250L
private const val IDLE_MS = 60_000L
private val watching = HashMap<Long, Long>()
private val owners = HashMap<Long, String>()
private const val INVALIDATE = "denuvo-invalidate"
fun bridge(context: Context, product: Long) = File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/ubisoft/bridge-$product")
/** Starts answering the product's activations; stale requests are cleared before this returns. */
fun watch(app: Context, product: Long) {
fun watch(app: Context, product: Long, owner: String?) {
val dir = bridge(app, product)
synchronized(watching) {
val running = watching.containsKey(product)
watching[product] = System.currentTimeMillis()
if (owner.isNullOrEmpty()) owners.remove(product) else owners[product] = owner
if (running) return
dir.mkdirs()
dir.listFiles()?.forEach { it.delete() }
dir.listFiles()?.forEach { if (it.name != INVALIDATE) it.delete() }
}
Thread({
var idleSince = 0L
while (true) {
runCatching { dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }?.forEach { answer(app, product, it) } }
runCatching {
val marker = File(dir, INVALIDATE)
val (owner, requests) = synchronized(watching) {
owners[product] to dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }.orEmpty()
}
if (marker.exists()) {
val named = runCatching { marker.readText().trim() }.getOrNull()?.takeIf { it.isNotEmpty() }
val issuer = named ?: owner
if (invalidate(app, product, issuer)) marker.delete()
else if (named == null && issuer != null) runCatching {
val part = File(dir, "$INVALIDATE.part")
part.writeText(issuer)
check(part.renameTo(marker))
}
}
val pending = marker.exists()
requests.forEach { answer(app, product, it, owner, pending) }
}
.onFailure { StoresState.logLine("Ubisoft: activation for $product: ${it.javaClass.simpleName}") }
val now = System.currentTimeMillis()
if (SessionState.running) idleSince = 0L
@@ -44,18 +65,31 @@ object UbisoftActivation {
}, "ubisoft-activation-$product").start()
}
private fun answer(app: Context, product: Long, request: File) {
private fun answer(app: Context, product: Long, request: File, owner: String?, pending: Boolean) {
val challenge = runCatching { request.readBytes() }.getOrNull() ?: return
request.delete()
val reply = File(request.parentFile, request.name.removeSuffix(".req") + ".rsp")
val token = activate(app, product, challenge)
val reply = File(request.parentFile, request.name.removeSuffix(".req").removeSuffix(".cache") + ".rsp")
val token = activate(app, product, challenge, owner, cached = request.name.endsWith(".cache.req") && !pending)
val part = File(reply.path + ".part")
part.writeBytes(token ?: ByteArray(0))
part.renameTo(reply)
}
private fun activate(app: Context, product: Long, challenge: ByteArray): ByteArray? {
private fun invalidate(app: Context, product: Long, owner: String?): Boolean {
val user = owner ?: return false
val gone = TokenCache(cacheDir(app)).drop(user, product)
if (gone) StoresState.logLine("Ubisoft: activation for $product: kept game token dropped")
return gone
}
private fun activate(app: Context, product: Long, challenge: ByteArray, owner: String?, cached: Boolean): ByteArray? {
val s = UbisoftAuth.current(app) ?: return null.also { StoresState.logLine("Ubisoft: activation for $product: signed out") }
if (owner == null || s.userId != owner) return null.also { StoresState.logLine("Ubisoft: activation for $product: the signed-in account changed") }
val cache = TokenCache(cacheDir(app))
if (cached) cache.get(s.userId, product)?.let {
StoresState.logLine("Ubisoft: activation for $product: kept ${it.size} B game token")
return it
}
val answer = UbisoftNative.call("denuvo", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId)
.put("productId", product).put("challenge", hex(challenge)))
answer?.optString("error")?.takeIf { it.isNotEmpty() }?.let {
@@ -64,9 +98,28 @@ object UbisoftActivation {
}
val token = answer?.optString("token")?.takeIf { it.isNotEmpty() }?.let(::unhex)
StoresState.logLine("Ubisoft: activation for $product: ${token?.size ?: 0} B game token")
if (token != null && !cache.put(s.userId, product, token)) StoresState.logLine("Ubisoft: activation for $product: game token not kept")
return token
}
private fun cacheDir(app: Context) = File(app.filesDir, "ubisoft/denuvo")
internal class TokenCache(private val dir: File) {
private fun file(user: String, product: Long) = File(dir, "${user.filter { it.isLetterOrDigit() || it == '-' }}-$product.token")
fun get(user: String, product: Long): ByteArray? = runCatching { file(user, product).readBytes() }.getOrNull()?.takeIf { it.isNotEmpty() }
fun put(user: String, product: Long, token: ByteArray): Boolean = runCatching {
dir.mkdirs()
val target = file(user, product)
val part = File(target.path + ".part")
part.writeBytes(token)
check(part.renameTo(target))
}.isSuccess
fun drop(user: String, product: Long): Boolean = file(user, product).let { it.delete() || !it.exists() }
}
internal fun hex(b: ByteArray): String = b.joinToString("") { "%02x".format(it) }
internal fun unhex(s: String): ByteArray? =
@@ -168,14 +168,14 @@ object UbisoftLibrary {
internal fun assemble(listed: List<CatalogItem>, owned: JSONObject?): List<CatalogItem> {
val known = owned?.optJSONArray("games") != null && owned.optString("error").isEmpty()
val bySpace = ownedBySpace(owned)
val matched = listed.map { g -> bySpace[g.id]?.let { g.copy(extra = g.extra + download(it)) } ?: g }
val matched = listed.map { g -> bySpace[g.id]?.let { withArt(g.copy(extra = g.extra + download(it)), it) } ?: g }
.filter { !known || it.extra["productId"] != null }
.let { games -> games.filter { g -> g.extra["productId"] == null || games.first { it.extra["productId"] == g.extra["productId"] } === g } }
.let { games -> games.filter { g -> g.extra["productId"] != null || games.none { it !== g && it.title == g.title && it.extra["productId"] != null } } }
val products = matched.mapNotNull { it.extra["productId"] }.toSet()
val unlisted = bySpace.filterKeys { space -> listed.none { it.id == space } }.filterValues { it.optLong("productId").toString() !in products }.mapNotNull { (space, o) ->
val title = title(o.optString("configuration")) ?: return@mapNotNull null
CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o))
withArt(CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o)), o)
}
return (matched + unlisted).sortedBy { it.title.lowercase() }
}
@@ -184,12 +184,36 @@ object UbisoftLibrary {
private val NAME = Regex("""^\s{1,4}name:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE)
/** The default text of a localisation key such as `l1` or `THUMBIMAGE`. */
private fun localized(configuration: String, key: String): String? {
if (!Regex("""\w+""").matches(key)) return null
val local = configuration.indexOf("localizations:").takeIf { it >= 0 } ?: return null
return Regex("""^\s+${key}:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE).find(configuration, local)?.groupValues?.get(1)?.trim()
}
/** The product's name from its configuration, following a localisation key such as `l1` to its default text. */
internal fun title(configuration: String): String? {
val raw = NAME.find(configuration)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() } ?: return null
if (!Regex("""l\d+""").matches(raw)) return raw
val local = configuration.indexOf("localizations:").takeIf { it >= 0 } ?: return raw
return Regex("""^\s+${raw}:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE).find(configuration, local)?.groupValues?.get(1)?.trim() ?: raw
return localized(configuration, raw) ?: raw
}
private const val ASSETS = "https://static3.cdn.ubi.com/orbit/uplay_launcher_3_0/assets/"
private val ASSET = Regex("""[\w.-]+\.(?:jpe?g|png)""", RegexOption.IGNORE_CASE)
/** The URL of an image the configuration's `root` names, such as `thumb_image`, following a localisation key to its file. */
internal fun image(configuration: String, key: String): String? {
val raw = Regex("""^ {1,2}${key}:[ \t]*['"]?([^'"\r\n]+?)['"]?[ \t]*$""", RegexOption.MULTILINE).find(configuration)?.groupValues?.get(1)?.trim() ?: return null
val file = raw.takeIf { ASSET.matches(it) } ?: localized(configuration, raw)?.takeIf { ASSET.matches(it) } ?: return null
return ASSETS + file
}
/** Art the profile's game list lacks, from the product's configuration: games Connect owns but the list leaves out have none. */
private fun withArt(g: CatalogItem, owned: JSONObject): CatalogItem {
if (g.imageUrl != null && g.tallImageUrl != null) return g
val configuration = owned.optString("configuration")
val thumb = image(configuration, "thumb_image")
return g.copy(imageUrl = g.imageUrl ?: image(configuration, "background_image") ?: thumb, tallImageUrl = g.tallImageUrl ?: thumb)
}
/** The first launch path under `start_game` in a product's configuration. */
@@ -0,0 +1,220 @@
package com.droiddeck.launcher.stores.ubisoft
import android.os.Build
import android.util.Base64
import com.droiddeck.launcher.stores.CloudChanged
import com.droiddeck.launcher.stores.CloudFile
import com.droiddeck.launcher.stores.CloudTransport
import org.json.JSONArray
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.time.Instant
import java.util.zip.Deflater
import java.util.zip.Inflater
internal interface UbisoftSlots {
fun entity(): UbisoftCloud.Entity?
fun upload(slot: String, data: ByteArray)
fun update(entity: UbisoftCloud.Entity, slots: JSONArray)
fun download(slot: String): ByteArray?
}
internal class UbisoftCloud(private val session: UbisoftAuth.Session, val product: Long) : UbisoftSlots {
class Slot(val id: Int, val filename: String, val hash: String, val size: Long, val modifiedMs: Long)
class Entity(val json: JSONObject) {
val id: String get() = json.optString("entityId")
val revision: Int get() = json.optInt("revision")
val slots: List<Slot> get() {
val list = json.optJSONObject("obj")?.optJSONArray("slots") ?: JSONArray()
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.map {
Slot(it.optInt("id"), it.optString("filename"), it.optString("hash"), it.optLong("size"), UbisoftAuth.parseTime(it.optString("lastModified")))
}
}
}
private val authorization get() = "ubi_v1 t=${session.ticket}"
override fun entity(): Entity? {
val url = "https://public-ubiservices.ubi.com/v1/profiles/${session.profileId}/entities?name=${entityName(product)}"
val reply = UbisoftAuth.request(url, authorization = authorization, sessionId = session.sessionId)
check(reply.ok) { "Ubisoft cloud saves answered ${reply.status}" }
val list = JSONObject(reply.body).optJSONArray("entities") ?: return null
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.firstOrNull { it.optString("name") == entityName(product) }?.let(::Entity)
}
override fun upload(slot: String, data: ByteArray) {
val packed = deflate(data)
val md5 = Base64.encodeToString(MessageDigest.getInstance("MD5").digest(packed), Base64.NO_WRAP)
val signed = signed("put", JSONArray().put(JSONObject().put("name", slot).put("size", packed.size).put("md5", md5))).single()
val c = URL(signed.getString("url")).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
c.readTimeout = 60_000
c.requestMethod = "PUT"
c.doOutput = true
c.setFixedLengthStreamingMode(packed.size)
c.setRequestProperty("Content-MD5", md5)
try {
c.outputStream.use { it.write(packed) }
check(c.responseCode in 200..299) { "Ubisoft cloud save upload answered ${c.responseCode}" }
} finally {
c.disconnect()
}
}
override fun update(entity: Entity, slots: JSONArray) {
val obj = JSONObject(entity.json.optJSONObject("obj")?.toString() ?: "{}")
.put("slots", slots).put("timestamp", (System.currentTimeMillis() / 1000).toString()).put("pc_name", Build.MODEL ?: "Android")
val body = JSONObject().put("revision", entity.revision).put("name", entity.json.optString("name")).put("type", "cloudSave")
.put("spaceId", entity.json.optString("spaceId")).put("tags", entity.json.optJSONArray("tags") ?: JSONArray()).put("obj", obj)
val reply = UbisoftAuth.request("https://public-ubiservices.ubi.com/v1/profiles/entities/${entity.id}", "PUT",
authorization, session.sessionId, body.toString())
check(reply.ok) { "Ubisoft cloud save record answered ${reply.status}" }
}
override fun download(slot: String): ByteArray? {
val signed = signed("get", JSONArray().put(JSONObject().put("name", slot))).single()
val c = URL(signed.getString("url")).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
c.readTimeout = 60_000
return try {
when (c.responseCode) {
404 -> null
in 200..299 -> c.inputStream.use(::inflate)
else -> error("Ubisoft cloud save download answered ${c.responseCode}")
}
} finally {
c.disconnect()
}
}
private fun signed(method: String, items: JSONArray): List<JSONObject> {
val answer = UbisoftNative.call("cloud-urls", JSONObject().put("ticket", session.ticket).put("sessionId", session.sessionId)
.put("productId", product).put("method", method).put("items", items)) ?: error("Ubisoft cloud saves are unavailable")
answer.optString("error").takeIf { it.isNotEmpty() }?.let { error(it) }
val requests = answer.getJSONArray("requests")
return (0 until requests.length()).map { requests.getJSONObject(it) }
}
companion object {
private const val MAX_SAVE = 256L * 1024 * 1024
fun entityName(product: Long) = "upcCloudSaveUplayId_$product"
private val MARK = Regex("[0-9a-f]{32}")
internal fun freshMark(): String = java.util.UUID.randomUUID().toString().replace("-", "")
internal fun mark(save: ByteArray): String? =
if (save.size < 40) null else String(save, 8, 32, Charsets.ISO_8859_1).takeIf { MARK.matches(it) }
internal fun deflate(data: ByteArray): ByteArray {
val deflater = Deflater(Deflater.BEST_COMPRESSION)
deflater.setInput(data)
deflater.finish()
val out = ByteArrayOutputStream(data.size / 2 + 64)
val buffer = ByteArray(64 * 1024)
try {
while (!deflater.finished()) out.write(buffer, 0, deflater.deflate(buffer))
} finally {
deflater.end()
}
return out.toByteArray()
}
internal fun inflate(data: ByteArray): ByteArray = inflate(data.inputStream())
internal fun inflate(input: java.io.InputStream): ByteArray {
val inflater = Inflater()
val out = ByteArrayOutputStream(64 * 1024)
val buffer = ByteArray(64 * 1024)
val chunk = ByteArray(64 * 1024)
try {
while (!inflater.finished()) {
if (inflater.needsInput()) {
val read = input.read(chunk)
if (read < 0) error("Ubisoft cloud save is truncated")
inflater.setInput(chunk, 0, read)
continue
}
if (inflater.needsDictionary()) error("Ubisoft cloud save is truncated")
val n = inflater.inflate(buffer)
check(out.size().toLong() + n <= MAX_SAVE) { "Ubisoft cloud save is too large" }
out.write(buffer, 0, n)
}
} finally {
inflater.end()
}
return out.toByteArray()
}
internal fun version(slot: Slot): String = "${slot.size}:${slot.modifiedMs}:${slot.hash}"
}
}
internal class UbisoftCloudTransport(private val cloud: UbisoftSlots, val user: String) : CloudTransport {
private var listed: UbisoftCloud.Entity? = null
private val committed = HashMap<String, CloudFile>()
override val contentDigests: Boolean get() = false
override fun committed(name: String): CloudFile? = committed[name]
override fun wants(name: String): Boolean = name.endsWith(SUFFIX) && !name.contains('/')
override fun list(): List<CloudFile> {
val entity = cloud.entity()
listed = entity
return entity?.slots.orEmpty().map { CloudFile(it.filename + SUFFIX, it.modifiedMs, UbisoftCloud.version(it)) }
}
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val data = cloud.download(file.name.removeSuffix(SUFFIX)) ?: error("Ubisoft has no data for ${file.name}")
return data to file.modifiedMs
}
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> {
var expected = listed ?: cloud.entity() ?: error("Ubisoft has no cloud save record for this game yet; play it once in Ubisoft Connect")
val marks = files.mapValues { (name, data) ->
check(name.endsWith(SUFFIX) && !name.contains('/')) { "$name is not a Ubisoft save slot" }
UbisoftCloud.mark(data) ?: error("$name has no save identifier for Ubisoft Connect")
}
val sent = LinkedHashMap<String, Long>()
try {
for ((name, data) in files) {
val slot = name.removeSuffix(SUFFIX)
val live = cloud.entity() ?: error("Ubisoft's cloud save record disappeared")
if (live.revision != expected.revision) throw CloudChanged(sent, files.keys.filter { it !in sent })
val now = System.currentTimeMillis()
cloud.upload(slot, data)
val slots = JSONArray(live.json.optJSONObject("obj")?.optJSONArray("slots")?.toString() ?: "[]")
val entry = (0 until slots.length()).map { slots.getJSONObject(it) }.firstOrNull { it.optString("filename") == slot }
?: JSONObject().put("filename", slot).also { if (slot.toIntOrNull() != null) it.put("id", slot.toInt()); slots.put(it) }
entry.put("hash", marks.getValue(name)).put("size", data.size).put("lastModified", Instant.ofEpochMilli(now).toString())
cloud.update(live, slots)
val after = cloud.entity()
val mine = after?.let { committedSlot(live, it, slot, marks.getValue(name), data.size.toLong()) }
?: throw CloudChanged(sent, files.keys.filter { it !in sent })
sent[name] = now
committed[name] = CloudFile(name, mine.modifiedMs, UbisoftCloud.version(mine))
expected = after
}
} finally {
listed = null
}
return sent
}
companion object {
const val SUFFIX = ".save"
internal fun committedSlot(before: UbisoftCloud.Entity, after: UbisoftCloud.Entity, filename: String, hash: String, size: Long): UbisoftCloud.Slot? {
fun others(e: UbisoftCloud.Entity) = e.slots.filter { it.filename != filename }.associate { it.filename to UbisoftCloud.version(it) }
if (others(before) != others(after)) return null
return after.slots.firstOrNull { it.filename == filename && it.hash == hash && it.size == size }
}
}
}
@@ -58,7 +58,7 @@ object UbisoftLaunch {
}
} ?: cached
setup?.let { StoresState.logLine("Ubisoft: setup for $product: ${it.toString().take(1500)}") }
UbisoftActivation.watch(app, product)
UbisoftActivation.watch(app, product, s.userId)
return JSONObject().put("ok", true)
.put("productId", product)
.put("ticket", native.optString("ticket"))
@@ -122,6 +122,7 @@ import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogWindowProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentDraft
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.AgentSetup
@@ -207,7 +208,7 @@ private fun AgentPageContent(
}
remember { AgentSetup.check(context) }
var setup by rememberSaveable { mutableStateOf(false) }
val draft = rememberSaveable { mutableStateOf("") }
val draft = remember { AgentDraft.state(context) }
if (setup || AgentHost.state == AgentHost.State.MISSING || !(AgentSetup.ready || AgentSetup.completed(context))) {
AgentSetupView(modifier, firstControl = inputModifier, onDone = { setup = false })
return
@@ -397,11 +397,14 @@ internal class PetWindows(private val context: Context) {
/**
* The chat window is always drawn; closed, it waits off the screen and takes neither touches nor
* keys, so opening it is a move and not a first layout.
* keys, so opening it is a move and not a first layout. Only FLAG_LAYOUT_NO_LIMITS keeps it off the
* screen: without it the system moves the window back over the app below, where every touch reaches
* that app marked obscured, and apps that filter obscured touches, such as GitHub, ignore them all.
*/
private fun showChat(on: Boolean) {
chat.params.x = if (on) 0 else OFFSCREEN
val quiet = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
val quiet = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
chat.params.flags = if (on) chat.params.flags and quiet.inv() else chat.params.flags or quiet
if (added) runCatching { windows.updateViewLayout(chat.view, chat.params) }
}
@@ -220,9 +220,9 @@ private fun StorageCard() {
modifier = Modifier.fillMaxWidth().heightIn(min = 60.dp).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(stringResource(storageTitle(item)), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(stringResource(agentStorageTitle(item)), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(
if (armed) stringResource(storageWarning(item)) else Formatter.formatShortFileSize(context, AgentStorage.sizes[item] ?: 0L),
if (armed) stringResource(agentStorageWarning(item)) else Formatter.formatShortFileSize(context, AgentStorage.sizes[item] ?: 0L),
fontSize = 13.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
@@ -241,7 +241,7 @@ private fun StorageCard() {
}
}
private fun storageTitle(item: AgentStorage.Item) = when (item) {
internal fun agentStorageTitle(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.CLAUDE_CODE -> R.string.agent_storage_claude
AgentStorage.Item.CODEX -> R.string.agent_storage_codex
AgentStorage.Item.OPENCODE -> R.string.agent_storage_opencode
@@ -250,7 +250,7 @@ private fun storageTitle(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.CACHES -> R.string.agent_storage_caches
}
private fun storageWarning(item: AgentStorage.Item) = when (item) {
internal fun agentStorageWarning(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.SOURCE -> R.string.agent_storage_source_warning
AgentStorage.Item.CACHES -> R.string.agent_storage_caches_warning
else -> R.string.agent_storage_reinstall_warning
@@ -38,6 +38,7 @@ class BottomDesktopPanel(
steamButtons: Pair<() -> Unit, () -> Unit>?,
onSwap: (() -> Unit)? = null,
private val fullResolution: Boolean = false,
picker: (() -> ScreenPicker?)? = null,
) : LinearLayout(context), SurfaceHolder.Callback {
private lateinit var surfaceView: SurfaceView
private val area = FrameLayout(context).apply { clipChildren = true }
@@ -67,7 +68,7 @@ class BottomDesktopPanel(
setBackgroundColor(Color.BLACK)
isFocusable = true
isFocusableInTouchMode = true
addView(bar(onClose, onMenu, steamButtons, onSwap), LayoutParams(-1, -2))
addView(bar(onClose, onMenu, steamButtons, onSwap, picker), LayoutParams(-1, -2))
area.addView(keyboardHost)
addSurface()
area.addView(status, FrameLayout.LayoutParams(-1, -1))
@@ -84,7 +85,8 @@ class BottomDesktopPanel(
area.addView(surfaceView, 1, FrameLayout.LayoutParams(fullWidth.takeIf { it > 0 } ?: -1, fullHeight.takeIf { it > 0 } ?: -1))
}
private fun bar(onClose: (() -> Unit)?, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?, onSwap: (() -> Unit)?): View =
private fun bar(onClose: (() -> Unit)?, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?, onSwap: (() -> Unit)?,
picker: (() -> ScreenPicker?)?): View =
bottomScreenBarView(context) {
val touch = touchMode.value
BottomBarModel(
@@ -97,6 +99,7 @@ class BottomDesktopPanel(
BarExtra(context.getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) { keyboardHost.toggle() },
onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, onClick = it) },
),
picker = picker?.invoke(),
)
}
@@ -100,7 +100,7 @@ fun BottomDownloadsPage() {
formatSpeed(e.speedBps),
).filter { it.isNotEmpty() }.joinToString(" · ")
}
BottomDownloadRow(e.name, e.store.label, detail, e.stageFraction.takeIf { it >= 0f })
BottomDownloadRow(e.name, e.store.label, detail, steadyProgress(e))
}
}
}
@@ -7,10 +7,10 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.Forum
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.PhotoLibrary
import androidx.compose.material.icons.filled.Speed
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.People
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
@@ -32,10 +32,10 @@ class BottomPageActions(
internal const val BOTTOM_PAGE_TELEMETRY = "telemetry"
fun sessionBottomPages(actions: BottomPageActions): List<BottomPage> = listOf(
BottomPage(BOTTOM_PAGE_TELEMETRY, R.string.bottom_page_telemetry, Icons.Outlined.Speed) { BottomTelemetryPage(actions.fps, actions.runningGame) },
BottomPage("downloads", R.string.bottom_page_downloads, Icons.Outlined.Download) { BottomDownloadsPage() },
BottomPage("screenshots", R.string.bottom_page_screenshots, Icons.Outlined.PhotoLibrary) { BottomScreenshotsPage(actions.takeScreenshot) },
BottomPage("chat", R.string.bottom_page_chat, Icons.Outlined.Forum) { BottomChatPage() },
BottomPage(BOTTOM_PAGE_TELEMETRY, R.string.bottom_page_telemetry, Icons.Filled.Speed) { BottomTelemetryPage(actions.fps, actions.runningGame) },
BottomPage("downloads", R.string.bottom_page_downloads, Icons.Filled.Download) { BottomDownloadsPage() },
BottomPage("screenshots", R.string.bottom_page_screenshots, Icons.Filled.Image) { BottomScreenshotsPage(actions.takeScreenshot) },
BottomPage("chat", R.string.bottom_page_chat, Icons.Filled.People) { BottomChatPage() },
)
@Composable
@@ -24,12 +24,24 @@ import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Dashboard
import androidx.compose.material.icons.outlined.DesktopAccessDisabled
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.Keyboard
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material.icons.outlined.Terminal
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.foundation.rememberScrollState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -49,6 +61,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
@@ -61,6 +74,15 @@ internal class BarExtra(
val onClick: () -> Unit,
)
/** What the bottom screen shows: the DroidDeck menu or one of the panels, picked from the bar's dropdown. */
class ScreenPicker(
val modes: List<SecondScreenMode>,
val current: SecondScreenMode,
val onPick: (SecondScreenMode) -> Unit,
val onMenu: (() -> Unit)? = null,
val menuShown: Boolean = false,
)
internal class BarTabs(val labels: List<String>, val selected: Int, val onSelect: (Int) -> Unit)
internal class BottomBarModel(
@@ -72,6 +94,7 @@ internal class BottomBarModel(
val extras: List<BarExtra> = emptyList(),
val menuActive: Boolean = false,
val tabs: BarTabs? = null,
val picker: ScreenPicker? = null,
)
@Composable
@@ -89,9 +112,15 @@ internal fun BottomScreenBar(model: BottomBarModel, modifier: Modifier = Modifie
private fun BarRow(model: BottomBarModel, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
BoxWithConstraints(modifier.fillMaxWidth().height(BAR_HEIGHT).blockTouches()) {
val buttons = listOfNotNull(model.onClose, model.onMenu, model.onQam).size + model.extras.size
val picker = model.picker
val onMenu = model.onMenu.takeIf { picker == null }
val buttons = listOfNotNull(model.onClose, onMenu, model.onQam).size + model.extras.size
val steamWidth = if (model.onSteam != null) STEAM_WIDTH + BAR_GAP else 0.dp
val titleWidth = if (model.title != null) MIN_TITLE + BAR_GAP else 0.dp
val titleWidth = when {
picker != null -> PICKER_WIDTH + BAR_GAP
model.title != null -> MIN_TITLE + BAR_GAP
else -> 0.dp
}
val needed = BAR_PAD * 2 + BUTTON * buttons + BAR_GAP * (buttons - 1).coerceAtLeast(0) + steamWidth + titleWidth
val fits = maxWidth >= needed
Row(
@@ -103,7 +132,9 @@ private fun BarRow(model: BottomBarModel, modifier: Modifier = Modifier) {
model.onClose?.let {
BarButton(stringResource(R.string.common_close), Modifier.testTag("bottom-bar-close"), vector = Icons.Outlined.Close, onClick = it)
}
if (model.title != null) Text(
if (picker != null) Box(if (fits) Modifier.weight(1f) else Modifier) {
ScreenPickerChip(picker, Modifier.testTag("bottom-bar-screen"))
} else if (model.title != null) Text(
model.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = (if (fits) Modifier.weight(1f) else Modifier).padding(start = 4.dp),
@@ -112,7 +143,7 @@ private fun BarRow(model: BottomBarModel, modifier: Modifier = Modifier) {
BarButton(extra.description, extra.tag?.let { Modifier.testTag(it) } ?: Modifier, icon = extra.icon, vector = extra.vector,
active = extra.active, onClick = extra.onClick)
}
BarActions(model.onMenu, model.menuActive, model.onSteam, model.onQam)
BarActions(onMenu, model.menuActive, model.onSteam, model.onQam)
}
}
}
@@ -197,12 +228,94 @@ internal fun BarButton(
}
}
internal val SecondScreenMode.icon: ImageVector get() = when (this) {
SecondScreenMode.NONE -> Icons.Outlined.DesktopAccessDisabled
SecondScreenMode.KEYBOARD_TRACKPAD -> Icons.Outlined.Keyboard
SecondScreenMode.TERMINAL -> Icons.Outlined.Terminal
SecondScreenMode.DECK_CONTROLS -> Icons.Outlined.SportsEsports
SecondScreenMode.CUSTOM_CONTROLS -> Icons.Outlined.Tune
SecondScreenMode.DASHBOARD -> Icons.Outlined.Dashboard
SecondScreenMode.DESKTOP -> Icons.Outlined.DesktopWindows
}
@Composable
internal fun ScreenPickerChip(picker: ScreenPicker, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by remember { mutableStateOf(false) }
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(22.dp)
val label = if (picker.menuShown) stringResource(R.string.touch_droiddeck_menu) else stringResource(picker.current.label)
val description = stringResource(R.string.screen_picker_description, label)
val toggle = { open = !open }
Box(modifier) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.height(44.dp).widthIn(max = PICKER_MAX_WIDTH)
.semantics { contentDescription = description }
.clip(shape).background(if (hot || open) pal.signal.copy(alpha = 0.14f) else colors.surfaceVariant)
.glideBorder(hot || open, shape, pal.signal, pal.line2)
.hoverable(source)
.clickable(role = Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = toggle)
.controllerConfirm(onClick = toggle)
.padding(start = 14.dp, end = 10.dp),
) {
if (picker.menuShown) Icon(painterResource(R.drawable.ic_stat_session), contentDescription = null, tint = colors.onBackground,
modifier = Modifier.size(18.dp))
else Icon(picker.current.icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp))
Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, contentDescription = null,
tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
ScreenPickerMenu(picker, open) { open = false }
}
}
/** On a panel, focus starts on the menu entry; from the menu (or with no menu entry), on the panel in use. */
internal fun ScreenPicker.focusTarget(): SecondScreenMode? =
if (onMenu != null && !menuShown) null else current.takeIf { it in modes } ?: modes.firstOrNull()
@Composable
private fun ScreenPickerMenu(picker: ScreenPicker, open: Boolean, dismiss: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val target = picker.focusTarget()
AnchoredMenu(open, dismiss, compact = true, minWidth = 240.dp) { first ->
picker.onMenu?.let { menu ->
MenuItem(
stringResource(R.string.touch_droiddeck_menu), checked = picker.menuShown,
leading = { Icon(painterResource(R.drawable.ic_stat_session), contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) },
focusRequester = first.takeIf { target == null }, modifier = Modifier.testTag("screen-picker-menu"),
) { dismiss(); menu() }
Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(pal.line))
Text(
stringResource(R.string.drawer_second_screen).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 4.dp),
)
}
picker.modes.forEach { mode ->
val current = mode == picker.current
MenuItem(
stringResource(mode.label), checked = current && !picker.menuShown,
detail = if (current && picker.menuShown) stringResource(R.string.screen_picker_last_used) else null,
leading = { Icon(mode.icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) },
focusRequester = first.takeIf { mode == target }, modifier = Modifier.testTag("screen-picker:${mode.id}"),
) { dismiss(); picker.onPick(mode) }
}
}
}
internal val BAR_HEIGHT = 64.dp
private val BAR_PAD = 12.dp
private val BAR_GAP = 8.dp
private val BUTTON = 44.dp
private val STEAM_WIDTH = 80.dp
private val MIN_TITLE = 72.dp
private val PICKER_WIDTH = 180.dp
private val PICKER_MAX_WIDTH = 240.dp
internal fun sessionBarModel(
title: String?,
@@ -212,9 +325,10 @@ internal fun sessionBarModel(
onQam: () -> Unit,
extras: List<BarExtra> = emptyList(),
tabs: BarTabs? = null,
picker: ScreenPicker? = null,
): BottomBarModel {
val steam = SessionState.mode == SessionService.MODE_STEAM
return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras, tabs = tabs)
return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras, tabs = tabs, picker = picker)
}
internal fun deckPanelTabs(context: Context, selected: DeckPanel, onSelect: (DeckPanel) -> Unit) =
@@ -84,6 +84,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.ComponentUpdater
import com.droiddeck.launcher.session.ComponentUpdates
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.ComponentsManager.CatalogItem
import com.droiddeck.launcher.session.ComponentsManager.Snapshot
import kotlinx.coroutines.delay
@@ -524,7 +525,7 @@ fun ComponentsPage(
}
val availableTitle: @Composable (String) -> String = { l ->
when (l) {
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count { it.installed == null || it.update != null })
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
}
}
@@ -539,7 +540,8 @@ fun ComponentsPage(
val key = "proton:${v.proton.id}"
val swaps = v.components.values.count { it.activeFile != null }
val extra = protons.rows.firstOrNull { v.proton.dir.name in it.installedAll }
val removable = extra != null && protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
val experimental = v.proton.dir.name in protons.experimental
val removable = (extra != null || experimental) && protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
ChoiceLine(
v.proton.name,
(if (swaps > 0) stringResource(R.string.comp_swapped, v.proton.version, swaps) else stringResource(R.string.comp_all_original, v.proton.version))
@@ -548,7 +550,10 @@ fun ComponentsPage(
modifier = (if (i == 0 && !moded(l)) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
onSelect = { if (v.proton.id != view?.proton?.id) { onProton(v.proton.id); flyHome(key, PROTON_TAB) } },
onDelete = {
if (extra != null) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), ctx.getString(R.string.proton_remove_body), ctx.getString(R.string.store_remove), true, v.proton.name) {
if (experimental) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), ctx.getString(R.string.proton_remove_body), ctx.getString(R.string.store_remove), true, v.proton.name) {
protonActions.onRemoveExperimental(v.proton.dir.name)
}
else if (extra != null) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), ctx.getString(R.string.proton_remove_body), ctx.getString(R.string.store_remove), true, v.proton.name) {
protonActions.onRemove(extra.id, v.proton.dir.name)
}
},
@@ -589,21 +594,24 @@ fun ComponentsPage(
val availableRows: @Composable ColumnScope.(String) -> Unit = { l ->
when (l) {
PROTON_TAB -> {
val rows = protons.rows.filter { it.installed == null || it.update != null }
val rows = protons.rows.filter(ProtonRow::available)
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_new))
for (row in rows) GetLine(
row.name,
when {
row.update != null -> stringResource(R.string.proton_update_available, row.update)
row.queued -> stringResource(R.string.proton_queued)
else -> stringResource(R.string.proton_not_installed)
},
progress = if (protons.busyId == row.id) protons.percent else null,
stage = if (protons.busyId == row.id) protons.stage else null,
enabled = protons.busyId == null && protons.runtimeReady && !protons.sessionRunning,
onCancel = if (row.queued && protons.busyId == null && !protons.sessionRunning) ({ protonActions.onCancel(row.id) }) else null,
action = if (row.update != null) stringResource(R.string.common_update) else null,
) { protonActions.onInstall(row.id) }
for (row in rows) {
val idle = protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
GetLine(
row.name,
when {
row.update != null -> stringResource(R.string.proton_update_available, row.update)
row.queued -> stringResource(R.string.proton_queued)
else -> stringResource(R.string.proton_not_installed)
},
progress = if (protons.busyId == row.id) protons.percent else null,
stage = if (protons.busyId == row.id) protons.stage else null,
enabled = idle,
onCancel = if (row.queued && protons.busyId == null && !protons.sessionRunning) ({ protonActions.onCancel(row.id) }) else null,
action = if (row.update != null) stringResource(R.string.common_update) else null,
) { protonActions.onInstall(row.id) }
}
}
else -> {
val available = availableRows(l, catalog, snapshot)
@@ -731,6 +739,8 @@ fun ComponentsPage(
}
}
if (l == PROTON_TAB) {
Spacer(Modifier.height(12.dp))
ExperimentalProtonGroup(protons, protonActions)
Spacer(Modifier.height(12.dp))
Note(stringResource(R.string.comp_about_text))
}
@@ -1528,12 +1538,12 @@ private fun GetLine(
}
@Composable
private fun ChannelToggle(nightly: Boolean, enabled: Boolean, onFlip: () -> Unit) {
private fun ChannelToggle(nightly: Boolean, enabled: Boolean, other: Int = R.string.comp_channel_nightly, onFlip: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && enabled
val state = stringResource(if (nightly) R.string.comp_channel_nightly else R.string.comp_channel_stable)
val state = stringResource(if (nightly) other else R.string.comp_channel_stable)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp),
modifier = Modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
@@ -1544,12 +1554,12 @@ private fun ChannelToggle(nightly: Boolean, enabled: Boolean, onFlip: () -> Unit
.semantics { stateDescription = state }
.padding(4.dp),
) {
for ((label, on) in listOf(R.string.comp_channel_stable to !nightly, R.string.comp_channel_nightly to nightly)) {
for ((label, on) in listOf(R.string.comp_channel_stable to !nightly, other to nightly)) {
Text(
stringResource(label), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
color = if (!enabled) colors.onSurfaceVariant else if (on) (if (hot) pal.onSignal else pal.signal) else colors.onSurfaceVariant,
color = if (on) (if (hot) pal.onSignal else pal.signal) else colors.onSurfaceVariant,
modifier = Modifier.clip(RoundedCornerShape(7.dp))
.background(if (on && enabled) (if (hot) pal.signal else pal.signal.copy(alpha = 0.16f)) else Color.Transparent)
.background(if (on) (if (hot) pal.signal else pal.signal.copy(alpha = 0.16f)) else Color.Transparent)
.padding(horizontal = 10.dp, vertical = 6.dp),
)
}
@@ -1623,6 +1633,25 @@ private fun DeviceChip(s: GpuDriversState) {
) { face() }
}
@Composable
private fun ExperimentalProtonGroup(protons: ProtonsState, actions: ProtonsActions) {
val busy = protons.busyId == com.droiddeck.launcher.ProtonMenu.EXPERIMENTAL
val idle = protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
RowGroup(stringResource(R.string.xproton_title)) {
if (busy) GetLine(stringResource(R.string.xproton_title), "", progress = protons.percent, enabled = false, stage = protons.stage) {}
else {
protons.experimentalReleases.forEach { release ->
GetLine(release.name, release.tag, progress = null, enabled = idle, action = stringResource(R.string.proton_install_now)) {
actions.onExperimentalRelease(release)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.padding(start = 14.dp, top = 4.dp, bottom = 8.dp)) {
SmallButton(stringResource(R.string.xproton_install_file), enabled = idle, onClick = actions.onExperimentalFile)
}
}
}
}
class ProtonsState(
val rows: List<ProtonRow> = emptyList(),
val busyId: String? = null,
@@ -1630,6 +1659,8 @@ class ProtonsState(
val percent: Int = -1,
val runtimeReady: Boolean = true,
val sessionRunning: Boolean = false,
val experimental: List<String> = emptyList(),
val experimentalReleases: List<ExperimentalProtons.Release> = emptyList(),
)
class ProtonsActions(
@@ -1637,12 +1668,17 @@ class ProtonsActions(
val onCancel: (String) -> Unit = {},
val onRemove: (String, String) -> Unit = { _, _ -> },
val onRemoveOlder: (String) -> Unit = {},
val onExperimentalFile: () -> Unit = {},
val onExperimentalRelease: (ExperimentalProtons.Release) -> Unit = {},
val onRemoveExperimental: (String) -> Unit = {},
)
class ProtonRow(
val id: String, val name: String, val installed: String?, val queued: Boolean,
val installedAll: List<String> = listOfNotNull(installed), val update: String? = null,
)
) {
val available: Boolean get() = installed == null || update != null
}
@Composable
private fun gpuCardValue(gpu: GpuDriversState, auto: String): String {
@@ -0,0 +1,268 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.outlined.Science
import androidx.compose.material.icons.outlined.Visibility
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
/** What the Library pretends while a developer previews it. Nothing here is saved: a restart always comes back to [OFF]. */
internal enum class LibraryPreview { OFF, NOTHING_INSTALLED, SIGNED_OUT, SAMPLE }
internal enum class DrawerPreview { STEAM, DESKTOP, GAME }
/** Developer tools' preview states: screens that are otherwise hard to reach, shown without changing anything real. */
internal object DevPreview {
var library by mutableStateOf(LibraryPreview.OFF)
var drawer by mutableStateOf<DrawerPreview?>(null)
/** The UI zoo sheet: where previews are picked, one at a time, only when asked for. */
var zoo by mutableStateOf(false)
/** Opt-in: a preview button where its state lives (the Library's toolbar), for switching states without the zoo. */
var shortcuts by mutableStateOf(false)
fun setShortcuts(context: android.content.Context, on: Boolean) {
shortcuts = on
SessionPrefs.setPreviewShortcuts(context, on)
}
/** Set when a Library preview is picked, so the launcher switches to the Library to show it. */
var openLibrary by mutableStateOf(false)
}
/** How many of each store's sample games look installed. */
private const val SAMPLE_INSTALLED = 3
/** A store's storefront games, passed off as owned, for the sample library. Empty until the store's shelves have loaded. */
internal fun sampleOwned(store: Store): List<CatalogItem> =
StoresState.shelves[store]?.all.orEmpty().filter { !it.mature }.distinctBy { it.id }.take(24).map { it.copy(owned = true) }
internal fun sampleInstalled(owned: Map<Store, List<CatalogItem>>): Set<String> =
owned.values.flatMap { items -> items.take(SAMPLE_INSTALLED).map { it.key } }.toSet()
/** The pill a previewed Library shows, so the fake state is never mistaken for the real one. */
@Composable
internal fun LibraryPreviewPill(modifier: Modifier = Modifier) {
val preview = DevPreview.library
if (preview == LibraryPreview.OFF) return
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val label = stringResource(
when (preview) {
LibraryPreview.NOTHING_INSTALLED -> R.string.dev_preview_library_nothing_installed
LibraryPreview.SIGNED_OUT -> R.string.dev_preview_library_signed_out
else -> R.string.dev_preview_library_sample
},
)
val end = stringResource(R.string.dev_preview_end)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = modifier.background(colors.surface, CircleShape).border(1.dp, pal.signal, CircleShape)
.clickable(role = Role.Button, onClickLabel = end) { DevPreview.library = LibraryPreview.OFF }
.padding(start = 14.dp, end = 10.dp, top = 8.dp, bottom = 8.dp).testTag("dev-preview-end"),
) {
Icon(Icons.Outlined.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp))
Text(stringResource(R.string.dev_preview_banner, label), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Icon(Icons.Filled.Close, end, tint = colors.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
}
/**
* The in-game menu over the launcher, for looking at without starting a session. Its switches change only this preview: nothing
* is saved and no session is told. Back or Close ends it.
*/
@Composable
internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
val mode = DevPreview.drawer ?: return
val ctx = LocalContext.current
val close = { DevPreview.drawer = null }
var page by remember { mutableStateOf(SessionDrawerPage.CONTROLLER) }
// A session's activity routes these keys to its menu; the launcher has no such routing, so the preview does it.
var layerOpen by remember { mutableStateOf(false) }
var backRequests by remember { mutableStateOf(0) }
val back = { if (layerOpen) backRequests++ else close() }
BackHandler { back() }
var hud by remember { mutableStateOf(SessionPrefs.hudEnabled(ctx)) }
var touch by remember { mutableStateOf(SessionPrefs.touchMode(ctx)) }
var osc by remember { mutableStateOf(SessionPrefs.oscMode(ctx)) }
var fex by remember { mutableStateOf(SessionPrefs.fexPreset(ctx)) }
var inverted by remember { mutableStateOf(SessionPrefs.backActionsInverted(ctx)) }
var suspend by remember { mutableStateOf(SessionPrefs.SUSPEND_MANUAL) }
var frameGen by remember { mutableStateOf(FrameGen.Mode.OFF) }
var second by remember { mutableStateOf(SecondScreenMode.NONE) }
var fps by remember { mutableStateOf(0) }
val steam = mode == DrawerPreview.STEAM
val actions = DrawerActions(
steam = steam,
desktop = mode == DrawerPreview.DESKTOP,
title = if (mode == DrawerPreview.GAME) stringResource(R.string.session_title_game) else null,
isHomeApp = false,
androidApps = emptyList(),
hudOn = hud, onHud = { hud = it },
frameGen = frameGen, onFrameGenPick = { frameGen = it },
lossless = Lossless.State.NONE,
oscMode = osc, onOsc = { osc = it },
suspendPolicy = suspend, onSuspendPolicy = { suspend = it },
backActionsInverted = inverted, onBackActionsInverted = { inverted = it },
touchMode = touch, onTouch = { touch = it },
touchAuto = stringResource(R.string.session_touch_auto_direct),
fexPreset = fex, onFexPreset = { fex = it },
fpsLimit = fps, onFpsLimit = { fps = it },
secondScreenMode = second, onSecondScreenMode = { second = it },
secondScreenDisplays = secondScreens,
selectedSecondScreenDisplay = secondScreens.firstOrNull()?.id ?: -1,
onSecondScreenDisplay = {},
onImportLossless = {},
onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = if (steam) ({}) else null,
onQam = if (steam) ({}) else null,
onLaunchAndroidApp = { _, _ -> },
onBackground = close,
onShareLogs = {},
onStop = close,
onClose = close,
)
Box(
Modifier.fillMaxSize().testTag("dev-preview-drawer")
.onPreviewKeyEvent { e ->
val code = e.nativeKeyEvent.keyCode
if (code != android.view.KeyEvent.KEYCODE_BUTTON_L1 && code != android.view.KeyEvent.KEYCODE_BUTTON_R1) return@onPreviewKeyEvent false
if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) {
page = sessionDrawerPages().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
}
true
}
.onKeyEvent { e ->
if (e.nativeKeyEvent.keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@onKeyEvent false
if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) back()
true
}
.background(Brush.linearGradient(listOf(Color(0xFF1B2A3A), Color(0xFF0B0F14), Color(0xFF2A1B2E)))),
) {
Text(
stringResource(R.string.dev_preview_drawer_backdrop), fontSize = 13.sp, color = Color.White.copy(alpha = 0.5f),
modifier = Modifier.align(Alignment.BottomStart).padding(24.dp),
)
SessionDrawer(
true, page, controllerActive = true, onPageChange = { page = it }, a = actions,
backRequest = backRequests, onLayerChange = { layerOpen = it },
)
}
}
/** Developer tools' UI zoo: a sheet listing the previews. Nothing shows until one is picked, and picking one closes the sheet. */
@Composable
internal fun UiZooSheet() {
val close = { DevPreview.zoo = false }
SideSheet(DevPreview.zoo, onClose = close, returnFocus = null, tag = "ui-zoo-sheet") {
PageHeader(stringResource(R.string.dev_ui_zoo)) {
androidx.compose.foundation.layout.Spacer(Modifier.weight(1f))
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.onSurfaceVariant) { close() }
}
androidx.compose.foundation.layout.Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) {
val show = stringResource(R.string.dev_ui_zoo_show)
SettingsGroup(stringResource(R.string.dev_preview_drawer)) {
for ((mode, label) in listOf(
DrawerPreview.STEAM to R.string.source_steam,
DrawerPreview.DESKTOP to R.string.rail_desktop,
DrawerPreview.GAME to R.string.session_title_game,
)) ActionRow(stringResource(label), null, show, onClick = { close(); DevPreview.drawer = mode }, modifier = Modifier.testTag("zoo-drawer-${mode.name.lowercase()}"))
}
SettingsGroup(stringResource(R.string.dev_preview_library)) {
for ((mode, label) in listOf(
LibraryPreview.NOTHING_INSTALLED to R.string.dev_preview_library_nothing_installed,
LibraryPreview.SIGNED_OUT to R.string.dev_preview_library_signed_out,
LibraryPreview.SAMPLE to R.string.dev_preview_library_sample,
)) ActionRow(
stringResource(label), null, show,
onClick = { close(); DevPreview.library = mode; DevPreview.openLibrary = true },
modifier = Modifier.testTag("zoo-library-${mode.name.lowercase()}"),
)
}
Text(
stringResource(R.string.dev_ui_zoo_note), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
)
}
}
}
/** The Library toolbar's preview button, shown only with preview shortcuts on: picks the Library state in place. */
@Composable
internal fun LibraryPreviewButton() {
val pal = LocalPalette.current
val title = stringResource(R.string.dev_preview_library)
var at by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
val states = listOf(
LibraryPreview.OFF to R.string.dev_preview_real,
LibraryPreview.NOTHING_INSTALLED to R.string.dev_preview_library_nothing_installed,
LibraryPreview.SIGNED_OUT to R.string.dev_preview_library_signed_out,
LibraryPreview.SAMPLE to R.string.dev_preview_library_sample,
)
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
HeaderIconButton(stringResource(R.string.dev_preview_shortcut), Icons.Outlined.Science, "library-preview") {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = states.size,
handle = { Icon(Icons.Outlined.Science, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
StepList {
states.forEachIndexed { i, (state, label) ->
StepChoice(
stringResource(label), selected = DevPreview.library == state, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(i).let { if (i == 0) it.focusRequester(first) else it },
) { DevPreview.library = state; Steps.fold() }
}
}
})
}
}
}
@@ -14,6 +14,7 @@ import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.hud.DroidDeckHudConfig
import com.droiddeck.launcher.hud.DroidDeckHudSize
import com.droiddeck.launcher.session.GpuClockPin
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.StripMetric
@@ -47,6 +48,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
ToggleRow(host, "hud-snap", stringResource(R.string.hud_snap), stringResource(R.string.hud_snap_hint), on("hudSnap"),
chipModifier = track("hud-snap")) { a.onHudSetting("hudSnap", flag(it)) }
}
if (GpuClockPin.supported) GpuClockGroup(host, a.gpuClockPin, track("gpuclock"), a.onGpuClockPin)
if (a.dashboardAvailable && a.secondScreenDisplays.isNotEmpty()) BottomStripSettings(host, track)
if (!a.hudOn) return
@@ -276,11 +276,18 @@ private fun Content(
return
}
if (selected == "stores") {
StoresPage(s, a, modifier)
Box(modifier) {
StoresPage(s, a, Modifier.fillMaxSize())
ManageStoresSheet()
}
return
}
if (selected == "games" || selected.startsWith("app:") || selected == "soundtracks" || selected.startsWith("sound:")) {
LibraryPage(s, a, selected, onSelect, modifier)
Box(modifier) {
LibraryPage(s, a, selected, onSelect, Modifier.fillMaxSize())
if (selected == "games") LibraryPreviewPill(Modifier.align(androidx.compose.ui.Alignment.BottomCenter).padding(bottom = 20.dp))
ManageStoresSheet()
}
return
}
if (selected == "desktop") {
@@ -82,6 +82,12 @@ internal fun cloudMessage(context: android.content.Context, r: com.droiddeck.lau
r.files == 0 -> context.getString(R.string.cloud_up_to_date)
else -> context.getString(R.string.cloud_done, r.files)
}
"partial" -> when {
r.conflicts > 0 && r.detail.isNotEmpty() -> context.getString(R.string.cloud_conflict_files_detail, r.conflicts, r.detail)
r.conflicts > 0 -> context.getString(R.string.cloud_conflict_files, r.conflicts)
r.detail.isNotEmpty() -> context.getString(R.string.cloud_partial, r.detail)
else -> context.getString(R.string.cloud_not_synced)
}
"skipped" -> context.getString(when (r.reason) {
"not-signed-in" -> R.string.cloud_signed_out
"no-cloud-saves" -> R.string.cloud_none
@@ -46,21 +46,20 @@ import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.SdStorage
import androidx.compose.material.icons.outlined.Sync
import androidx.compose.material.icons.outlined.Terminal
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.LocalMall
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.filled.SportsEsports
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.LocalOffer
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.DesktopWindows
import androidx.compose.material.icons.filled.Layers
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.Apps
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SdStorage
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material.icons.outlined.SystemUpdate
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material.icons.outlined.VideoLibrary
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
@@ -194,21 +193,22 @@ internal fun SideRail(
}
}
// Solid icons in the Steam Deck menu's style; where Steam has the same place (Library, Store, Downloads, Settings) its glyph is used.
internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
"steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports
"games" -> R.string.rail_games to Icons.Outlined.VideoLibrary
"steam" -> R.string.rail_steam to Icons.Filled.SportsEsports
"games" -> R.string.rail_games to Icons.Filled.GridView
"soundtracks" -> R.string.rail_music to SoundtrackIcon
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
"downloads" -> R.string.stores_tab_downloads to Icons.Outlined.Download
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
"components" -> R.string.rail_components to Icons.Outlined.Layers
"agent" -> R.string.rail_agent to Icons.Outlined.Terminal
"android-apps" -> R.string.rail_apps to Icons.Outlined.Apps
"setup" -> R.string.rail_setup to Icons.Outlined.Tune
"storage" -> R.string.rail_storage to Icons.Outlined.SdStorage
"sync" -> R.string.rail_sync to Icons.Outlined.Sync
NavTabs.MORE -> R.string.rail_more to Icons.Outlined.MoreHoriz
else -> R.string.rail_updates to Icons.Outlined.SystemUpdate
"stores" -> R.string.rail_stores to Icons.Filled.LocalOffer
"downloads" -> R.string.stores_tab_downloads to Icons.Filled.Download
"desktop" -> R.string.rail_desktop to Icons.Filled.DesktopWindows
"components" -> R.string.rail_components to Icons.Filled.Layers
"agent" -> R.string.rail_agent to Icons.Filled.Terminal
"android-apps" -> R.string.rail_apps to Icons.Filled.Apps
"setup" -> R.string.rail_setup to Icons.Filled.Settings
"storage" -> R.string.rail_storage to Icons.Filled.SdStorage
"sync" -> R.string.rail_sync to Icons.Filled.Sync
NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz
else -> R.string.rail_updates to Icons.Filled.SystemUpdate
}
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) ||
@@ -650,6 +650,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
LaunchedEffect(SetupTabs.openSection) {
if (SetupTabs.openSection != null && (railSelection != "setup" || s.pageKey != null)) showRailPage("setup", true)
}
LaunchedEffect(DevPreview.openLibrary) {
if (!DevPreview.openLibrary) return@LaunchedEffect
DevPreview.openLibrary = false
LibraryView.source = LIBRARY_ALL
showRailPage("games", true)
}
val onRailFocus: (String) -> Unit = { key ->
if (key != railSelection) showRailPage(key, false)
}
@@ -806,6 +812,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
StepsLayer(screenAt)
UiZooSheet()
SessionDrawerPreview(s.secondScreenDisplays)
appToChooseDisplay?.let { app ->
val secondaryDisplay = s.secondScreenDisplays.firstOrNull()
@@ -876,7 +884,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"))
val exitArmed = !processSettingsPageVisible && !hasBackTarget
LaunchedEffect(exitArmed, selected) { ExitGesture.reset() }
BackHandler(enabled = exitArmed) {
BackHandler(enabled = exitArmed && DevPreview.drawer == null) {
when (ExitGesture.back()) {
2 -> android.widget.Toast.makeText(ctx, R.string.exit_hint_back, android.widget.Toast.LENGTH_SHORT).show()
3 -> {
@@ -59,6 +59,7 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
@@ -437,6 +438,7 @@ internal fun SetupPanel(
}
if (s.theme == Themes.INNER_GAMER) RgbSpeedRow()
if (s.theme == Themes.GRADIENT) GradientColorRows()
if (s.theme == Themes.CUSTOM) CustomColorRows()
if (s.theme == Themes.TRUE_BLACK) HighlightColorRow()
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
@@ -594,6 +596,14 @@ internal fun SetupPanel(
ToggleRow(host, "developer-tools", stringResource(R.string.dev_tools_title), stringResource(R.string.dev_tools_hint), DeveloperTools.on) {
DeveloperTools.set(devContext, it)
}
if (DeveloperTools.on) ActionRow(
stringResource(R.string.dev_ui_zoo), stringResource(R.string.dev_ui_zoo_hint), stringResource(R.string.dev_ui_zoo_open),
onClick = { DevPreview.zoo = true }, modifier = Modifier.testTag("dev-ui-zoo"),
)
if (DeveloperTools.on) ToggleRow(
host, "preview-shortcuts", stringResource(R.string.dev_preview_shortcuts), stringResource(R.string.dev_preview_shortcuts_hint),
DevPreview.shortcuts,
) { DevPreview.setShortcuts(devContext, it) }
}
SettingsGroup(stringResource(R.string.dev_group_logs)) {
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
@@ -1212,3 +1222,42 @@ private fun GradientColorRows() {
if (picking == 1) Themes.setGradient(ctx, argb, secondary) else Themes.setGradient(ctx, primary, argb)
}
}
@Composable
private fun CustomColorRows() {
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
val colors = Themes.customColors
var picking by remember { mutableStateOf<String?>(null) }
val rows = listOf(
Triple("background", stringResource(R.string.theme_custom_background), colors.background),
Triple("surface", stringResource(R.string.theme_custom_surface), colors.surface),
Triple("surfaceVariant", stringResource(R.string.theme_custom_surface_variant), colors.surfaceVariant),
Triple("line", stringResource(R.string.theme_custom_line), colors.line),
Triple("line2", stringResource(R.string.theme_custom_line2), colors.line2),
Triple("onBackground", stringResource(R.string.theme_custom_on_background), colors.onBackground),
Triple("onSurfaceVariant", stringResource(R.string.theme_custom_on_surface_variant), colors.onSurfaceVariant),
Triple("primary", stringResource(R.string.theme_custom_primary), colors.primary),
Triple("onPrimary", stringResource(R.string.theme_custom_on_primary), colors.onPrimary),
Triple("signal", stringResource(R.string.theme_custom_signal), colors.signal),
Triple("good", stringResource(R.string.theme_custom_good), colors.good),
Triple("error", stringResource(R.string.theme_custom_error), colors.error),
)
rows.forEach { (key, label, argb) ->
SettingsRow(label, null) {
ColorCube(Color(argb), label) { picking = key }
}
}
val selected = rows.firstOrNull { it.first == picking }
if (selected != null) {
ColorPickerDialog(
selected.second,
selected.third,
onDismiss = { picking = null },
) { argb ->
Themes.setCustomColor(ctx, selected.first, argb)
}
}
}
@@ -27,6 +27,7 @@ import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
@@ -113,8 +114,8 @@ internal fun Actions(content: @Composable () -> Unit) = FlowRow(
) { content() }
@Composable
internal fun ActionChip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null) =
Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok, fraction, key) }
internal fun ActionChip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null, minWidth: androidx.compose.ui.unit.Dp = 0.dp) =
Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok, fraction, key, minWidth) }
internal val Shape16 = RoundedCornerShape(16.dp)
@@ -141,15 +142,16 @@ internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Un
}
@Composable
internal fun Chip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null) {
internal fun Chip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null, minWidth: androidx.compose.ui.unit.Dp = 0.dp) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(99.dp)
val ink = if (ok) pal.good else colors.onSurfaceVariant
Box(Modifier.clip(shape).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, shape)) {
Box(Modifier.widthIn(min = minWidth).clip(shape).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, shape), contentAlignment = Alignment.CenterStart) {
if (fraction != null) ChipFill(fraction, key, pal.signal.copy(alpha = 0.3f))
Text(
t, fontSize = 12.sp, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis,
style = androidx.compose.ui.text.TextStyle(fontFeatureSettings = "tnum"),
modifier = Modifier.padding(horizontal = 9.dp, vertical = 4.dp),
)
}
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import android.widget.Toast
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.LocalIndication
@@ -79,6 +81,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
@@ -258,7 +261,7 @@ internal fun GameDetail(
stringResource(R.string.game_tab_achievements_count, stringResource(R.string.achievements_title), achievementState.done, list.size)
} ?: stringResource(R.string.achievements_title)
GameTab.LAUNCH -> stringResource(R.string.game_tab_launch)
GameTab.SAVES -> stringResource(if (Store.byId(source).let { it == Store.GOG || it == Store.EPIC }) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.SAVES -> stringResource(if (CloudSaves.supports(Store.byId(source))) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.ADDONS -> stringResource(R.string.game_tab_addons)
GameTab.INSTALL -> stringResource(R.string.game_tab_install)
}
@@ -359,7 +362,7 @@ private fun GameTabBar(
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(modifier.fillMaxWidth().glass(CircleShape).padding(4.dp), verticalAlignment = Alignment.CenterVertically) {
if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) }
if (bumpers) TabBarBumper("LB", stringResource(R.string.widgets_prev_tab), leading = true) { onSelect((selected + tabs.size - 1) % tabs.size) }
tabs.forEachIndexed { i, label ->
val on = i == selected
val src = remember { MutableInteractionSource() }
@@ -383,7 +386,30 @@ private fun GameTabBar(
)
}
}
if (bumpers) BumperKey("RB", stringResource(R.string.widgets_next_tab)) { onSelect((selected + 1) % tabs.size) }
if (bumpers) TabBarBumper("RB", stringResource(R.string.widgets_next_tab), leading = false) { onSelect((selected + 1) % tabs.size) }
}
}
@Composable
private fun TabBarBumper(label: String, description: String, leading: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val round = 22.dp
val flat = 7.dp
val cap = if (leading) RoundedCornerShape(round, flat, flat, round) else RoundedCornerShape(flat, round, round, flat)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = if (leading) 0.dp else 3.dp, end = if (leading) 3.dp else 0.dp)
.size(width = 46.dp, height = 44.dp)
.clip(cap).background(colors.surfaceVariant).border(1.dp, pal.line2, cap)
.focusProperties { canFocus = false }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, role = Role.Button, onClick = onClick)
.semantics { contentDescription = description },
) {
Text(
label, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = if (leading) 4.dp else 0.dp, end = if (leading) 0.dp else 4.dp),
)
}
}
@@ -458,7 +484,7 @@ internal fun GameActions(
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
ActionChip(downloadLabel(download), ok = false, fraction = download.stageFraction.takeIf { it >= 0f }, key = download.stage)
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
@@ -473,7 +499,7 @@ internal fun GameActions(
}
}
download != null -> {
ActionChip(downloadLabel(download), ok = false, fraction = download.stageFraction.takeIf { it >= 0f }, key = download.stage)
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
@@ -892,8 +918,10 @@ private fun ShortcutFields(game: Library.SteamGame, folder: File) {
@Composable
private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
val saves by produceState<List<GameSaves.SaveDir>?>(null, g.gameId) {
value = withContext(Dispatchers.IO) { runCatching { GameSaves.locate(prefix, g) }.getOrDefault(emptyList()) }
val context = LocalContext.current.applicationContext
var synced by remember(g.gameId) { mutableStateOf(0) }
val saves by produceState<List<GameSaves.SaveDir>?>(null, g.gameId, synced) {
value = withContext(Dispatchers.IO) { runCatching { GameSaves.saves(context, prefix, g) }.getOrDefault(emptyList()) }
}
val found = saves
val summary = when {
@@ -911,9 +939,9 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
}
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(summary, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp).readable().padding(4.dp))
if (Store.byId(g.source).let { it == Store.GOG || it == Store.EPIC }) {
if (CloudSaves.supports(Store.byId(g.source))) {
SectionLabel(stringResource(R.string.store_cloud_saves))
CloudRows(g)
CloudRows(g) { synced++ }
SectionLabel(stringResource(R.string.games_saves))
}
MenuItem(stringResource(R.string.games_import_saves), checked = false) { a.onSaveImport(g) }
@@ -969,14 +997,16 @@ private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions)
}
@Composable
private fun CloudRows(g: Library.SteamGame) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON && it != Store.EA } ?: return
private fun CloudRows(g: Library.SteamGame, onSynced: () -> Unit = {}) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
val id = g.storeId ?: return
val context = LocalContext.current.applicationContext
var busy by remember(g.gameId) { mutableStateOf<String?>(null) }
var tick by remember(g.gameId) { mutableStateOf(0) }
var refreshing by remember(g.gameId) { mutableStateOf(false) }
val status by produceState<CloudSaves.Status?>(null, g.gameId, tick) {
value = withContext(Dispatchers.IO) { runCatching { CloudSaves.status(context, store, id) }.getOrNull() }
refreshing = false
}
val folder = g.gameFiles
var enabled by remember(g.gameId) { mutableStateOf(folder?.let { StoreGameSidecar.read(it)?.cloud } ?: true) }
@@ -988,7 +1018,7 @@ private fun CloudRows(g: Library.SteamGame) {
busy = if (up) "up" else "down"
Thread({
val r = if (up) CloudSaves.upload(context, store, id, force) else CloudSaves.download(context, store, id, force)
StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
StoresState.post { refreshing = true; busy = null; tick++; onSynced(); android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
}, "cloud-manual").start()
}
MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported,
@@ -1000,11 +1030,13 @@ private fun CloudRows(g: Library.SteamGame) {
StoresState.post { enabled = written?.cloud ?: enabled }
}, "cloud-switch").start()
}
val ready = st != null && supported && enabled && busy == null
val ready = st != null && supported && enabled && busy == null && !refreshing && st.folder != null && st.signedIn
val pending = stringResource(R.string.cloud_pending)
val summary = when {
st == null || busy != null -> pending
!supported -> stringResource(R.string.cloud_none)
!st.signedIn || st.reason == "not-signed-in" -> stringResource(R.string.cloud_signed_out)
st.folder == null -> stringResource(R.string.cloud_not_synced)
conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size)
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
else -> stringResource(R.string.cloud_never)
@@ -1116,3 +1148,47 @@ internal object FolderSizes {
}, "folder-size").start()
}
}
@Composable
private fun SteadyDownloadChip(download: com.droiddeck.launcher.stores.download.DownloadEntry) {
val progress = steadyProgress(download)
val label = steadyLabel(download, progress)
val show = LocalShowSection.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = if (LocalPillButtons.current) androidx.compose.foundation.shape.CircleShape else Shape12
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by androidx.compose.animation.core.animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, androidx.compose.animation.core.Spring.StiffnessMedium), label = "dlScale")
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
val description = stringResource(R.string.stores_tab_downloads)
val open = {
placed[0]?.takeIf { it.isAttached }?.boundsInRoot()?.let { StoresMotion.fly(it) }
show("downloads")
}
Box(
contentAlignment = Alignment.CenterStart,
modifier = Modifier.paneItem("detail-download").testTag("detail-download")
.onGloballyPositioned { placed[0] = it }
.widthIn(min = 200.dp).heightIn(min = 48.dp)
.graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape)
.background(Color.White.copy(alpha = 0.04f))
.glideBorder(hot, shape, pal.signal, pal.line2)
.hoverable(src)
.clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button, onClickLabel = description, onClick = open)
.controllerConfirm(onClick = open),
) {
ChipFill(progress, download.key, pal.signal.copy(alpha = 0.42f))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.widthIn(min = 200.dp).padding(start = 16.dp, end = 10.dp),
) {
Text(
label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1,
style = androidx.compose.ui.text.TextStyle(fontFeatureSettings = "tnum"), modifier = Modifier.padding(end = 8.dp),
)
Icon(androidx.compose.material.icons.Icons.AutoMirrored.Filled.KeyboardArrowRight, description, tint = if (hot) colors.onBackground else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
}
}
@@ -1,171 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
@Composable
internal fun StoreAccountsButton() {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val placed = remember { arrayOfNulls<LayoutCoordinates>(1) }
var itchKey by remember { mutableStateOf(false) }
val home = { placed[0]?.takeIf { it.isAttached }?.boundsInRoot() }
if (itchKey) ItchKeyDialog { itchKey = false }
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val label = stringResource(R.string.library_accounts)
val open = {
placed[0]?.takeIf { it.isAttached }?.boundsInRoot()?.let { at ->
Steps.ask(StepAsk(
anchor = at, side = StepSide.Left, accent = pal.signal, items = storesWithSignIn().size + 1, pillCorner = 20.dp, maxWidth = 380.dp,
handle = { Icon(Icons.Filled.Add, null, tint = pal.signal, modifier = Modifier.size(20.dp)) },
) {
StoreAccountsStep(onSignIn = { store, row ->
Steps.fold()
when {
store == Store.ITCH -> itchKey = true
row == null || Motion.scale == 0f || StoresMotion.signIn != null -> StoresState.signIn(ctx, store)
else -> {
val accent = storePalette(pal, store).signal
StoresMotion.signIn = SignInFlood(store, row, accent, sourceColours(store.id).dot, home = home())
}
}
})
})
}
Unit
}
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("libchip:accounts").testTag("library-accounts").size(40.dp).clip(CircleShape)
.background(colors.surface)
.glideBorder(hot, CircleShape, pal.signal, pal.line)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClickLabel = label, onClick = open)
.controllerConfirm(onClick = open),
) { Icon(Icons.Filled.Add, label, tint = if (hot) colors.onBackground else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
}
private fun storesWithSignIn(): List<Store> = Store.entries.filter { StoresState.backend(it) != null }
@Composable
private fun StepOutScope.StoreAccountsStep(onSignIn: (Store, androidx.compose.ui.geometry.Rect?) -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
var leaving by remember { mutableStateOf<Store?>(null) }
LaunchedEffect(leaving) { if (leaving != null) focusSoon { first } }
val out = leaving
if (out == null) {
StepTitle(stringResource(R.string.library_accounts))
Column(Modifier.fillMaxWidth().heightIn(max = (maxHeight - 72.dp).coerceAtLeast(120.dp)).verticalScroll(rememberScrollState())) {
storesWithSignIn().forEachIndexed { i, store ->
val name = StoresState.accounts[store]
val at = remember { arrayOfNulls<LayoutCoordinates>(1) }
StoreTheme(store) {
AccountRow(
store, name,
modifier = Modifier.stepItem(1 + i).then(if (i == 0) Modifier.focusRequester(first) else Modifier)
.onGloballyPositioned { at[0] = it },
enabled = open,
) { if (name != null) leaving = store else onSignIn(store, at[0]?.takeIf { it.isAttached }?.boundsInRoot()) }
}
}
}
} else {
StepTitle(stringResource(R.string.stores_signout_title, out.label))
Text(stringResource(R.string.stores_signout_note), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
StepChoice(stringResource(R.string.stores_signout_stay), enabled = open, modifier = Modifier.focusRequester(first)) { leaving = null }
StepChoice(stringResource(R.string.stores_signout_go), danger = true, enabled = open) {
Steps.fold()
StoresState.signOut(ctx, out)
}
}
}
}
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun AccountRow(store: Store, account: String?, modifier: Modifier, enabled: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(20.dp)
val signedIn = account != null
val accent = pal.signal
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = modifier.fillMaxWidth().heightIn(min = 44.dp).clip(shape)
.background(if (hot) accent.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(hot, shape, accent, Color.Transparent)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, role = Role.Button, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.testTag("account-${store.id}")
.padding(horizontal = 16.dp),
) {
Box(Modifier.size(10.dp).background(sourceColours(store.id).dot.copy(alpha = if (signedIn) 1f else 0.45f), CircleShape))
Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(store.label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, softWrap = false)
if (account != null) Text(
account, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, softWrap = false,
modifier = Modifier.weight(1f, fill = false).basicMarquee(iterations = Int.MAX_VALUE, initialDelayMillis = 1_200),
)
}
Text(
stringResource(if (signedIn) R.string.library_account_sign_out else R.string.library_account_sign_in),
fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = if (signedIn) (if (hot) colors.error else colors.onSurfaceVariant) else if (hot) accent else colors.onBackground, maxLines = 1,
)
}
}
@@ -17,6 +17,7 @@ import com.droiddeck.launcher.frontend.SteamHidden
import com.droiddeck.launcher.session.SessionPrefs
internal const val LIBRARY_HIDDEN = "hidden"
internal val HIDDEN_DOT = androidx.compose.ui.graphics.Color(0xFF9AA0A6)
internal object LibraryHidden {
var keys by mutableStateOf<Set<String>>(emptySet())
@@ -41,6 +41,18 @@ import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ManageAccounts
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.border
import androidx.compose.material.icons.outlined.FolderOpen
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.layout.boundsInParent
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.FilterAlt
@@ -165,33 +177,35 @@ internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = e
internal const val LIBRARY_ALL = "all"
internal fun librarySources(
entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet(), favorites: Set<String> = emptySet(),
hidden: (LibraryEntry) -> Boolean = { false }, showHidden: Boolean = false,
): List<String> =
(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED + Library.SOURCE_COLLECTION + LIBRARY_HIDDEN)
hidden: (LibraryEntry) -> Boolean = { false }, offStores: Set<String> = emptySet(),
places: List<Pair<String, String?>> = DEFAULT_LIBRARY_PLACES, offTabs: Set<String> = setOf(LIBRARY_HIDDEN),
): List<String> {
val tabs = arrangeStoreTabs(order, offStores)
val shown = tabs.filter { it.shown }.map { it.store.id }.toSet() + LIBRARY_OWN_TABS - offTabs
return (placeLibraryTabs(tabs.map { it.store.id }, places).filter { it in shown } + Library.SOURCE_COLLECTION)
.filter { source ->
when (source) {
LIBRARY_HIDDEN -> showHidden
LIBRARY_HIDDEN -> true
LIBRARY_FAVORITES -> entries.any { it.favoriteKey in favorites && !hidden(it) }
else -> source in always || entries.any { it.source == source && !hidden(it) }
}
}
}
internal object LibraryDisplay {
const val DEFAULT_LEVEL = 2
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
var level by mutableIntStateOf(2)
var level by mutableIntStateOf(DEFAULT_LEVEL)
private set
var title by mutableStateOf(true)
private set
var size by mutableStateOf(true)
private set
var hidden by mutableStateOf(false)
private set
fun load(context: android.content.Context) {
level = SessionPrefs.libraryCardLevel(context).coerceIn(0, scales.lastIndex)
title = SessionPrefs.libraryShowTitle(context)
size = SessionPrefs.libraryShowSize(context)
hidden = SessionPrefs.libraryShowHidden(context)
}
fun step(context: android.content.Context, by: Int) {
@@ -208,13 +222,70 @@ internal object LibraryDisplay {
size = !size
SessionPrefs.setLibraryShowSize(context, size)
}
}
fun toggleHidden(context: android.content.Context) {
hidden = !hidden
SessionPrefs.setLibraryShowHidden(context, hidden)
private enum class ToggleAt { NONE, TOP, SPLIT, BOTTOM }
private const val NOT_INSTALLED_ROW = "library-not-installed"
@Composable
private fun NotInstalledRow(count: Int, expanded: Boolean, keys: Modifier, onFocus: (Boolean) -> Unit, onToggle: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(12.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 2.dp).then(keys).paneItem(NOT_INSTALLED_ROW).onFocusChanged { onFocus(it.isFocused) }.testTag(NOT_INSTALLED_ROW)
.heightIn(min = 44.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, Color.Transparent)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onToggle)
.controllerConfirm(onClick = onToggle)
.padding(horizontal = 4.dp, vertical = 8.dp),
) {
Text(
stringResource(R.string.stores_section_not_installed).uppercase() + " · " + count,
fontSize = 12.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.2.sp, color = if (hot) colors.onBackground else colors.onSurfaceVariant, maxLines = 1,
)
Box(Modifier.weight(1f).height(1.dp).background(pal.line))
val hop = remember { androidx.compose.animation.core.Animatable(0f) }
LaunchedEffect(expanded, hot, Motion.scale) {
hop.snapTo(0f)
if (Motion.scale == 0f) return@LaunchedEffect
val toward = if (expanded) -3.5f else 3.5f
kotlinx.coroutines.delay(if (hot) 0L else 1_200L)
while (true) {
repeat(2) {
hop.animateTo(toward, androidx.compose.animation.core.tween(150, easing = androidx.compose.animation.core.FastOutSlowInEasing))
hop.animateTo(0f, androidx.compose.animation.core.spring(dampingRatio = 0.45f, stiffness = androidx.compose.animation.core.Spring.StiffnessMedium))
}
kotlinx.coroutines.delay(3_500L)
}
}
Icon(
if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, stringResource(if (expanded) R.string.library_filter_installed else R.string.library_browse_owned),
tint = if (hot) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier.size(22.dp).graphicsLayer { translationY = hop.value.dp.toPx() },
)
}
}
internal fun libraryColumns(width: Int, base: Int, gap: Int, level: Int): Int =
(((width + gap) / (base + gap)).coerceAtLeast(1) + LibraryDisplay.DEFAULT_LEVEL - level).coerceAtLeast(1)
private class LevelCells(private val base: androidx.compose.ui.unit.Dp, private val level: Int) : GridCells {
override fun androidx.compose.ui.unit.Density.calculateCrossAxisCellSizes(availableSize: Int, spacing: Int): List<Int> {
val count = libraryColumns(availableSize, base.roundToPx(), spacing, level)
val usable = (availableSize - spacing * (count - 1)).coerceAtLeast(0)
return List(count) { usable / count + if (it < usable % count) 1 else 0 }
}
override fun equals(other: Any?): Boolean = other is LevelCells && other.base == base && other.level == level
override fun hashCode(): Int = 31 * base.hashCode() + level
}
internal object LibraryView {
var source by mutableStateOf(LIBRARY_ALL)
var query by mutableStateOf("")
@@ -247,20 +318,33 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val favorites = if (soundMode) emptySet() else LibraryFavorites.keys
val concealed: (LibraryEntry) -> Boolean = { !soundMode && LibraryHidden.isHidden(it) }
val stores = !s.shortcutPicker && !soundMode
val signedIn = Store.entries.filter { StoresState.isSignedIn(it) }
LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } }
val owned = if (stores) signedIn.associateWith { StoresState.library[it].orEmpty() } else emptyMap()
val installedStore = StoresState.installed.map { it.key }.toSet()
val syncing = if (stores) signedIn.mapNotNull { st -> StoresState.status[st]?.let { st to it } } else emptyList()
val preview = if (stores) DevPreview.library else LibraryPreview.OFF
val signedIn = when (preview) {
LibraryPreview.SAMPLE -> Store.entries.filter { StoresState.backend(it) != null }
LibraryPreview.SIGNED_OUT -> emptyList()
else -> Store.entries.filter { StoresState.isSignedIn(it) }
}
LaunchedEffect(stores, signedIn, preview) {
if (stores) signedIn.forEach { if (preview == LibraryPreview.SAMPLE) StoresState.preview(ctx, it) else StoresState.loadLibrary(ctx, it) }
}
val owned = when {
!stores -> emptyMap()
preview == LibraryPreview.SAMPLE -> signedIn.associateWith { sampleOwned(it) }
else -> signedIn.associateWith { StoresState.library[it].orEmpty() }
}
val reallyInstalled = StoresState.installed.map { it.key }.toSet()
val installedStore = reallyInstalled + if (preview == LibraryPreview.SAMPLE) sampleInstalled(owned) else emptySet()
val syncing = if (stores && preview == LibraryPreview.OFF) signedIn.mapNotNull { st -> StoresState.status[st]?.let { st to it } } else emptyList()
val cloudRows = rememberXboxCloudRows(s)
remember { SoundtrackCollections.load(ctx) }
val savedSnapshot = SoundtrackCollections.snapshot
val favoritesLabel = stringResource(R.string.soundtracks_favorites)
val all = remember(soundMode, s.steamGames, s.soundtracks, s.soundtracksEnabled, cloudRows, owned, installedStore, savedSnapshot, favoritesLabel) {
val all = remember(soundMode, s.steamGames, s.soundtracks, s.soundtracksEnabled, cloudRows, owned, installedStore, savedSnapshot, favoritesLabel, preview) {
if (soundMode) s.soundtracks.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } +
(if (s.soundtracks.isEmpty() && savedSnapshot.favorites.isEmpty() && savedSnapshot.collections.isEmpty()) emptyList() else SoundtrackCollections.games(ctx, favoritesLabel, skipEmptyFavorites = true))
.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) }
else libraryEntries(s.steamGames + cloudRows + if (s.soundtracksEnabled) emptyList() else s.soundtracks.filter { it.library != Library.ADDED }, owned, installedStore)
.let { rows -> if (preview == LibraryPreview.NOTHING_INSTALLED) rows.map { LibraryEntry(it.key, it.source, it.title, it.game, it.item, false) } else rows }
}
var addingSoundtrack by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) }
@@ -280,10 +364,18 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
}
val itchSignedIn = owned.containsKey(Store.ITCH)
val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT)
remember { StoreTabsState.load(ctx) }
val storeTabs = StoreTabsState.tabs
val signInChips = if (!stores || !StoresState.accountsLoaded || preview == LibraryPreview.SAMPLE) emptySet() else storeTabs
.filter { it.shown && StoresState.backend(it.store) != null && (preview == LibraryPreview.SIGNED_OUT || storeAccount(it.store) != StoreAccount.SIGNED_IN) }
.map { it.store.id }.toSet()
val sources = librarySources(
all, SessionPrefs.storesTabOrder(ctx),
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }).toSet(),
favorites, concealed, LibraryDisplay.hidden && !soundMode,
all, storeTabs.map { it.store.id },
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.ADDED.takeIf { stores }).toSet() + signInChips,
favorites, concealed,
offStores = if (soundMode) emptySet() else storeTabs.filterNot { it.shown }.map { it.store.id }.toSet(),
places = if (soundMode) DEFAULT_LIBRARY_PLACES else StoreTabsState.libraryPlaces,
offTabs = if (soundMode) setOf(LIBRARY_HIDDEN) else StoreTabsState.libraryHidden,
)
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
val q = LibraryView.query.trim().lowercase()
@@ -342,7 +434,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
fun sizeOf(e: LibraryEntry): Long? {
val key = e.storeKey
return when {
key != null && key in installedStore -> StoreSizes.onDisk[key]
key != null && e.installed && key in installedStore -> StoreSizes.onDisk[key]
e.game?.gameFiles != null -> FolderSizes.known[e.game.gameFiles.path]
e.item != null -> StoreSizes.size(e.item).takeIf { it > 0 }
else -> 0L
@@ -363,7 +455,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
var sizesWaited by remember(sizeSort) { mutableStateOf(false) }
LaunchedEffect(sizeSort) { if (sizeSort) { kotlinx.coroutines.delay(8_000); sizesWaited = true } }
fun sizeComing(e: LibraryEntry): Boolean = when {
e.storeKey != null && e.storeKey in installedStore -> true
e.storeKey != null && e.storeKey in installedStore -> e.storeKey in reallyInstalled // a sample install has no size to wait for
e.game?.gameFiles != null -> true
e.item != null -> StoreSizes.coming(e.item)
else -> false
@@ -425,7 +517,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
kotlinx.coroutines.delay(Motion.ms(240).toLong())
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
}
if (!soundMode && all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
if (!soundMode && s.shortcutPicker && all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
LibraryEmpty(s, a, modifier)
return
}
@@ -433,7 +525,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val detailScroll = rememberScrollState()
var cycled by remember { mutableIntStateOf(0) }
var gridFocused by remember { mutableStateOf(false) }
LaunchedEffect(source, sort, listUninstalled) { grid.scrollToItem(0) }
LaunchedEffect(source, sort) { grid.scrollToItem(0) }
LaunchedEffect(cycled) {
if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
focusWithinFrames({ gridFocused }) {
@@ -448,7 +540,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
bleedHorizontal = if (narrow) 14.dp else 22.dp, bleedTop = if (narrow) 10.dp else 14.dp,
wrap = { key, content -> StoreTheme(GameRef.parse(key).let { r -> r.store ?: r.game(s.steamGames)?.source?.let { Store.byId(it) } }) { content() } },
grid = {
LibraryGrid(
StoreTheme(Store.byId(source)) { LibraryGrid(
s, a, grid, visible, split, visible.size, sources, source, sizesPending, syncing,
showUninstalled = listUninstalled.takeIf { !s.shortcutPicker },onShowUninstalled = setShowUninstalled,
hiddenUninstalled = hiddenUninstalled,
@@ -458,19 +550,27 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
LibraryView.source = ids[(ids.indexOf(source).coerceAtLeast(0) + step + ids.size) % ids.size]
cycled++
},
onOpen = { focusManager.clearFocus(force = true); onSelect(it) },
onOpen = {
// A preview is read-only: a game's page would act on the real install behind the pretend one.
if (preview != LibraryPreview.OFF) android.widget.Toast.makeText(ctx, R.string.dev_preview_read_only, android.widget.Toast.LENGTH_SHORT).show()
else { focusManager.clearFocus(force = true); onSelect(it) }
},
searchCleared = open != null,
onFocus = { gridFocused = it },
soundMode = soundMode,
wallArt = { wallTiles(all.filterNot(concealed).mapNotNull { entryArt(it, tall = true) }) },
emptyText = when {
soundMode && all.isEmpty() -> R.string.soundtracks_empty
!soundMode && all.isEmpty() && source == LIBRARY_ALL -> R.string.games_empty
soundMode && source == Library.SOURCE_COLLECTION && q.isEmpty() -> R.string.soundtracks_collections_empty
else -> R.string.stores_nothing_matches
},
onAddSoundtrack = { addingSoundtrack = true },
onCollections = { savedDialog = true },
trackHits = shownHits, onPlayHit = playHit,
)
// An expired account keeps showing its cached games; with none cached it asks to sign in again, like a signed-out store.
signInStore = Store.byId(source)?.takeIf { st -> st.id in signInChips && (preview == LibraryPreview.SIGNED_OUT || storeAccount(st) != StoreAccount.EXPIRED || all.none { it.source == st.id }) },
) }
},
) { key ->
if (soundMode || (!s.soundtracksEnabled && s.soundtracks.any { GameRef.key(it) == key })) SoundtrackDetail(key, s, a, lead, backLabel, onBack = back)
@@ -492,7 +592,7 @@ private fun LibraryEmpty(s: FrontEndState, a: FrontEndActions, modifier: Modifie
if (s.steamGamesX64) ClientTag()
if (!s.shortcutPicker) {
AddGameButton { GamesDialogState.adding = true }
StoreAccountsButton()
ManageStoresChip()
}
}
}
@@ -514,15 +614,53 @@ private fun LibraryGrid(
onSource: (String) -> Unit, onCycle: (Int) -> Unit, onOpen: (String) -> Unit, onFocus: (Boolean) -> Unit, searchCleared: Boolean,
soundMode: Boolean = false, emptyText: Int = R.string.stores_nothing_matches, onAddSoundtrack: () -> Unit = {},
onCollections: () -> Unit = {}, trackHits: List<SoundtrackIndex.Hit> = emptyList(), onPlayHit: (SoundtrackIndex.Hit) -> Unit = {},
signInStore: Store? = null, wallArt: () -> List<Any> = { emptyList() },
) {
val listMode = s.storesView == "list"
val capsules = s.storesView == "capsules"
val tileWidth = (if (capsules) CapsuleWidth else if (listMode) CardWidth else LibraryCardWidth) * LibraryDisplay.scales[LibraryDisplay.level]
val baseWidth = if (capsules) CapsuleWidth else LibraryCardWidth
val level = LibraryDisplay.level
val focus = LocalFrontFocus.current
val scope = rememberCoroutineScope()
val density = androidx.compose.ui.platform.LocalDensity.current
var columns by remember { mutableIntStateOf(1) }
val headerItems = 2 + (if (sizesPending) 1 else 0) + syncing.size
var gridH by remember { mutableIntStateOf(0) }
var chipsH by remember { mutableIntStateOf(0) }
// A search that matches nothing keeps the toolbar, so the search can still be cleared.
val customEmpty = !soundMode && source == Library.ADDED && visible.isEmpty() && hiddenUninstalled == 0 && LibraryView.query.isBlank()
val splash = !soundMode && (signInStore != null || customEmpty)
val headerItems = (if (splash) 1 else 2) + (if (sizesPending) 1 else 0) + syncing.size
val expanded = showUninstalled == true
val notInstalled = if (expanded) visible.count { !it.installed } else hiddenUninstalled
val toggleAt = when {
showUninstalled == null || soundMode || notInstalled == 0 || (expanded && visible.isEmpty()) -> ToggleAt.NONE
!expanded -> ToggleAt.BOTTOM
split > 0 -> ToggleAt.SPLIT
else -> ToggleAt.TOP
}
val itemIndex: (Int) -> Int = { i ->
headerItems + i + when {
split > 0 -> if (i < split) 0 else 1
toggleAt == ToggleAt.TOP -> 1
else -> 0
}
}
val toggleIndex = when (toggleAt) {
ToggleAt.TOP -> headerItems
ToggleAt.SPLIT -> headerItems + split
else -> headerItems + visible.size
}
val gapPx = with(density) { 10.dp.toPx() }
val moveFocus: (String, Int, Int, Int) -> Unit = { target, targetIndex, currentIndex, direction ->
val shown = grid.layoutInfo.visibleItemsInfo.any { it.index == targetIndex }
if (focus != null && (!shown || (focus.attached[target] ?: 0) == 0 ||
runCatching { focus.items.getValue(target).requestFocus() }.isFailure)) scope.launch {
launch { grid.revealRow(currentIndex, targetIndex, direction, gapPx) }
focusWithinFrames({ focus.last == target }) { focus.items[target] ?: FocusRequester.Default }
}
}
val rowStart: (Int) -> Int? = { i -> if (i < 0) null else if (listMode) i else i - i % columns.coerceAtLeast(1) }
val switchedAt = remember(source) { android.os.SystemClock.uptimeMillis() }
val tile: @Composable (LibraryEntry) -> Unit = { e ->
val first = e.key == visible.firstOrNull()?.key
val navigation = if (focus == null) Modifier else Modifier.onPreviewKeyEvent { event ->
@@ -534,45 +672,98 @@ private fun LibraryGrid(
}
val index = visible.indexOfFirst { it.key == e.key }
val next = storeGridNeighbor(index, visible.size, if (listMode) 1 else columns, direction, split)
val toToggle = index >= 0 && when (toggleAt) {
ToggleAt.BOTTOM -> next == null && direction > 0
ToggleAt.TOP -> next == null && direction < 0
ToggleAt.SPLIT -> next != null && (index < split) != (next < split)
ToggleAt.NONE -> false
}
when {
direction == 0 || index < 0 -> false
toToggle -> {
if (key.action == KeyEvent.ACTION_DOWN) moveFocus(NOT_INSTALLED_ROW, toggleIndex, itemIndex(index), direction)
true
}
next == null -> direction > 0 && trackHits.isEmpty()
else -> {
if (key.action == KeyEvent.ACTION_DOWN) {
val target = "card:${visible[next].key}"
val targetIndex = headerItems + next + if (split == 0) 0 else if (next < split) 1 else 2
val currentIndex = headerItems + index + if (split == 0) 0 else if (index < split) 1 else 2
val shown = grid.layoutInfo.visibleItemsInfo.any { it.index == targetIndex }
if (!shown || (focus.attached[target] ?: 0) == 0 ||
runCatching { focus.items.getValue(target).requestFocus() }.isFailure) scope.launch {
launch { grid.revealRow(currentIndex, targetIndex, direction, with(density) { 10.dp.toPx() }) }
focusWithinFrames({ focus.last == target }) { focus.items[target] ?: FocusRequester.Default }
}
}
if (key.action == KeyEvent.ACTION_DOWN) moveFocus("card:${visible[next].key}", itemIndex(next), itemIndex(index), direction)
true
}
}
}
val picker = s.shortcutPicker && e.game != null
val choose = if (picker) ({ a.onSteamGame(e.game!!) }) else null
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL || source == LIBRARY_FAVORITES || source == LIBRARY_HIDDEN)
val enter = remember(source) {
androidx.compose.animation.core.Animatable(if (Motion.scale == 0f || android.os.SystemClock.uptimeMillis() - switchedAt > 600) 1f else 0f)
}
LaunchedEffect(source) {
if (enter.value >= 1f) return@LaunchedEffect
kotlinx.coroutines.delay(Motion.ms(minOf(visible.indexOfFirst { it.key == e.key }.coerceAtLeast(0), 11) * 28).toLong())
enter.animateTo(1f, Motion.tw(320))
}
Box(Modifier.graphicsLayer { alpha = enter.value; translationY = (1f - enter.value) * 18.dp.toPx() }) {
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL || source == LIBRARY_FAVORITES || source == LIBRARY_HIDDEN)
}
}
var rowFocused by remember { mutableStateOf(false) }
val toggleRow: @Composable () -> Unit = {
val keys = if (focus == null) Modifier else Modifier.onPreviewKeyEvent { event ->
val key = event.nativeKeyEvent
val direction = when (key.keyCode) {
KeyEvent.KEYCODE_DPAD_DOWN -> 1
KeyEvent.KEYCODE_DPAD_UP -> -1
else -> 0
}
val target = when {
direction > 0 && toggleAt == ToggleAt.TOP -> 0
direction > 0 && toggleAt == ToggleAt.SPLIT -> split
direction < 0 && toggleAt == ToggleAt.SPLIT -> rowStart(split - 1)
direction < 0 && toggleAt == ToggleAt.BOTTOM -> rowStart(visible.lastIndex)
else -> null
}
when {
direction == 0 -> false
target == null -> direction > 0 && toggleAt == ToggleAt.BOTTOM && trackHits.isEmpty()
else -> {
if (key.action == KeyEvent.ACTION_DOWN) moveFocus("card:${visible[target].key}", itemIndex(target), toggleIndex, direction)
true
}
}
}
NotInstalledRow(notInstalled, expanded, keys, onFocus = { rowFocused = it }) {
rowFocused = false
val landing = if (expanded) headerItems + split else headerItems + visible.size
onShowUninstalled(!expanded)
if (focus != null && focus.last == NOT_INSTALLED_ROW) scope.launch {
androidx.compose.runtime.withFrameNanos { }
if (grid.layoutInfo.visibleItemsInfo.none { it.key == NOT_INSTALLED_ROW }) grid.scrollToItem((landing - 1).coerceAtLeast(0))
repeat(30) {
androidx.compose.runtime.withFrameNanos { }
if (rowFocused) return@launch
runCatching { focus.items[NOT_INSTALLED_ROW]?.requestFocus() }
}
}
}
}
LazyVerticalGrid(
columns = if (listMode) GridCells.Fixed(1) else GridCells.Adaptive(tileWidth), state = grid,
columns = if (listMode) GridCells.Fixed(1) else remember(baseWidth, level) { LevelCells(baseWidth, level) }, state = grid,
modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup().bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }).onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
val minimum = with(density) { (if (listMode) CardWidth * 2 else tileWidth).roundToPx() }
columns = ((it.width + gap) / (minimum + gap)).coerceAtLeast(1)
columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level)
gridH = it.height
},
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections) }
val header: @Composable () -> Unit = {
LibraryHeader(s, a, if (soundMode) total else visible.size + hiddenUninstalled, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections, source = source)
}
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
Rise(1) { LibraryFilters(sources, source, onSource, accounts = !soundMode && !s.shortcutPicker) }
val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage = !soundMode && !s.shortcutPicker) }
item(key = if (soundMode) "header" else "filters", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.onSizeChanged { chipsH = it.height }) { Rise(0) { if (soundMode) header() else filters() } }
}
val splashHeight = with(density) { (gridH - chipsH).toDp() - 28.dp }.coerceAtLeast(300.dp)
if (!splash) item(key = if (soundMode) "filters" else "header", span = { GridItemSpan(maxLineSpan) }) { Rise(1) { if (soundMode) filters() else header() } }
for ((store, line) in syncing) item(key = "sync-${store.id}", span = { GridItemSpan(maxLineSpan) }) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
Text(store.shortLabel + " · " + line, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
@@ -587,17 +778,23 @@ private fun LibraryGrid(
}
}
val empty = emptyText
if (visible.isEmpty() && hiddenUninstalled > 0) item(key = "browse-owned", span = { GridItemSpan(maxLineSpan) }) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp)) {
Text(stringResource(R.string.library_no_installed_matches), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
SecondaryButton(stringResource(R.string.library_browse_owned), modifier = Modifier.testTag("library-browse-owned")) { onShowUninstalled(true) }
}
if (customEmpty) item(key = "custom-empty", span = { GridItemSpan(maxLineSpan) }) {
val art = remember { wallArt() }
Box(Modifier.padding(top = 4.dp, bottom = 16.dp)) { CustomGamesCard(splashHeight, art) }
}
else if (signInStore != null) item(key = "sign-in:${signInStore.id}", span = { GridItemSpan(maxLineSpan) }) {
StoreTheme(signInStore) { Box(Modifier.padding(top = 4.dp, bottom = 16.dp)) { SignInCard(signInStore, splashHeight, inert = DevPreview.library != LibraryPreview.OFF) } }
}
else if (split == 0) {
if (toggleAt == ToggleAt.TOP) item(key = NOT_INSTALLED_ROW, span = { GridItemSpan(maxLineSpan) }) { toggleRow() }
if (visible.isNotEmpty() || toggleAt == ToggleAt.NONE) libraryGrid(visible, empty, tile)
if (toggleAt == ToggleAt.BOTTOM) item(key = NOT_INSTALLED_ROW, span = { GridItemSpan(maxLineSpan) }) { toggleRow() }
}
else if (split == 0) libraryGrid(visible, empty, tile)
else {
item(key = "installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_installed)) }
libraryGrid(visible.take(split), empty, tile)
item(key = "not-installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_not_installed)) }
item(key = NOT_INSTALLED_ROW, span = { GridItemSpan(maxLineSpan) }) {
if (toggleAt == ToggleAt.SPLIT) toggleRow() else SectionLabel(stringResource(R.string.stores_section_not_installed))
}
libraryGrid(visible.drop(split), empty, tile)
}
if (trackHits.isNotEmpty()) {
@@ -664,87 +861,172 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
private fun LibraryHeader(
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Store?,
soundMode: Boolean = false, onAddSoundtrack: () -> Unit = {}, onCollections: () -> Unit = {},
soundMode: Boolean = false, onAddSoundtrack: () -> Unit = {}, onCollections: () -> Unit = {}, source: String = LIBRARY_ALL,
) {
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
val heading = stringResource(if (soundMode) R.string.rail_soundtracks else R.string.rail_games)
val heading = if (soundMode) stringResource(R.string.rail_soundtracks) else sourceTitle(source)
val soundLead: (@Composable () -> Unit)? = if (!soundMode) { -> if (s.steamGamesX64 && !narrow) ClientTag() } else { ->
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
Text(heading, fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(total.toString(), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
if (s.steamGamesX64 && !narrow) ClientTag()
}
}
ModeHeader(
heading, LibraryView.query, { LibraryView.query = it },
placeholder = stringResource(if (soundMode) R.string.soundtracks_search else R.string.stores_search_library),
clearSearchFocus = searchCleared, inlineWhenStacked = true,
lead = {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
Text(heading, fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(if (soundMode) total.toString() else pluralStringResource(R.plurals.mode_added_count, total, total), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
if (s.steamGamesX64 && !narrow) ClientTag()
}
},
lead = soundLead,
) {
if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onClick = onCollections)
if (!soundMode && DeveloperTools.on && DevPreview.shortcuts) LibraryPreviewButton()
DisplayButton()
if (!soundMode && (showUninstalled != null || xbox)) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
if (!soundMode && xbox) LibraryFilterButton(null, onShowUninstalled, xbox)
if (collections != null) CollectionsButton(collections)
SortButton(s, a)
ViewButton(s, a)
if (!soundMode) GameFileFolderActions(s, a)
if (!s.shortcutPicker) AddGameButton { if (soundMode) onAddSoundtrack() else GamesDialogState.adding = true }
// No sign-out in a preview: it would sign the real account out.
Store.byId(source)?.takeIf { !soundMode && DevPreview.library == LibraryPreview.OFF && StoresState.isSignedIn(it) }?.let { StoreAccountButton(it) }
if (!s.shortcutPicker && (soundMode || (source == Library.ADDED && total > 0))) AddGameButton { if (soundMode) onAddSoundtrack() else GamesDialogState.adding = true }
}
if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
}
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, accounts: Boolean) {
val chips = sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
if (!chips && !accounts) return
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp).horizontalScroll(rememberScrollState()),
) {
if (chips) SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) }
if (chips) for (src in sources) {
val store = Store.byId(src)
val dot = when {
store != null -> sourceColours(src).dot.copy(alpha = if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f)
src == LIBRARY_FAVORITES -> FavoritesColours.dot
src == LIBRARY_HIDDEN -> Color(0xFF9AA0A6)
src == Library.SOURCE_STEAM || src == Library.ADDED || src == Library.SOURCE_COLLECTION -> sourceColours(src).dot
else -> null
private fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, manage: Boolean) {
val chips = (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
if (!chips && !manage) return
val pal = LocalPalette.current
val keys = if (chips) listOf(LIBRARY_ALL) + sources else emptyList()
var focused by remember { mutableStateOf<String?>(null) }
val highlighted = focused?.takeIf { it in keys } ?: source
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
val inputMode = LocalInputModeManager.current.inputMode
val fillShown = inputMode != InputMode.Keyboard
val scroll = rememberScrollState()
StoreTheme(Store.byId(highlighted)) {
val tint = androidx.compose.animation.animateColorAsState(sourceDot(highlighted) ?: LocalPalette.current.signal, Motion.tw(160), label = "libChipTint")
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp),
) {
if (manage) ManageStoresChip()
Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (id in keys) {
val store = Store.byId(id)
val dot = sourceDot(id)
val label = when (id) {
LIBRARY_ALL -> stringResource(R.string.stores_tab_all)
Library.ADDED -> stringResource(R.string.library_custom_games)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> store?.shortLabel ?: sourceLabel(id)
}
androidx.compose.runtime.key(id) {
val reveal = remember { BringIntoViewRequester() }
LaunchedEffect(source) { if (source == id) reveal.bringIntoView() }
StoreChip(
label = label, on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal,
modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id")
.onGloballyPositioned { bounds[id] = it.boundsInParent() },
lead = {
if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape))
else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp))
},
onFocused = { focused = it },
paneKey = "libchip:$id",
) { onSource(id) }
}
}
}
if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
SourceFilterChip(
src,
when (src) {
Library.ADDED -> stringResource(R.string.library_filter_added)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> store?.shortLabel ?: sourceLabel(src)
},
source == src, dot,
) { onSource(src) }
}
if (accounts) StoreAccountsButton()
}
}
@Composable
private fun SourceFilterChip(key: String, label: String, on: Boolean, dot: Color?, onClick: () -> Unit) {
private fun sourceTitle(src: String): String = when (src) {
LIBRARY_ALL -> stringResource(R.string.library_all_games)
Library.ADDED -> stringResource(R.string.library_custom_games)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> Store.byId(src)?.label ?: sourceLabel(src)
}
@Composable
private fun StoreAccountButton(store: Store) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val name = StoresState.accounts[store] ?: store.label
val label = stringResource(R.string.stores_signout_named, name)
val title = stringResource(R.string.stores_signout_title, store.label)
val note = stringResource(R.string.stores_signout_note)
val stay = stringResource(R.string.stores_signout_stay)
val go = stringResource(R.string.stores_signout_go)
var at by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
HeaderIconButton(label, Icons.Filled.ManageAccounts, "library-account") {
val from = at ?: run { StoresState.signOut(ctx, store); return@HeaderIconButton }
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = colors.error, pillCorner = 8.dp, items = 3,
handle = { Icon(Icons.Filled.ManageAccounts, null, tint = colors.error, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
StepChoice(stay, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() }
StepChoice(go, danger = true, enabled = open) { Steps.fold(); StoresState.signOut(ctx, store) }
}
})
}
}
}
@Composable
private fun CustomGamesCard(height: androidx.compose.ui.unit.Dp, art: List<Any>) {
HeroWallCard(stringResource(R.string.library_custom_games), art, sourceColours(Library.ADDED), height, Modifier.testTag("library-custom-empty")) {
PrimaryButton(stringResource(R.string.games_add), main = true, large = true, icon = Icons.Filled.Add, modifier = Modifier.testTag("library-custom-add")) {
GamesDialogState.adding = true
}
}
}
private fun sourceDot(src: String): Color? {
val store = Store.byId(src)
return when {
store != null -> sourceColours(src).dot.copy(
alpha = if (DevPreview.library == LibraryPreview.SAMPLE || (DevPreview.library != LibraryPreview.SIGNED_OUT && StoresState.isSignedIn(store) && StoresState.expired[store] != true)) 1f else 0.35f,
)
src == LIBRARY_FAVORITES -> FavoritesColours.dot
src == LIBRARY_HIDDEN -> HIDDEN_DOT
src == Library.SOURCE_STEAM || src == Library.ADDED || src == Library.SOURCE_COLLECTION -> sourceColours(src).dot
else -> null
}
}
@Composable
internal fun ManageStoresChip() {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(99.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp),
modifier = Modifier.paneItem("libchip:$key").testTag("library-source-$key").heightIn(min = 40.dp).clip(shape)
.background(if (on) pal.signal.copy(alpha = 0.16f) else colors.surface)
.glideBorder(hot, shape, pal.signal, if (on) pal.signal else pal.line)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape))
Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (on || hot) colors.onBackground else colors.onSurfaceVariant, maxLines = 1)
}
val back = remember { FocusRequester() }
val label = stringResource(R.string.library_manage_stores)
val open = { ManageStores.returnTo = back; ManageStores.custom = true; ManageStores.open = true }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("libchip:manage").focusRequester(back).testTag("library-manage-stores").size(44.dp).clip(CircleShape)
.background(colors.surface)
.glideBorder(hot, CircleShape, pal.signal, pal.line)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClickLabel = label, onClick = open)
.controllerConfirm(onClick = open),
) { Icon(Icons.Filled.Tune, label, tint = if (hot) colors.onBackground else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
private fun entryArt(e: LibraryEntry, tall: Boolean): Any? {
@@ -792,7 +1074,7 @@ internal fun libraryTileWidth() = LibraryCardWidth * LibraryDisplay.scales[Libra
@Composable
private fun LibraryArt(e: LibraryEntry, wide: Any?, tall: Any?, download: DownloadEntry?, hot: Boolean, capsule: Boolean, showSource: Boolean) {
val chip = when {
download != null -> "${download.percent}%"
download != null -> "${(steadyProgress(download) * 100).toInt()}%"
e.item != null && StoresState.isUnfinished(e.item) -> stringResource(R.string.stores_resume)
e.installed && libraryUpdateAvailable(e) -> stringResource(R.string.common_update)
else -> null
@@ -835,7 +1117,7 @@ internal fun ArtCard(
)
badge?.invoke(this)
if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) {
StateChip(chip, ChipTone.BUSY, small = true, fraction = download?.stageFraction?.takeIf { it >= 0f }, key = download?.stage)
StateChip(chip, ChipTone.BUSY, small = true, fraction = download?.let { steadyProgress(it) }, key = download?.key)
}
val showName = LibraryDisplay.title || hot
val showDetail = LibraryDisplay.size || hot
@@ -1079,7 +1361,7 @@ internal fun DisplayButton() {
HeaderIconButton(title, Icons.Filled.Visibility, "display") {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 5,
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 4,
handle = { Icon(Icons.Filled.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
@@ -1102,10 +1384,6 @@ internal fun DisplayButton() {
stringResource(R.string.library_display_size), selected = LibraryDisplay.size, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(3),
) { LibraryDisplay.toggleSize(ctx) }
StepChoice(
stringResource(R.string.apps_filter_hidden), selected = LibraryDisplay.hidden, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(4),
) { LibraryDisplay.toggleHidden(ctx) }
}
})
}
@@ -0,0 +1,364 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.focusable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DragHandle
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreTab
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.arrangeStoreTabs
internal object StoreTabsState {
var tabs by mutableStateOf<List<StoreTab>>(emptyList())
private set
var libraryPlaces by mutableStateOf(DEFAULT_LIBRARY_PLACES)
private set
var libraryHidden by mutableStateOf<Set<String>>(emptySet())
private set
fun load(context: android.content.Context) {
SessionPrefs.settleStoresTabOrder(context, Store.entries.map { it.id })
tabs = arrangeStoreTabs(SessionPrefs.storesTabOrder(context), SessionPrefs.storesTabHidden(context))
libraryPlaces = SessionPrefs.libraryTabPlaces(context) ?: DEFAULT_LIBRARY_PLACES
libraryHidden = SessionPrefs.libraryTabsHidden(context) + listOfNotNull(LIBRARY_HIDDEN.takeUnless { SessionPrefs.libraryShowHidden(context) })
}
/** [ids] may hold the Library's own tabs among the stores; each one's place is kept as the tab it follows. */
fun reorder(context: android.content.Context, ids: List<String>) {
if (ids.any { it in LIBRARY_OWN_TABS }) {
val places = libraryPlacesOf(ids)
libraryPlaces = places
SessionPrefs.setLibraryTabPlaces(context, places)
}
val byId = tabs.associateBy { it.store.id }
val order = ids.mapNotNull { byId[it] }
if (order.map { it.store } != tabs.map { it.store }) {
tabs = order
save(context, arranged = true)
}
}
// The Stores tab needs at least one shown store to open on.
fun setShown(context: android.content.Context, store: Store, show: Boolean): Boolean {
if (!show && tabs.count { it.shown } <= 1) return false
tabs = tabs.map { if (it.store == store) it.copy(shown = show) else it }
save(context, arranged = false)
return true
}
fun setLibraryShown(context: android.content.Context, id: String, show: Boolean) {
libraryHidden = if (show) libraryHidden - id else libraryHidden + id
if (id == LIBRARY_HIDDEN) SessionPrefs.setLibraryShowHidden(context, show)
else SessionPrefs.setLibraryTabsHidden(context, libraryHidden - LIBRARY_HIDDEN)
}
private fun save(context: android.content.Context, arranged: Boolean) =
SessionPrefs.saveStoresTabs(context, tabs.map { it.store.id }, tabs.filterNot { it.shown }.map { it.store.id }.toSet(), arranged)
}
/** The Library tabs that are not stores but sort among them in Manage stores. Only Favorites, Custom games and Hidden can be turned off; Hidden starts off. */
internal val LIBRARY_OWN_TABS = listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, Library.ADDED, LIBRARY_HIDDEN)
internal val LIBRARY_HIDEABLE_TABS = setOf(LIBRARY_FAVORITES, Library.ADDED, LIBRARY_HIDDEN)
/** Favorites, then Steam, ahead of the stores; Custom games and Hidden after them (null: the end). */
internal val DEFAULT_LIBRARY_PLACES: List<Pair<String, String?>> =
listOf(LIBRARY_FAVORITES to "", Library.SOURCE_STEAM to LIBRARY_FAVORITES, Library.ADDED to null, LIBRARY_HIDDEN to null)
/**
* Puts the Library's own tabs into a store tab order. Each goes after the tab it follows ("" for first; null or a tab that is gone
* for last), in [places] order, so a place may name a tab placed before it. A tab [places] misses keeps its default place.
*/
internal fun placeLibraryTabs(stores: List<String>, places: List<Pair<String, String?>>): List<String> {
var out = stores.filterNot { it in LIBRARY_OWN_TABS }
for ((id, after) in places.filter { it.first in LIBRARY_OWN_TABS } + DEFAULT_LIBRARY_PLACES) {
if (id in out) continue
val at = when {
after == "" -> 0
after != null && after in out -> out.indexOf(after) + 1
else -> out.size
}
out = out.take(at) + id + out.drop(at)
}
return out
}
/** The places that rebuild [order] with [placeLibraryTabs]. */
internal fun libraryPlacesOf(order: List<String>): List<Pair<String, String>> =
order.mapIndexedNotNull { i, id -> if (id in LIBRARY_OWN_TABS) id to (order.getOrNull(i - 1) ?: "") else null }
internal object ManageStores {
var open by mutableStateOf(false)
/** Opened from the Library, which also lists the Custom games tab. */
var custom by mutableStateOf(false)
var returnTo: FocusRequester? = null
}
internal enum class StoreAccount { SIGNED_IN, SIGNED_OUT, EXPIRED, NEEDS_KEY }
internal fun storeAccount(store: Store): StoreAccount = when {
StoresState.isSignedIn(store) && StoresState.expired[store] == true -> StoreAccount.EXPIRED
StoresState.isSignedIn(store) -> StoreAccount.SIGNED_IN
store == Store.ITCH -> StoreAccount.NEEDS_KEY
else -> StoreAccount.SIGNED_OUT
}
internal fun startStoreSignIn(context: android.content.Context, store: Store, at: Rect?, start: Color, onItchKey: () -> Unit) {
when {
store == Store.ITCH -> onItchKey()
at == null || Motion.scale == 0f || StoresMotion.signIn != null -> StoresState.signIn(context, store)
else -> StoresMotion.signIn = SignInFlood(store, at, start, sourceColours(store.id).dot)
}
}
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusRequester?, tag: String, content: @Composable ColumnScope.() -> Unit) {
val pal = LocalPalette.current
BackHandler(enabled = open) { onClose() }
var wasOpen by remember { mutableStateOf(false) }
val closeInput = androidx.compose.ui.platform.LocalInputModeManager.current
LaunchedEffect(open) {
if (open) wasOpen = true
else if (wasOpen && returnFocus != null && closeInput.inputMode == androidx.compose.ui.input.InputMode.Keyboard) focusSoon { returnFocus }
}
Box(Modifier.fillMaxSize()) {
AnimatedVisibility(open, enter = fadeIn(), exit = fadeOut()) {
Box(
Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.45f))
.focusProperties { canFocus = false }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { onClose() },
)
}
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
val width = minOf(560.dp, maxWidth * 0.92f)
AnimatedVisibility(open, enter = slideInHorizontally { it } + fadeIn(), exit = slideOutHorizontally { it } + fadeOut()) {
val inside = remember { FocusRequester() }
var holds by remember { mutableStateOf(false) }
val pad = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode == androidx.compose.ui.input.InputMode.Keyboard
// Focus (and its ring) only matters to a controller: opened by touch the sheet waits until one is picked up.
LaunchedEffect(pad) {
if (!pad) return@LaunchedEffect
repeat(60) {
androidx.compose.runtime.withFrameNanos { }
if (holds || !open) return@LaunchedEffect
runCatching { inside.requestFocus() }
}
}
Column(
Modifier.width(width).fillMaxHeight()
.onFocusChanged { holds = it.hasFocus }
.focusRequester(inside)
.focusProperties { exit = { if (open) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup()
.background(MaterialTheme.colorScheme.background)
.border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag(tag),
content = content,
)
}
}
}
}
private val STORE_ROW = 60.dp
private val STORE_HANDLE = 44.dp
@Composable
internal fun ManageStoresSheet() {
val ctx = LocalContext.current
LaunchedEffect(ManageStores.open) { if (ManageStores.open) StoreTabsState.load(ctx) }
SideSheet(ManageStores.open, onClose = { ManageStores.open = false }, returnFocus = ManageStores.returnTo, tag = "manage-stores-sheet") {
PageHeader(stringResource(R.string.library_manage_stores)) {
Spacer(Modifier.weight(1f))
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.onSurfaceVariant) {
ManageStores.open = false
}
}
Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) {
SortableRows(
rows = {
val ids = StoreTabsState.tabs.map { it.store.id }
if (ManageStores.custom) placeLibraryTabs(ids, StoreTabsState.libraryPlaces) else ids
},
commit = { StoreTabsState.reorder(ctx, it) },
movable = { true },
rowHeight = STORE_ROW, handleWidth = STORE_HANDLE,
onActivate = { id ->
if (id in LIBRARY_HIDEABLE_TABS) {
StoreTabsState.setLibraryShown(ctx, id, id in StoreTabsState.libraryHidden)
return@SortableRows
}
val tab = StoreTabsState.tabs.firstOrNull { it.store.id == id } ?: return@SortableRows
StoreTabsState.setShown(ctx, tab.store, !tab.shown)
},
) { id, held, offset, hint, modifier, onFocus ->
val tab = StoreTabsState.tabs.firstOrNull { it.store.id == id }
if (id in LIBRARY_OWN_TABS) LibraryTabSortRow(id, held, offset, hint, modifier, onFocus)
else if (tab != null) StoreSortRow(tab, held, offset, hint, modifier, onFocus)
}
}
}
}
@Composable
private fun StoreSortRow(
tab: StoreTab, held: Boolean, offset: Float, hint: String?, modifier: Modifier, onFocus: (Boolean) -> Unit,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val store = tab.store
val account = storeAccount(store)
val name = StoresState.accounts[store]
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val note = when (account) {
StoreAccount.SIGNED_IN -> name ?: ""
StoreAccount.SIGNED_OUT -> stringResource(R.string.store_account_signed_out)
StoreAccount.EXPIRED -> stringResource(R.string.store_account_expired)
StoreAccount.NEEDS_KEY -> stringResource(R.string.store_account_api_key)
}
SortRowFrame(held, offset, modifier.testTag("store-row-${store.id}"), hot, src, onFocus) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(width = STORE_HANDLE, height = STORE_ROW).testTag("store-handle-${store.id}")) {
Icon(Icons.Filled.DragHandle, null, tint = if (held) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.weight(1f).alpha(if (tab.shown) 1f else 0.5f)) {
Box(Modifier.size(10.dp).background(sourceColours(store.id).dot.copy(alpha = if (account == StoreAccount.SIGNED_IN) 1f else 0.4f), CircleShape))
Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
Text(store.label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (note.isNotEmpty()) Text(
note, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (account == StoreAccount.EXPIRED) colors.error else colors.onSurfaceVariant,
)
}
}
if (hint != null) KeyHint("Y", hint)
ToggleSwitch(
tab.shown, true, store.label,
Modifier.testTag("store-shown-${store.id}").focusProperties { canFocus = false },
) { StoreTabsState.setShown(ctx, store, it) }
}
}
@Composable
private fun SortRowFrame(
held: Boolean, offset: Float, modifier: Modifier, hot: Boolean, src: MutableInteractionSource, onFocus: (Boolean) -> Unit,
content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(
modifier.fillMaxWidth().height(STORE_ROW)
.zIndex(if (held) 1f else 0f)
.graphicsLayer { translationY = offset }
.background(if (held) colors.surfaceVariant else colors.surface)
.glideBorder(hot, Shape12, pal.signal)
.onFocusChanged { onFocus(it.isFocused) }
.hoverable(src)
.focusable(interactionSource = src),
) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().weight(1f).padding(end = 10.dp),
content = content,
)
Box(Modifier.fillMaxWidth().height(1.dp).background(if (held) Color.Transparent else pal.line))
}
}
@Composable
private fun LibraryTabSortRow(id: String, held: Boolean, offset: Float, hint: String?, modifier: Modifier, onFocus: (Boolean) -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val hideable = id in LIBRARY_HIDEABLE_TABS
val shown = id !in StoreTabsState.libraryHidden
val label = when (id) {
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
Library.ADDED -> stringResource(R.string.library_custom_games)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> stringResource(R.string.source_steam)
}
val dot = when (id) {
LIBRARY_FAVORITES -> FavoritesColours.dot
LIBRARY_HIDDEN -> HIDDEN_DOT
else -> sourceColours(id).dot
}
SortRowFrame(held, offset, modifier.testTag("store-row-$id"), hot, src, onFocus) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(width = STORE_HANDLE, height = STORE_ROW).testTag("store-handle-$id")) {
Icon(Icons.Filled.DragHandle, null, tint = if (held) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.weight(1f).alpha(if (shown) 1f else 0.5f)) {
Box(Modifier.size(10.dp).background(dot, CircleShape))
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (hint != null) KeyHint("Y", hint)
if (hideable) ToggleSwitch(
shown, true, label,
Modifier.testTag("store-shown-$id").focusProperties { canFocus = false },
) { StoreTabsState.setLibraryShown(ctx, id, it) }
}
}
@@ -15,6 +15,7 @@ internal object DeveloperTools {
fun load(context: Context) {
on = SessionPrefs.developerTools(context)
DevPreview.shortcuts = SessionPrefs.previewShortcuts(context)
}
fun set(context: Context, enabled: Boolean) {
@@ -24,12 +24,11 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.session.GpuClockPin
import com.droiddeck.launcher.session.SessionPrefs
class CoreRow(val core: Int, val label: String)
private const val MEMORY_CAP_STEP_MB = 256
@Composable
fun PerformancePage(
cores: List<CoreRow>,
@@ -47,12 +46,6 @@ fun PerformancePage(
fsyncFirst: Boolean,
gamescopeRealtime: Boolean,
gpuClockPin: Boolean,
ramCapMb: Int,
zramClient: Boolean,
zramIdle: Boolean,
vramCapMb: Int,
deviceRamMb: Int,
ramCapAvailable: Boolean,
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
@@ -71,10 +64,6 @@ fun PerformancePage(
onFsyncFirst: (Boolean) -> Unit,
onGamescopeRealtime: (Boolean) -> Unit,
onGpuClockPin: (Boolean) -> Unit,
onRamCapMb: (Int) -> Unit,
onZramClient: (Boolean) -> Unit,
onZramIdle: (Boolean) -> Unit,
onVramCapMb: (Int) -> Unit,
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
@@ -134,39 +123,7 @@ fun PerformancePage(
gamescopeRealtime, onChange = onGamescopeRealtime,
)
}
SettingsGroup(stringResource(R.string.perf_gpu)) {
ToggleRow(
host, "gpuclock", stringResource(R.string.perf_gpuclock),
stringResource(R.string.perf_gpuclock_hint),
gpuClockPin, onChange = onGpuClockPin,
)
}
SettingsGroup(stringResource(R.string.perf_memory)) {
val top = (deviceRamMb / MEMORY_CAP_STEP_MB * MEMORY_CAP_STEP_MB).coerceAtLeast(MEMORY_CAP_STEP_MB)
val off = stringResource(R.string.perf_cap_off)
val auto = stringResource(R.string.perf_cap_auto)
ToggleRow(
host, "zramidle", stringResource(R.string.perf_zram_idle),
if (ramCapAvailable) stringResource(R.string.perf_zram_idle_hint) else stringResource(R.string.perf_ram_cap_unavailable),
zramIdle && ramCapAvailable, enabled = ramCapAvailable, onChange = onZramIdle,
)
ToggleRow(
host, "zramclient", stringResource(R.string.perf_zram_client),
if (ramCapAvailable) stringResource(R.string.perf_zram_client_hint) else stringResource(R.string.perf_ram_cap_unavailable),
zramClient && ramCapAvailable, enabled = ramCapAvailable, onChange = onZramClient,
)
SliderRow(
stringResource(R.string.perf_ram_cap),
if (ramCapAvailable) stringResource(R.string.perf_ram_cap_hint) else stringResource(R.string.perf_ram_cap_unavailable),
ramCapMb.coerceAtMost(top), 0..top, step = MEMORY_CAP_STEP_MB, enabled = ramCapAvailable,
format = { if (it == 0) off else "$it MB" }, onChange = onRamCapMb,
)
SliderRow(
stringResource(R.string.perf_vram_cap), stringResource(R.string.perf_vram_cap_hint),
vramCapMb.coerceAtMost(top), 0..top, step = MEMORY_CAP_STEP_MB,
format = { if (it == 0) auto else "$it MB" }, onChange = onVramCapMb,
)
}
if (GpuClockPin.supported) GpuClockGroup(host, gpuClockPin, onChange = onGpuClockPin)
SettingsGroup(stringResource(R.string.perf_fixes)) {
ToggleRow(
host, "sysmem", stringResource(R.string.perf_sysmem),
@@ -258,3 +215,14 @@ fun PerformancePage(
onBack = onDismiss,
) { body() }
}
@Composable
internal fun GpuClockGroup(host: MenuHost, on: Boolean, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
SettingsGroup(stringResource(R.string.perf_gpu)) {
ToggleRow(
host, "gpuclock", stringResource(R.string.perf_gpuclock),
null,
on, chipModifier = chipModifier, onChange = onChange,
)
}
}
@@ -105,62 +105,19 @@ private fun ResetTabsRow() {
} }
}
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
internal fun EditTabsSheet(s: FrontEndState, a: FrontEndActions) {
val pal = LocalPalette.current
BackHandler(enabled = MoreTabs.editing) { MoreTabs.editing = false }
androidx.compose.runtime.DisposableEffect(Unit) { onDispose { MoreTabs.editing = false } }
var wasOpen by remember { mutableStateOf(false) }
val closeInput = androidx.compose.ui.platform.LocalInputModeManager.current
LaunchedEffect(MoreTabs.editing) {
if (MoreTabs.editing) wasOpen = true
else if (wasOpen && closeInput.inputMode == androidx.compose.ui.input.InputMode.Keyboard) focusSoon { MoreTabs.button }
}
Box(Modifier.fillMaxSize()) {
AnimatedVisibility(MoreTabs.editing, enter = fadeIn(), exit = fadeOut()) {
Box(
Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.45f))
.focusProperties { canFocus = false }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { MoreTabs.editing = false },
)
}
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
val width = minOf(560.dp, maxWidth * 0.92f)
AnimatedVisibility(MoreTabs.editing, enter = slideInHorizontally { it } + fadeIn(), exit = slideOutHorizontally { it } + fadeOut()) {
val inside = remember { FocusRequester() }
var holds by remember { mutableStateOf(false) }
val openInput = androidx.compose.ui.platform.LocalInputModeManager.current
// The launcher only takes focus in controller mode, so opening by touch switches to it like startup does.
LaunchedEffect(Unit) {
repeat(60) {
androidx.compose.runtime.withFrameNanos { }
if (holds || !MoreTabs.editing) return@LaunchedEffect
if (openInput.inputMode != androidx.compose.ui.input.InputMode.Keyboard) openInput.requestInputMode(androidx.compose.ui.input.InputMode.Keyboard)
runCatching { inside.requestFocus() }
}
}
Column(
Modifier.width(width).fillMaxHeight()
.onFocusChanged { holds = it.hasFocus }
.focusRequester(inside)
.focusProperties { exit = { if (MoreTabs.editing) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup()
.background(MaterialTheme.colorScheme.background)
.border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag("edit-tabs-sheet"),
) {
PageHeader(stringResource(R.string.more_edit_tabs)) {
Spacer(Modifier.weight(1f))
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.onSurfaceVariant) {
MoreTabs.editing = false
}
}
Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) {
TabsSettingsGroup(rememberMenuHost(), s, a)
if (!NavTabs.isDefault()) ResetTabsRow()
}
}
SideSheet(MoreTabs.editing, onClose = { MoreTabs.editing = false }, returnFocus = MoreTabs.button, tag = "edit-tabs-sheet") {
PageHeader(stringResource(R.string.more_edit_tabs)) {
Spacer(Modifier.weight(1f))
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.onSurfaceVariant) {
MoreTabs.editing = false
}
}
Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) {
TabsSettingsGroup(rememberMenuHost(), s, a)
if (!NavTabs.isDefault()) ResetTabsRow()
}
}
}
@@ -42,6 +42,7 @@ class SecondScreenPresentation(
private val onSwap: (() -> Unit)? = null,
private val onMenuTouched: () -> Unit = {},
private val onDeckPanel: (DeckPanel) -> Unit = { SessionPrefs.setDeckPanel(sessionActivity, it) },
private val picker: ((SecondScreenMode) -> ScreenPicker?)? = null,
) : Presentation(sessionActivity, display) {
private val frame = FrameLayout(context)
private var menuView: androidx.compose.ui.platform.ComposeView? = null
@@ -299,7 +300,8 @@ class SecondScreenPresentation(
SecondScreenMode.DASHBOARD -> renderDashboard()
SecondScreenMode.DESKTOP -> {
root.addView(BottomDesktopPanel(context, onClose, onMenu,
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap), weightParams())
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap,
picker = picker?.let { pick -> { pick(SecondScreenMode.DESKTOP) } }), weightParams())
}
SecondScreenMode.NONE -> Unit
}
@@ -316,15 +318,15 @@ class SecondScreenPresentation(
internal fun barModel(mode: SecondScreenMode): BottomBarModel? {
val swap = listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) })
fun model(extras: List<BarExtra>, tabs: BarTabs? = null) =
sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras, tabs)
sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras, tabs, picker?.invoke(mode))
return when (mode) {
SecondScreenMode.KEYBOARD_TRACKPAD -> model(listOf(BarExtra(
context.getString(if (keyboardShown.value) R.string.second_hide_keyboard else R.string.second_show_keyboard),
icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") { showKeyboard() }))
icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") { showKeyboard() }) + swap)
SecondScreenMode.DECK_CONTROLS -> model(swap, deckPanelTabs(context, deckPanel.value, ::selectDeckPanel))
SecondScreenMode.DASHBOARD, SecondScreenMode.CUSTOM_CONTROLS -> model(swap)
SecondScreenMode.TERMINAL -> model(listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard,
tag = "bottom-keyboard") { terminalPanel?.showKeyboard() }))
tag = "bottom-keyboard") { terminalPanel?.showKeyboard() }) + swap)
else -> null
}
}
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.ui
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("input-profile"),
GLASSES("glasses-game"),
SECOND_SCREEN("second-screen:custom-controls"),
DISPLAY("fg"),
HUD("hud"),
EFFECTS("look"),
@@ -14,10 +13,10 @@ internal enum class SessionDrawerPage(val firstControl: String) {
}
internal fun sessionDrawerPages(
hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter {
(hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES) &&
(hasGlasses || it != SessionDrawerPage.GLASSES) &&
(hasAgent || it != SessionDrawerPage.AGENT)
}
@@ -43,7 +43,6 @@ import androidx.compose.material.icons.outlined.PowerSettingsNew
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.ScreenShare
import androidx.compose.material.icons.outlined.Pause
import androidx.compose.material.icons.outlined.PictureInPictureAlt
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
@@ -51,8 +50,6 @@ import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material3.Icon
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.ui.semantics.Role
@@ -166,7 +163,6 @@ import java.util.Locale
private val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller
SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses
SessionDrawerPage.SECOND_SCREEN -> R.string.drawer_second_screen
SessionDrawerPage.DISPLAY -> R.string.drawer_page_display
SessionDrawerPage.HUD -> R.string.drawer_hud
SessionDrawerPage.VR -> R.string.vr_title
@@ -179,7 +175,6 @@ private val SessionDrawerPage.title: Int get() = when (this) {
private val SessionDrawerPage.icon get() = when (this) {
SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports
SessionDrawerPage.GLASSES -> GlassesIcon
SessionDrawerPage.SECOND_SCREEN -> Icons.Outlined.ScreenShare
SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows
SessionDrawerPage.HUD -> Icons.Outlined.Speed
SessionDrawerPage.VR -> VrHeadsetIcon
@@ -218,6 +213,7 @@ class DrawerActions(
val androidApps: List<HomeApp.LaunchableApp>,
val hudOn: Boolean,
val hudConfig: Map<String, String> = emptyMap(),
val gpuClockPin: Boolean = false,
val frameGen: FrameGen.Mode,
val frameGenTargetGameId: String? = null,
val frameGenTargetGameName: String? = null,
@@ -269,6 +265,7 @@ class DrawerActions(
val selectedSecondScreenDisplay: Int,
val onHud: (Boolean) -> Unit,
val onHudSetting: (String, String) -> Unit = { _, _ -> },
val onGpuClockPin: (Boolean) -> Unit = {},
val onHudOrder: (Map<String, Boolean>, List<String>) -> Unit = { _, _ -> },
val onHudOrderReset: () -> Unit = {},
val onHudReset: () -> Unit = {},
@@ -384,7 +381,7 @@ class DrawerActions(
@Composable
internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions, docked: Boolean = false,
backRequest: Int = 0, onLayerChange: (Boolean) -> Unit = {}) {
val pages = sessionDrawerPages(a.secondScreenDisplays.isNotEmpty(), a.glassesPresent)
val pages = sessionDrawerPages(a.glassesPresent)
val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER
LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) }
val colors = MaterialTheme.colorScheme
@@ -458,8 +455,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
val first = when {
page == SessionDrawerPage.GLASSES -> "glasses-tab-$glassesTab"
page == SessionDrawerPage.SESSION && a.isHomeApp -> "apps"
page == SessionDrawerPage.SECOND_SCREEN -> "second-screen:" +
(if (a.secondScreenMode == SecondScreenMode.NONE && !a.secondScreenNone) SecondScreenMode.KEYBOARD_TRACKPAD else a.secondScreenMode).id
else -> page.firstControl
}
if (turned) focus.forget(page)
@@ -508,7 +503,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
.padding(12.dp),
) {
val roomyHeader = sheetWidth >= 408.dp
val showPicker = a.secondScreenDisplays.isNotEmpty()
val roomyHeader = sheetWidth >= if (showPicker) 560.dp else 408.dp
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
@@ -518,7 +514,16 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SteamActionPill(
stringResource(R.string.common_close), Icons.Outlined.Close, focus.track(page, "close"),
) { host.open = null; (a.onDismissScreen ?: a.onClose)() }
if (roomyHeader) Spacer(Modifier.weight(1f))
if (showPicker) Box(if (roomyHeader) Modifier.weight(1f) else Modifier) {
ScreenPickerChip(
ScreenPicker(
secondScreenModes(a.secondScreenNone, com.droiddeck.launcher.session.SessionState.deckPad, a.dashboardAvailable, a.desktopAvailable),
a.secondScreenMode, onPick = { host.open = null; a.onSecondScreenMode(it) },
onMenu = if (docked) ({ host.open = null }) else null, menuShown = docked,
),
focus.track(page, "screen").testTag("drawer-screen-picker"),
)
} else if (roomyHeader) Spacer(Modifier.weight(1f))
SteamActionPill(
stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"),
) { host.open = null; a.onPause() }
@@ -541,7 +546,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
BarActions(
onMenu = if (docked) ({ host.open = null; a.onClose() }) else null, menuActive = true,
onMenu = null, menuActive = false,
onSteam = if (steamActions) ({ host.open = null; a.onSteamMenu?.invoke() }) else null,
onQam = if (steamActions) ({
host.open = null
@@ -648,6 +653,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5,
format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), onChange = a.onUpscaleSharpness)
}
SecondScreenGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.EFFECTS -> {
ScreenEffectsGroup(host, a, advancedEffectsExpanded,
@@ -789,9 +795,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
}
SessionDrawerPage.SECOND_SCREEN -> {
SecondScreenGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.GLASSES -> if (glassesTab == GlassesTab.CONTROLLERS) {
VrControllerGroups(host) { key -> focus.track(page, key) }
} else {
@@ -1277,41 +1280,17 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole
@Composable
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val modes = secondScreenModes(a.secondScreenNone, com.droiddeck.launcher.session.SessionState.deckPad, a.dashboardAvailable, a.desktopAvailable)
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
Column(Modifier.fillMaxWidth().selectableGroup()) {
modes.forEach { mode ->
val selected = a.secondScreenMode == mode
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val pick = { host.open = null; a.onSecondScreenMode(mode) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = track("second-screen:${mode.id}").fillMaxWidth().heightIn(min = 56.dp)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, RoundedCornerShape(8.dp), pal.signal)
.hoverable(source)
.selectable(selected, interactionSource = source, indication = null, role = Role.RadioButton, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
Text(stringResource(mode.label), fontSize = 15.sp, color = colors.onBackground, modifier = Modifier.weight(1f))
RadioButton(selected, onClick = null,
colors = RadioButtonDefaults.colors(selectedColor = pal.signal, unselectedColor = colors.onSurfaceVariant))
}
}
}
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", stringResource(R.string.drawer_page_display), null,
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay)
}
if (a.gameSwapAvailable || a.gameOnBottom) SettingsGroup(stringResource(R.string.swap_game_screen_group)) {
ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
val choosesDisplay = a.secondScreenDisplays.size > 1
val swapsGame = a.gameSwapAvailable || a.gameOnBottom
if (!choosesDisplay && !swapsGame) return
SettingsGroup(stringResource(R.string.drawer_second_screen)) {
if (swapsGame) ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom))
else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)),
a.gameOnBottom, chipModifier = track("game-screen"), onPick = a.onGameOnBottom)
if (choosesDisplay) ChoiceRow(host, "second-screen-display", stringResource(R.string.drawer_page_display), null,
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay)
}
}
@@ -76,10 +76,6 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_noglerror),
s(SettingsSection.PERFORMANCE, R.string.perf_gsrealtime, "gamescope"),
s(SettingsSection.PERFORMANCE, R.string.perf_gpuclock, "gpu", "clock", "max"),
s(SettingsSection.PERFORMANCE, R.string.perf_ram_cap, "ram", "memory"),
s(SettingsSection.PERFORMANCE, R.string.perf_vram_cap, "vram", "memory"),
s(SettingsSection.PERFORMANCE, R.string.perf_zram_idle, "zram", "swap", "memory"),
s(SettingsSection.PERFORMANCE, R.string.perf_zram_client, "zram", "swap", "memory"),
s(SettingsSection.PERFORMANCE, R.string.setup_clear_cached, "memory", "ram", "crash", "sleep", "killed"),
s(SettingsSection.PERFORMANCE, R.string.setup_bg_limit, "memory", "ram", "background apps"),
s(SettingsSection.PERFORMANCE, R.string.setup_memory_hud, "memory", "ram", "overlay"),
@@ -130,6 +126,7 @@ internal object SettingsIndex {
d(R.string.drawer_page_display, R.string.frame_gen_title, "lsfg", "lossless", "fps"),
d(R.string.drawer_page_display, R.string.display_filter, "upscale", "fsr", "sharpness"),
d(R.string.drawer_hud, R.string.drawer_hud, "fps", "counter", "overlay", "performance"),
d(R.string.drawer_hud, R.string.perf_gpuclock, "gpu", "clock", "max"),
d(R.string.drawer_page_controller, R.string.input_touchscreen, "touch", "mouse", "direct", "touchpad", "click"),
d(R.string.drawer_page_controller, R.string.mode_osc, "on-screen", "controls", "touch controls", "buttons"),
d(R.string.drawer_page_controller, R.string.osc_steam_layout, "touch layout", "edit layout", "on-screen"),
@@ -186,19 +186,19 @@ internal fun Modifier.overhang(by: androidx.compose.ui.unit.Dp = 4.dp): Modifier
}
@Composable
internal fun WallFade() {
internal fun WallFade(modifier: Modifier = Modifier.fillMaxSize().overhang()) {
val colors = MaterialTheme.colorScheme
Box(
Modifier.fillMaxSize().overhang().background(
modifier.background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.97f),
0.34f to colors.background.copy(alpha = 0.86f),
0.68f to colors.background.copy(alpha = 0.25f),
1f to colors.background.copy(alpha = 0.1f),
0f to colors.background.copy(alpha = 0.86f),
0.34f to colors.background.copy(alpha = 0.6f),
0.68f to colors.background.copy(alpha = 0.14f),
1f to colors.background.copy(alpha = 0.04f),
),
),
)
Box(Modifier.fillMaxSize().overhang().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to colors.background.copy(alpha = 0.9f))))
Box(modifier.background(Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
}
@Composable
@@ -91,8 +91,12 @@ import com.droiddeck.launcher.storage.GameUsage
import com.droiddeck.launcher.storage.KeptPrefix
import com.droiddeck.launcher.storage.PrefixOwner
import com.droiddeck.launcher.storage.StoreGameUsage
import com.droiddeck.launcher.storage.SystemCache
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentStorage
import com.droiddeck.launcher.storage.StorageReport
import com.droiddeck.launcher.storage.StorageState
import com.droiddeck.launcher.storage.StorageSummary
import com.droiddeck.launcher.storage.ToolReason
import com.droiddeck.launcher.storage.ToolState
import com.droiddeck.launcher.storage.ToolUsage
@@ -124,9 +128,10 @@ internal fun StoragePanel(s: FrontEndState, a: FrontEndActions) {
var view by remember { mutableStateOf("overview") }
var cleanup by remember { mutableStateOf(false) }
val report = StorageState.report
LaunchedEffect(Unit) { StorageState.refresh(ctx) }
val summary = report?.let { remember(it) { StorageSummary.of(it) } } ?: StorageState.saved
LaunchedEffect(Unit) { StorageState.refresh(ctx); AgentStorage.measure(ctx) }
LaunchedEffect(s.sessionRunning) { if (!s.sessionRunning) StorageState.refresh(ctx, force = report != null) }
if (report == null) {
if (summary == null) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(MaterialTheme.colorScheme.surface)
@@ -140,7 +145,7 @@ internal fun StoragePanel(s: FrontEndState, a: FrontEndActions) {
}
return
}
if (cleanup) CleanUpDialog(report, s.sessionRunning) { cleanup = false }
if (cleanup && report != null) CleanUpDialog(report, s.sessionRunning) { cleanup = false }
val top = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() }
LaunchedEffect(view) {
StorageState.lastFreed = null
@@ -148,14 +153,17 @@ internal fun StoragePanel(s: FrontEndState, a: FrontEndActions) {
runCatching { top.bringIntoView() }
}
Box(Modifier.fillMaxWidth().height(1.dp).bringIntoViewRequester(top))
when (view) {
// Until this run's scan lands, the saved overview shows; a section opened meanwhile appears once it does.
if (report == null) Overview(summary, s.sessionRunning, onCleanUp = { cleanup = true }, onOpen = { view = it })
else when (view) {
"games" -> GamesView(report, s.sessionRunning, a) { view = "overview" }
"data" -> GameDataView(report, s.sessionRunning) { view = "overview" }
"components" -> ComponentsView(report, s.sessionRunning) { view = "overview" }
"desktop" -> DesktopView(report, s.sessionRunning) { view = "overview" }
"stores" -> StoreGamesView(report, s.sessionRunning) { view = "overview" }
"tools" -> ToolsView(report, s.sessionRunning) { view = "overview" }
else -> Overview(report, s.sessionRunning, onCleanUp = { cleanup = true }, onOpen = { view = it })
"system" -> SystemView(report, s.sessionRunning) { view = "overview" }
else -> Overview(summary, s.sessionRunning, onCleanUp = { cleanup = true }, onOpen = { view = it })
}
}
@@ -267,7 +275,7 @@ private fun DefaultStorageGroup() {
}
@Composable
private fun Overview(report: StorageReport, sessionRunning: Boolean, onCleanUp: () -> Unit, onOpen: (String) -> Unit) {
private fun Overview(report: StorageSummary, sessionRunning: Boolean, onCleanUp: () -> Unit, onOpen: (String) -> Unit) {
val narrowPane = LocalNarrowPane.current
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = !narrowPane && maxWidth >= WIDE_OVERVIEW
@@ -280,11 +288,11 @@ private val NARROW_ROW = 640.dp
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun OverviewContent(report: StorageReport, sessionRunning: Boolean, wide: Boolean, onCleanUp: () -> Unit, onOpen: (String) -> Unit) {
private fun OverviewContent(report: StorageSummary, sessionRunning: Boolean, wide: Boolean, onCleanUp: () -> Unit, onOpen: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val used = report.total - report.free
val safe = StorageState.safeBytes(report)
val safe = report.safe
val low = report.free < StorageState.LOW_SPACE_BYTES
ActionStatus()
val summary = Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)
@@ -311,7 +319,7 @@ private fun OverviewContent(report: StorageReport, sessionRunning: Boolean, wide
Text(stringResource(R.string.storage_safe_now), fontSize = 13.sp, color = colors.onSurfaceVariant)
Text(gb(safe), fontSize = 26.sp, fontWeight = FontWeight.Bold, color = if (safe > 0) pal.good else colors.onBackground)
Text(stringResource(R.string.storage_safe_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 10.dp))
PrimaryButton(stringResource(R.string.storage_clean_up), enabled = !sessionRunning && !StorageState.busy, compact = true, onClick = onCleanUp)
PrimaryButton(stringResource(R.string.storage_clean_up), enabled = !sessionRunning && !StorageState.busy && StorageState.report != null, compact = true, onClick = onCleanUp)
} }
if (wide) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(18.dp), modifier = summary) {
usage(Modifier.weight(1f))
@@ -328,11 +336,11 @@ private fun OverviewContent(report: StorageReport, sessionRunning: Boolean, wide
}
DefaultStorageGroup()
SectionTitle(stringResource(R.string.storage_where), null)
val unused = report.unusedTools.sumOf { it.bytes }
val unused = report.unusedTools
val tiles = listOf<@Composable (Modifier) -> Unit>(
{ m ->
BucketCard(Bucket.GAMES, Icons.Outlined.VideogameAsset, stringResource(R.string.storage_games),
pluralStringResource(R.plurals.storage_games_installed, report.games.size, report.games.size) +
pluralStringResource(R.plurals.storage_games_installed, report.games, report.games) +
if (report.gamesOnSd > 0) " · " + pluralStringResource(R.plurals.storage_games_on_sd, report.gamesOnSd, report.gamesOnSd) else "",
report.buckets.getValue(Bucket.GAMES), m) { onOpen("games") }
},
@@ -343,30 +351,32 @@ private fun OverviewContent(report: StorageReport, sessionRunning: Boolean, wide
},
{ m ->
BucketCard(Bucket.TOOLS, Icons.Outlined.Layers, stringResource(R.string.storage_tools),
if (unused > 0) stringResource(R.string.storage_tools_unused, gb(unused)) else pluralStringResource(R.plurals.storage_tools_count, report.tools.size, report.tools.size),
if (unused > 0) stringResource(R.string.storage_tools_unused, gb(unused)) else pluralStringResource(R.plurals.storage_tools_count, report.tools, report.tools),
report.buckets.getValue(Bucket.TOOLS), m, attention = unused > 0) { onOpen("tools") }
},
{ m ->
val unusedComponents = report.unusedComponents.sumOf { it.bytes }
val unusedComponents = report.unusedComponents
BucketCard(Bucket.COMPONENTS, Icons.Outlined.Extension, stringResource(R.string.storage_components),
if (unusedComponents > 0) stringResource(R.string.storage_tools_unused, gb(unusedComponents))
else pluralStringResource(R.plurals.storage_components_count, report.components.size, report.components.size),
else pluralStringResource(R.plurals.storage_components_count, report.components, report.components),
report.buckets.getValue(Bucket.COMPONENTS), m, attention = unusedComponents > 0) { onOpen("components") }
},
{ m ->
BucketCard(Bucket.STORES, Icons.Outlined.ShoppingBag, stringResource(R.string.storage_stores),
pluralStringResource(R.plurals.storage_games_installed, report.storeGames.size, report.storeGames.size),
pluralStringResource(R.plurals.storage_games_installed, report.storeGames, report.storeGames),
report.buckets.getValue(Bucket.STORES), m) { onOpen("stores") }
},
{ m ->
BucketCard(Bucket.DESKTOP, Icons.Outlined.Monitor, stringResource(R.string.storage_desktop),
pluralStringResource(R.plurals.storage_desktop_apps, report.flatpakApps.size, report.flatpakApps.size) +
" · " + stringResource(R.string.storage_desktop_shared, gb(report.flatpakRuntimes + report.flatpakCache)),
pluralStringResource(R.plurals.storage_desktop_apps, report.flatpakApps, report.flatpakApps) +
" · " + stringResource(R.string.storage_desktop_shared, gb(report.flatpakShared)),
report.buckets.getValue(Bucket.DESKTOP), m) { onOpen("desktop") }
},
{ m ->
val clearable = report.systemClearable + agentBytes().sumOf { it.second }
BucketCard(Bucket.SYSTEM, Icons.Outlined.Storage, stringResource(R.string.storage_system),
stringResource(R.string.storage_system_hint), report.buckets.getValue(Bucket.SYSTEM), m, locked = true)
if (clearable >= ONE_MB) stringResource(R.string.storage_system_clearable, gb(clearable)) else stringResource(R.string.storage_system_hint),
report.buckets.getValue(Bucket.SYSTEM), m) { onOpen("system") }
},
{ m ->
BucketCard(Bucket.DROIDDECK, Icons.Outlined.Folder, stringResource(R.string.storage_app_data),
@@ -397,7 +407,7 @@ private fun bucketLabel(bucket: Bucket) = stringResource(when (bucket) {
})
@Composable
private fun UsageBar(report: StorageReport, modifier: Modifier) {
private fun UsageBar(report: StorageSummary, modifier: Modifier) {
val total = report.total.coerceAtLeast(1).toFloat()
val other = (report.total - report.free - report.droiddeck).coerceAtLeast(0)
Row(modifier.fillMaxWidth().height(14.dp).clip(RoundedCornerShape(7.dp)).background(Color(0xFF0A0C0F))) {
@@ -532,6 +542,7 @@ private fun CleanRow(item: CleanItem, report: StorageReport, on: Boolean, modifi
CleanItem.UNUSED_CUSTOM -> Triple(custom.joinToString(", ") { it.name }, stringResource(R.string.storage_item_custom_detail), 1)
CleanItem.UNUSED_COMPONENTS -> Triple(stringResource(R.string.storage_item_components), unusedLabels.joinToString(", "), 1)
CleanItem.SHADERS -> Triple(stringResource(R.string.storage_item_shaders), stringResource(R.string.storage_item_shaders_detail), 2)
CleanItem.SYSTEM_CACHES -> Triple(stringResource(R.string.storage_item_system_caches), stringResource(R.string.storage_item_system_caches_detail), 0)
}
ToggleRow(
title, detail, StorageState.bytes(report, item), on, modifier,
@@ -962,7 +973,7 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
}
if (safe.isNotEmpty()) add(DataTarget("safe", safeLabel, safe.mapNotNull { l -> l.prefix?.let { it to l.prefixBytes } }, safe.mapNotNull { l -> l.shaders?.let { it to l.bytes - l.prefixBytes } }))
unsure.forEach { l -> add(DataTarget("left:${leftoverKey(l)}", unsureNames[leftoverKey(l)].orEmpty(), listOfNotNull(l.prefix?.let { it to l.prefixBytes }), listOfNotNull(l.shaders?.let { it to l.bytes - l.prefixBytes }))) }
kept.filter { it.owner == PrefixOwner.SHARED || it.owner == PrefixOwner.GAME }
kept.filter { StorageState.keptRemovable(report, it) }
.forEach { k -> add(DataTarget("kept:${k.dir.path}", keptNames[k.dir.path].orEmpty(), listOf(k.dir to k.bytes), listOfNotNull(k.shaders?.let { it to k.shaderBytes }))) }
}.associateBy { it.key }
val chosen = picked.mapNotNull { targets[it] }
@@ -1019,7 +1030,8 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
SectionTitle(stringResource(R.string.storage_data_other), gb(kept.sumOf { it.bytes + it.shaderBytes }))
ListCard {
kept.forEachIndexed { i, k ->
val resettable = k.owner == PrefixOwner.SHARED || k.owner == PrefixOwner.GAME
val removable = StorageState.keptRemovable(report, k)
val reset = k.owner == PrefixOwner.SHARED || k.owner == PrefixOwner.GAME
val key = "kept:${k.dir.path}"
ItemRow(
keptName(k),
@@ -1028,13 +1040,14 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
PrefixOwner.LAUNCHER -> if (k.users.isEmpty()) stringResource(R.string.storage_launcher_prefix)
else stringResource(R.string.storage_launcher_used_by, k.users.distinct().joinToString(", "))
PrefixOwner.GAME -> stringResource(R.string.storage_prefix_shaders, gb(k.bytes), gb(k.shaderBytes))
PrefixOwner.UNKNOWN -> stringResource(R.string.storage_unknown_prefix_detail)
PrefixOwner.UNKNOWN -> stringResource(R.string.storage_leftover_unsure_detail)
}, k.shaderBytes.takeIf { it >= ONE_MB && k.owner != PrefixOwner.GAME }?.let { stringResource(R.string.storage_bulk_shaders) + " " + gb(it).replace(' ', ' ') }).joinToString(" · "),
k.bytes + k.shaderBytes, i == kept.lastIndex,
pill = if (k.owner == PrefixOwner.LAUNCHER) { { Pill(stringResource(R.string.storage_tag_required), MaterialTheme.colorScheme.onSurfaceVariant) } } else null,
selected = if (resettable) key in picked else null, slot = true, selectable = !busy, onSelect = { toggle(key) },
action = if (resettable) {
{ SecondaryButton(stringResource(R.string.storage_reset_prefix), compact = true, enabled = !busy) { confirmKept = k } }
pill = if (!removable) { { Pill(stringResource(R.string.storage_tag_required), MaterialTheme.colorScheme.onSurfaceVariant) } }
else if (k.owner == PrefixOwner.UNKNOWN) { { Pill(stringResource(R.string.storage_tag_saves), AttentionAmber) } } else null,
selected = if (removable) key in picked else null, slot = true, selectable = !busy, onSelect = { toggle(key) },
action = if (removable) {
{ SecondaryButton(stringResource(if (reset) R.string.storage_reset_prefix else R.string.storage_remove), compact = true, enabled = !busy) { confirmKept = k } }
} else null,
)
}
@@ -1051,11 +1064,16 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
onDismiss = { confirmBulk = false },
)
confirmKept?.let { k ->
val reset = k.owner == PrefixOwner.SHARED || k.owner == PrefixOwner.GAME
ConfirmDialog(
stringResource(R.string.storage_reset_prefix_title, keptName(k)),
if (k.owner == PrefixOwner.SHARED) stringResource(R.string.storage_reset_shared_confirm, gb(k.bytes))
else stringResource(R.string.storage_reset_prefix_confirm, gb(k.bytes), k.library),
stringResource(R.string.storage_reset_prefix),
stringResource(if (reset) R.string.storage_reset_prefix_title else R.string.storage_remove_title, keptName(k)),
when (k.owner) {
PrefixOwner.SHARED -> stringResource(R.string.storage_reset_shared_confirm, gb(k.bytes))
PrefixOwner.GAME -> stringResource(R.string.storage_reset_prefix_confirm, gb(k.bytes), k.library)
PrefixOwner.LAUNCHER -> stringResource(R.string.storage_remove_launcher_confirm, gb(k.bytes + k.shaderBytes))
PrefixOwner.UNKNOWN -> stringResource(R.string.storage_leftover_confirm, gb(k.bytes + k.shaderBytes))
},
stringResource(if (reset) R.string.storage_reset_prefix else R.string.storage_remove),
onConfirm = { StorageState.resetKept(ctx, k) }, onDismiss = { confirmKept = null },
)
}
@@ -1181,6 +1199,93 @@ private fun StoreGamesView(report: StorageReport, sessionRunning: Boolean, onBac
}
}
/** What the Agent tab added to the Linux userland, with sizes once measured. */
private fun agentBytes(): List<Pair<AgentStorage.Item, Long>> =
AgentStorage.Item.entries.mapNotNull { item -> AgentStorage.sizes[item]?.takeIf { it >= ONE_MB }?.let { item to it } }
private fun cacheName(kind: SystemCache) = when (kind) {
SystemCache.TEMP -> R.string.storage_cache_temp
SystemCache.PACKAGES -> R.string.storage_cache_packages
SystemCache.STEAM_WEB -> R.string.storage_cache_steam_web
SystemCache.STEAM_CORRUPT -> R.string.storage_cache_steam_corrupt
}
/**
* The Linux system bucket opened up: caches that come back on their own, what the Agent tab installed, and the rest,
* which runs everything and stays.
*/
@Composable
private fun SystemView(report: StorageReport, sessionRunning: Boolean, onBack: () -> Unit) {
val ctx = LocalContext.current
val busy = sessionRunning || StorageState.busy
var confirmAgent by remember { mutableStateOf<AgentStorage.Item?>(null) }
var confirmCheckout by remember { mutableStateOf<com.droiddeck.launcher.storage.CheckoutUsage?>(null) }
val removing = AgentStorage.removing.size
var wasRemoving by remember { mutableStateOf(false) }
LaunchedEffect(removing) {
if (wasRemoving && removing == 0) StorageState.refresh(ctx, force = true)
wasRemoving = removing > 0
}
val caches = report.systemCaches.sortedByDescending { it.bytes }
val agent = agentBytes().sortedByDescending { it.second }
val checkouts = report.checkouts.filter { it.bytes >= ONE_MB }
val agentTotal = agent.sumOf { it.second } + checkouts.sumOf { it.bytes }
val rest = (report.buckets.getValue(Bucket.SYSTEM) - report.systemCacheBytes - agentTotal).coerceAtLeast(0)
SubHeader(stringResource(R.string.storage_system), stringResource(R.string.storage_system_clearable, gb(report.systemCacheBytes + agentTotal)), onBack) {
if (caches.isNotEmpty()) PrimaryButton(stringResource(R.string.storage_free_button, gb(report.systemCacheBytes)), compact = true, enabled = !busy) {
StorageState.clean(ctx, setOf(CleanItem.SYSTEM_CACHES)) { }
}
}
ActionStatus()
if (sessionRunning) { Note(stringResource(R.string.storage_session_running)); Spacer(Modifier.height(4.dp)) }
if (caches.isNotEmpty()) {
SectionTitle(stringResource(R.string.storage_item_system_caches), gb(report.systemCacheBytes))
ListCard {
caches.forEachIndexed { i, c ->
ItemRow(stringResource(cacheName(c.kind)), stringResource(R.string.storage_cache_detail), c.bytes, i == caches.lastIndex,
pill = { Pill(stringResource(R.string.storage_tag_safe), LocalPalette.current.good) },
action = { SecondaryButton(stringResource(R.string.storage_clear), compact = true, enabled = !busy) { StorageState.clearSystemCache(ctx, c.kind) } })
}
}
}
if (agent.isNotEmpty() || checkouts.isNotEmpty()) {
SectionTitle(stringResource(R.string.rail_agent), gb(agentTotal))
ListCard {
agent.forEachIndexed { i, (item, bytes) ->
ItemRow(stringResource(agentStorageTitle(item)), stringResource(agentStorageWarning(item)), bytes, i == agent.lastIndex && checkouts.isEmpty(),
action = {
SecondaryButton(stringResource(R.string.storage_remove), compact = true,
enabled = AgentStorage.removing[item] != true && AgentHost.state != AgentHost.State.WORKING) { confirmAgent = item }
})
}
checkouts.forEachIndexed { i, c ->
ItemRow(c.dir.name, stringResource(R.string.agent_storage_source_warning), c.bytes, i == checkouts.lastIndex,
action = {
SecondaryButton(stringResource(R.string.storage_remove), compact = true,
enabled = !busy && AgentHost.state != AgentHost.State.WORKING) { confirmCheckout = c }
})
}
}
}
SectionTitle(stringResource(R.string.storage_in_use), gb(rest))
ListCard {
ItemRow(stringResource(R.string.storage_system), stringResource(R.string.storage_system_hint), rest, true,
action = { Icon(Icons.Outlined.Lock, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(16.dp)) })
}
confirmAgent?.let { item ->
ConfirmDialog(
stringResource(R.string.storage_remove_title, stringResource(agentStorageTitle(item))), stringResource(agentStorageWarning(item)),
stringResource(R.string.storage_remove), onConfirm = { AgentStorage.remove(ctx, item) }, onDismiss = { confirmAgent = null },
)
}
confirmCheckout?.let { c ->
ConfirmDialog(
stringResource(R.string.storage_remove_title, c.dir.name), stringResource(R.string.agent_storage_source_warning),
stringResource(R.string.storage_remove), onConfirm = { StorageState.removeCheckout(ctx, c.dir) }, onDismiss = { confirmCheckout = null },
)
}
}
@Composable
internal fun ComponentsView(report: StorageReport, sessionRunning: Boolean, onBack: () -> Unit) {
val ctx = LocalContext.current
@@ -92,6 +92,7 @@ import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.automirrored.filled.Login
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.foundation.basicMarquee
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Download
@@ -153,41 +154,10 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
val focusManager = LocalFocusManager.current
val narrow = LocalNarrowPane.current
val padH = if (narrow) 14.dp else 22.dp
val tabs = remember {
androidx.compose.runtime.mutableStateListOf<StoreTab>().apply {
SessionPrefs.settleStoresTabOrder(ctx, Store.entries.map { it.id })
addAll(arrangeStoreTabs(SessionPrefs.storesTabOrder(ctx), SessionPrefs.storesTabHidden(ctx)))
}
}
remember { StoreTabsState.load(ctx) }
val tabs = StoreTabsState.tabs
var chip by rememberSaveable { mutableStateOf(tabs.firstOrNull { it.shown }?.store?.id ?: Store.GOG.id) }
var arranging by remember { mutableStateOf(false) }
val shownStores = tabs.filter { it.shown }.map { it.store }
fun commitTabs(markCustomized: Boolean = false) {
SessionPrefs.saveStoresTabs(ctx, tabs.map { it.store.id }, tabs.filterNot { it.shown }.map { it.store.id }.toSet(), markCustomized)
}
fun shiftTab(store: Store, delta: Int) {
val from = tabs.indexOfFirst { it.store == store }
val to = from + delta
if (from < 0 || to !in tabs.indices) return
tabs.add(to, tabs.removeAt(from))
commitTabs(markCustomized = true)
}
fun moveTab(store: Store, to: Int) {
val from = tabs.indexOfFirst { it.store == store }
if (from < 0) return
val target = to.coerceIn(0, tabs.lastIndex)
if (target == from) return
tabs.add(target, tabs.removeAt(from))
commitTabs(markCustomized = true)
}
fun toggleTab(store: Store) {
val i = tabs.indexOfFirst { it.store == store }
if (i < 0) return
val show = !tabs[i].shown
if (!show && tabs.count { it.shown } <= 1) return
tabs[i] = tabs[i].copy(shown = show)
commitTabs()
}
LaunchedEffect(tabs.map { it.store to it.shown }, chip) {
val picked = Store.byId(chip) ?: return@LaunchedEffect
if (tabs.none { it.store == picked && it.shown }) chip = tabs.firstOrNull { it.shown }?.store?.id ?: chip
@@ -261,18 +231,8 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
if (chip != st.id) pickChip(st.id) else move("first")
}
BackHandler(enabled = openGame != null) { closeGame() }
BackHandler(enabled = arranging) { arranging = false }
var contentFocused by remember { mutableStateOf(false) }
BackHandler(enabled = contentFocused && openGame == null && !arranging) { move("item:storechip:$chip") }
LaunchedEffect(arranging) {
val focus = ff ?: return@LaunchedEffect
if (!arranging || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
repeat(45) {
androidx.compose.runtime.withFrameNanos { }
val req = tabs.firstOrNull()?.let { focus.items["storechip:${it.store.id}"] } ?: return@repeat
if (runCatching { req.requestFocus() }.isSuccess) return@LaunchedEffect
}
}
BackHandler(enabled = contentFocused && openGame == null) { move("item:storechip:$chip") }
val scroll = rememberScrollState()
val detailScroll = rememberScrollState()
LaunchedEffect(chip) { scroll.scrollTo(0); grid.scrollToItem(0) }
@@ -316,28 +276,16 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
Box(modifier.onGloballyPositioned { hostAt = it.positionInRoot() }) {
Column(
modifier = Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp)
.then(if (openGame != null && !arranging) Modifier else Modifier.bumpers(
onPrevious = {
val picked = Store.byId(focusedChip)
if (arranging) { if (picked != null) shiftTab(picked, -1) } else cycleStore(-1)
},
onNext = {
val picked = Store.byId(focusedChip)
if (arranging) { if (picked != null) shiftTab(picked, 1) } else cycleStore(1)
},
)),
.then(if (openGame != null) Modifier else Modifier.bumpers(onPrevious = { cycleStore(-1) }, onNext = { cycleStore(1) })),
) {
Box(Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
StoreTheme(Store.byId(focusedChip ?: chip)) {
Rise(0) {
StoreChips(
chip, focusedChip, tabs, arranging,
chip, focusedChip, tabs,
onStore = { st -> openModes(st) },
onFocusChip = { focusedChip = it },
onArrangeDone = { arranging = false },
onMoveTab = { st, to -> moveTab(st, to) },
onToggleTab = { toggleTab(it) },
onSettings = { at -> if (at != null) StoresMotion.ask(storesSettingsStep(at, liveState, a, pal.signal) { arranging = true }) },
onSettings = { at -> if (at != null) StoresMotion.ask(storesSettingsStep(at, liveState, a, pal.signal) { ManageStores.custom = false; ManageStores.open = true }) },
)
}
}
@@ -492,13 +440,6 @@ internal fun SignInFloodLayer(hostAt: Offset) {
}
private class ChipDrag {
var store by mutableStateOf<Store?>(null)
var from by mutableIntStateOf(-1)
var target by mutableIntStateOf(-1)
var x by mutableFloatStateOf(0f)
}
@Composable
private fun StoreDot(store: Store, signedIn: Boolean) {
val c = sourceColours(store.id)
@@ -510,106 +451,30 @@ private fun StoreDot(store: Store, signedIn: Boolean) {
)
}
@Composable
private fun RowScope.ArrangeStoreChip(
tab: StoreTab, index: Int, last: Int, gapPx: Float, drag: ChipDrag,
onFocusChip: (String?) -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit,
) {
val store = tab.store
val box = remember(store) { mutableFloatStateOf(0f) }
val pitch = box.floatValue + gapPx
val held = drag.store == store
val lift by animateFloatAsState(if (held) 1f else 0f, Motion.sp(0.7f, Spring.StiffnessMediumLow), label = "chipLift")
val shift by animateFloatAsState(
when {
drag.store == null || held -> 0f
drag.from < index && drag.target >= index -> -pitch
drag.from > index && drag.target <= index -> pitch
else -> 0f
},
Motion.sp(0.6f, Spring.StiffnessMediumLow), label = "chipShift",
)
val pill = remember { RoundedCornerShape(99.dp) }
val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true
fun reset() {
drag.store = null
drag.from = -1
drag.target = -1
drag.x = 0f
}
fun commit() {
val from = drag.from
val to = drag.target
reset()
if (from >= 0 && to >= 0 && to != from) onMoveTab(store, to)
}
StoreChip(
label = store.shortLabel, on = false, under = false, key = store.id, mark = sourceColours(store.id).dot, lift = lift,
modifier = Modifier.weight(1f)
.zIndex(if (held) 2f else 0f)
.onSizeChanged { box.floatValue = it.width.toFloat() }
.graphicsLayer {
translationX = if (held) drag.x else shift
shadowElevation = 14.dp.toPx() * lift
shape = pill
clip = false
}
.pointerInput(store, index) {
detectDragGestures(
onDragStart = {
drag.store = store
drag.from = index
drag.target = index
drag.x = 0f
},
onDragEnd = { commit() },
onDragCancel = { reset() },
) { change, amount ->
change.consume()
val step = box.floatValue + gapPx
if (step <= 0f) return@detectDragGestures
drag.x = (drag.x + amount.x).coerceIn(-drag.from * step, (last - drag.from) * step)
drag.target = (drag.from + (drag.x / step).roundToInt()).coerceIn(0, last)
}
}
.alpha(if (tab.shown) 1f else 0.32f),
lead = { StoreDot(store, signedIn) },
onFocused = onFocusChip,
) { onToggleTab(store) }
}
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun StoreChips(
selected: String, focused: String?, tabs: List<StoreTab>, arranging: Boolean,
selected: String, focused: String?, tabs: List<StoreTab>,
onStore: (Store) -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit,
onArrangeDone: () -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit,
) {
val pal = LocalPalette.current
val keys = tabs.filter { it.shown }.map { it.store.id }
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, Rect>() }
val highlighted = focused ?: selected
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode
val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard && !arranging
val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard
val tint = androidx.compose.animation.animateColorAsState(
Store.byId(highlighted)?.let { sourceColours(it.id).dot } ?: pal.signal, Motion.tw(160), label = "chipTint",
)
val gap = 8.dp
val gapPx = with(androidx.compose.ui.platform.LocalDensity.current) { gap.toPx() }
val drag = remember { ChipDrag() }
val tabScroll = rememberScrollState()
Box(Modifier.fillMaxWidth()) {
Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Box(Modifier.weight(1f).then(if (arranging) Modifier else Modifier.edgeFade(tabScroll).horizontalScroll(tabScroll))) {
Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically,
modifier = (if (arranging) Modifier.fillMaxWidth() else Modifier).focusGroup(),
) {
Box(Modifier.weight(1f).edgeFade(tabScroll).horizontalScroll(tabScroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (tab in tabs) {
val store = tab.store
if (arranging) {
val index = tabs.indexOfFirst { it.store == store }
key(store) { ArrangeStoreChip(tab, index, tabs.lastIndex, gapPx, drag, onFocusChip, onMoveTab, onToggleTab) }
} else if (tab.shown) {
if (tab.shown) {
val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true
key(store) {
val reveal = remember { BringIntoViewRequester() }
@@ -627,23 +492,19 @@ private fun StoreChips(
}
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
if (arranging) {
IconChip(Icons.Filled.Check, stringResource(R.string.stores_tabs_arrange_done)) { onArrangeDone() }
} else {
var cogAt by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) {
IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) }
}
var cogAt by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) {
IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) }
}
}
}
}
@Composable
private fun StoreChip(
internal fun StoreChip(
label: String?, on: Boolean, under: Boolean, key: String, mark: Color, modifier: Modifier, lead: @Composable () -> Unit,
trail: (@Composable () -> Unit)? = null, description: String? = null, lift: Float = 0f,
onFocused: (String?) -> Unit = {}, onClick: () -> Unit,
onFocused: (String?) -> Unit = {}, paneKey: String = "storechip:$key", onClick: () -> Unit,
) {
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
val colors = MaterialTheme.colorScheme
@@ -662,7 +523,7 @@ private fun StoreChip(
}
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
modifier = modifier.paneItem("storechip:$key")
modifier = modifier.paneItem(paneKey)
.onFocusChanged { f ->
if (f.isFocused && inputMode.inputMode == androidx.compose.ui.input.InputMode.Keyboard) onFocused(key)
else if (!f.isFocused) onFocused(null)
@@ -710,62 +571,66 @@ internal fun CountPill(count: Int) {
@Composable
private fun SignInCard(store: Store, height: Dp) {
/** [inert]: shown in a Library preview, where signing in would act on the real account; the button only says so. */
internal fun SignInCard(store: Store, height: Dp, inert: Boolean = false) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val c = sourceColours(store.id)
LaunchedEffect(store) { StoresState.preview(ctx, store) }
val art = remember(StoresState.shelves[store]) {
val shelves = StoresState.shelves[store]
val urls = (shelves?.art?.takeIf { it.isNotEmpty() }
?: shelves?.all.orEmpty().filter { !it.mature && !it.owned }.mapNotNull { it.tallImageUrl ?: it.imageUrl }).distinct().take(48)
when {
urls.size >= 8 -> urls
urls.size >= 4 -> urls + urls.drop(urls.size / 2) + urls.take(urls.size / 2)
else -> emptyList()
}
wallTiles(
shelves?.art?.takeIf { it.isNotEmpty() }
?: shelves?.all.orEmpty().filter { !it.mature && !it.owned }.mapNotNull { it.tallImageUrl ?: it.imageUrl },
)
}
HeroWallCard(store.label, art, sourceColours(store.id), height) { SignInButton(store, large = true, inert = inert) }
}
/** Repeats a short cover list so the wall has enough tiles to drift; too few covers leave it to the blank capsules. */
internal fun wallTiles(urls: List<Any>): List<Any> {
val u = urls.distinct().take(48)
return when {
u.size >= 8 -> u
u.size >= 4 -> u + u.drop(u.size / 2) + u.take(u.size / 2)
else -> emptyList()
}
}
/** Full-height splash used where a tab has nothing to list yet: a drifting cover wall, the shared wall fade, a title and one action. */
@Composable
internal fun HeroWallCard(title: String, art: List<Any>, c: SourceColours, height: Dp, modifier: Modifier = Modifier, action: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val shape = RoundedCornerShape(20.dp)
val blank = WallCapsule(Brush.linearGradient(listOf(c.fill, colors.background)), edge = c.dot.copy(alpha = 0.22f))
val ground = SolidColor(c.fill)
Box(Modifier.fillMaxWidth().heightIn(min = height.coerceAtLeast(0.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) {
androidx.compose.animation.Crossfade(art, animationSpec = Motion.tw(600), label = "signInWall", modifier = Modifier.matchParentSize()) { tiles ->
Box(modifier.fillMaxWidth().heightIn(min = height.coerceAtLeast(0.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) {
androidx.compose.animation.Crossfade(art, animationSpec = Motion.tw(600), label = "heroWall", modifier = Modifier.matchParentSize()) { tiles ->
TiltedWall(tiles.size, if (tiles.isEmpty()) 75_000 else 50_000) { i -> if (tiles.isEmpty()) blank else WallCapsule(ground, tiles[i]) }
}
Box(
Modifier.matchParentSize().background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.97f), 0.45f to colors.background.copy(alpha = 0.9f),
0.78f to colors.background.copy(alpha = 0.35f), 1f to colors.background.copy(alpha = 0.15f),
),
),
)
Box(Modifier.matchParentSize().background(Brush.verticalGradient(0.5f to Color.Transparent, 1f to colors.background.copy(alpha = 0.92f))))
WallFade(Modifier.matchParentSize())
Box(
Modifier.matchParentSize().drawBehind {
drawRect(Brush.radialGradient(listOf(c.dot.copy(alpha = 0.22f), Color.Transparent), center = Offset(size.width * 0.16f, size.height * 0.9f), radius = size.height * 0.75f))
},
)
Column(
verticalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.align(Alignment.BottomStart).padding(start = if (narrow) 20.dp else 40.dp, bottom = if (narrow) 20.dp else 36.dp, end = 20.dp),
) {
Rise(2) {
Text(
store.label, fontSize = if (narrow) 30.sp else 42.sp, lineHeight = if (narrow) 34.sp else 46.sp,
title, fontSize = if (narrow) 30.sp else 42.sp, lineHeight = if (narrow) 34.sp else 46.sp,
fontWeight = FontWeight.Black, color = colors.onBackground,
)
}
Spacer(Modifier.height(6.dp))
Rise(3) { SignInButton(store, large = true) }
Rise(3) { action() }
}
}
}
@Composable
private fun SignInButton(store: Store, large: Boolean = false) {
private fun SignInButton(store: Store, large: Boolean = false, inert: Boolean = false) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
@@ -773,12 +638,8 @@ private fun SignInButton(store: Store, large: Boolean = false) {
if (askKey) ItchKeyDialog { askKey = false }
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
PrimaryButton(stringResource(R.string.stores_signin), main = true, large = large, icon = if (large) Icons.AutoMirrored.Filled.Login else null) {
if (store == Store.ITCH) askKey = true
else {
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot()
if (at == null || Motion.scale == 0f || StoresMotion.signIn != null) StoresState.signIn(ctx, store)
else StoresMotion.signIn = SignInFlood(store, at, colors.primary, sourceColours(store.id).dot)
}
if (inert) android.widget.Toast.makeText(ctx, R.string.dev_preview_read_only, android.widget.Toast.LENGTH_SHORT).show()
else startStoreSignIn(ctx, store, placed[0]?.takeIf { it.isAttached }?.boundsInRoot(), colors.primary) { askKey = true }
}
}
}
@@ -804,7 +665,7 @@ private fun Storefront(
LaunchedEffect(store, q) { StoresState.search(ctx, store, q) }
val gameJolt = store == Store.GAMEJOLT
LaunchedEffect(gameJolt, s.storesShowMature) { if (gameJolt) GameJoltBrowseState.sync(ctx, s.storesShowMature) }
val browsing = q.isEmpty() && ((store == Store.ITCH && ItchBrowseState.active) || gameJolt)
val browsing = q.isEmpty() && (store == Store.ITCH || gameJolt)
val browseItems = if (!browsing) emptyList() else if (gameJolt) GameJoltBrowseState.items else ItchBrowseState.items
val catalog = store == Store.BATTLENET && q.isEmpty()
val visible = remember(found, library, shelves, q, s.storesShowMature, browsing, browseItems, catalog) {
@@ -927,16 +788,13 @@ private fun ProfileStrip(store: Store, owned: Int, loaded: Boolean, s: FrontEndS
}
Column(Modifier.weight(1f)) {
Text(name.ifEmpty { store.label }, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (loaded) store.shortLabel + " · " + androidx.compose.ui.res.pluralStringResource(R.plurals.mode_added_count, owned, owned) else store.label,
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
Actions {
SmallTextButton(stringResource(R.string.stores_owned_in_library), key = "owned-in-library") {
if (loaded) OwnedLink(store.shortLabel + " · " + androidx.compose.ui.res.pluralStringResource(R.plurals.mode_added_count, owned, owned)) {
LibraryView.showOwned(ctx, store)
show("games")
}
else Text(store.label, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Actions {
SmallTextButton(stringResource(R.string.stores_refresh)) { StoresState.open(ctx, store, force = true) }
if (store == Store.XBOX) SmallTextButton(stringResource(R.string.stores_xbox_cloud_settings), key = "xbox-cloud-settings") {
ctx.startActivity(android.content.Intent(ctx, com.droiddeck.launcher.stores.xbox.XboxCloudSettingsActivity::class.java))
@@ -949,6 +807,28 @@ private fun ProfileStrip(store: Store, owned: Int, loaded: Boolean, s: FrontEndS
}
}
@Composable
private fun OwnedLink(label: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(8.dp)
val description = stringResource(R.string.stores_owned_in_library)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp),
modifier = Modifier.paneItem("owned-in-library").testTag("owned-in-library").clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, Color.Transparent)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClickLabel = description, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(start = 2.dp, end = 4.dp, top = 2.dp, bottom = 2.dp),
) {
Text(label, fontSize = 12.sp, color = if (hot) colors.onBackground else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, description, tint = if (hot) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
@Composable
private fun BattleNetLauncherRow(s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
@@ -1385,7 +1265,25 @@ internal fun ProgressBarThin(fraction: Float, paused: Boolean = false, verify: B
internal fun downloadLabel(d: com.droiddeck.launcher.stores.download.DownloadEntry): String = when (d.state) {
DownloadState.PAUSED -> stringResource(R.string.stores_dl_paused)
DownloadState.QUEUED -> stringResource(R.string.stores_dl_queued)
else -> if (d.stageFraction >= 0f) stringResource(R.string.stores_dl_active_percent, activeStageLabel(d), d.percent) else activeStageLabel(d)
else -> when {
d.streaming -> stringResource(R.string.stores_dl_active_percent, stringResource(R.string.stores_stage_installing), (d.installFraction * 100).toInt())
d.stageFraction >= 0f -> stringResource(R.string.stores_dl_active_percent, activeStageLabel(d), d.percent)
else -> activeStageLabel(d)
}
}
@Composable
internal fun steadyProgress(d: com.droiddeck.launcher.stores.download.DownloadEntry): Float {
val best = androidx.compose.runtime.remember(d.key) { floatArrayOf(0f) }
best[0] = maxOf(best[0], d.overallFraction)
return best[0]
}
@Composable
internal fun steadyLabel(d: com.droiddeck.launcher.stores.download.DownloadEntry, progress: Float): String = when (d.state) {
DownloadState.QUEUED -> stringResource(R.string.stores_dl_queued)
DownloadState.PAUSED -> stringResource(R.string.stores_dl_active_percent, stringResource(R.string.stores_dl_paused), (progress * 100).toInt())
else -> stringResource(R.string.stores_dl_active_percent, stringResource(R.string.stores_stage_installing), (progress * 100).toInt())
}
@Composable
@@ -81,7 +81,6 @@ internal fun TabsSettingsGroup(host: MenuHost, s: FrontEndState, a: FrontEndActi
androidx.compose.runtime.withFrameNanos { }
reveal.bringIntoView()
}
val pad = LocalInputModeManager.current.inputMode == InputMode.Keyboard
val state by rememberUpdatedState(s)
val rows = {
val keys = NavTabs.listed(state)
@@ -95,98 +94,113 @@ internal fun TabsSettingsGroup(host: MenuHost, s: FrontEndState, a: FrontEndActi
NavTabs.setHidden(ctx, key, !show)
}
Box(Modifier.bringIntoViewRequester(reveal)) {
SettingsGroup(stringResource(R.string.setup_group_tabs)) {
SortableRows(
rows = rows, commit = commit, movable = { it != MORE_LINE }, rowHeight = TAB_ROW, handleWidth = TAB_HANDLE,
onActivate = { tab -> if (NavTabs.hideable(tab)) setShown(tab, NavTabs.place(state, tab) == TabPlace.HIDDEN) },
) { tab, held, offset, hint, modifier, onFocus ->
if (tab == MORE_LINE) MoreLine()
else TabRow(
tab, NavTabs.place(s, tab) != TabPlace.HIDDEN, NavTabs.hideable(tab), held, offset, hint, modifier, onFocus,
) { host.open = null; setShown(tab, it) }
}
}
}
}
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
internal fun SortableRows(
rows: () -> List<String>,
commit: (List<String>) -> Unit,
movable: (String) -> Boolean,
rowHeight: androidx.compose.ui.unit.Dp,
handleWidth: androidx.compose.ui.unit.Dp,
onActivate: (String) -> Unit,
row: @Composable (key: String, held: Boolean, offset: Float, hint: String?, modifier: Modifier, onFocus: (Boolean) -> Unit) -> Unit,
) {
val pad = LocalInputModeManager.current.inputMode == InputMode.Keyboard
var dragging by remember { mutableStateOf<String?>(null) }
var dragOffset by remember { mutableFloatStateOf(0f) }
var grabbed by remember { mutableStateOf<String?>(null) }
var before by remember { mutableStateOf<List<String>>(emptyList()) }
var focused by remember { mutableStateOf<String?>(null) }
val rowPx = with(LocalDensity.current) { TAB_ROW.toPx() }
val handlePx = with(LocalDensity.current) { TAB_HANDLE.toPx() }
val rowPx = with(LocalDensity.current) { rowHeight.toPx() }
val handlePx = with(LocalDensity.current) { handleWidth.toPx() }
val list = rows()
Box(Modifier.bringIntoViewRequester(reveal)) {
SettingsGroup(stringResource(R.string.setup_group_tabs)) {
Column(
Modifier.fillMaxWidth().pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
val start = (down.position.y / rowPx).toInt()
val key = rows().getOrNull(start)
if (key == null || key == MORE_LINE || down.position.x > handlePx || grabbed != null) return@awaitEachGesture
down.consume()
dragging = key
dragOffset = 0f
while (true) {
val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break
change.consume()
if (!change.pressed) break
val travel = change.position.y - down.position.y
val current = rows()
val target = (start + (travel / rowPx).roundToInt()).coerceIn(0, current.lastIndex)
var at = current.indexOf(key)
var next = current
while (target != at) {
next = moveTabRow(next, key, if (target > at) 1 else -1) ?: break
at = next.indexOf(key)
Column(
Modifier.fillMaxWidth().pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
val start = (down.position.y / rowPx).toInt()
val key = rows().getOrNull(start)
if (key == null || !movable(key) || down.position.x > handlePx || grabbed != null) return@awaitEachGesture
down.consume()
dragging = key
dragOffset = 0f
while (true) {
val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break
change.consume()
if (!change.pressed) break
val travel = change.position.y - down.position.y
val current = rows()
val target = (start + (travel / rowPx).roundToInt()).coerceIn(0, current.lastIndex)
var at = current.indexOf(key)
var next = current
while (target != at) {
next = moveTabRow(next, key, if (target > at) 1 else -1) ?: break
at = next.indexOf(key)
}
if (next !== current) commit(next)
dragOffset = travel - (at - start) * rowPx
}
dragging = null
dragOffset = 0f
}
},
) {
list.forEachIndexed { index, item ->
key(item) {
if (!movable(item)) row(item, false, 0f, null, Modifier) {}
else {
val bring = remember { BringIntoViewRequester() }
LaunchedEffect(index, grabbed) { if (grabbed == item) bring.bringIntoView() }
row(
item, item == dragging || item == grabbed, if (item == dragging) dragOffset else 0f,
if (pad && focused == item) stringResource(if (grabbed == item) R.string.hud_hint_drop else R.string.hud_hint_grab) else null,
Modifier.bringIntoViewRequester(bring).onPreviewKeyEvent { event ->
val e = event.nativeKeyEvent
val down = e.action == KeyEvent.ACTION_DOWN
val first = down && e.repeatCount == 0
val mine = grabbed == item
when (e.keyCode) {
KeyEvent.KEYCODE_BUTTON_Y -> {
if (first) {
if (mine) grabbed = null
else if (grabbed == null) { before = rows(); grabbed = item }
}
true
}
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> {
if (mine && down) moveTabRow(rows(), item, if (e.keyCode == KeyEvent.KEYCODE_DPAD_UP) -1 else 1)?.let(commit)
mine
}
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> mine
KeyEvent.KEYCODE_BUTTON_B, KeyEvent.KEYCODE_BACK -> {
if (mine && first) { commit(before); grabbed = null }
mine
}
KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_SPACE -> {
if (first) {
if (mine) grabbed = null else onActivate(item)
}
true
}
else -> false
}
if (next !== current) commit(next)
dragOffset = travel - (at - start) * rowPx
}
dragging = null
dragOffset = 0f
}
},
) {
list.forEachIndexed { index, tab ->
key(tab) {
if (tab == MORE_LINE) {
MoreLine()
} else {
val shown = NavTabs.place(s, tab) != TabPlace.HIDDEN
val held = tab == dragging || tab == grabbed
val bring = remember { BringIntoViewRequester() }
LaunchedEffect(index, grabbed) { if (grabbed == tab) bring.bringIntoView() }
TabRow(
tab, shown, NavTabs.hideable(tab), held,
offset = if (tab == dragging) dragOffset else 0f,
hint = if (pad && focused == tab) stringResource(if (grabbed == tab) R.string.hud_hint_drop else R.string.hud_hint_grab) else null,
modifier = Modifier.bringIntoViewRequester(bring)
.onPreviewKeyEvent { event ->
val e = event.nativeKeyEvent
val down = e.action == KeyEvent.ACTION_DOWN
val first = down && e.repeatCount == 0
val mine = grabbed == tab
when (e.keyCode) {
KeyEvent.KEYCODE_BUTTON_Y -> {
if (first) {
if (mine) grabbed = null
else if (grabbed == null) { before = rows(); grabbed = tab }
}
true
}
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> {
if (mine && down) moveTabRow(rows(), tab, if (e.keyCode == KeyEvent.KEYCODE_DPAD_UP) -1 else 1)?.let(commit)
mine
}
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> mine
KeyEvent.KEYCODE_BUTTON_B, KeyEvent.KEYCODE_BACK -> {
if (mine && first) { commit(before); grabbed = null }
mine
}
KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_SPACE -> {
if (first) {
if (mine) grabbed = null
else if (NavTabs.hideable(tab)) setShown(tab, !shown)
}
true
}
else -> false
}
},
onFocus = { if (it) focused = tab else if (focused == tab) { focused = null; if (grabbed == tab) grabbed = null } },
) { host.open = null; setShown(tab, it) }
}
}
},
) { if (it) focused = item else if (focused == item) { focused = null; if (grabbed == item) grabbed = null } }
}
}
}
@@ -41,6 +41,21 @@ class Palette(
val good: Color, val error: Color = Color(0xFFFF8A80),
)
data class CustomThemeColors(
val background: Int = 0xFF0A0B0D.toInt(),
val surface: Int = 0xFF121417.toInt(),
val surfaceVariant: Int = 0xFF1A1D22.toInt(),
val line: Int = 0xFF262A31.toInt(),
val line2: Int = 0xFF343A43.toInt(),
val onBackground: Int = 0xFFF2F4F7.toInt(),
val onSurfaceVariant: Int = 0xFF9AA3AF.toInt(),
val primary: Int = 0xFF1A9FFF.toInt(),
val onPrimary: Int = 0xFF03111F.toInt(),
val signal: Int = 0xFF1A9FFF.toInt(),
val good: Int = 0xFF4CD37F.toInt(),
val error: Int = 0xFFFF8A80.toInt(),
)
object Themes {
const val GRAPHITE = "graphite"
const val PAPER = "paper"
@@ -48,6 +63,7 @@ object Themes {
const val ELECTRIC = "electric"
const val INNER_GAMER = "inner_gamer"
const val GRADIENT = "gradient"
const val CUSTOM = "custom"
const val DEFAULT_PRIMARY = 0xFF8B5CF6.toInt()
const val DEFAULT_SECONDARY = 0xFF22D3EE.toInt()
@@ -55,6 +71,9 @@ object Themes {
var gradientColors by mutableStateOf(DEFAULT_PRIMARY to DEFAULT_SECONDARY)
private set
var customColors by mutableStateOf(CustomThemeColors())
private set
const val RGB_SPEEDS = 10
const val DEFAULT_RGB_SPEED = 3
const val RGB_HUE_STEP = 3f
@@ -87,6 +106,7 @@ object Themes {
gradientColors = SessionPrefs.gradientColors(context)
rgbSpeed = SessionPrefs.rgbSpeed(context)
trueBlackHighlight = SessionPrefs.trueBlackHighlight(context)
customColors = SessionPrefs.customThemeColors(context)
}
fun setTrueBlackHighlight(context: Context, highlight: Int) {
@@ -104,9 +124,51 @@ object Themes {
gradientColors = primary to secondary
}
fun setCustomColors(context: Context, colors: CustomThemeColors) {
SessionPrefs.setCustomThemeColors(context, colors)
customColors = colors
}
fun setCustomColor(context: Context, key: String, color: Int) {
val current = customColors
val updated = when (key) {
"background" -> current.copy(background = color)
"surface" -> current.copy(surface = color)
"surfaceVariant" -> current.copy(surfaceVariant = color)
"line" -> current.copy(line = color)
"line2" -> current.copy(line2 = color)
"onBackground" -> current.copy(onBackground = color)
"onSurfaceVariant" -> current.copy(onSurfaceVariant = color)
"primary" -> current.copy(primary = color)
"onPrimary" -> current.copy(onPrimary = color)
"signal" -> current.copy(signal = color)
"good" -> current.copy(good = color)
"error" -> current.copy(error = color)
else -> return
}
setCustomColors(context, updated)
}
private fun customPalette(colors: CustomThemeColors): Palette = Palette(
CUSTOM, R.string.theme_custom, R.string.theme_custom_detail,
background = Color(colors.background),
surface = Color(colors.surface),
surfaceVariant = Color(colors.surfaceVariant),
line = Color(colors.line),
line2 = Color(colors.line2),
onBackground = Color(colors.onBackground),
onSurfaceVariant = Color(colors.onSurfaceVariant),
primary = Color(colors.primary),
primary2 = Color(colors.primary),
onPrimary = Color(colors.onPrimary),
signal = Color(colors.signal),
good = Color(colors.good),
error = Color(colors.error),
)
fun current(context: Context): Palette {
val id = SessionPrefs.theme(context)
if (id == GRADIENT || id == INNER_GAMER || id == TRUE_BLACK) loadGradient(context)
if (id == GRADIENT || id == INNER_GAMER || id == TRUE_BLACK || id == CUSTOM) loadGradient(context)
return byId(id)
}
@@ -149,11 +211,13 @@ object Themes {
),
innerGamer(0f),
ThemeColors.palette(DEFAULT_PRIMARY, DEFAULT_SECONDARY, R.string.theme_gradient, R.string.theme_gradient_detail),
customPalette(customColors),
)
fun byId(id: String): Palette {
if (id == INNER_GAMER) return innerGamer(rgbHue)
if (id == TRUE_BLACK) return ThemeColors.trueBlack(trueBlackHighlight)
if (id == CUSTOM) return customPalette(customColors)
if (id == GRADIENT) return ThemeColors.palette(gradientColors.first, gradientColors.second, R.string.theme_gradient, R.string.theme_gradient_detail)
return all.firstOrNull { it.id == id } ?: all[0]
}
@@ -203,7 +267,6 @@ private val ContentDirected = Typography().run {
@Composable
private fun InnerGamerHue(speed: Int) {
if (Motion.scale == 0f) return
key(speed) { InnerGamerCycle(speed) }
}