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

+7 -3
View File
@@ -619,14 +619,18 @@ jobs:
export NDK="$ANDROID_HOME/ndk/$NDK_VERSION"
tools/syncthing/build.sh app/src/main/jniLibs/arm64-v8a
- name: Note when the proot pack pin is behind this build
- name: Check the proot pack pin against this build
run: |
set -euo pipefail
# shellcheck disable=SC1091
source tools/packs/proot/release.env
sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1)
if [ "$sha" != "$PROOT_PACK_SHA256" ]; then
echo "::warning::built proot pack $sha does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256). This build publishes the pack it just built. Source builds keep downloading the pinned pack until release.env is updated."
size=$(stat -c %s app/build/packs/proot.tar.zst)
if [ "$sha" != "$PROOT_PACK_SHA256" ] || [ "$size" != "$PROOT_PACK_SIZE" ]; then
level=warning
if [ "$GITHUB_EVENT_NAME" = pull_request ]; then level=error; fi
echo "::$level::built proot pack $sha ($size bytes) does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256, $PROOT_PACK_SIZE bytes). Source builds download the pinned pack, so set PROOT_PACK_SHA256=$sha and PROOT_PACK_SIZE=$size in tools/packs/proot/release.env."
if [ "$level" = error ]; then exit 1; fi
fi
- name: Check out MaliBridge
+2
View File
@@ -388,6 +388,8 @@ dependencies {
implementation 'androidx.compose.material3:material3'
implementation 'androidx.compose.ui:ui-tooling-preview'
debugImplementation 'androidx.compose.ui:ui-tooling'
// Declares the ComponentActivity that createComposeRule launches, for PreviewRenderTest.
debugImplementation 'androidx.compose.ui:ui-test-manifest'
implementation 'androidx.activity:activity-compose:1.8.2'
implementation 'androidx.compose.material:material-icons-extended'
implementation 'io.coil-kt:coil-compose:2.6.0'
@@ -0,0 +1,79 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.SecondScreenMode
/** The launcher as a whole: rail and page, opened on each tab through FrontEndState.navigate. */
@Composable
private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Library.SteamGame> = sampleGames, ready: Boolean = true) =
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
@DroidDeckPreviews @Composable private fun DownloadsPreview() = Launcher("downloads")
@DroidDeckPreviews @Composable private fun SettingsPreview() = Launcher("setup")
@DroidDeckPreviews @Composable private fun RuntimeMissingPreview() = Launcher("setup", ready = false)
/** The in-game menu on one page, as a session shows it. */
@Composable
private fun SessionMenu(page: SessionDrawerPage, steam: Boolean = true, desktop: Boolean = false) = PreviewHost {
SessionDrawer(true, page, controllerActive = true, onPageChange = {}, a = sampleDrawerActions(steam, desktop))
}
@DroidDeckPreviews @Composable private fun SessionMenuControllerPreview() = SessionMenu(SessionDrawerPage.CONTROLLER)
@DroidDeckPreviews @Composable private fun SessionMenuDisplayPreview() = SessionMenu(SessionDrawerPage.DISPLAY)
@DroidDeckPreviews @Composable private fun SessionMenuHudPreview() = SessionMenu(SessionDrawerPage.HUD)
@DroidDeckPreviews @Composable private fun SessionMenuSessionPreview() = SessionMenu(SessionDrawerPage.SESSION)
@DroidDeckPreviews @Composable private fun SessionMenuDesktopPreview() = SessionMenu(SessionDrawerPage.CONTROLLER, steam = false, desktop = true)
/** The in-game menu docked on the bottom screen, with the screen picker in its header. */
@Composable
private fun DockedMenu(page: SessionDrawerPage) = PreviewHost {
SessionDrawer(true, page, controllerActive = false, onPageChange = {},
a = sampleDrawerActions(secondScreen = SecondScreenMode.KEYBOARD_TRACKPAD), docked = true)
}
/** The bottom screen's bar on a panel: the panel's name is the screen picker. */
@Composable
private fun BottomPanelBar() = PreviewHost {
val modes = secondScreenModes(false, deckPad = false, dashboard = true, desktop = false)
Column(Modifier.fillMaxSize().background(Color.Black)) {
BottomScreenBar(BottomBarModel("Keyboard + trackpad", {}, {}, {}, {},
listOf(BarExtra("Keyboard", icon = R.drawable.ic_bottom_keyboard) {}),
picker = ScreenPicker(modes, SecondScreenMode.KEYBOARD_TRACKPAD, {}, onMenu = {})))
}
}
@DroidDeckPreviews @Composable private fun SessionMenuDockedPreview() = DockedMenu(SessionDrawerPage.CONTROLLER)
@DroidDeckPreviews @Composable private fun SessionMenuDockedDisplayPreview() = DockedMenu(SessionDrawerPage.DISPLAY)
@DroidDeckPreviews @Composable private fun BottomPanelBarPreview() = BottomPanelBar()
/** The Library and Stores tabs read store accounts, which load on a background thread. */
private val storesLoaded = { com.droiddeck.launcher.stores.StoresState.accountsLoaded }
/** Every preview above, for the render test. Add a case when adding a preview. */
internal val previewCases: List<PreviewCase> = listOf(
PreviewCase("steam-tab") { Launcher("steam") },
PreviewCase("library", storesLoaded) { Launcher("games") },
PreviewCase("library-empty", storesLoaded) { Launcher("games", games = emptyList()) },
PreviewCase("stores", storesLoaded) { Launcher("stores") },
PreviewCase("downloads") { Launcher("downloads") },
PreviewCase("settings") { Launcher("setup") },
PreviewCase("runtime-missing") { Launcher("setup", ready = false) },
PreviewCase("session-menu-controller") { SessionMenu(SessionDrawerPage.CONTROLLER) },
PreviewCase("session-menu-display") { SessionMenu(SessionDrawerPage.DISPLAY) },
PreviewCase("session-menu-hud") { SessionMenu(SessionDrawerPage.HUD) },
PreviewCase("session-menu-session") { SessionMenu(SessionDrawerPage.SESSION) },
PreviewCase("session-menu-desktop") { SessionMenu(SessionDrawerPage.CONTROLLER, steam = false, desktop = true) },
PreviewCase("session-menu-docked") { DockedMenu(SessionDrawerPage.CONTROLLER) },
PreviewCase("session-menu-docked-display") { DockedMenu(SessionDrawerPage.DISPLAY) },
PreviewCase("bottom-panel-bar") { BottomPanelBar() },
)
@@ -0,0 +1,88 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.droiddeck.launcher.frontend.Library
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
/**
* Debug-only support for Compose previews: the production theme around a screen, and sample state and no-op actions so
* production composables render without a device, a runtime or a network. See docs/compose-previews.md.
*/
/** The sizes the previews come in. The Duo's top screen is 1920x1080 at xhdpi, i.e. 960x540 dp. */
@Preview(name = "Handheld", widthDp = 960, heightDp = 540, device = "spec:width=960dp,height=540dp,dpi=320,orientation=landscape")
@Preview(name = "Portrait", widthDp = 540, heightDp = 960, device = "spec:width=540dp,height=960dp,dpi=320")
internal annotation class DroidDeckPreviews
@Composable
internal fun PreviewHost(content: @Composable () -> Unit) {
DroidDeckTheme {
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) { content() }
}
}
/**
* A case the render test draws: a name for its PNG and the preview's content. [ready] is what the test waits for before
* drawing, for a screen that loads something off the main thread first.
*/
internal class PreviewCase(val name: String, val ready: () -> Boolean = { true }, val content: @Composable () -> Unit) {
override fun toString() = name
}
internal val sampleGames: List<Library.SteamGame> = listOf(
"Portal 2" to 620, "Hades" to 1145360, "Celeste" to 504230, "Stardew Valley" to 413150, "Hollow Knight" to 367520,
"Balatro" to 2379780, "Dead Cells" to 588650, "Terraria" to 105600, "Vampire Survivors" to 1794680, "Slay the Spire" to 646570,
).mapIndexed { i, (name, appId) ->
Library.SteamGame(appId, name, art = null, library = "steam", lastPlayed = 1_700_000_000_000L - i * 86_400_000L)
}
internal fun sampleState(
games: List<Library.SteamGame> = sampleGames,
navigate: String? = null,
ready: Boolean = true,
): FrontEndState = FrontEndState(
installed = "ubuntu-r1", ready = ready, available = "ubuntu-r1", busy = false, stage = "", percent = 0,
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "Off", romsDir = null, logsEnabled = true,
steamGames = games, emulators = emptyList(), running = null, navigate = navigate,
)
internal val sampleActions: FrontEndActions = FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {},
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> },
)
/** The in-game menu's actions with settled sample values; its switches do nothing. */
internal fun sampleDrawerActions(
steam: Boolean = true, desktop: Boolean = false, secondScreen: SecondScreenMode? = null,
): DrawerActions = DrawerActions(
steam = steam, desktop = desktop, title = if (!steam && !desktop) "Hades" else null,
isHomeApp = false, androidApps = emptyList(),
hudOn = true, onHud = {},
frameGen = FrameGen.Mode.OFF, onFrameGenPick = {},
lossless = Lossless.State.NONE,
oscMode = SessionPrefs.OSC_AUTO, onOsc = {},
suspendPolicy = SessionPrefs.SUSPEND_MANUAL, onSuspendPolicy = {},
backActionsInverted = false, onBackActionsInverted = {},
touchMode = SessionPrefs.TOUCH_AUTO, onTouch = {}, touchAuto = "Auto (direct)",
fexPreset = "", onFexPreset = {},
secondScreenMode = secondScreen ?: SecondScreenMode.NONE, onSecondScreenMode = {}, secondScreenNone = secondScreen == null,
secondScreenDisplays = listOfNotNull(secondScreen?.let { SecondScreenDisplay(2, "Built-in · 1240×1080") }),
selectedSecondScreenDisplay = if (secondScreen != null) 2 else -1, onSecondScreenDisplay = {},
gameSwapAvailable = secondScreen != null, dashboardAvailable = secondScreen != null,
onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null,
onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {},
)
@@ -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) }
}
+36 -16
View File
@@ -22,7 +22,6 @@
<item>أضف مكتبات Steam من بطاقة SD أو محرك USB أو SSD، وسيجمع DroidDeck الألعاب معًا في «المكتبة».</item>
<item>تتيح لك «المتاجر» تسجيل الدخول إلى Epic Games وGOG وXbox وEA وBattle.net وUbisoft Connect وAmazon Games وitch.io وGame Jolt، ثم تثبيت ألعابها وتحديثها من DroidDeck.</item>
<item>تحدّث المكوّنات مثل FEX وDXVK وVKD3D-Proton نفسها تلقائيًا، ويكون Proton Experimental ARM64 هو الافتراضي، أو Proton 11.0 ARM64 بعد تثبيت هذا الإصدار.</item>
<item>يحرر «ضغط Steam أثناء تشغيل لعبة» مساحة من الذاكرة في الأجهزة قليلة الذاكرة.</item>
<item>اسحب من الحافة اليمنى للداخل لفتح قائمة الجلسة: وضع «لوحة اللمس» و«لوحة مفاتيح الكمبيوتر» و«وضع زمن الاستجابة المنخفض» وملف اللعبة والمزيد.</item>
<item>اللعبة بطيئة؟ حدّد معدل الإطارات في الوصول السريع، ثم جرّب إصدار Proton آخر أو إعدادًا مسبقًا آخر لـ FEX في مكوّنات اللعبة.</item>
<item>هل الصوت متقطع أو مفقود في اللعبة؟ جرّب مفتاح «DirectAudio للألعاب» في إعدادات Steam ضمن «الصوت».</item>
@@ -629,20 +628,8 @@
<string name="perf_gsrealtime">gamescope: طابور GPU بأولوية الوقت الفعلي</string>
<string name="perf_gsrealtime_hint">يعطي الأولوية لعمل GPU الخاص بالمُركِّب. قد يحسّن انتظام الإطارات على حساب أداء الألعاب قليلًا.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">الذاكرة</string>
<string name="perf_cap_off">إيقاف</string>
<string name="perf_cap_auto">افتراضي برنامج التشغيل</string>
<string name="perf_zram_client">ضغط Steam أثناء تشغيل لعبة</string>
<string name="perf_zram_idle">ضغط ذاكرة اللعبة الخاملة</string>
<string name="perf_zram_idle_hint">يرحّل ذاكرة اللعبة الخاملة عند انخفاض RAM. أوقفه إذا كانت الألعاب تتجمد لبضع ثوانٍ كل نصف دقيقة تقريبًا. يُطبَّق عند بدء الجلسة التالية.</string>
<string name="perf_zram_client_hint">بعد 20 ثانية من بدء اللعبة، يُضغط عميل Steam في zRAM لترك ذاكرة أكبر للعبة، ثم يُقرأ مجددًا عند إغلاقها. أوقف هذا الخيار إذا كانت الجلسة تُغلَق بعد بدء الألعاب بقليل. يظل حد RAM أعلاه يضغط Steam عندما تتجاوزه الجلسة.</string>
<string name="perf_ram_cap">حد RAM</string>
<string name="perf_ram_cap_hint">يُطبَّق أثناء تشغيل عميل Steam، في جلسة Steam أو من سطح المكتب. عندما تستخدم الجلسة أكثر من هذا الحد، يُضغط Steam ثم عمليات الجلسة المدعومة الأخرى في zRAM. حد مرن: لا يُغلَق شيء، لكن قد تتقطّع الألعاب أثناء استعادة الصفحات.</string>
<string name="perf_ram_cap_unavailable">يتطلب مساحة تبديل zRAM، وهي غير متوفرة على هذا الجهاز.</string>
<string name="perf_vram_cap">حد VRAM</string>
<string name="perf_vram_cap_hint">يُبلّغ ألعاب Direct3D من 9 إلى 12 بميزانية ذاكرة الفيديو هذه لتشجيع تقليل استخدامها. قد تتجاوزها الألعاب؛ لا يضيف هذا ترحيل ذاكرة GPU ولا يضمن منع الانهيار بسبب نفاد الذاكرة. يسري في الجلسة التالية.</string>
<string name="perf_gpuclock">تثبيت GPU على أعلى تردد له</string>
<string name="perf_gpuclock_hint">لـ Adreno فقط. تقطّع أقل، مع استهلاك أكبر للبطارية والحرارة.</string>
<string name="perf_fixes">إصلاحات الجلسة</string>
<string name="perf_sysmem">Turnip: التصيير عبر sysmem</string>
<string name="perf_sysmem_hint">ينطبق على عميل Steam والألعاب. مطلوب على Adreno 710/720/722.</string>
@@ -819,7 +806,6 @@
<string name="drawer_pc_keyboard">لوحة مفاتيح الكمبيوتر</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">الشاشة الثانية</string>
<string name="drawer_second_screen_mode">الوضع</string>
<string name="drawer_second_screen_shows">يعرض</string>
<string name="drawer_android_apps">تطبيقات Android</string>
<string name="drawer_launch_app">تشغيل تطبيق</string>
@@ -2391,6 +2377,17 @@
<string name="pextra_checksum_mismatch">عدم تطابق المجموع الاختباري؛ تم حذف التنزيل</string>
<string name="pextra_session_started">بدأت جلسة خلال التنزيل، أوقفها قبل تثبيت أدوات التوافق</string>
<string name="pextra_installing">جارٍ تثبيت %1$s</string>
<string name="xproton_title">إصدارات تجريبية</string>
<string name="xproton_install_file">تثبيت من ملف</string>
<string name="xproton_archive_unsafe">يحتوي الأرشيف على رابط أو مسار غير آمن</string>
<string name="xproton_archive_invalid">أرشيف غير مدعوم أو غير صالح</string>
<string name="xproton_no_space">لا توجد مساحة كافية لإصدار Proton هذا</string>
<string name="xproton_unpacking">جارٍ تفريغ Proton (بضع دقائق)</string>
<string name="xproton_untar_failed">فشل التفريغ (tar %1$d)</string>
<string name="xproton_no_tree">الأرشيف لا يحتوي على إصدار Proton</string>
<string name="xproton_place_failed">تعذّر وضع إصدار Proton</string>
<string name="xproton_remove_failed">تعذّرت الإزالة الكاملة لـ %1$s</string>
<string name="xproton_installed">تم تثبيت Proton التجريبي. اختره في Steam → الخصائص → التوافق.</string>
<string name="pextra_install_failed">فشل تثبيت %1$s (حالة الخروج %2$d)</string>
<string name="pextra_could_not_install">تعذّر تثبيت %1$s</string>
<string name="esync_fetching">جارٍ جلب حزمة droiddeck-esync</string>
@@ -3465,10 +3462,19 @@
<string name="storage_shared_prefix">بادئة Steam المشتركة</string>
<string name="storage_shared_prefix_detail">يشغّل Steam مساعدات Windows الخاصة به هنا</string>
<string name="storage_reset_shared_confirm">يحذفها (%1$s). ينشئ Steam بادئة جديدة في المرة التالية التي يحتاجها فيها.</string>
<string name="storage_remove_launcher_confirm">يحذف بادئة Wine وذاكرة التظليل المؤقتة لتطبيق المتجر هذا (%1$s)، مع تسجيل الدخول وأي حفظ موجود فيها فقط. تحصل الألعاب التي تعمل فيها على بادئة جديدة، وقد تحتاج إلى إعداد التطبيق مرة أخرى. تبقى عمليات الحفظ السحابية في حسابك.</string>
<string name="storage_system_clearable">يمكن مسح %1$s</string>
<string name="storage_item_system_caches">ذاكرات Linux وSteam المؤقتة</string>
<string name="storage_item_system_caches_detail">الملفات المؤقتة القديمة والحزم المنزّلة وذاكرة الويب المؤقتة لـ Steam</string>
<string name="storage_cache_temp">الملفات المؤقتة القديمة</string>
<string name="storage_cache_packages">الحزم المنزّلة</string>
<string name="storage_cache_steam_web">ذاكرة الويب المؤقتة لـ Steam</string>
<string name="storage_cache_steam_corrupt">تنزيلات Steam التالفة</string>
<string name="storage_cache_detail">تُنشأ مجددًا عند الحاجة</string>
<string name="storage_clear">مسح</string>
<string name="storage_launcher_prefix">تطبيق متجر والألعاب التي تعمل به</string>
<string name="storage_launcher_used_by">مستخدَمة بواسطة %1$s</string>
<string name="storage_shortcut_app">لعبة خارج Steam %1$s</string>
<string name="storage_unknown_prefix_detail">غير مطابقة لأي لعبة، لذا يُحتفظ بها</string>
<string name="storage_remove_selected">حذف المحدد · %1$s</string>
<string name="storage_uninstall_selected">إلغاء تثبيت المحدد · %1$s</string>
<string name="storage_bulk_prefixes">بادئات Wine</string>
@@ -4225,4 +4231,18 @@
<string name="display_scaling_integer">عدد صحيح</string>
<string name="display_scaling_fit">ملاءمة</string>
<string name="drawer_antialiasing">تنعيم الحواف</string>
</resources>
<string name="theme_custom">مخصص</string>
<string name="theme_custom_detail">اختر كل لون في الواجهة بشكل مستقل.</string>
<string name="theme_custom_background">الخلفية</string>
<string name="theme_custom_surface">اللوحات</string>
<string name="theme_custom_surface_variant">اللوحات المرتفعة</string>
<string name="theme_custom_line">الفواصل</string>
<string name="theme_custom_line2">الحدود</string>
<string name="theme_custom_on_background">النص الرئيسي</string>
<string name="theme_custom_on_surface_variant">النص الثانوي</string>
<string name="theme_custom_primary">الأزرار واللون الأساسي</string>
<string name="theme_custom_on_primary">نص الأزرار</string>
<string name="theme_custom_signal">الإبرازات</string>
<string name="theme_custom_good">نجاح</string>
<string name="theme_custom_error">خطأ</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Añade bibliotecas de Steam desde una tarjeta SD, una unidad USB o un SSD, y DroidDeck mantiene los juegos juntos en tu Biblioteca.</item>
<item>Tiendas te permite iniciar sesión en Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io y Game Jolt, y luego instalar y actualizar sus juegos desde DroidDeck.</item>
<item>Componentes como FEX, DXVK y VKD3D-Proton se actualizan solos, y Proton Experimental ARM64 es el predeterminado, o Proton 11.0 ARM64 una vez instalada esa versión.</item>
<item>Comprimir Steam mientras se ejecuta un juego libera RAM en dispositivos con poca memoria.</item>
<item>Desliza desde el borde derecho para abrir el menú de sesión: modo touchpad, Teclado de PC, Modo de baja latencia, perfil del juego y más.</item>
<item>¿El juego va lento? Limita la tasa de fotogramas en Quick Access y prueba otra versión de Proton o un ajuste preestablecido de FEX en los componentes del juego.</item>
<item>¿Audio del juego entrecortado o ausente? Prueba el interruptor DirectAudio para juegos en los ajustes de Steam, en Audio.</item>
@@ -623,20 +622,8 @@
<string name="perf_gsrealtime">gamescope: cola de GPU en tiempo real</string>
<string name="perf_gsrealtime_hint">Da prioridad al trabajo de GPU del compositor. Puede suavizar el ritmo de fotogramas a costa de algo de rendimiento en los juegos.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Memoria</string>
<string name="perf_cap_off">Desactivado</string>
<string name="perf_cap_auto">Predeterminado del controlador</string>
<string name="perf_zram_client">Comprimir Steam mientras se ejecuta un juego</string>
<string name="perf_zram_idle">Comprimir memoria inactiva del juego</string>
<string name="perf_zram_idle_hint">Comprime la memoria inactiva del juego cuando queda poca RAM. Desactívalo si los juegos se congelan unos segundos cada medio minuto aproximadamente. Se aplica la próxima vez que se inicie la sesión.</string>
<string name="perf_zram_client_hint">20 s después de que empiece un juego, el cliente de Steam se comprime en zRAM para dejarle más memoria al juego, y se vuelve a leer cuando el juego se cierra. Desactívalo si la sesión se cierra poco después de iniciar los juegos. Un límite de RAM definido arriba sigue comprimiendo Steam cuando la sesión lo supera.</string>
<string name="perf_ram_cap">Límite de RAM</string>
<string name="perf_ram_cap_hint">Se aplica mientras se ejecuta el cliente de Steam, en modo Steam o desde el escritorio. Cuando la sesión usa más de esto, Steam y luego los demás procesos compatibles de la sesión se comprimen en zRAM. Es un límite flexible: no se cierra nada, pero los juegos pueden tener microcortes mientras se recuperan las páginas.</string>
<string name="perf_ram_cap_unavailable">Requiere swap de zRAM, y este dispositivo no lo tiene.</string>
<string name="perf_vram_cap">Límite de VRAM</string>
<string name="perf_vram_cap_hint">Informa a los juegos Direct3D 9 a 12 de este presupuesto de memoria de video para reducir su uso. Los juegos pueden superarlo; no agrega paginación de GPU ni garantiza evitar fallos por falta de memoria. Se aplica en la próxima sesión.</string>
<string name="perf_gpuclock">Mantener la GPU a su reloj máximo</string>
<string name="perf_gpuclock_hint">Solo Adreno. Menos microcortes, más consumo de batería y calor.</string>
<string name="perf_fixes">Correcciones de sesión</string>
<string name="perf_sysmem">Turnip: renderizado sysmem</string>
<string name="perf_sysmem_hint">Se aplica al cliente de Steam y a los juegos. Obligatorio en Adreno 710/720/722.</string>
@@ -836,7 +823,6 @@
<string name="drawer_pc_keyboard">Teclado de PC</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Segunda pantalla</string>
<string name="drawer_second_screen_mode">Modo</string>
<string name="drawer_second_screen_shows">Muestra</string>
<string name="drawer_android_apps">Apps de Android</string>
<string name="drawer_launch_app">Abrir una app</string>
@@ -2381,6 +2367,17 @@
<string name="pextra_checksum_mismatch">La suma de verificación no coincide; se eliminó la descarga</string>
<string name="pextra_session_started">Se inició una sesión durante la descarga; detenla antes de instalar herramientas de compatibilidad</string>
<string name="pextra_installing">Instalando %1$s</string>
<string name="xproton_title">Versiones experimentales</string>
<string name="xproton_install_file">Instalar desde archivo</string>
<string name="xproton_archive_unsafe">El archivo contiene un enlace o una ruta no segura</string>
<string name="xproton_archive_invalid">Archivo no compatible o no válido</string>
<string name="xproton_no_space">No hay espacio libre suficiente para esta versión de Proton</string>
<string name="xproton_unpacking">Desempaquetando Proton (unos minutos)</string>
<string name="xproton_untar_failed">Error al desempaquetar (tar %1$d)</string>
<string name="xproton_no_tree">El archivo no contiene ninguna versión de Proton</string>
<string name="xproton_place_failed">No se pudo colocar la versión de Proton</string>
<string name="xproton_remove_failed">No se pudo quitar %1$s por completo</string>
<string name="xproton_installed">Proton experimental instalado. Elígelo en Steam → Propiedades → Compatibilidad.</string>
<string name="pextra_install_failed">Falló la instalación de %1$s (salida %2$d)</string>
<string name="pextra_could_not_install">No se pudo instalar %1$s</string>
<string name="esync_fetching">Descargando el paquete droiddeck-esync</string>
@@ -3320,10 +3317,19 @@
<string name="storage_shared_prefix">Prefijo compartido de Steam</string>
<string name="storage_shared_prefix_detail">Steam ejecuta aquí sus propias herramientas de Windows</string>
<string name="storage_reset_shared_confirm">Lo borra (%1$s). Steam crea uno nuevo la próxima vez que lo necesite.</string>
<string name="storage_remove_launcher_confirm">Borra el prefijo de Wine y la caché de shaders de esta app de tienda (%1$s), junto con su inicio de sesión y cualquier partida guardada solo ahí. Los juegos que se ejecutan en él reciben un prefijo nuevo y quizá debas configurar la app otra vez. Las partidas en la nube se quedan en tu cuenta.</string>
<string name="storage_system_clearable">Se pueden liberar %1$s</string>
<string name="storage_item_system_caches">Cachés de Linux y Steam</string>
<string name="storage_item_system_caches_detail">Archivos temporales viejos, paquetes descargados y la caché web de Steam</string>
<string name="storage_cache_temp">Archivos temporales viejos</string>
<string name="storage_cache_packages">Paquetes descargados</string>
<string name="storage_cache_steam_web">Caché web de Steam</string>
<string name="storage_cache_steam_corrupt">Descargas dañadas de Steam</string>
<string name="storage_cache_detail">Se vuelven a crear cuando hacen falta</string>
<string name="storage_clear">Borrar</string>
<string name="storage_launcher_prefix">Una app de tienda y los juegos que se ejecutan con ella</string>
<string name="storage_launcher_used_by">Usado por %1$s</string>
<string name="storage_shortcut_app">Juego que no es de Steam %1$s</string>
<string name="storage_unknown_prefix_detail">No coincide con ningún juego, así que se conserva</string>
<string name="storage_remove_selected">Quitar selección · %1$s</string>
<string name="storage_uninstall_selected">Desinstalar selección · %1$s</string>
<string name="storage_bulk_prefixes">Prefijos de Wine</string>
@@ -4105,4 +4111,18 @@
<string name="display_scaling_integer">Entero</string>
<string name="display_scaling_fit">Ajustar</string>
<string name="drawer_antialiasing">Antialiasing</string>
</resources>
<string name="theme_custom">Personalizado</string>
<string name="theme_custom_detail">Elige cada color de la interfaz por separado.</string>
<string name="theme_custom_background">Fondo</string>
<string name="theme_custom_surface">Paneles</string>
<string name="theme_custom_surface_variant">Paneles elevados</string>
<string name="theme_custom_line">Separadores</string>
<string name="theme_custom_line2">Bordes</string>
<string name="theme_custom_on_background">Texto principal</string>
<string name="theme_custom_on_surface_variant">Texto secundario</string>
<string name="theme_custom_primary">Botones y color principal</string>
<string name="theme_custom_on_primary">Texto de los botones</string>
<string name="theme_custom_signal">Destacados</string>
<string name="theme_custom_good">Éxito</string>
<string name="theme_custom_error">Error</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Добавяйте библиотеки на Steam от SD карта, USB устройство или SSD, а DroidDeck държи игрите заедно в Библиотека.</item>
<item>Магазини ви позволява да влезете в Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io и Game Jolt, а после да инсталирате и обновявате техните игри от DroidDeck.</item>
<item>Компоненти като FEX, DXVK и VKD3D-Proton се обновяват сами, а Proton Experimental ARM64 е по подразбиране, или Proton 11.0 ARM64, щом тази версия е инсталирана.</item>
<item>Компресиране на Steam, докато върви игра освобождава RAM на устройства с малко памет.</item>
<item>Плъзнете навътре от десния ръб, за да отворите менюто на сесията: режим на тъчпад, Клавиатура за компютър, Режим на ниска латентност, профил на играта и други.</item>
<item>Играта е бавна? Ограничете кадрите в Quick Access, после опитайте друга версия на Proton или друга предварителна настройка на FEX в компонентите на играта.</item>
<item>Пращене или липсващ звук в играта? Опитайте превключвателя DirectAudio за игри в настройките на Steam, под Звук.</item>
@@ -621,20 +620,8 @@
<string name="perf_gsrealtime">gamescope: GPU опашка в реално време</string>
<string name="perf_gsrealtime_hint">Дава приоритет на GPU работата на компоситора. Може да изглади темпото на кадрите с известна цена за игрите.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Памет</string>
<string name="perf_cap_off">Изкл.</string>
<string name="perf_cap_auto">По подразбиране за драйвера</string>
<string name="perf_zram_client">Компресиране на Steam, докато върви игра</string>
<string name="perf_zram_idle">Компресиране на неактивната памет на играта</string>
<string name="perf_zram_idle_hint">Компресира неактивната памет на играта при малко RAM. Изключете го, ако игрите замръзват за няколко секунди приблизително на всеки половин минута. Прилага се при следващото стартиране на сесията.</string>
<string name="perf_zram_client_hint">20 s след стартиране на игра клиентът на Steam се компресира в zRAM, за да остави повече памет на играта, и се прочита обратно, когато играта се затвори. Изключете, ако сесията се затваря малко след стартиране на игри. Ограничение на RAM по-горе пак компресира Steam, когато сесията го надхвърли.</string>
<string name="perf_ram_cap">Ограничение на RAM</string>
<string name="perf_ram_cap_hint">Прилага се, докато клиентът на Steam работи, в режим Steam или от работния плот. Когато сесията използва повече от това, Steam и след това другите поддържани процеси на сесията се компресират в zRAM. Меко ограничение: нищо не се затваря, но игрите може да засичат, докато страниците се връщат.</string>
<string name="perf_ram_cap_unavailable">Изисква zRAM swap, който това устройство няма.</string>
<string name="perf_vram_cap">Ограничение на VRAM</string>
<string name="perf_vram_cap_hint">Съобщава този бюджет за видео памет на игри с Direct3D 9 до 12, за да намали използването на памет. Игрите може да го надвишат; това не добавя странициране на GPU и не гарантира защита от сривове при недостиг на памет. Прилага се от следващата сесия.</string>
<string name="perf_gpuclock">Задръжте GPU на максималната му честота</string>
<string name="perf_gpuclock_hint">Само за Adreno. По-малко засечки, по-голямо използване на батерията и повече топлина.</string>
<string name="perf_fixes">Корекции на сесията</string>
<string name="perf_sysmem">Turnip: рендиране sysmem</string>
<string name="perf_sysmem_hint">Прилага се за клиента на Steam и игрите. Изисква се при Adreno 710/720/722.</string>
@@ -811,7 +798,6 @@
<string name="drawer_pc_keyboard">Клавиатура за компютър</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Втори екран</string>
<string name="drawer_second_screen_mode">Режим</string>
<string name="drawer_second_screen_shows">Показва</string>
<string name="drawer_android_apps">Приложения за Android</string>
<string name="drawer_launch_app">Стартиране на приложение</string>
@@ -2287,6 +2273,17 @@
<string name="pextra_checksum_mismatch">Несъответствие в контролната сума; изтеглянето беше изтрито</string>
<string name="pextra_session_started">По време на изтеглянето започна сесия - спри я, преди да инсталираш инструменти за съвместимост</string>
<string name="pextra_installing">Инсталиране на %1$s</string>
<string name="xproton_title">Експериментални версии</string>
<string name="xproton_install_file">Инсталиране от файл</string>
<string name="xproton_archive_unsafe">Архивът съдържа опасна връзка или път</string>
<string name="xproton_archive_invalid">Неподдържан или невалиден архив</string>
<string name="xproton_no_space">Няма достатъчно свободно място за тази версия на Proton</string>
<string name="xproton_unpacking">Разопаковане на Proton (няколко минути)</string>
<string name="xproton_untar_failed">Разопаковането не успя (tar %1$d)</string>
<string name="xproton_no_tree">Архивът не съдържа версия на Proton</string>
<string name="xproton_place_failed">Версията на Proton не можа да бъде поставена</string>
<string name="xproton_remove_failed">%1$s не можа да бъде премахнат напълно</string>
<string name="xproton_installed">Експерименталният Proton е инсталиран. Изберете го в Steam → Свойства → Съвместимост.</string>
<string name="pextra_install_failed">Инсталирането на %1$s се провали (код %2$d)</string>
<string name="pextra_could_not_install">%1$s не можа да бъде инсталиран</string>
<string name="esync_fetching">Извличане на пакета droiddeck-esync</string>
@@ -3317,10 +3314,19 @@
<string name="storage_shared_prefix">Споделен Steam префикс</string>
<string name="storage_shared_prefix_detail">Steam изпълнява тук свои помощни програми за Windows</string>
<string name="storage_reset_shared_confirm">Изтрива го (%1$s). Steam създава нов следващия път, когато му потрябва.</string>
<string name="storage_remove_launcher_confirm">Изтрива Wine префикса и кеша на шейдърите на това приложение на магазин (%1$s), заедно с влизането и записите, пазени само там. Игрите, които работят в него, получават нов префикс и може да се наложи да настроите приложението отново. Записите в облака остават в профила ви.</string>
<string name="storage_system_clearable">Може да се изчистят %1$s</string>
<string name="storage_item_system_caches">Кешове на Linux и Steam</string>
<string name="storage_item_system_caches_detail">Стари временни файлове, изтеглени пакети и уеб кешът на Steam</string>
<string name="storage_cache_temp">Стари временни файлове</string>
<string name="storage_cache_packages">Изтеглени пакети</string>
<string name="storage_cache_steam_web">Уеб кеш на Steam</string>
<string name="storage_cache_steam_corrupt">Повредени изтегляния на Steam</string>
<string name="storage_cache_detail">Създават се отново при нужда</string>
<string name="storage_clear">Изчисти</string>
<string name="storage_launcher_prefix">Приложение магазин и игрите, които работят с него</string>
<string name="storage_launcher_used_by">Използва се от %1$s</string>
<string name="storage_shortcut_app">Игра извън Steam %1$s</string>
<string name="storage_unknown_prefix_detail">Не е свързан с игра, затова се запазва</string>
<string name="storage_remove_selected">Премахни избраните · %1$s</string>
<string name="storage_uninstall_selected">Деинсталирай избраните · %1$s</string>
<string name="storage_bulk_prefixes">Префикси на Wine</string>
@@ -4065,4 +4071,18 @@
<string name="display_scaling_integer">Цяло число</string>
<string name="display_scaling_fit">Побиране</string>
<string name="drawer_antialiasing">Заглаждане на ръбовете</string>
</resources>
<string name="theme_custom">Персонализирана</string>
<string name="theme_custom_detail">Изберете поотделно всеки цвят на интерфейса.</string>
<string name="theme_custom_background">Фон</string>
<string name="theme_custom_surface">Панели</string>
<string name="theme_custom_surface_variant">Повдигнати панели</string>
<string name="theme_custom_line">Разделители</string>
<string name="theme_custom_line2">Рамки</string>
<string name="theme_custom_on_background">Основен текст</string>
<string name="theme_custom_on_surface_variant">Вторичен текст</string>
<string name="theme_custom_primary">Бутони и основен акцент</string>
<string name="theme_custom_on_primary">Текст на бутоните</string>
<string name="theme_custom_signal">Акценти</string>
<string name="theme_custom_good">Успех</string>
<string name="theme_custom_error">Грешка</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Přidejte knihovny Steamu z SD karty, USB disku nebo SSD a DroidDeck udrží hry pohromadě v Knihovně.</item>
<item>Obchody vám umožní přihlásit se do Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io a Game Jolt a pak instalovat a aktualizovat jejich hry přímo z DroidDeck.</item>
<item>Komponenty jako FEX, DXVK a VKD3D-Proton se aktualizují samy a výchozí je Proton Experimental ARM64, případně Proton 11.0 ARM64, jakmile je tato verze nainstalovaná.</item>
<item>Komprimovat Steam během hry uvolní RAM na zařízeních s nedostatkem paměti.</item>
<item>Přejetím od pravého okraje otevřete nabídku relace: režim touchpadu, Klávesnice PC, Režim nízkého zpoždění, profil hry a další.</item>
<item>Hra běží pomalu? Omezte snímkovou frekvenci v Quick Access a zkuste jinou verzi Proton nebo jinou předvolbu FEX v komponentách hry.</item>
<item>Praskání nebo chybějící zvuk ve hře? Zkuste přepínač DirectAudio pro hry v nastavení Steamu v části Zvuk.</item>
@@ -625,20 +624,8 @@
<string name="perf_gsrealtime">gamescope: fronta GPU v reálném čase</string>
<string name="perf_gsrealtime_hint">Dává prioritu práci GPU kompozitoru. Může vyhladit tempo snímků na úkor her.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Paměť</string>
<string name="perf_cap_off">Vypnuto</string>
<string name="perf_cap_auto">Výchozí ovladače</string>
<string name="perf_zram_client">Komprimovat Steam během hry</string>
<string name="perf_zram_idle">Komprimovat neaktivní paměť hry</string>
<string name="perf_zram_idle_hint">Při nedostatku RAM stránkuje neaktivní paměť hry. Vypněte to, pokud hry zhruba každou půlminutu na několik sekund zamrznou. Projeví se při příštím spuštění relace.</string>
<string name="perf_zram_client_hint">20 s po spuštění hry se klient Steam zkomprimuje do zRAM, aby hře zbylo více paměti, a po zavření hry se načte zpět. Vypněte, pokud se relace krátce po spuštění her zavírá. Limit RAM výše stále komprimuje Steam, když ho relace překročí.</string>
<string name="perf_ram_cap">Limit RAM</string>
<string name="perf_ram_cap_hint">Platí, když běží klient Steam, v režimu Steam nebo z Plochy. Když relace použije víc, zkomprimuje se do zRAM Steam a poté další podporované procesy relace. Měkký limit: nic se nezavře, ale hry mohou trhat, než se stránky načtou zpět.</string>
<string name="perf_ram_cap_unavailable">Vyžaduje swap zRAM, který toto zařízení nemá.</string>
<string name="perf_vram_cap">Limit VRAM</string>
<string name="perf_vram_cap_hint">Hlásí hrám s Direct3D 9 až 12 tento rozpočet videopaměti, aby snížily její využití. Hry jej mohou překročit; nepřidává stránkování GPU ani nezaručuje ochranu před pády kvůli nedostatku paměti. Platí od příští relace.</string>
<string name="perf_gpuclock">Udržet GPU na nejvyšších taktech</string>
<string name="perf_gpuclock_hint">Jen Adreno. Méně zadrhávání, více spotřeby baterie a tepla.</string>
<string name="perf_fixes">Opravy relace</string>
<string name="perf_sysmem">Turnip: vykreslování sysmem</string>
<string name="perf_sysmem_hint">Platí pro klienta Steam i hry. Vyžadováno na Adreno 710/720/722.</string>
@@ -815,7 +802,6 @@
<string name="drawer_pc_keyboard">Klávesnice PC</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Druhá obrazovka</string>
<string name="drawer_second_screen_mode">Režim</string>
<string name="drawer_second_screen_shows">Zobrazuje</string>
<string name="drawer_android_apps">Aplikace Android</string>
<string name="drawer_launch_app">Spustit aplikaci</string>
@@ -2339,6 +2325,17 @@
<string name="pextra_checksum_mismatch">Neshoda kontrolního součtu; stahování bylo odstraněno</string>
<string name="pextra_session_started">Během stahování se spustila relace; před instalací nástrojů kompatibility ji zastavte</string>
<string name="pextra_installing">Instalování %1$s</string>
<string name="xproton_title">Experimentální sestavení</string>
<string name="xproton_install_file">Instalovat ze souboru</string>
<string name="xproton_archive_unsafe">Archiv obsahuje nebezpečný odkaz nebo cestu</string>
<string name="xproton_archive_invalid">Nepodporovaný nebo neplatný archiv</string>
<string name="xproton_no_space">Pro toto sestavení Proton není dost volného místa</string>
<string name="xproton_unpacking">Rozbalování Proton (několik minut)</string>
<string name="xproton_untar_failed">Rozbalení se nezdařilo (tar %1$d)</string>
<string name="xproton_no_tree">Archiv neobsahuje sestavení Proton</string>
<string name="xproton_place_failed">Sestavení Proton se nepodařilo umístit</string>
<string name="xproton_remove_failed">Nepodařilo se úplně odebrat %1$s</string>
<string name="xproton_installed">Experimentální Proton je nainstalován. Vyberte ho ve Steam → Vlastnosti → Kompatibilita.</string>
<string name="pextra_install_failed">Instalace %1$s se nezdařila (návratový kód %2$d)</string>
<string name="pextra_could_not_install">Nepodařilo se nainstalovat %1$s</string>
<string name="esync_fetching">Stahování balíčku droiddeck-esync</string>
@@ -3391,10 +3388,19 @@
<string name="storage_shared_prefix">Sdílený prefix Steamu</string>
<string name="storage_shared_prefix_detail">Steam zde spouští své pomocné programy pro Windows</string>
<string name="storage_reset_shared_confirm">Smaže ho (%1$s). Steam si vytvoří nový, až ho bude příště potřebovat.</string>
<string name="storage_remove_launcher_confirm">Smaže Wine prefix a mezipaměť shaderů této aplikace obchodu (%1$s) včetně přihlášení a uložených pozic, které jsou jen tam. Hry, které v něm běží, dostanou nový prefix a aplikaci možná bude třeba znovu nastavit. Cloudové uložené pozice zůstanou ve vašem účtu.</string>
<string name="storage_system_clearable">Lze uvolnit %1$s</string>
<string name="storage_item_system_caches">Mezipaměti Linuxu a Steamu</string>
<string name="storage_item_system_caches_detail">Staré dočasné soubory, stažené balíčky a webová mezipaměť Steamu</string>
<string name="storage_cache_temp">Staré dočasné soubory</string>
<string name="storage_cache_packages">Stažené balíčky</string>
<string name="storage_cache_steam_web">Webová mezipaměť Steamu</string>
<string name="storage_cache_steam_corrupt">Poškozená stahování Steamu</string>
<string name="storage_cache_detail">V případě potřeby se vytvoří znovu</string>
<string name="storage_clear">Vymazat</string>
<string name="storage_launcher_prefix">Aplikace obchodu a hry, které s ní běží</string>
<string name="storage_launcher_used_by">Používá: %1$s</string>
<string name="storage_shortcut_app">Hra mimo Steam %1$s</string>
<string name="storage_unknown_prefix_detail">Nepatří k žádné hře, proto zůstává</string>
<string name="storage_remove_selected">Odebrat vybrané · %1$s</string>
<string name="storage_uninstall_selected">Odinstalovat vybrané · %1$s</string>
<string name="storage_bulk_prefixes">Prefixy Wine</string>
@@ -4145,4 +4151,18 @@
<string name="display_scaling_integer">Celé číslo</string>
<string name="display_scaling_fit">Přizpůsobit</string>
<string name="drawer_antialiasing">Vyhlazování hran</string>
</resources>
<string name="theme_custom">Vlastní</string>
<string name="theme_custom_detail">Vyberte samostatně každou barvu rozhraní.</string>
<string name="theme_custom_background">Pozadí</string>
<string name="theme_custom_surface">Panely</string>
<string name="theme_custom_surface_variant">Vyvýšené panely</string>
<string name="theme_custom_line">Oddělovače</string>
<string name="theme_custom_line2">Ohraničení</string>
<string name="theme_custom_on_background">Hlavní text</string>
<string name="theme_custom_on_surface_variant">Vedlejší text</string>
<string name="theme_custom_primary">Tlačítka a hlavní zvýraznění</string>
<string name="theme_custom_on_primary">Text tlačítek</string>
<string name="theme_custom_signal">Zvýraznění</string>
<string name="theme_custom_good">Úspěch</string>
<string name="theme_custom_error">Chyba</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Tilføj Steam-biblioteker fra et SD-kort, et USB-drev eller en SSD, så samler DroidDeck spillene i dit Bibliotek.</item>
<item>Butikker lader dig logge ind på Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io og Game Jolt og derefter installere og opdatere deres spil fra DroidDeck.</item>
<item>Komponenter som FEX, DXVK og VKD3D-Proton opdaterer sig selv, og Proton Experimental ARM64 er standard, eller Proton 11.0 ARM64, når den version er installeret.</item>
<item>Komprimer Steam, mens et spil kører frigør RAM på enheder med lidt hukommelse.</item>
<item>Stryg ind fra højre kant for at åbne sessionsmenuen: touchpad-tilstand, PC-tastatur, Lav forsinkelse, spilprofil og mere.</item>
<item>Kører spillet langsomt? Begræns billedfrekvensen i Hurtig adgang, og prøv så en anden Proton-version eller FEX-forudindstilling i spillets komponenter.</item>
<item>Knitrende eller manglende lyd i spillet? Prøv kontakten DirectAudio til spil i Steam-indstillingerne under Lyd.</item>
@@ -621,20 +620,8 @@
<string name="perf_gsrealtime">gamescope: realtids-GPU-kø</string>
<string name="perf_gsrealtime_hint">Prioriterer compositorens GPU-arbejde. Kan give jævnere billedtiming på bekostning af spillene.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Hukommelse</string>
<string name="perf_cap_off">Fra</string>
<string name="perf_cap_auto">Driverstandard</string>
<string name="perf_zram_client">Komprimer Steam, mens et spil kører</string>
<string name="perf_zram_idle">Komprimer spillets inaktive hukommelse</string>
<string name="perf_zram_idle_hint">Pager spillets inaktive hukommelse ud, når RAM er lav. Slå det fra, hvis spil fryser i et par sekunder cirka hvert halve minut. Træder i kraft, næste gang sessionen starter.</string>
<string name="perf_zram_client_hint">20 s efter et spil starter, komprimeres Steam-klienten i zRAM for at give spillet mere hukommelse, og læses tilbage, når spillet lukkes. Slå fra, hvis sessionen lukker kort efter, at spil starter. En RAM-grænse ovenfor komprimerer stadig Steam, når sessionen overskrider den.</string>
<string name="perf_ram_cap">RAM-grænse</string>
<string name="perf_ram_cap_hint">Gælder, mens Steam-klienten kører, i Steam-tilstand eller fra skrivebordet. Når sessionen bruger mere end dette, komprimeres Steam og derefter sessionens andre understøttede processer i zRAM. En blød grænse: intet lukkes, men spil kan hakke, mens sider hentes tilbage.</string>
<string name="perf_ram_cap_unavailable">Kræver zRAM-swap, som denne enhed ikke har.</string>
<string name="perf_vram_cap">VRAM-grænse</string>
<string name="perf_vram_cap_hint">Rapporterer dette videohukommelsesbudget til Direct3D 9 til 12-spil for at mindske hukommelsesforbruget. Spil kan overskride det; dette tilføjer ikke GPU-paging og garanterer ikke beskyttelse mod nedbrud ved hukommelsesmangel. Gælder fra næste session.</string>
<string name="perf_gpuclock">Hold GPU’en på dens højeste clock</string>
<string name="perf_gpuclock_hint">Kun Adreno. Færre hak, mere batteribrug og varme.</string>
<string name="perf_fixes">Sessionsrettelser</string>
<string name="perf_sysmem">Turnip: sysmem-rendering</string>
<string name="perf_sysmem_hint">Gælder Steam-klienten og spil. Påkrævet på Adreno 710/720/722.</string>
@@ -811,7 +798,6 @@
<string name="drawer_pc_keyboard">PC-tastatur</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Anden skærm</string>
<string name="drawer_second_screen_mode">Tilstand</string>
<string name="drawer_second_screen_shows">Viser</string>
<string name="drawer_android_apps">Android-apps</string>
<string name="drawer_launch_app">Start en app</string>
@@ -2287,6 +2273,17 @@
<string name="pextra_checksum_mismatch">Tjeksum stemmer ikke; downloadet blev slettet</string>
<string name="pextra_session_started">En session startede under downloadet; stop den før du installerer kompatibilitetsværktøjer</string>
<string name="pextra_installing">Installerer %1$s</string>
<string name="xproton_title">Eksperimentelle builds</string>
<string name="xproton_install_file">Installer fra fil</string>
<string name="xproton_archive_unsafe">Arkivet indeholder et usikkert link eller en sti</string>
<string name="xproton_archive_invalid">Ikke-understøttet eller ugyldigt arkiv</string>
<string name="xproton_no_space">Der er ikke nok ledig plads til denne Proton-build</string>
<string name="xproton_unpacking">Udpakker Proton (nogle få minutter)</string>
<string name="xproton_untar_failed">Udpakning mislykkedes (tar %1$d)</string>
<string name="xproton_no_tree">Arkivet indeholder ingen Proton-build</string>
<string name="xproton_place_failed">Kunne ikke placere Proton-builden</string>
<string name="xproton_remove_failed">Kunne ikke fjerne %1$s helt</string>
<string name="xproton_installed">Eksperimentel Proton er installeret. Vælg den i Steam → Egenskaber → Kompatibilitet.</string>
<string name="pextra_install_failed">Installation af %1$s mislykkedes (afslutningskode %2$d)</string>
<string name="pextra_could_not_install">Kunne ikke installere %1$s</string>
<string name="esync_fetching">Henter droiddeck-esync-pakken</string>
@@ -3317,10 +3314,19 @@
<string name="storage_shared_prefix">Steams delte præfiks</string>
<string name="storage_shared_prefix_detail">Steam kører sine egne Windows-hjælpere her</string>
<string name="storage_reset_shared_confirm">Sletter det (%1$s). Steam opretter et nyt, næste gang det skal bruges.</string>
<string name="storage_remove_launcher_confirm">Sletter denne butiksapps Wine-præfiks og shader-cache (%1$s) sammen med login og gemte spil, der kun ligger der. Spil, der kører i det, får et nyt præfiks, og du skal måske sætte appen op igen. Gemte spil i skyen bliver på din konto.</string>
<string name="storage_system_clearable">%1$s kan ryddes</string>
<string name="storage_item_system_caches">Linux- og Steam-cache</string>
<string name="storage_item_system_caches_detail">Gamle midlertidige filer, hentede pakker og Steams webcache</string>
<string name="storage_cache_temp">Gamle midlertidige filer</string>
<string name="storage_cache_packages">Hentede pakker</string>
<string name="storage_cache_steam_web">Steams webcache</string>
<string name="storage_cache_steam_corrupt">Beskadigede Steam-downloads</string>
<string name="storage_cache_detail">Oprettes igen efter behov</string>
<string name="storage_clear">Ryd</string>
<string name="storage_launcher_prefix">En butiksapp og de spil, der kører med den</string>
<string name="storage_launcher_used_by">Bruges af %1$s</string>
<string name="storage_shortcut_app">Ikke-Steam-spil %1$s</string>
<string name="storage_unknown_prefix_detail">Ikke knyttet til et spil, så det bevares</string>
<string name="storage_remove_selected">Fjern valgte · %1$s</string>
<string name="storage_uninstall_selected">Afinstaller valgte · %1$s</string>
<string name="storage_bulk_prefixes">Wine-prefixer</string>
@@ -4065,4 +4071,18 @@
<string name="display_scaling_integer">Heltal</string>
<string name="display_scaling_fit">Tilpas</string>
<string name="drawer_antialiasing">Kantudjævning</string>
</resources>
<string name="theme_custom">Tilpasset</string>
<string name="theme_custom_detail">Vælg hver grænsefladefarve individuelt.</string>
<string name="theme_custom_background">Baggrund</string>
<string name="theme_custom_surface">Paneler</string>
<string name="theme_custom_surface_variant">Hævede paneler</string>
<string name="theme_custom_line">Skillestreger</string>
<string name="theme_custom_line2">Kanter</string>
<string name="theme_custom_on_background">Primær tekst</string>
<string name="theme_custom_on_surface_variant">Sekundær tekst</string>
<string name="theme_custom_primary">Knapper og hovedaccent</string>
<string name="theme_custom_on_primary">Knaptekst</string>
<string name="theme_custom_signal">Fremhævninger</string>
<string name="theme_custom_good">Succes</string>
<string name="theme_custom_error">Fejl</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Füge Steam-Bibliotheken von einer SD-Karte, einem USB-Laufwerk oder einer SSD hinzu, und DroidDeck hält die Spiele in deiner Bibliothek zusammen.</item>
<item>Mit Stores meldest du dich bei Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io und Game Jolt an und installierst und aktualisierst deren Spiele direkt in DroidDeck.</item>
<item>Komponenten wie FEX, DXVK und VKD3D-Proton aktualisieren sich selbst, und Proton Experimental ARM64 ist der Standard, oder Proton 11.0 ARM64, sobald diese Version installiert ist.</item>
<item>Steam komprimieren, während ein Spiel läuft gibt auf Geräten mit knappem Arbeitsspeicher RAM frei.</item>
<item>Wische vom rechten Rand nach innen, um das Sitzungsmenü zu öffnen: Touchpad-Modus, PC-Tastatur, Modus mit geringer Latenz, Spielprofil und mehr.</item>
<item>Das Spiel läuft langsam? Begrenze die Bildrate im Schnellzugriff und probiere dann eine andere Proton-Version oder ein anderes FEX-Preset in den Komponenten des Spiels.</item>
<item>Knacken oder fehlender Spielton? Probiere den Schalter DirectAudio für Spiele in den Steam-Einstellungen unter Audio.</item>
@@ -621,20 +620,8 @@
<string name="perf_gsrealtime">gamescope: Echtzeit-GPU-Warteschlange</string>
<string name="perf_gsrealtime_hint">Priorisiert die GPU-Arbeit des Compositors. Kann das Frame-Pacing glätten, kostet Spiele aber etwas Leistung.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Arbeitsspeicher</string>
<string name="perf_cap_off">Aus</string>
<string name="perf_cap_auto">Treiberstandard</string>
<string name="perf_zram_client">Steam komprimieren, während ein Spiel läuft</string>
<string name="perf_zram_idle">Inaktiven Spielspeicher komprimieren</string>
<string name="perf_zram_idle_hint">Lagert inaktiven Spielspeicher bei knappem RAM aus. Schalte dies aus, wenn Spiele etwa jede halbe Minute für einige Sekunden einfrieren. Gilt ab dem nächsten Start der Sitzung.</string>
<string name="perf_zram_client_hint">20 s nach dem Spielstart wird der Steam-Client in zRAM komprimiert, um dem Spiel mehr Speicher zu lassen, und beim Beenden des Spiels zurückgelesen. Schalte dies aus, wenn sich die Sitzung kurz nach dem Spielstart schließt. Ein RAM-Limit oben komprimiert Steam weiterhin, wenn die Sitzung es überschreitet.</string>
<string name="perf_ram_cap">RAM-Limit</string>
<string name="perf_ram_cap_hint">Gilt, solange der Steam-Client läuft, im Steam-Modus oder vom Desktop aus. Verbraucht die Sitzung mehr als diesen Wert, werden Steam und danach die übrigen unterstützten Prozesse der Sitzung in zRAM komprimiert. Ein weiches Limit: Nichts wird geschlossen, aber Spiele können ruckeln, während Seiten zurückgeladen werden.</string>
<string name="perf_ram_cap_unavailable">Benötigt zRAM-Swap, den dieses Gerät nicht hat.</string>
<string name="perf_vram_cap">VRAM-Limit</string>
<string name="perf_vram_cap_hint">Meldet Direct3D-9-bis-12-Spielen dieses Videospeicherbudget, um den Speicherverbrauch zu senken. Spiele können es überschreiten; dies fügt kein GPU-Paging hinzu und garantiert keinen Schutz vor Abstürzen durch Speichermangel. Gilt ab der nächsten Sitzung.</string>
<string name="perf_gpuclock">GPU auf höchstem Takt halten</string>
<string name="perf_gpuclock_hint">Nur Adreno. Weniger Ruckler, mehr Akkuverbrauch und Wärme.</string>
<string name="perf_fixes">Sitzungskorrekturen</string>
<string name="perf_sysmem">Turnip: Sysmem-Rendering</string>
<string name="perf_sysmem_hint">Gilt für den Steam-Client und Spiele. Erforderlich bei Adreno 710/720/722.</string>
@@ -811,7 +798,6 @@
<string name="drawer_pc_keyboard">PC-Tastatur</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Zweiter Bildschirm</string>
<string name="drawer_second_screen_mode">Modus</string>
<string name="drawer_second_screen_shows">Zeigt</string>
<string name="drawer_android_apps">Android-Apps</string>
<string name="drawer_launch_app">App starten</string>
@@ -2279,6 +2265,17 @@
<string name="pextra_checksum_mismatch">Prüfsumme stimmt nicht überein; der Download wurde gelöscht</string>
<string name="pextra_session_started">Während des Downloads wurde eine Sitzung gestartet; beende sie, bevor du Kompatibilitätstools installierst</string>
<string name="pextra_installing">%1$s wird installiert</string>
<string name="xproton_title">Experimentelle Builds</string>
<string name="xproton_install_file">Aus Datei installieren</string>
<string name="xproton_archive_unsafe">Das Archiv enthält einen unsicheren Link oder Pfad</string>
<string name="xproton_archive_invalid">Nicht unterstütztes oder ungültiges Archiv</string>
<string name="xproton_no_space">Nicht genug freier Speicher für diesen Proton-Build</string>
<string name="xproton_unpacking">Proton wird entpackt (einige Minuten)</string>
<string name="xproton_untar_failed">Entpacken fehlgeschlagen (tar %1$d)</string>
<string name="xproton_no_tree">Das Archiv enthält keinen Proton-Build</string>
<string name="xproton_place_failed">Der Proton-Build konnte nicht abgelegt werden</string>
<string name="xproton_remove_failed">%1$s konnte nicht vollständig entfernt werden</string>
<string name="xproton_installed">Experimentelles Proton installiert. Wähle es unter Steam → Eigenschaften → Kompatibilität aus.</string>
<string name="pextra_install_failed">Installation von %1$s fehlgeschlagen (Exit-Code %2$d)</string>
<string name="pextra_could_not_install">%1$s konnte nicht installiert werden</string>
<string name="esync_fetching">droiddeck-esync-Paket wird abgerufen</string>
@@ -3317,10 +3314,19 @@
<string name="storage_shared_prefix">Gemeinsames Präfix von Steam</string>
<string name="storage_shared_prefix_detail">Steam führt hier eigene Windows-Hilfsprogramme aus</string>
<string name="storage_reset_shared_confirm">Löscht es (%1$s). Steam erstellt ein neues, sobald es wieder eines braucht.</string>
<string name="storage_remove_launcher_confirm">Löscht Wine-Präfix und Shader-Cache dieser Store-App (%1$s), samt Anmeldung und Speicherständen, die nur dort liegen. Spiele, die darin laufen, bekommen ein neues Präfix, und die App muss eventuell neu eingerichtet werden. Cloud-Speicherstände bleiben im Konto.</string>
<string name="storage_system_clearable">%1$s können geleert werden</string>
<string name="storage_item_system_caches">Linux- und Steam-Caches</string>
<string name="storage_item_system_caches_detail">Alte temporäre Dateien, heruntergeladene Pakete und Steams Web-Cache</string>
<string name="storage_cache_temp">Alte temporäre Dateien</string>
<string name="storage_cache_packages">Heruntergeladene Pakete</string>
<string name="storage_cache_steam_web">Steam-Web-Cache</string>
<string name="storage_cache_steam_corrupt">Beschädigte Steam-Downloads</string>
<string name="storage_cache_detail">Wird bei Bedarf neu erstellt</string>
<string name="storage_clear">Leeren</string>
<string name="storage_launcher_prefix">Eine Store-App und die Spiele, die damit laufen</string>
<string name="storage_launcher_used_by">Verwendet von %1$s</string>
<string name="storage_shortcut_app">Nicht-Steam-Spiel %1$s</string>
<string name="storage_unknown_prefix_detail">Keinem Spiel zugeordnet, daher bleibt es erhalten</string>
<string name="storage_remove_selected">Auswahl entfernen · %1$s</string>
<string name="storage_uninstall_selected">Auswahl deinstallieren · %1$s</string>
<string name="storage_bulk_prefixes">Wine-Präfixe</string>
@@ -4065,4 +4071,18 @@
<string name="display_scaling_integer">Ganzzahlig</string>
<string name="display_scaling_fit">Anpassen</string>
<string name="drawer_antialiasing">Kantenglättung</string>
</resources>
<string name="theme_custom">Benutzerdefiniert</string>
<string name="theme_custom_detail">Wähle jede Farbe der Oberfläche einzeln aus.</string>
<string name="theme_custom_background">Hintergrund</string>
<string name="theme_custom_surface">Flächen</string>
<string name="theme_custom_surface_variant">Erhöhte Flächen</string>
<string name="theme_custom_line">Trennlinien</string>
<string name="theme_custom_line2">Rahmen</string>
<string name="theme_custom_on_background">Haupttext</string>
<string name="theme_custom_on_surface_variant">Sekundärtext</string>
<string name="theme_custom_primary">Schaltflächen und Hauptakzent</string>
<string name="theme_custom_on_primary">Schaltflächentext</string>
<string name="theme_custom_signal">Hervorhebungen</string>
<string name="theme_custom_good">Erfolg</string>
<string name="theme_custom_error">Fehler</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Προσθέστε βιβλιοθήκες Steam από κάρτα SD, μονάδα USB ή SSD, και το DroidDeck κρατά τα παιχνίδια μαζί στη Βιβλιοθήκη σας.</item>
<item>Τα Καταστήματα σάς επιτρέπουν να συνδεθείτε σε Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io και Game Jolt και μετά να εγκαθιστάτε και να ενημερώνετε τα παιχνίδια τους από το DroidDeck.</item>
<item>Στοιχεία όπως τα FEX, DXVK και VKD3D-Proton ενημερώνονται μόνα τους, και το Proton Experimental ARM64 είναι το προεπιλεγμένο, ή το Proton 11.0 ARM64 μόλις εγκατασταθεί αυτή η έκδοση.</item>
<item>Η επιλογή Συμπίεση του Steam όσο τρέχει παιχνίδι ελευθερώνει RAM σε συσκευές με λίγη μνήμη.</item>
<item>Σύρετε προς τα μέσα από τη δεξιά άκρη για να ανοίξετε το μενού συνεδρίας: λειτουργία πινακίδας αφής, Πληκτρολόγιο PC, Λειτουργία χαμηλής καθυστέρησης, προφίλ παιχνιδιού και άλλα.</item>
<item>Το παιχνίδι τρέχει αργά; Περιορίστε τον ρυθμό καρέ στο Quick Access και δοκιμάστε άλλη έκδοση Proton ή άλλη προεπιλογή FEX στα στοιχεία του παιχνιδιού.</item>
<item>Κροταλίσματα ή απουσία ήχου στο παιχνίδι; Δοκιμάστε τον διακόπτη DirectAudio για παιχνίδια στις ρυθμίσεις του Steam, στην ενότητα Ήχος.</item>
@@ -621,20 +620,8 @@
<string name="perf_gsrealtime">gamescope: ουρά GPU πραγματικού χρόνου</string>
<string name="perf_gsrealtime_hint">Δίνει προτεραιότητα στην εργασία GPU του compositor. Μπορεί να εξομαλύνει τον ρυθμό καρέ με κάποιο κόστος για τα παιχνίδια.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Μνήμη</string>
<string name="perf_cap_off">Ανενεργό</string>
<string name="perf_cap_auto">Προεπιλογή προγράμματος οδήγησης</string>
<string name="perf_zram_client">Συμπίεση του Steam όσο τρέχει παιχνίδι</string>
<string name="perf_zram_idle">Συμπίεση ανενεργής μνήμης παιχνιδιού</string>
<string name="perf_zram_idle_hint">Σελιδοποιεί την ανενεργή μνήμη του παιχνιδιού όταν η RAM είναι χαμηλή. Απενεργοποιήστε το αν τα παιχνίδια παγώνουν για λίγα δευτερόλεπτα περίπου κάθε μισό λεπτό. Ισχύει από την επόμενη έναρξη της συνεδρίας.</string>
<string name="perf_zram_client_hint">20 s μετά την εκκίνηση ενός παιχνιδιού, ο πελάτης Steam συμπιέζεται στη zRAM για να μείνει περισσότερη μνήμη στο παιχνίδι, και διαβάζεται πίσω όταν το παιχνίδι κλείσει. Απενεργοποιήστε το αν η συνεδρία κλείνει λίγο μετά την εκκίνηση παιχνιδιών. Ένα όριο RAM παραπάνω εξακολουθεί να συμπιέζει το Steam όταν η συνεδρία το ξεπεράσει.</string>
<string name="perf_ram_cap">Όριο RAM</string>
<string name="perf_ram_cap_hint">Ισχύει όσο τρέχει ο πελάτης Steam, σε λειτουργία Steam ή από την επιφάνεια εργασίας. Όταν η συνεδρία χρησιμοποιεί περισσότερη, το Steam και έπειτα οι άλλες υποστηριζόμενες διεργασίες της συνεδρίας συμπιέζονται στη zRAM. Ήπιο όριο: τίποτα δεν κλείνει, αλλά τα παιχνίδια μπορεί να κολλάνε όσο επιστρέφουν οι σελίδες.</string>
<string name="perf_ram_cap_unavailable">Απαιτεί zRAM swap, που δεν υπάρχει σε αυτή τη συσκευή.</string>
<string name="perf_vram_cap">Όριο VRAM</string>
<string name="perf_vram_cap_hint">Αναφέρει αυτόν τον προϋπολογισμό μνήμης βίντεο σε παιχνίδια Direct3D 9 έως 12 για να μειωθεί η χρήση μνήμης. Τα παιχνίδια μπορεί να τον υπερβούν· δεν προσθέτει σελιδοποίηση GPU ούτε εγγυάται προστασία από σφάλματα έλλειψης μνήμης. Ισχύει από την επόμενη συνεδρία.</string>
<string name="perf_gpuclock">Διατήρηση της GPU στη μέγιστη συχνότητά της</string>
<string name="perf_gpuclock_hint">Μόνο Adreno. Λιγότερα κολλήματα, μεγαλύτερη χρήση μπαταρίας και θερμότητα.</string>
<string name="perf_fixes">Διορθώσεις συνεδρίας</string>
<string name="perf_sysmem">Turnip: απόδοση sysmem</string>
<string name="perf_sysmem_hint">Ισχύει για το πρόγραμμα-πελάτη Steam και τα παιχνίδια. Απαιτείται σε Adreno 710/720/722.</string>
@@ -811,7 +798,6 @@
<string name="drawer_pc_keyboard">Πληκτρολόγιο PC</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Δεύτερη οθόνη</string>
<string name="drawer_second_screen_mode">Λειτουργία</string>
<string name="drawer_second_screen_shows">Εμφανίζει</string>
<string name="drawer_android_apps">Εφαρμογές Android</string>
<string name="drawer_launch_app">Εκκίνηση εφαρμογής</string>
@@ -2287,6 +2273,17 @@
<string name="pextra_checksum_mismatch">Αναντιστοιχία αθροίσματος ελέγχου· η λήψη διαγράφηκε</string>
<string name="pextra_session_started">Μια συνεδρία ξεκίνησε κατά τη λήψη· διακόψτε την πριν εγκαταστήσετε εργαλεία συμβατότητας</string>
<string name="pextra_installing">Εγκατάσταση %1$s</string>
<string name="xproton_title">Πειραματικές εκδόσεις</string>
<string name="xproton_install_file">Εγκατάσταση από αρχείο</string>
<string name="xproton_archive_unsafe">Το αρχείο περιέχει μη ασφαλή σύνδεσμο ή διαδρομή</string>
<string name="xproton_archive_invalid">Μη υποστηριζόμενο ή μη έγκυρο αρχείο</string>
<string name="xproton_no_space">Δεν υπάρχει αρκετός ελεύθερος χώρος για αυτήν την έκδοση Proton</string>
<string name="xproton_unpacking">Αποσυσκευασία του Proton (λίγα λεπτά)</string>
<string name="xproton_untar_failed">Η αποσυσκευασία απέτυχε (tar %1$d)</string>
<string name="xproton_no_tree">Το αρχείο δεν περιέχει έκδοση Proton</string>
<string name="xproton_place_failed">Δεν ήταν δυνατή η τοποθέτηση της έκδοσης Proton</string>
<string name="xproton_remove_failed">Δεν ήταν δυνατή η πλήρης κατάργηση του %1$s</string>
<string name="xproton_installed">Το πειραματικό Proton εγκαταστάθηκε. Επιλέξτε το στο Steam → Ιδιότητες → Συμβατότητα.</string>
<string name="pextra_install_failed">Η εγκατάσταση του %1$s απέτυχε (έξοδος %2$d)</string>
<string name="pextra_could_not_install">Δεν ήταν δυνατή η εγκατάσταση του %1$s</string>
<string name="esync_fetching">Λήψη πακέτου droiddeck-esync</string>
@@ -3317,10 +3314,19 @@
<string name="storage_shared_prefix">Κοινό prefix του Steam</string>
<string name="storage_shared_prefix_detail">Το Steam εκτελεί εδώ τα δικά του βοηθητικά προγράμματα Windows</string>
<string name="storage_reset_shared_confirm">Το διαγράφει (%1$s). Το Steam δημιουργεί νέο την επόμενη φορά που θα το χρειαστεί.</string>
<string name="storage_remove_launcher_confirm">Διαγράφει το πρόθεμα Wine και την cache των shader αυτής της εφαρμογής καταστήματος (%1$s), μαζί με τη σύνδεση και όσες αποθηκεύσεις υπάρχουν μόνο εκεί. Τα παιχνίδια που τρέχουν σε αυτό παίρνουν νέο πρόθεμα και ίσως χρειαστεί να ρυθμίσετε ξανά την εφαρμογή. Οι αποθηκεύσεις στο cloud μένουν στον λογαριασμό σας.</string>
<string name="storage_system_clearable">Μπορούν να εκκαθαριστούν %1$s</string>
<string name="storage_item_system_caches">Cache του Linux και του Steam</string>
<string name="storage_item_system_caches_detail">Παλιά προσωρινά αρχεία, πακέτα που κατέβηκαν και η cache ιστού του Steam</string>
<string name="storage_cache_temp">Παλιά προσωρινά αρχεία</string>
<string name="storage_cache_packages">Πακέτα που κατέβηκαν</string>
<string name="storage_cache_steam_web">Cache ιστού του Steam</string>
<string name="storage_cache_steam_corrupt">Κατεστραμμένες λήψεις Steam</string>
<string name="storage_cache_detail">Δημιουργούνται ξανά όταν χρειάζεται</string>
<string name="storage_clear">Εκκαθάριση</string>
<string name="storage_launcher_prefix">Μια εφαρμογή καταστήματος και τα παιχνίδια που τρέχουν με αυτήν</string>
<string name="storage_launcher_used_by">Χρησιμοποιείται από %1$s</string>
<string name="storage_shortcut_app">Παιχνίδι εκτός Steam %1$s</string>
<string name="storage_unknown_prefix_detail">Δεν αντιστοιχεί σε παιχνίδι, οπότε διατηρείται</string>
<string name="storage_remove_selected">Αφαίρεση επιλεγμένων · %1$s</string>
<string name="storage_uninstall_selected">Κατάργηση επιλεγμένων · %1$s</string>
<string name="storage_bulk_prefixes">Prefix Wine</string>
@@ -4065,4 +4071,18 @@
<string name="display_scaling_integer">Ακέραιος</string>
<string name="display_scaling_fit">Προσαρμογή</string>
<string name="drawer_antialiasing">Εξομάλυνση ακμών</string>
</resources>
<string name="theme_custom">Προσαρμοσμένο</string>
<string name="theme_custom_detail">Επιλέξτε ξεχωριστά κάθε χρώμα της διεπαφής.</string>
<string name="theme_custom_background">Φόντο</string>
<string name="theme_custom_surface">Πλαίσια</string>
<string name="theme_custom_surface_variant">Ανυψωμένα πλαίσια</string>
<string name="theme_custom_line">Διαχωριστικά</string>
<string name="theme_custom_line2">Περιγράμματα</string>
<string name="theme_custom_on_background">Κύριο κείμενο</string>
<string name="theme_custom_on_surface_variant">Δευτερεύον κείμενο</string>
<string name="theme_custom_primary">Κουμπιά και κύριο χρώμα έμφασης</string>
<string name="theme_custom_on_primary">Κείμενο κουμπιών</string>
<string name="theme_custom_signal">Επισημάνσεις</string>
<string name="theme_custom_good">Επιτυχία</string>
<string name="theme_custom_error">Σφάλμα</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Añade bibliotecas de Steam desde una tarjeta SD, una unidad USB o un SSD, y DroidDeck mantiene los juegos juntos en tu Biblioteca.</item>
<item>Tiendas te permite iniciar sesión en Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io y Game Jolt, y luego instalar y actualizar sus juegos desde DroidDeck.</item>
<item>Componentes como FEX, DXVK y VKD3D-Proton se actualizan solos, y Proton Experimental ARM64 es el predeterminado, o Proton 11.0 ARM64 una vez instalada esa versión.</item>
<item>Comprimir Steam mientras se ejecuta un juego libera RAM en dispositivos con poca memoria.</item>
<item>Desliza desde el borde derecho para abrir el menú de sesión: modo touchpad, Teclado de PC, Modo de baja latencia, perfil del juego y más.</item>
<item>¿El juego va lento? Limita la tasa de fotogramas en Quick Access y prueba otra versión de Proton o un ajuste preestablecido de FEX en los componentes del juego.</item>
<item>¿Audio del juego entrecortado o ausente? Prueba el interruptor DirectAudio para juegos en los ajustes de Steam, en Audio.</item>
@@ -623,20 +622,8 @@
<string name="perf_gsrealtime">gamescope: cola de GPU en tiempo real</string>
<string name="perf_gsrealtime_hint">Da prioridad al trabajo de GPU del compositor. Puede suavizar el ritmo de fotogramas a costa de algo de rendimiento en los juegos.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Memoria</string>
<string name="perf_cap_off">Desactivado</string>
<string name="perf_cap_auto">Predeterminado del controlador</string>
<string name="perf_zram_client">Comprimir Steam mientras se ejecuta un juego</string>
<string name="perf_zram_idle">Comprimir memoria inactiva del juego</string>
<string name="perf_zram_idle_hint">Comprime la memoria inactiva del juego cuando queda poca RAM. Desactívalo si los juegos se congelan unos segundos cada medio minuto aproximadamente. Se aplica la próxima vez que se inicie la sesión.</string>
<string name="perf_zram_client_hint">20 s después de que empiece un juego, el cliente de Steam se comprime en zRAM para dejarle más memoria al juego, y se vuelve a leer cuando el juego se cierra. Desactívalo si la sesión se cierra poco después de iniciar los juegos. Un límite de RAM definido arriba sigue comprimiendo Steam cuando la sesión lo supera.</string>
<string name="perf_ram_cap">Límite de RAM</string>
<string name="perf_ram_cap_hint">Se aplica mientras se ejecuta el cliente de Steam, en modo Steam o desde el escritorio. Cuando la sesión usa más de esto, Steam y luego los demás procesos compatibles de la sesión se comprimen en zRAM. Es un límite flexible: no se cierra nada, pero los juegos pueden tener tirones mientras se recuperan las páginas.</string>
<string name="perf_ram_cap_unavailable">Requiere swap de zRAM, y este dispositivo no lo tiene.</string>
<string name="perf_vram_cap">Límite de VRAM</string>
<string name="perf_vram_cap_hint">Informa a los juegos Direct3D 9 a 12 de este presupuesto de memoria de vídeo para reducir su uso. Los juegos pueden superarlo; no añade paginación de GPU ni garantiza evitar fallos por falta de memoria. Se aplica en la próxima sesión.</string>
<string name="perf_gpuclock">Mantener la GPU a su reloj máximo</string>
<string name="perf_gpuclock_hint">Solo Adreno. Menos tirones, más consumo de batería y calor.</string>
<string name="perf_fixes">Correcciones de sesión</string>
<string name="perf_sysmem">Turnip: renderizado sysmem</string>
<string name="perf_sysmem_hint">Se aplica al cliente de Steam y a los juegos. Obligatorio en Adreno 710/720/722.</string>
@@ -813,7 +800,6 @@
<string name="drawer_pc_keyboard">Teclado de PC</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Segunda pantalla</string>
<string name="drawer_second_screen_mode">Modo</string>
<string name="drawer_second_screen_shows">Muestra</string>
<string name="drawer_android_apps">Apps de Android</string>
<string name="drawer_launch_app">Abrir una app</string>
@@ -2313,6 +2299,17 @@
<string name="pextra_checksum_mismatch">La suma de verificación no coincide; se eliminó la descarga</string>
<string name="pextra_session_started">Se inició una sesión durante la descarga; detenla antes de instalar herramientas de compatibilidad</string>
<string name="pextra_installing">Instalando %1$s</string>
<string name="xproton_title">Versiones experimentales</string>
<string name="xproton_install_file">Instalar desde archivo</string>
<string name="xproton_archive_unsafe">El archivo contiene un enlace o una ruta no segura</string>
<string name="xproton_archive_invalid">Archivo no compatible o no válido</string>
<string name="xproton_no_space">No hay espacio libre suficiente para esta versión de Proton</string>
<string name="xproton_unpacking">Desempaquetando Proton (unos minutos)</string>
<string name="xproton_untar_failed">Error al desempaquetar (tar %1$d)</string>
<string name="xproton_no_tree">El archivo no contiene ninguna versión de Proton</string>
<string name="xproton_place_failed">No se pudo colocar la versión de Proton</string>
<string name="xproton_remove_failed">No se pudo quitar %1$s por completo</string>
<string name="xproton_installed">Proton experimental instalado. Elígelo en Steam → Propiedades → Compatibilidad.</string>
<string name="pextra_install_failed">Falló la instalación de %1$s (salida %2$d)</string>
<string name="pextra_could_not_install">No se pudo instalar %1$s</string>
<string name="esync_fetching">Descargando el paquete droiddeck-esync</string>
@@ -3354,10 +3351,19 @@
<string name="storage_shared_prefix">Prefijo compartido de Steam</string>
<string name="storage_shared_prefix_detail">Steam ejecuta aquí sus propias herramientas de Windows</string>
<string name="storage_reset_shared_confirm">Lo borra (%1$s). Steam crea uno nuevo la próxima vez que lo necesite.</string>
<string name="storage_remove_launcher_confirm">Borra el prefijo de Wine y la caché de shaders de esta app de tienda (%1$s), junto con su inicio de sesión y las partidas guardadas solo ahí. Los juegos que se ejecutan en él reciben un prefijo nuevo y puede que tengas que configurar la app de nuevo. Las partidas en la nube se quedan en tu cuenta.</string>
<string name="storage_system_clearable">Se pueden liberar %1$s</string>
<string name="storage_item_system_caches">Cachés de Linux y Steam</string>
<string name="storage_item_system_caches_detail">Archivos temporales antiguos, paquetes descargados y la caché web de Steam</string>
<string name="storage_cache_temp">Archivos temporales antiguos</string>
<string name="storage_cache_packages">Paquetes descargados</string>
<string name="storage_cache_steam_web">Caché web de Steam</string>
<string name="storage_cache_steam_corrupt">Descargas dañadas de Steam</string>
<string name="storage_cache_detail">Se vuelven a crear cuando hacen falta</string>
<string name="storage_clear">Borrar</string>
<string name="storage_launcher_prefix">Una app de tienda y los juegos que se ejecutan con ella</string>
<string name="storage_launcher_used_by">Usado por %1$s</string>
<string name="storage_shortcut_app">Juego que no es de Steam %1$s</string>
<string name="storage_unknown_prefix_detail">No coincide con ningún juego, así que se conserva</string>
<string name="storage_remove_selected">Quitar selección · %1$s</string>
<string name="storage_uninstall_selected">Desinstalar selección · %1$s</string>
<string name="storage_bulk_prefixes">Prefijos de Wine</string>
@@ -4105,4 +4111,18 @@
<string name="display_scaling_integer">Entero</string>
<string name="display_scaling_fit">Ajustar</string>
<string name="drawer_antialiasing">Suavizado de bordes</string>
</resources>
<string name="theme_custom">Personalizado</string>
<string name="theme_custom_detail">Elige cada color de la interfaz por separado.</string>
<string name="theme_custom_background">Fondo</string>
<string name="theme_custom_surface">Paneles</string>
<string name="theme_custom_surface_variant">Paneles elevados</string>
<string name="theme_custom_line">Separadores</string>
<string name="theme_custom_line2">Bordes</string>
<string name="theme_custom_on_background">Texto principal</string>
<string name="theme_custom_on_surface_variant">Texto secundario</string>
<string name="theme_custom_primary">Botones y color principal</string>
<string name="theme_custom_on_primary">Texto de los botones</string>
<string name="theme_custom_signal">Destacados</string>
<string name="theme_custom_good">Éxito</string>
<string name="theme_custom_error">Error</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Lisää Steam-kirjastoja SD-kortilta, USB-asemalta tai SSD-levyltä, ja DroidDeck pitää pelit yhdessä Kirjastossasi.</item>
<item>Kaupat-osiossa voit kirjautua sisään palveluihin Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io ja Game Jolt sekä asentaa ja päivittää niiden pelejä DroidDeckistä.</item>
<item>Komponentit, kuten FEX, DXVK ja VKD3D-Proton, päivittyvät itsestään, ja oletuksena on Proton Experimental ARM64 tai Proton 11.0 ARM64, kun kyseinen versio on asennettu.</item>
<item>Pakkaa Steam pelin ollessa käynnissä vapauttaa RAM-muistia laitteilla, joilla muisti on vähissä.</item>
<item>Pyyhkäise oikeasta reunasta sisäänpäin avataksesi istuntovalikon: kosketuslevytila, PC-näppäimistö, matalan viiveen tila, pelin profiili ja muuta.</item>
<item>Peli pyörii hitaasti? Rajoita kuvanopeutta Pikavalikossa ja kokeile sitten toista Proton-versiota tai FEX-esiasetusta pelin komponenteissa.</item>
<item>Rätisevä tai puuttuva pelin ääni? Kokeile Steamin asetuksissa kohdassa Ääni asetusta DirectAudio peleille.</item>
@@ -621,20 +620,8 @@
<string name="perf_gsrealtime">gamescope: reaaliaikainen GPU-jono</string>
<string name="perf_gsrealtime_hint">Priorisoi kompositorin GPU-työtä. Voi tasoittaa kuvanopeuden tahditusta pelien kustannuksella.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Muisti</string>
<string name="perf_cap_off">Pois</string>
<string name="perf_cap_auto">Ajurin oletus</string>
<string name="perf_zram_client">Pakkaa Steam pelin ollessa käynnissä</string>
<string name="perf_zram_idle">Pakkaa pelin käyttämätöntä muistia</string>
<string name="perf_zram_idle_hint">Siirtää pelin käyttämätöntä muistia zRAMiin, kun RAM-muisti vähenee. Poista tämä käytöstä, jos pelit jäätyvät muutamaksi sekunniksi noin puolen minuutin välein. Tulee voimaan, kun istunto käynnistyy seuraavan kerran.</string>
<string name="perf_zram_client_hint">20 s pelin käynnistymisen jälkeen Steam-asiakasohjelma pakataan zRAMiin, jotta pelille jää enemmän muistia, ja luetaan takaisin, kun peli sulkeutuu. Poista tämä käytöstä, jos istunto sulkeutuu pian pelien käynnistymisen jälkeen. Yllä oleva RAM-raja pakkaa silti Steamin, kun istunto ylittää sen.</string>
<string name="perf_ram_cap">RAM-raja</string>
<string name="perf_ram_cap_hint">Koskee aikaa, jolloin Steam-asiakasohjelma on käynnissä, Steam-tilassa tai työpöydältä. Kun istunto käyttää tätä enemmän, Steam ja sen jälkeen istunnon muut tuetut prosessit pakataan zRAMiin. Pehmeä raja: mitään ei suljeta, mutta pelit voivat nykiä, kun sivuja luetaan takaisin.</string>
<string name="perf_ram_cap_unavailable">Vaatii zRAM-swapin, jota tässä laitteessa ei ole.</string>
<string name="perf_vram_cap">VRAM-raja</string>
<string name="perf_vram_cap_hint">Ilmoittaa tämän videomuistibudjetin Direct3D 9–12 -peleille muistin käytön vähentämiseksi. Pelit voivat ylittää sen; tämä ei lisää GPU-sivutusta eikä takaa suojaa muistin loppumisesta johtuvilta kaatumisilta. Tulee voimaan seuraavassa istunnossa.</string>
<string name="perf_gpuclock">Pidä GPU huippukellotaajuudessaan</string>
<string name="perf_gpuclock_hint">Vain Adreno. Vähemmän nykäyksiä, enemmän akun kulutusta ja lämpöä.</string>
<string name="perf_fixes">Istunnon korjaukset</string>
<string name="perf_sysmem">Turnip: sysmem-renderöinti</string>
<string name="perf_sysmem_hint">Koskee Steam-asiakasohjelmaa ja pelejä. Pakollinen Adreno 710/720/722:lla.</string>
@@ -811,7 +798,6 @@
<string name="drawer_pc_keyboard">PC-näppäimistö</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Toinen näyttö</string>
<string name="drawer_second_screen_mode">Tila</string>
<string name="drawer_second_screen_shows">Näyttää</string>
<string name="drawer_android_apps">Android-sovellukset</string>
<string name="drawer_launch_app">Käynnistä sovellus</string>
@@ -2287,6 +2273,17 @@
<string name="pextra_checksum_mismatch">Tarkistussumma ei täsmää; lataus poistettiin</string>
<string name="pextra_session_started">Istunto käynnistyi latauksen aikana; pysäytä se ennen yhteensopivuustyökalujen asentamista</string>
<string name="pextra_installing">Asennetaan %1$s</string>
<string name="xproton_title">Kokeelliset versiot</string>
<string name="xproton_install_file">Asenna tiedostosta</string>
<string name="xproton_archive_unsafe">Arkisto sisältää vaarallisen linkin tai polun</string>
<string name="xproton_archive_invalid">Arkistoa ei tueta tai se on virheellinen</string>
<string name="xproton_no_space">Tälle Proton-versiolle ei ole tarpeeksi vapaata tilaa</string>
<string name="xproton_unpacking">Puretaan Protonia (muutama minuutti)</string>
<string name="xproton_untar_failed">Purku epäonnistui (tar %1$d)</string>
<string name="xproton_no_tree">Arkisto ei sisällä Proton-versiota</string>
<string name="xproton_place_failed">Proton-versiota ei voitu sijoittaa</string>
<string name="xproton_remove_failed">Kohdetta %1$s ei voitu poistaa kokonaan</string>
<string name="xproton_installed">Kokeellinen Proton asennettu. Valitse se kohdassa Steam → Ominaisuudet → Yhteensopivuus.</string>
<string name="pextra_install_failed">%1$s-asennus epäonnistui (poistumiskoodi %2$d)</string>
<string name="pextra_could_not_install">Kohdetta %1$s ei voitu asentaa</string>
<string name="esync_fetching">Haetaan droiddeck-esync-pakettia</string>
@@ -3317,10 +3314,19 @@
<string name="storage_shared_prefix">Steamin jaettu etuliite</string>
<string name="storage_shared_prefix_detail">Steam suorittaa täällä omia Windows-apuohjelmiaan</string>
<string name="storage_reset_shared_confirm">Poistaa sen (%1$s). Steam luo uuden, kun tarvitsee sitä seuraavan kerran.</string>
<string name="storage_remove_launcher_confirm">Poistaa tämän kauppasovelluksen Wine-etuliitteen ja varjostinvälimuistin (%1$s) sekä kirjautumisen ja vain siellä olevat tallennukset. Siinä toimivat pelit saavat uuden etuliitteen, ja sovellus pitää ehkä ottaa uudelleen käyttöön. Pilvitallennukset säilyvät tililläsi.</string>
<string name="storage_system_clearable">%1$s voidaan tyhjentää</string>
<string name="storage_item_system_caches">Linuxin ja Steamin välimuistit</string>
<string name="storage_item_system_caches_detail">Vanhat väliaikaistiedostot, ladatut paketit ja Steamin verkkovälimuisti</string>
<string name="storage_cache_temp">Vanhat väliaikaistiedostot</string>
<string name="storage_cache_packages">Ladatut paketit</string>
<string name="storage_cache_steam_web">Steamin verkkovälimuisti</string>
<string name="storage_cache_steam_corrupt">Vioittuneet Steam-lataukset</string>
<string name="storage_cache_detail">Luodaan tarvittaessa uudelleen</string>
<string name="storage_clear">Tyhjennä</string>
<string name="storage_launcher_prefix">Kauppasovellus ja pelit, jotka toimivat sen kanssa</string>
<string name="storage_launcher_used_by">Käyttää: %1$s</string>
<string name="storage_shortcut_app">Muu kuin Steam-peli %1$s</string>
<string name="storage_unknown_prefix_detail">Ei vastaa mitään peliä, joten se säilytetään</string>
<string name="storage_remove_selected">Poista valitut · %1$s</string>
<string name="storage_uninstall_selected">Poista valittujen asennus · %1$s</string>
<string name="storage_bulk_prefixes">Wine-prefixit</string>
@@ -4065,4 +4071,18 @@
<string name="display_scaling_integer">Kokonaisluku</string>
<string name="display_scaling_fit">Sovita</string>
<string name="drawer_antialiasing">Reunanpehmennys</string>
</resources>
<string name="theme_custom">Mukautettu</string>
<string name="theme_custom_detail">Valitse käyttöliittymän jokainen väri erikseen.</string>
<string name="theme_custom_background">Tausta</string>
<string name="theme_custom_surface">Paneelit</string>
<string name="theme_custom_surface_variant">Korotetut paneelit</string>
<string name="theme_custom_line">Erottimet</string>
<string name="theme_custom_line2">Reunat</string>
<string name="theme_custom_on_background">Pääteksti</string>
<string name="theme_custom_on_surface_variant">Toissijainen teksti</string>
<string name="theme_custom_primary">Painikkeet ja pääkorostus</string>
<string name="theme_custom_on_primary">Painikkeiden teksti</string>
<string name="theme_custom_signal">Korostukset</string>
<string name="theme_custom_good">Onnistuminen</string>
<string name="theme_custom_error">Virhe</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Ajoutez des bibliothèques Steam depuis une carte SD, une clé USB ou un SSD, et DroidDeck réunit les jeux dans votre Bibliothèque.</item>
<item>Boutiques vous permet de vous connecter à Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io et Game Jolt, puis d\'installer et de mettre à jour leurs jeux depuis DroidDeck.</item>
<item>Les composants comme FEX, DXVK et VKD3D-Proton se mettent à jour seuls, et Proton Experimental ARM64 est la valeur par défaut, ou Proton 11.0 ARM64 une fois cette version installée.</item>
<item>Compresser Steam pendant un jeu libère de la RAM sur les appareils qui en manquent.</item>
<item>Balayez depuis le bord droit pour ouvrir le menu de session : mode pavé tactile, Clavier PC, Mode faible latence, Profil du jeu et plus encore.</item>
<item>Jeu lent ? Limitez la fréquence d\'images dans Accès rapide, puis essayez une autre version de Proton ou un autre préréglage FEX dans les composants du jeu.</item>
<item>Audio du jeu qui grésille ou absent ? Essayez l\'option Utiliser DirectAudio pour le jeu dans les paramètres Steam, sous Audio.</item>
@@ -623,20 +622,8 @@
<string name="perf_gsrealtime">gamescope : file d\'attente GPU temps réel</string>
<string name="perf_gsrealtime_hint">Augmente la priorité du travail GPU du compositeur. Peut améliorer la stabilité du temps de frame, mais consomme une partie des performances du jeu.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Mémoire</string>
<string name="perf_cap_off">Désactivé</string>
<string name="perf_cap_auto">Valeur par défaut du pilote</string>
<string name="perf_zram_client">Compresser Steam pendant un jeu</string>
<string name="perf_zram_idle">Compresser la mémoire inactive du jeu</string>
<string name="perf_zram_idle_hint">Compresse la mémoire inactive du jeu quand la RAM manque. Désactivez-le si les jeux se figent quelques secondes environ toutes les trente secondes. S\'applique au prochain démarrage de la session.</string>
<string name="perf_zram_client_hint">20 s après le démarrage d\'un jeu, le client Steam est compressé dans zRAM pour laisser plus de mémoire au jeu, puis relu à la fermeture du jeu. Désactivez cette option si la session se ferme peu après le démarrage des jeux. Une limite de RAM ci-dessus compresse toujours Steam lorsque la session la dépasse.</string>
<string name="perf_ram_cap">Limite de RAM</string>
<string name="perf_ram_cap_hint">S\'applique tant que le client Steam fonctionne, en mode Steam ou depuis le bureau. Lorsque la session dépasse cette valeur, Steam puis les autres processus pris en charge de la session sont compressés dans zRAM. Limite souple : rien n\'est fermé, mais les jeux peuvent saccader pendant le rechargement des pages.</string>
<string name="perf_ram_cap_unavailable">Nécessite un swap zRAM, dont cet appareil ne dispose pas.</string>
<string name="perf_vram_cap">Limite de VRAM</string>
<string name="perf_vram_cap_hint">Signale ce budget de mémoire vidéo aux jeux Direct3D 9 à 12 pour réduire leur consommation. Les jeux peuvent le dépasser ; cela ne fournit pas de pagination GPU et ne garantit pas une protection contre les plantages par manque de mémoire. Prend effet à la prochaine session.</string>
<string name="perf_gpuclock">Maintenir le GPU à sa fréquence maximale</string>
<string name="perf_gpuclock_hint">Uniquement pour Adreno. Moins de saccades, mais plus de consommation d\'énergie et de chaleur.</string>
<string name="perf_fixes">Correctifs de session</string>
<string name="perf_sysmem">Turnip : rendu sysmem</string>
<string name="perf_sysmem_hint">S’applique au client Steam et aux jeux. Requis sur Adreno 710/720/722.</string>
@@ -813,7 +800,6 @@
<string name="drawer_pc_keyboard">Clavier PC</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Deuxième écran</string>
<string name="drawer_second_screen_mode">Mode</string>
<string name="drawer_second_screen_shows">Afficher</string>
<string name="drawer_android_apps">Applications Android</string>
<string name="drawer_launch_app">Lancer l\'application</string>
@@ -2312,6 +2298,17 @@
<string name="pextra_checksum_mismatch">Somme de contrôle incorrecte ; le téléchargement a été supprimé</string>
<string name="pextra_session_started">Une session a démarré pendant le téléchargement ; arrêtez-la avant d\'installer des outils de compatibilité</string>
<string name="pextra_installing">Installation de %1$s</string>
<string name="xproton_title">Versions expérimentales</string>
<string name="xproton_install_file">Installer depuis un fichier</string>
<string name="xproton_archive_unsafe">L’archive contient un lien ou chemin dangereux</string>
<string name="xproton_archive_invalid">Archive non prise en charge ou invalide</string>
<string name="xproton_no_space">Espace libre insuffisant pour cette version de Proton</string>
<string name="xproton_unpacking">Extraction de Proton (quelques minutes)</string>
<string name="xproton_untar_failed">Échec de l\'extraction (tar %1$d)</string>
<string name="xproton_no_tree">L\'archive ne contient aucune version de Proton</string>
<string name="xproton_place_failed">Impossible de placer la version de Proton</string>
<string name="xproton_remove_failed">Impossible de supprimer entièrement %1$s</string>
<string name="xproton_installed">Proton expérimental installé. Sélectionnez-le dans Steam → Propriétés → Compatibilité.</string>
<string name="pextra_install_failed">Échec de l\'installation de %1$s (code %2$d)</string>
<string name="pextra_could_not_install">Impossible d\'installer %1$s</string>
<string name="esync_fetching">Récupération du pack droiddeck-esync</string>
@@ -3353,10 +3350,19 @@
<string name="storage_shared_prefix">Préfixe partagé de Steam</string>
<string name="storage_shared_prefix_detail">Steam y exécute ses propres utilitaires Windows</string>
<string name="storage_reset_shared_confirm">Le supprime (%1$s). Steam en crée un nouveau la prochaine fois qu\'il en a besoin.</string>
<string name="storage_remove_launcher_confirm">Supprime le préfixe Wine et le cache de shaders de cette app de boutique (%1$s), avec sa connexion et les sauvegardes présentes uniquement là. Les jeux qui s\'y exécutent reçoivent un nouveau préfixe, et il faudra peut-être reconfigurer l\'app. Les sauvegardes cloud restent dans votre compte.</string>
<string name="storage_system_clearable">%1$s peuvent être libérés</string>
<string name="storage_item_system_caches">Caches de Linux et de Steam</string>
<string name="storage_item_system_caches_detail">Anciens fichiers temporaires, paquets téléchargés et cache web de Steam</string>
<string name="storage_cache_temp">Anciens fichiers temporaires</string>
<string name="storage_cache_packages">Paquets téléchargés</string>
<string name="storage_cache_steam_web">Cache web de Steam</string>
<string name="storage_cache_steam_corrupt">Téléchargements Steam endommagés</string>
<string name="storage_cache_detail">Recréés au besoin</string>
<string name="storage_clear">Vider</string>
<string name="storage_launcher_prefix">Une app de boutique et les jeux qui tournent avec elle</string>
<string name="storage_launcher_used_by">Utilisé par %1$s</string>
<string name="storage_shortcut_app">Jeu hors Steam %1$s</string>
<string name="storage_unknown_prefix_detail">Associé à aucun jeu, il est donc conservé</string>
<string name="storage_remove_selected">Supprimer la sélection · %1$s</string>
<string name="storage_uninstall_selected">Désinstaller la sélection · %1$s</string>
<string name="storage_bulk_prefixes">Préfixes Wine</string>
@@ -4104,4 +4110,18 @@
<string name="display_scaling_integer">Entier</string>
<string name="display_scaling_fit">Ajuster</string>
<string name="drawer_antialiasing">Anticrénelage</string>
</resources>
<string name="theme_custom">Personnalisé</string>
<string name="theme_custom_detail">Choisissez séparément chaque couleur de l’interface.</string>
<string name="theme_custom_background">Arrière-plan</string>
<string name="theme_custom_surface">Panneaux</string>
<string name="theme_custom_surface_variant">Panneaux surélevés</string>
<string name="theme_custom_line">Séparateurs</string>
<string name="theme_custom_line2">Bordures</string>
<string name="theme_custom_on_background">Texte principal</string>
<string name="theme_custom_on_surface_variant">Texte secondaire</string>
<string name="theme_custom_primary">Boutons et accent principal</string>
<string name="theme_custom_on_primary">Texte des boutons</string>
<string name="theme_custom_signal">Mises en évidence</string>
<string name="theme_custom_good">Succès</string>
<string name="theme_custom_error">Erreur</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>SD कार्ड, USB ड्राइव या SSD से Steam लाइब्रेरी जोड़ें, और DroidDeck गेम को आपकी लाइब्रेरी में एक साथ रखता है।</item>
<item>स्टोर से आप Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io और Game Jolt में साइन इन कर सकते हैं, फिर DroidDeck से उनके गेम इंस्टॉल और अपडेट कर सकते हैं।</item>
<item>FEX, DXVK और VKD3D-Proton जैसे कॉम्पोनेंट खुद अपडेट होते हैं, और डिफ़ॉल्ट Proton Experimental ARM64 है, या वह बिल्ड इंस्टॉल होने पर Proton 11.0 ARM64।</item>
<item>गेम चलते समय Steam को कंप्रेस करें कम RAM वाले डिवाइस पर RAM खाली करता है।</item>
<item>सत्र मेनू खोलने के लिए दाएँ किनारे से अंदर की ओर स्वाइप करें: टचपैड मोड, पीसी कीबोर्ड, लो लेटेंसी मोड, गेम प्रोफ़ाइल और बहुत कुछ।</item>
<item>गेम धीमा चल रहा है? Quick Access में फ़्रेम रेट सीमित करें, फिर गेम के कॉम्पोनेंट में कोई दूसरा Proton वर्शन या FEX प्रीसेट आज़माएँ।</item>
<item>गेम की आवाज़ में खरखराहट है या आवाज़ नहीं आ रही? Steam सेटिंग में ऑडियो के अंतर्गत गेम के लिए DirectAudio टॉगल आज़माएँ।</item>
@@ -621,20 +620,8 @@
<string name="perf_gsrealtime">gamescope: रीयलटाइम GPU क्यू</string>
<string name="perf_gsrealtime_hint">कम्पोज़िटर के GPU काम को प्राथमिकता देता है। गेम की कुछ कीमत पर फ़्रेम पेसिंग को स्मूथ कर सकता है।</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">मेमोरी</string>
<string name="perf_cap_off">बंद</string>
<string name="perf_cap_auto">ड्राइवर डिफ़ॉल्ट</string>
<string name="perf_zram_client">गेम चलते समय Steam को कंप्रेस करें</string>
<string name="perf_zram_idle">गेम की निष्क्रिय मेमोरी को संपीड़ित करें</string>
<string name="perf_zram_idle_hint">RAM कम होने पर गेम की निष्क्रिय मेमोरी को पेज करता है। अगर गेम लगभग हर आधे मिनट में कुछ सेकंड के लिए रुकते हैं, तो इसे बंद करें। अगली बार सत्र शुरू होने पर लागू होता है।</string>
<string name="perf_zram_client_hint">गेम शुरू होने के 20 s बाद, Steam क्लाइंट को zRAM में कंप्रेस किया जाता है ताकि गेम को ज़्यादा मेमोरी मिले, और गेम बंद होने पर वापस पढ़ा जाता है। अगर गेम शुरू होने के कुछ देर बाद सेशन बंद हो जाता है तो इसे बंद करें। ऊपर दी गई RAM सीमा पार होने पर भी Steam कंप्रेस होता है।</string>
<string name="perf_ram_cap">RAM सीमा</string>
<string name="perf_ram_cap_hint">Steam क्लाइंट चलते समय लागू होती है, Steam मोड में या डेस्कटॉप से। जब सेशन इससे ज़्यादा इस्तेमाल करता है, तो Steam और फिर सेशन की दूसरी समर्थित प्रोसेस zRAM में कंप्रेस होती हैं। यह सॉफ़्ट सीमा है: कुछ बंद नहीं होता, लेकिन पेज वापस आते समय गेम अटक सकते हैं।</string>
<string name="perf_ram_cap_unavailable">zRAM स्वैप चाहिए, जो इस डिवाइस में नहीं है।</string>
<string name="perf_vram_cap">VRAM सीमा</string>
<string name="perf_vram_cap_hint">मेमोरी का उपयोग कम करने के लिए Direct3D 9 से 12 गेम को यह वीडियो मेमोरी बजट बताता है। गेम इसे पार कर सकते हैं; यह GPU पेजिंग नहीं जोड़ता और मेमोरी खत्म होने से क्रैश रोकने की गारंटी नहीं देता। अगले सत्र से लागू होगा।</string>
<string name="perf_gpuclock">GPU को उसकी टॉप क्लॉक पर बनाए रखें</string>
<string name="perf_gpuclock_hint">सिर्फ़ Adreno के लिए। कम हिचकोले, लेकिन ज़्यादा बैटरी खर्च और गर्मी।</string>
<string name="perf_fixes">सेशन फ़िक्स</string>
<string name="perf_sysmem">Turnip: sysmem रेंडरिंग</string>
<string name="perf_sysmem_hint">Steam क्लाइंट और गेम पर लागू। Adreno 710/720/722 पर ज़रूरी।</string>
@@ -811,7 +798,6 @@
<string name="drawer_pc_keyboard">पीसी कीबोर्ड</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">दूसरी स्क्रीन</string>
<string name="drawer_second_screen_mode">मोड</string>
<string name="drawer_second_screen_shows">दिखाता है</string>
<string name="drawer_android_apps">Android ऐप</string>
<string name="drawer_launch_app">ऐप लॉन्च करें</string>
@@ -2287,6 +2273,17 @@
<string name="pextra_checksum_mismatch">चेकसम मेल नहीं खाया; डाउनलोड हटा दिया गया</string>
<string name="pextra_session_started">डाउनलोड के दौरान एक सेशन शुरू हुआ; कम्पैटिबिलिटी टूल इंस्टॉल करने से पहले इसे बंद करें</string>
<string name="pextra_installing">%1$s इंस्टॉल हो रहा है</string>
<string name="xproton_title">प्रायोगिक बिल्ड</string>
<string name="xproton_install_file">फ़ाइल से इंस्टॉल करें</string>
<string name="xproton_archive_unsafe">आर्काइव में असुरक्षित लिंक या पथ है</string>
<string name="xproton_archive_invalid">असमर्थित या अमान्य आर्काइव</string>
<string name="xproton_no_space">इस Proton बिल्ड के लिए पर्याप्त खाली जगह नहीं है</string>
<string name="xproton_unpacking">Proton अनपैक हो रहा है (कुछ मिनट)</string>
<string name="xproton_untar_failed">अनपैक करना विफल रहा (tar %1$d)</string>
<string name="xproton_no_tree">आर्काइव में कोई Proton बिल्ड नहीं है</string>
<string name="xproton_place_failed">Proton बिल्ड को रखा नहीं जा सका</string>
<string name="xproton_remove_failed">%1$s को पूरी तरह हटाया नहीं जा सका</string>
<string name="xproton_installed">प्रायोगिक Proton इंस्टॉल हो गया। इसे Steam → गुण → संगतता में चुनें।</string>
<string name="pextra_install_failed">%1$s इंस्टॉलेशन विफल रहा (exit %2$d)</string>
<string name="pextra_could_not_install">%1$s इंस्टॉल नहीं हो सका</string>
<string name="esync_fetching">droiddeck-esync पैक लिया जा रहा है</string>
@@ -3317,10 +3314,19 @@
<string name="storage_shared_prefix">Steam का साझा प्रीफ़िक्स</string>
<string name="storage_shared_prefix_detail">Steam यहाँ अपने Windows हेल्पर चलाता है</string>
<string name="storage_reset_shared_confirm">इसे डिलीट करता है (%1$s)। अगली बार ज़रूरत पड़ने पर Steam नया बना लेता है।</string>
<string name="storage_remove_launcher_confirm">इस स्टोर ऐप का Wine प्रीफ़िक्स और शेडर कैश (%1$s) हटाता है, साथ में इसका साइन-इन और सिर्फ़ वहीं रखे सेव भी। इसमें चलने वाले गेम को नया प्रीफ़िक्स मिलता है, और ऐप को फिर से सेट अप करना पड़ सकता है। क्लाउड सेव आपके खाते में रहते हैं।</string>
<string name="storage_system_clearable">%1$s साफ़ किया जा सकता है</string>
<string name="storage_item_system_caches">Linux और Steam कैश</string>
<string name="storage_item_system_caches_detail">पुरानी अस्थायी फ़ाइलें, डाउनलोड किए गए पैकेज और Steam का वेब कैश</string>
<string name="storage_cache_temp">पुरानी अस्थायी फ़ाइलें</string>
<string name="storage_cache_packages">डाउनलोड किए गए पैकेज</string>
<string name="storage_cache_steam_web">Steam वेब कैश</string>
<string name="storage_cache_steam_corrupt">खराब Steam डाउनलोड</string>
<string name="storage_cache_detail">ज़रूरत पड़ने पर फिर से बनते हैं</string>
<string name="storage_clear">साफ़ करें</string>
<string name="storage_launcher_prefix">एक स्टोर ऐप और उसके साथ चलने वाले गेम</string>
<string name="storage_launcher_used_by">%1$s द्वारा इस्तेमाल</string>
<string name="storage_shortcut_app">गैर-Steam गेम %1$s</string>
<string name="storage_unknown_prefix_detail">किसी गेम से मेल नहीं खाता, इसलिए रखा जाता है</string>
<string name="storage_remove_selected">चुने गए हटाएँ · %1$s</string>
<string name="storage_uninstall_selected">चुने गए अनइंस्टॉल करें · %1$s</string>
<string name="storage_bulk_prefixes">Wine प्रीफ़िक्स</string>
@@ -4065,4 +4071,18 @@
<string name="display_scaling_integer">पूर्णांक</string>
<string name="display_scaling_fit">फ़िट</string>
<string name="drawer_antialiasing">एंटी-अलियासिंग</string>
</resources>
<string name="theme_custom">कस्टम</string>
<string name="theme_custom_detail">इंटरफ़ेस का हर रंग अलग-अलग चुनें।</string>
<string name="theme_custom_background">पृष्ठभूमि</string>
<string name="theme_custom_surface">पैनल</string>
<string name="theme_custom_surface_variant">उभरे हुए पैनल</string>
<string name="theme_custom_line">विभाजक</string>
<string name="theme_custom_line2">किनारे</string>
<string name="theme_custom_on_background">मुख्य टेक्स्ट</string>
<string name="theme_custom_on_surface_variant">द्वितीयक टेक्स्ट</string>
<string name="theme_custom_primary">बटन और मुख्य हाइलाइट</string>
<string name="theme_custom_on_primary">बटन का टेक्स्ट</string>
<string name="theme_custom_signal">हाइलाइट</string>
<string name="theme_custom_good">सफलता</string>
<string name="theme_custom_error">त्रुटि</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Adj hozzá Steam-könyvtárakat SD-kártyáról, USB-meghajtóról vagy SSD-ről, és a DroidDeck egy helyen tartja a játékokat a Könyvtárban.</item>
<item>Az Áruházak lehetővé teszi, hogy bejelentkezz a Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io és Game Jolt szolgáltatásokba, majd telepítsd és frissítsd a játékaikat a DroidDeckből.</item>
<item>Az olyan összetevők, mint a FEX, a DXVK és a VKD3D-Proton, maguktól frissülnek, az alapértelmezett pedig a Proton Experimental ARM64, vagy a Proton 11.0 ARM64, ha az a build telepítve van.</item>
<item>A Steam tömörítése játék közben RAM-ot szabadít fel a kevés memóriával rendelkező eszközökön.</item>
<item>Húzd be az ujjad a jobb szélről a munkamenet menü megnyitásához: érintőpad mód, PC-billentyűzet, alacsony késleltetésű mód, játékprofil és más.</item>
<item>Lassan fut a játék? Korlátozd a képkockasebességet a Gyors hozzáférésben, majd próbálj ki másik Proton-verziót vagy FEX-előbeállítást a játék összetevőiben.</item>
<item>Ropog vagy hiányzik a játék hangja? Próbáld ki a DirectAudio a játékokhoz kapcsolót a Steam beállításaiban a Hang alatt.</item>
@@ -621,20 +620,8 @@
<string name="perf_gsrealtime">gamescope: valós idejű GPU-sor</string>
<string name="perf_gsrealtime_hint">Előnyben részesíti a kompozitor GPU-munkáját. Egyenletesebbé teheti a képkocka-ütemezést, kisebb költséggel a játékoknak.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Memória</string>
<string name="perf_cap_off">Ki</string>
<string name="perf_cap_auto">Illesztőprogram alapértéke</string>
<string name="perf_zram_client">A Steam tömörítése játék közben</string>
<string name="perf_zram_idle">Játék inaktív memóriájának tömörítése</string>
<string name="perf_zram_idle_hint">Kevés RAM esetén tömöríti a játék inaktív memóriáját. Kapcsold ki, ha a játékok nagyjából félpercenként néhány másodpercre lefagynak. A munkamenet következő indításakor lép érvénybe.</string>
<string name="perf_zram_client_hint">20 mp-cel a játék indulása után a Steam-kliens a zRAM-ba tömörül, hogy több memória maradjon a játéknak, és a játék bezárásakor visszaolvasódik. Kapcsolja ki, ha a munkamenet röviddel a játékok indulása után bezárul. A fenti RAM-korlát akkor is tömöríti a Steamet, ha a munkamenet túllépi.</string>
<string name="perf_ram_cap">RAM-korlát</string>
<string name="perf_ram_cap_hint">Akkor érvényes, amikor a Steam-kliens fut, Steam módban vagy az asztalról. Ha a munkamenet ennél többet használ, a Steam, majd a munkamenet többi támogatott folyamata a zRAM-ba tömörül. Puha korlát: semmi sem zárul be, de a játékok akadhatnak, amíg a lapok visszatöltődnek.</string>
<string name="perf_ram_cap_unavailable">zRAM swap szükséges, amely ezen az eszközön nincs.</string>
<string name="perf_vram_cap">VRAM-korlát</string>
<string name="perf_vram_cap_hint">Ezt a videomemória-keretet jelzi a Direct3D 9–12 játékoknak a memóriahasználat csökkentésére. A játékok túlléphetik; nem biztosít GPU-lapozást, és nem garantál védelmet a memóriahiány miatti összeomlás ellen. A következő munkamenettől érvényes.</string>
<string name="perf_gpuclock">A GPU legmagasabb órajelen tartása</string>
<string name="perf_gpuclock_hint">Csak Adreno. Kevesebb akadás, nagyobb akkumulátorhasználat és hőtermelés.</string>
<string name="perf_fixes">Munkamenet-javítások</string>
<string name="perf_sysmem">Turnip: sysmem renderelés</string>
<string name="perf_sysmem_hint">A Steam kliensre és a játékokra vonatkozik. Adreno 710/720/722-n szükséges.</string>
@@ -811,7 +798,6 @@
<string name="drawer_pc_keyboard">PC-billentyűzet</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Második képernyő</string>
<string name="drawer_second_screen_mode">Mód</string>
<string name="drawer_second_screen_shows">Megjelenít</string>
<string name="drawer_android_apps">Android-alkalmazások</string>
<string name="drawer_launch_app">Alkalmazás indítása</string>
@@ -2287,6 +2273,17 @@
<string name="pextra_checksum_mismatch">Az ellenőrzőösszeg nem egyezik; a letöltés törlésre került</string>
<string name="pextra_session_started">Egy munkamenet elindult a letöltés közben; állítsa le a kompatibilitási eszközök telepítése előtt</string>
<string name="pextra_installing">%1$s telepítése</string>
<string name="xproton_title">Kísérleti buildek</string>
<string name="xproton_install_file">Telepítés fájlból</string>
<string name="xproton_archive_unsafe">Az archívum nem biztonságos hivatkozást vagy útvonalat tartalmaz</string>
<string name="xproton_archive_invalid">Nem támogatott vagy érvénytelen archívum</string>
<string name="xproton_no_space">Nincs elég szabad hely ehhez a Proton-buildhez</string>
<string name="xproton_unpacking">A Proton kibontása (néhány perc)</string>
<string name="xproton_untar_failed">A kibontás nem sikerült (tar %1$d)</string>
<string name="xproton_no_tree">Az archívum nem tartalmaz Proton-buildet</string>
<string name="xproton_place_failed">Nem sikerült elhelyezni a Proton-buildet</string>
<string name="xproton_remove_failed">Nem sikerült teljesen eltávolítani: %1$s</string>
<string name="xproton_installed">A kísérleti Proton telepítve. Válaszd ki a Steam → Tulajdonságok → Kompatibilitás menüben.</string>
<string name="pextra_install_failed">A %1$s telepítése sikertelen (kilépési kód: %2$d)</string>
<string name="pextra_could_not_install">Nem sikerült telepíteni a %1$s-t</string>
<string name="esync_fetching">droiddeck-esync csomag letöltése</string>
@@ -3317,10 +3314,19 @@
<string name="storage_shared_prefix">A Steam megosztott prefixe</string>
<string name="storage_shared_prefix_detail">A Steam itt futtatja saját Windows-segédprogramjait</string>
<string name="storage_reset_shared_confirm">Törli (%1$s). A Steam újat hoz létre, amikor legközelebb szüksége lesz rá.</string>
<string name="storage_remove_launcher_confirm">Törli ennek az áruházalkalmazásnak a Wine-prefixét és shadergyorsítótárát (%1$s), a bejelentkezéssel és a csak ott tárolt mentésekkel együtt. A benne futó játékok új prefixet kapnak, és lehet, hogy az alkalmazást újra be kell állítani. A felhőmentések a fiókodban maradnak.</string>
<string name="storage_system_clearable">%1$s üríthető</string>
<string name="storage_item_system_caches">Linux- és Steam-gyorsítótárak</string>
<string name="storage_item_system_caches_detail">Régi ideiglenes fájlok, letöltött csomagok és a Steam webes gyorsítótára</string>
<string name="storage_cache_temp">Régi ideiglenes fájlok</string>
<string name="storage_cache_packages">Letöltött csomagok</string>
<string name="storage_cache_steam_web">Steam webes gyorsítótár</string>
<string name="storage_cache_steam_corrupt">Sérült Steam-letöltések</string>
<string name="storage_cache_detail">Szükség esetén újra létrejön</string>
<string name="storage_clear">Ürítés</string>
<string name="storage_launcher_prefix">Egy áruházalkalmazás és a vele futó játékok</string>
<string name="storage_launcher_used_by">Használja: %1$s</string>
<string name="storage_shortcut_app">Nem Steam-es játék: %1$s</string>
<string name="storage_unknown_prefix_detail">Nem tartozik játékhoz, ezért megmarad</string>
<string name="storage_remove_selected">Kijelöltek eltávolítása · %1$s</string>
<string name="storage_uninstall_selected">Kijelöltek eltávolítása · %1$s</string>
<string name="storage_bulk_prefixes">Wine-prefixek</string>
@@ -4065,4 +4071,18 @@
<string name="display_scaling_integer">Egész szám</string>
<string name="display_scaling_fit">Igazítás</string>
<string name="drawer_antialiasing">Élsimítás</string>
</resources>
<string name="theme_custom">Egyéni</string>
<string name="theme_custom_detail">Válaszd ki külön a felület minden színét.</string>
<string name="theme_custom_background">Háttér</string>
<string name="theme_custom_surface">Panelek</string>
<string name="theme_custom_surface_variant">Kiemelt panelek</string>
<string name="theme_custom_line">Elválasztók</string>
<string name="theme_custom_line2">Szegélyek</string>
<string name="theme_custom_on_background">Fő szöveg</string>
<string name="theme_custom_on_surface_variant">Másodlagos szöveg</string>
<string name="theme_custom_primary">Gombok és fő kiemelés</string>
<string name="theme_custom_on_primary">Gombok szövege</string>
<string name="theme_custom_signal">Kiemelések</string>
<string name="theme_custom_good">Siker</string>
<string name="theme_custom_error">Hiba</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Tambahkan pustaka Steam dari kartu SD, drive USB, atau SSD, dan DroidDeck menyatukan semua gim di Pustaka kamu.</item>
<item>Toko memungkinkanmu masuk ke Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io, dan Game Jolt, lalu memasang dan memperbarui gim mereka dari DroidDeck.</item>
<item>Komponen seperti FEX, DXVK, dan VKD3D-Proton memperbarui diri sendiri, dan Proton Experimental ARM64 menjadi default, atau Proton 11.0 ARM64 setelah build tersebut terpasang.</item>
<item>Kompres Steam saat gim berjalan membebaskan RAM pada perangkat yang kekurangan memori.</item>
<item>Geser masuk dari tepi kanan untuk membuka menu sesi: mode touchpad, Keyboard PC, Mode latensi rendah, Profil gim, dan lainnya.</item>
<item>Gim berjalan lambat? Batasi frame rate di Akses cepat, lalu coba versi Proton lain atau preset FEX lain di komponen gim.</item>
<item>Audio gim pecah atau tidak ada? Coba opsi DirectAudio untuk gim di pengaturan Steam pada bagian Audio.</item>
@@ -619,20 +618,8 @@
<string name="perf_gsrealtime">gamescope: antrean GPU realtime</string>
<string name="perf_gsrealtime_hint">Memprioritaskan kerja GPU compositor. Dapat menghaluskan pacing frame dengan sedikit mengorbankan gim.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Memori</string>
<string name="perf_cap_off">Nonaktif</string>
<string name="perf_cap_auto">Default driver</string>
<string name="perf_zram_client">Kompres Steam saat gim berjalan</string>
<string name="perf_zram_idle">Kompres memori game yang tidak aktif</string>
<string name="perf_zram_idle_hint">Mengompres memori game yang tidak aktif saat RAM rendah. Matikan jika game membeku beberapa detik kira-kira setiap setengah menit. Berlaku saat sesi dimulai berikutnya.</string>
<string name="perf_zram_client_hint">20 detik setelah gim dimulai, klien Steam dikompres ke zRAM agar gim mendapat lebih banyak memori, lalu dibaca kembali saat gim ditutup. Nonaktifkan jika sesi tertutup sesaat setelah gim dimulai. Batas RAM di atas tetap mengompres Steam saat sesi melampauinya.</string>
<string name="perf_ram_cap">Batas RAM</string>
<string name="perf_ram_cap_hint">Berlaku saat klien Steam berjalan, di mode Steam atau dari desktop. Saat sesi menggunakan lebih dari ini, Steam lalu proses lain yang didukung dalam sesi dikompres ke zRAM. Batas lunak: tidak ada yang ditutup, tetapi gim dapat tersendat saat halaman dimuat kembali.</string>
<string name="perf_ram_cap_unavailable">Memerlukan swap zRAM, yang tidak dimiliki perangkat ini.</string>
<string name="perf_vram_cap">Batas VRAM</string>
<string name="perf_vram_cap_hint">Melaporkan anggaran memori video ini ke game Direct3D 9 hingga 12 untuk mengurangi penggunaan memori. Game dapat melampauinya; ini tidak menambahkan paging GPU atau menjamin perlindungan dari crash akibat kehabisan memori. Berlaku pada sesi berikutnya.</string>
<string name="perf_gpuclock">Pertahankan GPU pada clock tertingginya</string>
<string name="perf_gpuclock_hint">Hanya Adreno. Lebih sedikit tersendat, lebih banyak penggunaan baterai dan panas.</string>
<string name="perf_fixes">Perbaikan sesi</string>
<string name="perf_sysmem">Turnip: rendering sysmem</string>
<string name="perf_sysmem_hint">Berlaku untuk klien Steam dan gim. Diperlukan pada Adreno 710/720/722.</string>
@@ -809,7 +796,6 @@
<string name="drawer_pc_keyboard">Keyboard PC</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Layar kedua</string>
<string name="drawer_second_screen_mode">Mode</string>
<string name="drawer_second_screen_shows">Menampilkan</string>
<string name="drawer_android_apps">Aplikasi Android</string>
<string name="drawer_launch_app">Luncurkan aplikasi</string>
@@ -2262,6 +2248,17 @@
<string name="pextra_checksum_mismatch">Checksum tidak cocok; unduhan telah dihapus</string>
<string name="pextra_session_started">Sesi dimulai saat pengunduhan berlangsung; hentikan sesi tersebut sebelum menginstal alat kompatibilitas</string>
<string name="pextra_installing">Menginstal %1$s</string>
<string name="xproton_title">Build eksperimental</string>
<string name="xproton_install_file">Instal dari file</string>
<string name="xproton_archive_unsafe">Arsip berisi tautan atau jalur yang tidak aman</string>
<string name="xproton_archive_invalid">Arsip tidak didukung atau tidak valid</string>
<string name="xproton_no_space">Ruang kosong tidak cukup untuk build Proton ini</string>
<string name="xproton_unpacking">Membuka paket Proton (beberapa menit)</string>
<string name="xproton_untar_failed">Gagal membuka paket (tar %1$d)</string>
<string name="xproton_no_tree">Arsip tidak berisi build Proton</string>
<string name="xproton_place_failed">Tidak dapat menempatkan build Proton</string>
<string name="xproton_remove_failed">Tidak dapat menghapus %1$s sepenuhnya</string>
<string name="xproton_installed">Proton eksperimental terinstal. Pilih di Steam → Properti → Kompatibilitas.</string>
<string name="pextra_install_failed">Instalasi %1$s gagal (keluar %2$d)</string>
<string name="pextra_could_not_install">Tidak dapat menginstal %1$s</string>
<string name="esync_fetching">Mengambil paket droiddeck-esync</string>
@@ -3288,10 +3285,19 @@
<string name="storage_shared_prefix">Prefix Steam bersama</string>
<string name="storage_shared_prefix_detail">Steam menjalankan helper Windows-nya sendiri di sini</string>
<string name="storage_reset_shared_confirm">Menghapusnya (%1$s). Steam membuat yang baru saat membutuhkannya lagi.</string>
<string name="storage_remove_launcher_confirm">Menghapus prefiks Wine dan cache shader aplikasi toko ini (%1$s), beserta info masuk dan simpanan yang hanya ada di sana. Game yang berjalan di dalamnya mendapat prefiks baru, dan Anda mungkin perlu menyiapkan aplikasinya lagi. Simpanan cloud tetap ada di akun Anda.</string>
<string name="storage_system_clearable">%1$s dapat dibersihkan</string>
<string name="storage_item_system_caches">Cache Linux dan Steam</string>
<string name="storage_item_system_caches_detail">File sementara lama, paket yang diunduh, dan cache web Steam</string>
<string name="storage_cache_temp">File sementara lama</string>
<string name="storage_cache_packages">Paket yang diunduh</string>
<string name="storage_cache_steam_web">Cache web Steam</string>
<string name="storage_cache_steam_corrupt">Unduhan Steam yang rusak</string>
<string name="storage_cache_detail">Dibuat lagi saat diperlukan</string>
<string name="storage_clear">Bersihkan</string>
<string name="storage_launcher_prefix">Aplikasi toko dan gim yang berjalan dengannya</string>
<string name="storage_launcher_used_by">Dipakai oleh %1$s</string>
<string name="storage_shortcut_app">Gim non-Steam %1$s</string>
<string name="storage_unknown_prefix_detail">Tidak cocok dengan gim mana pun, jadi tetap disimpan</string>
<string name="storage_remove_selected">Hapus yang dipilih · %1$s</string>
<string name="storage_uninstall_selected">Hapus instalasi yang dipilih · %1$s</string>
<string name="storage_bulk_prefixes">Prefix Wine</string>
@@ -4035,4 +4041,18 @@
<string name="display_scaling_integer">Bilangan bulat</string>
<string name="display_scaling_fit">Sesuaikan</string>
<string name="drawer_antialiasing">Anti-aliasing</string>
</resources>
<string name="theme_custom">Kustom</string>
<string name="theme_custom_detail">Pilih setiap warna antarmuka secara terpisah.</string>
<string name="theme_custom_background">Latar belakang</string>
<string name="theme_custom_surface">Panel</string>
<string name="theme_custom_surface_variant">Panel terangkat</string>
<string name="theme_custom_line">Pemisah</string>
<string name="theme_custom_line2">Batas</string>
<string name="theme_custom_on_background">Teks utama</string>
<string name="theme_custom_on_surface_variant">Teks sekunder</string>
<string name="theme_custom_primary">Tombol dan aksen utama</string>
<string name="theme_custom_on_primary">Teks tombol</string>
<string name="theme_custom_signal">Sorotan</string>
<string name="theme_custom_good">Berhasil</string>
<string name="theme_custom_error">Kesalahan</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>Aggiungi librerie Steam da una scheda SD, un\'unità USB o un SSD, e DroidDeck tiene i giochi insieme nella tua Libreria.</item>
<item>Negozi ti permette di accedere a Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io e Game Jolt, poi di installare e aggiornare i loro giochi da DroidDeck.</item>
<item>I componenti come FEX, DXVK e VKD3D-Proton si aggiornano da soli, e Proton Experimental ARM64 è il predefinito, oppure Proton 11.0 ARM64 una volta installata quella build.</item>
<item>Comprimi Steam durante il gioco libera RAM sui dispositivi che ne hanno poca.</item>
<item>Scorri verso l\'interno dal bordo destro per aprire il menu della sessione: modalità touchpad, Tastiera PC, Modalità bassa latenza, Profilo del gioco e altro.</item>
<item>Il gioco è lento? Limita il frame rate in Accesso rapido, poi prova un\'altra versione di Proton o un altro preset FEX nei componenti del gioco.</item>
<item>Audio del gioco che gracchia o manca? Prova l\'opzione DirectAudio per i giochi nelle impostazioni di Steam, sotto Audio.</item>
@@ -623,20 +622,8 @@
<string name="perf_gsrealtime">gamescope: coda GPU in tempo reale</string>
<string name="perf_gsrealtime_hint">Dà priorità al lavoro GPU del compositor. Può rendere più regolare il frame pacing, a scapito dei giochi.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Memoria</string>
<string name="perf_cap_off">Disattivo</string>
<string name="perf_cap_auto">Predefinito del driver</string>
<string name="perf_zram_client">Comprimi Steam durante il gioco</string>
<string name="perf_zram_idle">Comprimi la memoria inattiva del gioco</string>
<string name="perf_zram_idle_hint">Comprime la memoria inattiva del gioco quando la RAM scarseggia. Disattivalo se i giochi si bloccano per qualche secondo circa ogni mezzo minuto. Si applica al prossimo avvio della sessione.</string>
<string name="perf_zram_client_hint">20 s dopo l\'avvio di un gioco, il client Steam viene compresso in zRAM per lasciare più memoria al gioco e viene riletto quando il gioco si chiude. Disattivalo se la sessione si chiude poco dopo l\'avvio dei giochi. Un limite di RAM impostato sopra comprime comunque Steam quando la sessione lo supera.</string>
<string name="perf_ram_cap">Limite RAM</string>
<string name="perf_ram_cap_hint">Si applica mentre il client Steam è in esecuzione, in modalità Steam o dal desktop. Quando la sessione usa più di questo valore, Steam e poi gli altri processi supportati della sessione vengono compressi in zRAM. È un limite morbido: non viene chiuso nulla, ma i giochi possono scattare mentre le pagine vengono recuperate.</string>
<string name="perf_ram_cap_unavailable">Richiede lo swap zRAM, che questo dispositivo non ha.</string>
<string name="perf_vram_cap">Limite VRAM</string>
<string name="perf_vram_cap_hint">La memoria video che DXVK comunica ai giochi Direct3D, così usano meno texture. Le impostazioni DXVK del gioco hanno comunque la priorità. Si applica dalla prossima sessione.</string>
<string name="perf_gpuclock">Mantieni la GPU alla frequenza massima</string>
<string name="perf_gpuclock_hint">Solo Adreno. Meno scatti, più consumo di batteria e più calore.</string>
<string name="perf_fixes">Correzioni della sessione</string>
<string name="perf_sysmem">Turnip: rendering sysmem</string>
<string name="perf_sysmem_hint">Si applica al client Steam e ai giochi. Necessario su Adreno 710/720/722.</string>
@@ -813,7 +800,6 @@
<string name="drawer_pc_keyboard">Tastiera PC</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Secondo schermo</string>
<string name="drawer_second_screen_mode">Modalità</string>
<string name="drawer_second_screen_shows">Mostra</string>
<string name="drawer_android_apps">App Android</string>
<string name="drawer_launch_app">Avvia un\'app</string>
@@ -2304,6 +2290,17 @@
<string name="pextra_checksum_mismatch">Checksum non corrispondente; il download è stato eliminato</string>
<string name="pextra_session_started">È stata avviata una sessione durante il download; interrompila prima di installare strumenti di compatibilità</string>
<string name="pextra_installing">Installazione di %1$s</string>
<string name="xproton_title">Build sperimentali</string>
<string name="xproton_install_file">Installa da file</string>
<string name="xproton_archive_unsafe">L\'archivio contiene un collegamento o percorso non sicuro</string>
<string name="xproton_archive_invalid">Archivio non supportato o non valido</string>
<string name="xproton_no_space">Spazio libero insufficiente per questa build di Proton</string>
<string name="xproton_unpacking">Estrazione di Proton (qualche minuto)</string>
<string name="xproton_untar_failed">Estrazione non riuscita (tar %1$d)</string>
<string name="xproton_no_tree">L\'archivio non contiene alcuna build di Proton</string>
<string name="xproton_place_failed">Impossibile posizionare la build di Proton</string>
<string name="xproton_remove_failed">Impossibile rimuovere completamente %1$s</string>
<string name="xproton_installed">Proton sperimentale installato. Selezionalo in Steam → Proprietà → Compatibilità.</string>
<string name="pextra_install_failed">Installazione di %1$s non riuscita (uscita %2$d)</string>
<string name="pextra_could_not_install">Impossibile installare %1$s</string>
<string name="esync_fetching">Recupero del pacchetto droiddeck-esync</string>
@@ -3353,10 +3350,19 @@
<string name="storage_shared_prefix">Prefisso condiviso di Steam</string>
<string name="storage_shared_prefix_detail">Steam esegue qui i propri strumenti Windows</string>
<string name="storage_reset_shared_confirm">Lo elimina (%1$s). Steam ne crea uno nuovo la prossima volta che serve.</string>
<string name="storage_remove_launcher_confirm">Elimina il prefisso Wine e la cache degli shader di questa app dello store (%1$s), con il suo accesso e i salvataggi presenti solo lì. I giochi che vi girano ricevono un nuovo prefisso e potrebbe essere necessario configurare di nuovo l\'app. I salvataggi cloud restano nel tuo account.</string>
<string name="storage_system_clearable">Si possono liberare %1$s</string>
<string name="storage_item_system_caches">Cache di Linux e Steam</string>
<string name="storage_item_system_caches_detail">Vecchi file temporanei, pacchetti scaricati e cache web di Steam</string>
<string name="storage_cache_temp">Vecchi file temporanei</string>
<string name="storage_cache_packages">Pacchetti scaricati</string>
<string name="storage_cache_steam_web">Cache web di Steam</string>
<string name="storage_cache_steam_corrupt">Download di Steam danneggiati</string>
<string name="storage_cache_detail">Ricreati quando servono</string>
<string name="storage_clear">Svuota</string>
<string name="storage_launcher_prefix">Un\'app di uno store e i giochi che girano con essa</string>
<string name="storage_launcher_used_by">Usato da %1$s</string>
<string name="storage_shortcut_app">Gioco non Steam %1$s</string>
<string name="storage_unknown_prefix_detail">Non associato a nessun gioco, quindi viene conservato</string>
<string name="storage_remove_selected">Rimuovi selezionati · %1$s</string>
<string name="storage_uninstall_selected">Disinstalla selezionati · %1$s</string>
<string name="storage_bulk_prefixes">Prefissi Wine</string>
@@ -4104,4 +4110,18 @@
<string name="display_scaling_integer">Intero</string>
<string name="display_scaling_fit">Adatta</string>
<string name="drawer_antialiasing">Antialiasing</string>
</resources>
<string name="theme_custom">Personalizzato</string>
<string name="theme_custom_detail">Scegli separatamente ogni colore dell’interfaccia.</string>
<string name="theme_custom_background">Sfondo</string>
<string name="theme_custom_surface">Pannelli</string>
<string name="theme_custom_surface_variant">Pannelli rialzati</string>
<string name="theme_custom_line">Separatori</string>
<string name="theme_custom_line2">Bordi</string>
<string name="theme_custom_on_background">Testo principale</string>
<string name="theme_custom_on_surface_variant">Testo secondario</string>
<string name="theme_custom_primary">Pulsanti e colore principale</string>
<string name="theme_custom_on_primary">Testo dei pulsanti</string>
<string name="theme_custom_signal">Evidenziazioni</string>
<string name="theme_custom_good">Successo</string>
<string name="theme_custom_error">Errore</string>
</resources>
+36 -16
View File
@@ -22,7 +22,6 @@
<item>SDカード、USBドライブ、SSDからSteamライブラリを追加でき、DroidDeckはゲームをライブラリにまとめて表示します。</item>
<item>ストアでは、Epic Games、GOG、Xbox、EA、Battle.net、Ubisoft Connect、Amazon Games、itch.io、Game Joltにサインインして、DroidDeckからそれらのゲームをインストール・更新できます。</item>
<item>FEX、DXVK、VKD3D-Protonなどのコンポーネントは自動で更新されます。既定はProton Experimental ARM64で、Proton 11.0 ARM64がインストールされている場合はそちらになります。</item>
<item>ゲーム実行中はSteamを圧縮すると、メモリが少ない端末でRAMを確保できます。</item>
<item>画面の右端から内側にスワイプするとセッションメニューが開きます。タッチパッドモード、PCキーボード、低遅延モード、ゲームプロファイルなどがあります。</item>
<item>ゲームが重い場合は、クイックアクセスでフレームレートを制限し、ゲームのコンポーネントで別のProtonバージョンやFEXプリセットを試してください。</item>
<item>ゲームの音が割れる、または出ない場合は、Steam設定のオーディオにある「ゲームでDirectAudioを使用」を試してください。</item>
@@ -619,20 +618,8 @@
<string name="perf_gsrealtime">gamescope:リアルタイムGPUキュー</string>
<string name="perf_gsrealtime_hint">コンポジタのGPU作業の優先度を上げます。フレームタイムの安定性が向上する場合がありますが、ゲームのパフォーマンスの一部を消費します。</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">メモリ</string>
<string name="perf_cap_off">オフ</string>
<string name="perf_cap_auto">ドライバーのデフォルト</string>
<string name="perf_zram_client">ゲーム実行中はSteamを圧縮</string>
<string name="perf_zram_idle">ゲームのアイドルメモリを圧縮</string>
<string name="perf_zram_idle_hint">RAMが少ないときにゲームのアイドルメモリを圧縮します。ゲームが30秒ごとに数秒止まる場合はオフにしてください。次回のセッション開始時に適用されます。</string>
<string name="perf_zram_client_hint">ゲーム開始の20秒後、SteamクライアントをzRAMに圧縮してゲームに使えるメモリを増やし、ゲーム終了時に読み戻します。ゲーム開始直後にセッションが終了する場合はオフにしてください。上のRAM上限を設定している場合は、セッションが上限を超えるとSteamは引き続き圧縮されます。</string>
<string name="perf_ram_cap">RAM上限</string>
<string name="perf_ram_cap_hint">Steamモードでもデスクトップからでも、Steamクライアントの実行中に適用されます。セッションの使用量がこの値を超えると、Steam、次にセッション内の対応する他のプロセスがzRAMに圧縮されます。ソフトな上限のため何も終了されませんが、ページの読み戻し中にゲームがカクつくことがあります。</string>
<string name="perf_ram_cap_unavailable">zRAMスワップが必要ですが、このデバイスにはありません。</string>
<string name="perf_vram_cap">VRAM上限</string>
<string name="perf_vram_cap_hint">Direct3D 9~12のゲームにこのビデオメモリ予算を通知し、メモリ使用量の削減を促します。ゲームは予算を超える場合があります。GPUのページングを追加するものではなく、メモリ不足によるクラッシュの防止は保証されません。次のセッションから有効になります。</string>
<string name="perf_gpuclock">GPUを最高クロックに保つ</string>
<string name="perf_gpuclock_hint">Adrenoのみ。スタッターは減りますが、消費電力と発熱が増えます。</string>
<string name="perf_fixes">セッション修正</string>
<string name="perf_sysmem">Turnip:sysmemレンダリング</string>
<string name="perf_sysmem_hint">Steamクライアントとゲームに適用。Adreno 710/720/722では必須です。</string>
@@ -809,7 +796,6 @@
<string name="drawer_pc_keyboard">PCキーボード</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">セカンドスクリーン</string>
<string name="drawer_second_screen_mode">モード</string>
<string name="drawer_second_screen_shows">表示</string>
<string name="drawer_android_apps">Androidアプリ</string>
<string name="drawer_launch_app">アプリを起動</string>
@@ -2262,6 +2248,17 @@
<string name="pextra_checksum_mismatch">チェックサムが一致しないため、ダウンロードを削除しました</string>
<string name="pextra_session_started">ダウンロード中にセッションが開始されました。停止してから互換性ツールをインストールしてください</string>
<string name="pextra_installing">%1$sをインストール中</string>
<string name="xproton_title">試験版ビルド</string>
<string name="xproton_install_file">ファイルからインストール</string>
<string name="xproton_archive_unsafe">アーカイブに安全でないリンクまたはパスが含まれています</string>
<string name="xproton_archive_invalid">未対応または無効なアーカイブ</string>
<string name="xproton_no_space">このProtonビルド用の空き容量が足りません</string>
<string name="xproton_unpacking">Protonを展開中(数分かかります)</string>
<string name="xproton_untar_failed">展開に失敗しました(tar %1$d)</string>
<string name="xproton_no_tree">アーカイブにProtonビルドが含まれていません</string>
<string name="xproton_place_failed">Protonビルドを配置できませんでした</string>
<string name="xproton_remove_failed">%1$sを完全に削除できませんでした</string>
<string name="xproton_installed">試験版Protonをインストールしました。Steam → プロパティ → 互換性 で選択してください。</string>
<string name="pextra_install_failed">%1$sのインストールに失敗しました(終了コード %2$d)</string>
<string name="pextra_could_not_install">%1$sをインストールできませんでした</string>
<string name="esync_fetching">droiddeck-esyncパックを取得中</string>
@@ -3288,10 +3285,19 @@
<string name="storage_shared_prefix">Steam の共有プレフィックス</string>
<string name="storage_shared_prefix_detail">Steam が独自の Windows ヘルパーをここで実行します</string>
<string name="storage_reset_shared_confirm">削除します(%1$s)。次に必要になったとき Steam が新しく作成します。</string>
<string name="storage_remove_launcher_confirm">このストアアプリの Wine プレフィックスとシェーダーキャッシュ(%1$s)を、サインイン情報やそこにしかないセーブデータごと削除します。中で動くゲームは新しいプレフィックスで始まり、アプリの再セットアップが必要になる場合があります。クラウドのセーブデータはアカウントに残ります。</string>
<string name="storage_system_clearable">%1$s を消去できます</string>
<string name="storage_item_system_caches">Linux と Steam のキャッシュ</string>
<string name="storage_item_system_caches_detail">古い一時ファイル、ダウンロード済みパッケージ、Steam のウェブキャッシュ</string>
<string name="storage_cache_temp">古い一時ファイル</string>
<string name="storage_cache_packages">ダウンロード済みパッケージ</string>
<string name="storage_cache_steam_web">Steam のウェブキャッシュ</string>
<string name="storage_cache_steam_corrupt">破損した Steam ダウンロード</string>
<string name="storage_cache_detail">必要なときに再作成されます</string>
<string name="storage_clear">消去</string>
<string name="storage_launcher_prefix">ストアアプリとそれで動くゲーム</string>
<string name="storage_launcher_used_by">%1$s が使用</string>
<string name="storage_shortcut_app">Steam 以外のゲーム %1$s</string>
<string name="storage_unknown_prefix_detail">どのゲームにも一致しないため保持されます</string>
<string name="storage_remove_selected">選択項目を削除 · %1$s</string>
<string name="storage_uninstall_selected">選択項目をアンインストール · %1$s</string>
<string name="storage_bulk_prefixes">Wineプレフィックス</string>
@@ -4035,4 +4041,18 @@
<string name="display_scaling_integer">整数</string>
<string name="display_scaling_fit">画面に合わせる</string>
<string name="drawer_antialiasing">アンチエイリアス</string>
</resources>
<string name="theme_custom">カスタム</string>
<string name="theme_custom_detail">インターフェースの各色を個別に選択します。</string>
<string name="theme_custom_background">背景</string>
<string name="theme_custom_surface">パネル</string>
<string name="theme_custom_surface_variant">浮き上がったパネル</string>
<string name="theme_custom_line">区切り線</string>
<string name="theme_custom_line2">境界線</string>
<string name="theme_custom_on_background">メインテキスト</string>
<string name="theme_custom_on_surface_variant">サブテキスト</string>
<string name="theme_custom_primary">ボタンとメインアクセント</string>
<string name="theme_custom_on_primary">ボタンのテキスト</string>
<string name="theme_custom_signal">強調表示</string>
<string name="theme_custom_good">成功</string>
<string name="theme_custom_error">エラー</string>
</resources>
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff. Show more