diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 08cb6341b..3816c1a52 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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 diff --git a/app/build.gradle b/app/build.gradle index cb5b882ec..c271f963b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -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' diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt new file mode 100644 index 000000000..e0003e134 --- /dev/null +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -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 = 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 = 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() }, +) diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt new file mode 100644 index 000000000..fc83727e1 --- /dev/null +++ b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt @@ -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 = 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 = 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 = {}, +) diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 284970c9c..d286cce1f 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -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(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(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, 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") } } diff --git a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt index c8fe30c9e..aaaa2cf34 100644 --- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt @@ -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(null) val percent = mutableIntStateOf(-1) val problem = mutableStateOf(null) + val experimental = mutableStateOf>(emptyList()) + val experimentalReleases = mutableStateOf>(emptyList()) + var fetchedReleases = emptyList() + 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.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() } diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index bbb2e47ed..f9dac0dc5 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -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(null) private var achievementsOpen by mutableStateOf(false) private var hudOn by mutableStateOf(true) + private var gpuClockPin by mutableStateOf(false) private var hudConfig by mutableStateOf>(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 diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt index 93922c805..1b5756227 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt @@ -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)) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentDraft.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentDraft.kt new file mode 100644 index 000000000..3a36be973 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentDraft.kt @@ -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? = null + + fun state(context: Context): MutableState = state ?: run { + val prefs = AgentHost.prefs(context.applicationContext) + val backing = mutableStateOf(prefs.getString(KEY, "") ?: "") + object : MutableState { + 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 } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index e917e3660..df90f6f86 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -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") diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentStores.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentStores.kt new file mode 100644 index 000000000..82ce426c8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentStores.kt @@ -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) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index 3c047d2e1..fe835b10c 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -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)) diff --git a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java index 7d5427a8c..7990e5707 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java +++ b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java @@ -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; diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt index 63b5f6b4d..3ab892892 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt index 6f71475cf..3e5d4ae0d 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt @@ -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() } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt new file mode 100644 index 000000000..a6baf2d70 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt @@ -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, 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, 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 = 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) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt index 7cc805177..26c9c9981 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -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, diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/ClockLogComponent.kt b/app/src/main/java/com/droiddeck/launcher/gpu/ClockLogComponent.kt index 6f6827ad0..9368bddcf 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/ClockLogComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/ClockLogComponent.kt @@ -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, read: (String) -> Long? = ::firstNumber): List = 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 = 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? = sources.firstOrNull { limit(it) != null } + + private fun mhz(raw: Long?): String = raw?.let { GpuLimits.mhz(it).toString() } ?: "?" } } diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/DeviceInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/DeviceInfo.kt index bf44d7eec..45a396b65 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/DeviceInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/DeviceInfo.kt @@ -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> { diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuLimits.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuLimits.kt new file mode 100644 index 000000000..67eaa2374 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuLimits.kt @@ -0,0 +1,41 @@ +package com.droiddeck.launcher.gpu + +import java.io.File + +object GpuLimits { + class Found(val path: String, val mhz: List) + + private const val KGSL = "/sys/class/kgsl/kgsl-3d0" + private const val QCOM_GPU = "/sys/kernel/gpu" + + fun stepSources(): List = listOf( + "$KGSL/gpu_available_frequencies", "$KGSL/freq_table_mhz", "$KGSL/devfreq/available_frequencies", "$QCOM_GPU/gpu_freq_table", + ) + devfreq("available_frequencies") + + fun maxSources(): List = listOf( + "$KGSL/max_gpuclk", "$KGSL/max_clock_mhz", "$KGSL/devfreq/max_freq", "$QCOM_GPU/gpu_max_clock", + ) + devfreq("max_freq") + + fun minSources(): List = listOf( + "$KGSL/min_clock_mhz", "$KGSL/devfreq/min_freq", "$QCOM_GPU/gpu_min_clock", + ) + devfreq("min_freq") + + fun first(sources: List): Found? = + sources.firstNotNullOfOrNull { path -> read(path).takeIf { it.isNotEmpty() }?.let { Found(path, it) } } + + fun read(path: String): List = 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 = + 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() +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt index e9409b74c..749532cdd 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt @@ -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 { val found = LinkedHashMap() 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) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt index 6f9f36453..b437f3ae4 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/session/ExperimentalProtons.kt b/app/src/main/java/com/droiddeck/launcher/session/ExperimentalProtons.kt new file mode 100644 index 000000000..c02858e44 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/ExperimentalProtons.kt @@ -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 = + 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? { + 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 = (0 until length()).mapNotNull { optJSONObject(it)?.optString("tag_name")?.takeIf(String::isNotEmpty) }.toSet() + + internal fun removeStaleDownloads(context: Context, availableTags: Set) { + 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, installed: List): List = + 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() + 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>() + 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, 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): 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() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt b/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt index 3a31da011..a1491ff85 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt @@ -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) { + data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List, 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 = + 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 { + 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 { 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 diff --git a/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt b/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt index 40135f08d..e02b3e7bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt @@ -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) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt index 849c0aafc..109f6d282 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt @@ -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() private const val START_TIMEOUT_MS = 2_000L private val starting = HashMap() + private val yielded = HashSet() + 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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/PipPolicy.kt b/app/src/main/java/com/droiddeck/launcher/session/PipPolicy.kt index d2d4d49bd..cef3489a3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PipPolicy.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PipPolicy.kt @@ -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 = when { width <= 0 || height <= 0 -> 16 to 9 width.toDouble() / height > 2.39 -> 239 to 100 diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index b27326969..0d0e20c41 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -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): 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 { + 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 = diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 9501915fe..53b54e9ca 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt index f32fe2abb..503b8c743 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 0b91e9e8b..1eece93b0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -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>? = + 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>) { + prefs(context).edit().putString("libraryTabPlaces", places.joinToString(",") { "${it.first}=${it.second}" }).apply() + } + + fun libraryTabsHidden(context: Context): Set = idList(prefs(context).getString("libraryTabsHidden", null)).toSet() + + fun setLibraryTabsHidden(context: Context, hidden: Set) { + prefs(context).edit().putString("libraryTabsHidden", hidden.joinToString(",")).apply() + } + fun storesTabHidden(context: Context): Set = idList(prefs(context).getString("storesTabHidden", null)).toSet() fun setStoresTabHidden(context: Context, hidden: Set) { @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 9c8e6fe2c..e15fac1c6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -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)) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 5f17212e5..612494715 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -43,6 +43,8 @@ object SessionState { @Volatile var stopRequested = false + val startLock = Any() + @Volatile var running = false @Volatile diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt index 221a1e78c..74f7d5ace 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt @@ -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, ProcessRecord>, root: Int, helpers: List) { 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, ProcessRecord>, root: Int, helpers: List) { + 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 diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index 0a0806799..f85318b59 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -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", diff --git a/app/src/main/java/com/droiddeck/launcher/storage/StorageScan.kt b/app/src/main/java/com/droiddeck/launcher/storage/StorageScan.kt index dc07daaba..aec3e5f66 100644 --- a/app/src/main/java/com/droiddeck/launcher/storage/StorageScan.kt +++ b/app/src/main/java/com/droiddeck/launcher/storage/StorageScan.kt @@ -71,7 +71,10 @@ class StorageReport( val kept: List, val leftoversChecked: Boolean, val storeGames: List = emptyList(), + val systemCaches: List = emptyList(), + val checkouts: List = 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, ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/storage/StorageState.kt b/app/src/main/java/com/droiddeck/launcher/storage/StorageState.kt index 40a48a366..2aa3f53e1 100644 --- a/app/src/main/java/com/droiddeck/launcher/storage/StorageState.kt +++ b/app/src/main/java/com/droiddeck/launcher/storage/StorageState.kt @@ -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(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) = 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) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/storage/StorageSummary.kt b/app/src/main/java/com/droiddeck/launcher/storage/StorageSummary.kt new file mode 100644 index 000000000..e8b4ca529 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/storage/StorageSummary.kt @@ -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, 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") + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/storage/SystemCaches.kt b/app/src/main/java/com/droiddeck/launcher/storage/SystemCaches.kt new file mode 100644 index 000000000..95277a312 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/storage/SystemCaches.kt @@ -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, 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, now: Long): Map> = 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(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) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt index 45b1be542..c2fd9890d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt @@ -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 = emptyList()) + class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List = emptyList(), val signedIn: Boolean = true) - private fun game(context: Context, store: Store, id: String): Pair? = - 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? { + 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? = - 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) = - prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply() + internal fun baseline(context: Context, store: Store, key: String): Map? = + CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$key", null)) + + private fun saveBaseline(context: Context, store: Store, key: String, b: Map) = + prefs(context, store).edit().putString("cloud_baseline_$key", CloudPlan.toJson(b)).apply() internal class Migration(val baseline: Map, 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 = - 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 = + 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) = - prefs(context, store).edit().putString("cloud_conflicts_$id", names.joinToString("\n")).apply() + private fun savedConflicts(context: Context, store: Store, key: String): List = + 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) = + prefs(context, store).edit().putString("cloud_conflicts_$key", names.joinToString("\n")).apply() + + private fun alike(cloud: CloudTransport, conflicts: List, local: Map, remote: Map): List = + 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): 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, 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 = - if (!dir.isDirectory) emptyMap() - else dir.walkTopDown().filter { it.isFile }.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') } + private fun localFiles(dir: File): Map { + if (!dir.isDirectory) return emptyMap() + val root = runCatching { dir.toPath().toRealPath() }.getOrNull() ?: return emptyMap() + val found = LinkedHashMap() + fun walk(d: File, prefix: String, ancestry: Set) { + 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() + val changed = ArrayList() + val blocked = ArrayList() + val fetched = LinkedHashMap>>() 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() + var raced = emptyList() + 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() val sentMd5 = HashMap() 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) { - if (files.isEmpty()) return + private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List): Map { + if (files.isEmpty()) return emptyMap() val root = backupRoot(context, store, id) val target = File(root, "cloud-${System.currentTimeMillis()}") + val copies = HashMap() 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): 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) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt index 2971bb61c..9e0ad9919 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt @@ -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 fun details(file: CloudFile) {} fun get(file: CloudFile): Pair @@ -182,6 +186,8 @@ internal fun isoDate(s: String?): Long { class NoCloudSaves : Exception("no cloud saves") +class CloudChanged(val sent: Map, val unsent: List) : Exception("cloud saves changed since they were read") + internal fun splitGogName(name: String): Pair { val slash = name.indexOf('/') return if (slash <= 0 || slash == name.length - 1) null to name diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt index 9ec0dad5f..cc231dfcb 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt @@ -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() } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadModels.kt b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadModels.kt index 57f07742c..115e0b113 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadModels.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadModels.kt @@ -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() } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt index 19dc8ea17..4ceb4278b 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt @@ -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) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaAuth.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaAuth.kt index 67fb8e655..a600c905b 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaAuth.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaAuth.kt @@ -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>): 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 diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaCloud.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaCloud.kt new file mode 100644 index 000000000..6c5242474 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaCloud.kt @@ -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, + 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, val snapshots: List) + + private class Signed(val url: String, val headers: Map) + + 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? = null + private val committed = HashMap() + + override fun wants(name: String): Boolean = rules.matches(base + name) + + override fun committed(name: String): CloudFile? = committed[name] + + override fun list(): List { + 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() + 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 { + 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, modifiedMs: Map): Map { + 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 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): List { + val body = buildString { + append("") + for ((i, r) in requests.withIndex()) { + append("").append(r.verb).append("").append(escape(r.resource)).append("") + r.md5?.let { append("").append(it).append("") } + r.type?.let { append("").append(it).append("") } + append("") + } + append("") + } + 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("]*\\bid=\"(\\d+)\"[^>]*>(.*?)", RegexOption.DOT_MATCHES_ALL) + private val HEADER = Regex("]*)/?>") + + fun keys(masterTitleId: String, multiplayerId: String): List = + if (multiplayerId.isNotEmpty()) listOf("${masterTitleId}_$multiplayerId") else listOf(masterTitleId, "${masterTitleId}_$masterTitleId") + + fun manifestUrl(lockBody: String): String? = Regex("([^<]+)").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() + val snapshots = ArrayList() + var file: Array? = 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("\n") + for (f in m.files) { + append(" \n") + append(" ") + append(escape(f.localName)).append("\n \n") + } + for (s in m.snapshots) append(" ").append(escape(s)).append("\n") + append("\n") + } + + private fun signedRequests(xml: String, count: Int): List { + val byId = REQUEST.findAll(xml).associate { m -> + val inner = m.groupValues[2] + val url = Regex("([^<]+)").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("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) + + private fun unescape(s: String) = EaSaveRules.unescape(s) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaSaveRules.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaSaveRules.kt new file mode 100644 index 000000000..b103473eb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaSaveRules.kt @@ -0,0 +1,84 @@ +package com.droiddeck.launcher.stores.ea + +internal class EaSaveRules(private val rules: List>) { + 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() + 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([^>]*)>([^<]*)", 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) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBrowse.kt b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBrowse.kt index d430d1143..90138c525 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBrowse.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/itch/ItchBrowse.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftActivation.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftActivation.kt index d11fde421..06075ca15 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftActivation.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftActivation.kt @@ -15,23 +15,44 @@ object UbisoftActivation { private const val POLL_MS = 250L private const val IDLE_MS = 60_000L private val watching = HashMap() + private val owners = HashMap() + + 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? = diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt index ba3053ef7..35fd96ed9 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt @@ -168,14 +168,14 @@ object UbisoftLibrary { internal fun assemble(listed: List, owned: JSONObject?): List { 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. */ diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftCloud.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftCloud.kt new file mode 100644 index 000000000..26001da37 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftCloud.kt @@ -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 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 { + 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() + + 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 { + 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 { + 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, modifiedMs: Map): Map { + 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() + 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 } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftLaunch.kt index 279d3b3e4..4f284f77b 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftLaunch.kt @@ -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")) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index 01a486b57..225b81444 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt index cea5fcaf3..72e5d0b63 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt @@ -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) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt index 3f7293b74..25b01904d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt index a0033d81a..c9e8362c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt @@ -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(), ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomDownloadsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomDownloadsPage.kt index 7ad576f95..7c33334a2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomDownloadsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomDownloadsPage.kt @@ -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)) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt index 2d2e401fa..b51aec8bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt @@ -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 = 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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt index e4715b6a1..0fbbcf3f3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt @@ -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, + val current: SecondScreenMode, + val onPick: (SecondScreenMode) -> Unit, + val onMenu: (() -> Unit)? = null, + val menuShown: Boolean = false, +) + internal class BarTabs(val labels: List, val selected: Int, val onSelect: (Int) -> Unit) internal class BottomBarModel( @@ -72,6 +94,7 @@ internal class BottomBarModel( val extras: List = 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 = 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) = diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index b00edeb98..908f229e3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -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 = 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 = emptyList(), + val experimentalReleases: List = 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 = listOfNotNull(installed), val update: String? = null, -) +) { + val available: Boolean get() = installed == null || update != null +} @Composable private fun gpuCardValue(gpu: GpuDriversState, auto: String): String { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt new file mode 100644 index 000000000..21057d1de --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt @@ -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(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 = + StoresState.shelves[store]?.all.orEmpty().filter { !it.mature }.distinctBy { it.id }.take(24).map { it.copy(owned = true) } + +internal fun sampleInstalled(owned: Map>): Set = + 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) { + 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(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() } + } + } + }) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt index cb5d4795f..5e86cf489 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 191956c17..adf55c4b1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -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") { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt index a276eb91e..ab0a80940 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index c35f3d10d..5503ef22a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -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 = 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) || diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index ef414c4eb..2267bef93 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -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 -> { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 9f457566b..b7976c89d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -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(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) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index 6d360d735..6bc4fd214 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -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), ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index b99a4331b..3b93f0652 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -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?>(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?>(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(null) } var tick by remember(g.gameId) { mutableStateOf(0) } + var refreshing by remember(g.gameId) { mutableStateOf(false) } val status by produceState(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(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)) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryAccounts.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryAccounts.kt deleted file mode 100644 index 2b10c7902..000000000 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryAccounts.kt +++ /dev/null @@ -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(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.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(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(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, - ) - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt index a0fb74ef6..c50a6c897 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt @@ -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>(emptySet()) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index 272f42840..d901b1a68 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -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): List = e internal const val LIBRARY_ALL = "all" internal fun librarySources( entries: List, order: List, always: Set = emptySet(), favorites: Set = emptySet(), - hidden: (LibraryEntry) -> Boolean = { false }, showHidden: Boolean = false, -): List = - (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 = emptySet(), + places: List> = DEFAULT_LIBRARY_PLACES, offTabs: Set = setOf(LIBRARY_HIDDEN), +): List { + 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 { + 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 = emptyList(), onPlayHit: (SoundtrackIndex.Hit) -> Unit = {}, + signInStore: Store? = null, wallArt: () -> List = { 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, 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, 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, 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(null) } + val highlighted = focused?.takeIf { it in keys } ?: source + val bounds = remember { androidx.compose.runtime.mutableStateMapOf() } + 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(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) { + 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) } } }) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt new file mode 100644 index 000000000..7e732d4fe --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -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>(emptyList()) + private set + var libraryPlaces by mutableStateOf(DEFAULT_LIBRARY_PLACES) + private set + var libraryHidden by mutableStateOf>(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) { + 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> = + 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, places: List>): List { + 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): List> = + 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) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index f7f4319d2..1a674da7f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -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) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt index df22a743f..0c3947f98 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt @@ -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, @@ -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, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt index debc0f86b..d25f72365 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt @@ -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() + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 0fe1f1006..486061bf7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -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, 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 } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index d65852ece..375170289 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -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.entries.filter { - (hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES) && + (hasGlasses || it != SessionDrawerPage.GLASSES) && (hasAgent || it != SessionDrawerPage.AGENT) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 2bb50e0f1..5a95a0eac 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -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, val hudOn: Boolean, val hudConfig: Map = 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, List) -> 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) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index 37de5eba3..135cd79a6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -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"), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 7f2d0cb0c..20dd2c280 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt index 7856fdcfe..f34161f6a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt @@ -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> = + 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(null) } + var confirmCheckout by remember { mutableStateOf(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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 440541dda..a54c7f9bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -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().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(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, arranging: Boolean, + selected: String, focused: String?, tabs: List, 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() } 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(null) } - Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) { - IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) } - } + var cogAt by remember { mutableStateOf(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): List { + 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, 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(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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt index 6d4605785..efe8a808b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt @@ -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, + commit: (List) -> 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(null) } var dragOffset by remember { mutableFloatStateOf(0f) } var grabbed by remember { mutableStateOf(null) } var before by remember { mutableStateOf>(emptyList()) } var focused by remember { mutableStateOf(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 } } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt index 6b4dd7d99..8cf7013d0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt @@ -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) } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 3e8795a7b..53fc57eab 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -22,7 +22,6 @@ أضف مكتبات Steam من بطاقة SD أو محرك USB أو SSD، وسيجمع DroidDeck الألعاب معًا في «المكتبة». تتيح لك «المتاجر» تسجيل الدخول إلى Epic Games وGOG وXbox وEA وBattle.net وUbisoft Connect وAmazon Games وitch.io وGame Jolt، ثم تثبيت ألعابها وتحديثها من DroidDeck. تحدّث المكوّنات مثل FEX وDXVK وVKD3D-Proton نفسها تلقائيًا، ويكون Proton Experimental ARM64 هو الافتراضي، أو Proton 11.0 ARM64 بعد تثبيت هذا الإصدار. - يحرر «ضغط Steam أثناء تشغيل لعبة» مساحة من الذاكرة في الأجهزة قليلة الذاكرة. اسحب من الحافة اليمنى للداخل لفتح قائمة الجلسة: وضع «لوحة اللمس» و«لوحة مفاتيح الكمبيوتر» و«وضع زمن الاستجابة المنخفض» وملف اللعبة والمزيد. اللعبة بطيئة؟ حدّد معدل الإطارات في الوصول السريع، ثم جرّب إصدار Proton آخر أو إعدادًا مسبقًا آخر لـ FEX في مكوّنات اللعبة. هل الصوت متقطع أو مفقود في اللعبة؟ جرّب مفتاح «DirectAudio للألعاب» في إعدادات Steam ضمن «الصوت». @@ -629,20 +628,8 @@ gamescope: طابور GPU بأولوية الوقت الفعلي يعطي الأولوية لعمل GPU الخاص بالمُركِّب. قد يحسّن انتظام الإطارات على حساب أداء الألعاب قليلًا. GPU - الذاكرة إيقاف - افتراضي برنامج التشغيل - ضغط Steam أثناء تشغيل لعبة - ضغط ذاكرة اللعبة الخاملة - يرحّل ذاكرة اللعبة الخاملة عند انخفاض RAM. أوقفه إذا كانت الألعاب تتجمد لبضع ثوانٍ كل نصف دقيقة تقريبًا. يُطبَّق عند بدء الجلسة التالية. - بعد 20 ثانية من بدء اللعبة، يُضغط عميل Steam في zRAM لترك ذاكرة أكبر للعبة، ثم يُقرأ مجددًا عند إغلاقها. أوقف هذا الخيار إذا كانت الجلسة تُغلَق بعد بدء الألعاب بقليل. يظل حد RAM أعلاه يضغط Steam عندما تتجاوزه الجلسة. - حد RAM - يُطبَّق أثناء تشغيل عميل Steam، في جلسة Steam أو من سطح المكتب. عندما تستخدم الجلسة أكثر من هذا الحد، يُضغط Steam ثم عمليات الجلسة المدعومة الأخرى في zRAM. حد مرن: لا يُغلَق شيء، لكن قد تتقطّع الألعاب أثناء استعادة الصفحات. - يتطلب مساحة تبديل zRAM، وهي غير متوفرة على هذا الجهاز. - حد VRAM - يُبلّغ ألعاب Direct3D من 9 إلى 12 بميزانية ذاكرة الفيديو هذه لتشجيع تقليل استخدامها. قد تتجاوزها الألعاب؛ لا يضيف هذا ترحيل ذاكرة GPU ولا يضمن منع الانهيار بسبب نفاد الذاكرة. يسري في الجلسة التالية. تثبيت GPU على أعلى تردد له - لـ Adreno فقط. تقطّع أقل، مع استهلاك أكبر للبطارية والحرارة. إصلاحات الجلسة Turnip: التصيير عبر sysmem ينطبق على عميل Steam والألعاب. مطلوب على Adreno 710/720/722. @@ -819,7 +806,6 @@ لوحة مفاتيح الكمبيوتر Android الشاشة الثانية - الوضع يعرض تطبيقات Android تشغيل تطبيق @@ -2391,6 +2377,17 @@ عدم تطابق المجموع الاختباري؛ تم حذف التنزيل بدأت جلسة خلال التنزيل، أوقفها قبل تثبيت أدوات التوافق جارٍ تثبيت %1$s + إصدارات تجريبية + تثبيت من ملف + يحتوي الأرشيف على رابط أو مسار غير آمن + أرشيف غير مدعوم أو غير صالح + لا توجد مساحة كافية لإصدار Proton هذا + جارٍ تفريغ Proton (بضع دقائق) + فشل التفريغ (tar %1$d) + الأرشيف لا يحتوي على إصدار Proton + تعذّر وضع إصدار Proton + تعذّرت الإزالة الكاملة لـ %1$s + تم تثبيت Proton التجريبي. اختره في Steam → الخصائص → التوافق. فشل تثبيت %1$s (حالة الخروج %2$d) تعذّر تثبيت %1$s جارٍ جلب حزمة droiddeck-esync @@ -3465,10 +3462,19 @@ بادئة Steam المشتركة يشغّل Steam مساعدات Windows الخاصة به هنا يحذفها (%1$s). ينشئ Steam بادئة جديدة في المرة التالية التي يحتاجها فيها. + يحذف بادئة Wine وذاكرة التظليل المؤقتة لتطبيق المتجر هذا (%1$s)، مع تسجيل الدخول وأي حفظ موجود فيها فقط. تحصل الألعاب التي تعمل فيها على بادئة جديدة، وقد تحتاج إلى إعداد التطبيق مرة أخرى. تبقى عمليات الحفظ السحابية في حسابك. + يمكن مسح %1$s + ذاكرات Linux وSteam المؤقتة + الملفات المؤقتة القديمة والحزم المنزّلة وذاكرة الويب المؤقتة لـ Steam + الملفات المؤقتة القديمة + الحزم المنزّلة + ذاكرة الويب المؤقتة لـ Steam + تنزيلات Steam التالفة + تُنشأ مجددًا عند الحاجة + مسح تطبيق متجر والألعاب التي تعمل به مستخدَمة بواسطة %1$s لعبة خارج Steam %1$s - غير مطابقة لأي لعبة، لذا يُحتفظ بها حذف المحدد · %1$s إلغاء تثبيت المحدد · %1$s بادئات Wine @@ -4225,4 +4231,18 @@ عدد صحيح ملاءمة تنعيم الحواف - \ No newline at end of file + مخصص + اختر كل لون في الواجهة بشكل مستقل. + الخلفية + اللوحات + اللوحات المرتفعة + الفواصل + الحدود + النص الرئيسي + النص الثانوي + الأزرار واللون الأساسي + نص الأزرار + الإبرازات + نجاح + خطأ + diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 9e9b3e76e..85ae43153 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -22,7 +22,6 @@ Añade bibliotecas de Steam desde una tarjeta SD, una unidad USB o un SSD, y DroidDeck mantiene los juegos juntos en tu Biblioteca. 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. 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. - Comprimir Steam mientras se ejecuta un juego libera RAM en dispositivos con poca memoria. 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. ¿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. ¿Audio del juego entrecortado o ausente? Prueba el interruptor DirectAudio para juegos en los ajustes de Steam, en Audio. @@ -623,20 +622,8 @@ gamescope: cola de GPU en tiempo real Da prioridad al trabajo de GPU del compositor. Puede suavizar el ritmo de fotogramas a costa de algo de rendimiento en los juegos. GPU - Memoria Desactivado - Predeterminado del controlador - Comprimir Steam mientras se ejecuta un juego - Comprimir memoria inactiva del juego - 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. - 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. - Límite de RAM - 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. - Requiere swap de zRAM, y este dispositivo no lo tiene. - Límite de VRAM - 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. Mantener la GPU a su reloj máximo - Solo Adreno. Menos microcortes, más consumo de batería y calor. Correcciones de sesión Turnip: renderizado sysmem Se aplica al cliente de Steam y a los juegos. Obligatorio en Adreno 710/720/722. @@ -836,7 +823,6 @@ Teclado de PC Android Segunda pantalla - Modo Muestra Apps de Android Abrir una app @@ -2381,6 +2367,17 @@ La suma de verificación no coincide; se eliminó la descarga Se inició una sesión durante la descarga; detenla antes de instalar herramientas de compatibilidad Instalando %1$s + Versiones experimentales + Instalar desde archivo + El archivo contiene un enlace o una ruta no segura + Archivo no compatible o no válido + No hay espacio libre suficiente para esta versión de Proton + Desempaquetando Proton (unos minutos) + Error al desempaquetar (tar %1$d) + El archivo no contiene ninguna versión de Proton + No se pudo colocar la versión de Proton + No se pudo quitar %1$s por completo + Proton experimental instalado. Elígelo en Steam → Propiedades → Compatibilidad. Falló la instalación de %1$s (salida %2$d) No se pudo instalar %1$s Descargando el paquete droiddeck-esync @@ -3320,10 +3317,19 @@ Prefijo compartido de Steam Steam ejecuta aquí sus propias herramientas de Windows Lo borra (%1$s). Steam crea uno nuevo la próxima vez que lo necesite. + 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. + Se pueden liberar %1$s + Cachés de Linux y Steam + Archivos temporales viejos, paquetes descargados y la caché web de Steam + Archivos temporales viejos + Paquetes descargados + Caché web de Steam + Descargas dañadas de Steam + Se vuelven a crear cuando hacen falta + Borrar Una app de tienda y los juegos que se ejecutan con ella Usado por %1$s Juego que no es de Steam %1$s - No coincide con ningún juego, así que se conserva Quitar selección · %1$s Desinstalar selección · %1$s Prefijos de Wine @@ -4105,4 +4111,18 @@ Entero Ajustar Antialiasing - \ No newline at end of file + Personalizado + Elige cada color de la interfaz por separado. + Fondo + Paneles + Paneles elevados + Separadores + Bordes + Texto principal + Texto secundario + Botones y color principal + Texto de los botones + Destacados + Éxito + Error + diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index f271d1d40..14ffae0eb 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -22,7 +22,6 @@ Добавяйте библиотеки на Steam от SD карта, USB устройство или SSD, а DroidDeck държи игрите заедно в Библиотека. Магазини ви позволява да влезете в Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io и Game Jolt, а после да инсталирате и обновявате техните игри от DroidDeck. Компоненти като FEX, DXVK и VKD3D-Proton се обновяват сами, а Proton Experimental ARM64 е по подразбиране, или Proton 11.0 ARM64, щом тази версия е инсталирана. - Компресиране на Steam, докато върви игра освобождава RAM на устройства с малко памет. Плъзнете навътре от десния ръб, за да отворите менюто на сесията: режим на тъчпад, Клавиатура за компютър, Режим на ниска латентност, профил на играта и други. Играта е бавна? Ограничете кадрите в Quick Access, после опитайте друга версия на Proton или друга предварителна настройка на FEX в компонентите на играта. Пращене или липсващ звук в играта? Опитайте превключвателя DirectAudio за игри в настройките на Steam, под Звук. @@ -621,20 +620,8 @@ gamescope: GPU опашка в реално време Дава приоритет на GPU работата на компоситора. Може да изглади темпото на кадрите с известна цена за игрите. GPU - Памет Изкл. - По подразбиране за драйвера - Компресиране на Steam, докато върви игра - Компресиране на неактивната памет на играта - Компресира неактивната памет на играта при малко RAM. Изключете го, ако игрите замръзват за няколко секунди приблизително на всеки половин минута. Прилага се при следващото стартиране на сесията. - 20 s след стартиране на игра клиентът на Steam се компресира в zRAM, за да остави повече памет на играта, и се прочита обратно, когато играта се затвори. Изключете, ако сесията се затваря малко след стартиране на игри. Ограничение на RAM по-горе пак компресира Steam, когато сесията го надхвърли. - Ограничение на RAM - Прилага се, докато клиентът на Steam работи, в режим Steam или от работния плот. Когато сесията използва повече от това, Steam и след това другите поддържани процеси на сесията се компресират в zRAM. Меко ограничение: нищо не се затваря, но игрите може да засичат, докато страниците се връщат. - Изисква zRAM swap, който това устройство няма. - Ограничение на VRAM - Съобщава този бюджет за видео памет на игри с Direct3D 9 до 12, за да намали използването на памет. Игрите може да го надвишат; това не добавя странициране на GPU и не гарантира защита от сривове при недостиг на памет. Прилага се от следващата сесия. Задръжте GPU на максималната му честота - Само за Adreno. По-малко засечки, по-голямо използване на батерията и повече топлина. Корекции на сесията Turnip: рендиране sysmem Прилага се за клиента на Steam и игрите. Изисква се при Adreno 710/720/722. @@ -811,7 +798,6 @@ Клавиатура за компютър Android Втори екран - Режим Показва Приложения за Android Стартиране на приложение @@ -2287,6 +2273,17 @@ Несъответствие в контролната сума; изтеглянето беше изтрито По време на изтеглянето започна сесия - спри я, преди да инсталираш инструменти за съвместимост Инсталиране на %1$s + Експериментални версии + Инсталиране от файл + Архивът съдържа опасна връзка или път + Неподдържан или невалиден архив + Няма достатъчно свободно място за тази версия на Proton + Разопаковане на Proton (няколко минути) + Разопаковането не успя (tar %1$d) + Архивът не съдържа версия на Proton + Версията на Proton не можа да бъде поставена + %1$s не можа да бъде премахнат напълно + Експерименталният Proton е инсталиран. Изберете го в Steam → Свойства → Съвместимост. Инсталирането на %1$s се провали (код %2$d) %1$s не можа да бъде инсталиран Извличане на пакета droiddeck-esync @@ -3317,10 +3314,19 @@ Споделен Steam префикс Steam изпълнява тук свои помощни програми за Windows Изтрива го (%1$s). Steam създава нов следващия път, когато му потрябва. + Изтрива Wine префикса и кеша на шейдърите на това приложение на магазин (%1$s), заедно с влизането и записите, пазени само там. Игрите, които работят в него, получават нов префикс и може да се наложи да настроите приложението отново. Записите в облака остават в профила ви. + Може да се изчистят %1$s + Кешове на Linux и Steam + Стари временни файлове, изтеглени пакети и уеб кешът на Steam + Стари временни файлове + Изтеглени пакети + Уеб кеш на Steam + Повредени изтегляния на Steam + Създават се отново при нужда + Изчисти Приложение магазин и игрите, които работят с него Използва се от %1$s Игра извън Steam %1$s - Не е свързан с игра, затова се запазва Премахни избраните · %1$s Деинсталирай избраните · %1$s Префикси на Wine @@ -4065,4 +4071,18 @@ Цяло число Побиране Заглаждане на ръбовете - \ No newline at end of file + Персонализирана + Изберете поотделно всеки цвят на интерфейса. + Фон + Панели + Повдигнати панели + Разделители + Рамки + Основен текст + Вторичен текст + Бутони и основен акцент + Текст на бутоните + Акценти + Успех + Грешка + diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index fc64f5af0..72895e79a 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -22,7 +22,6 @@ Přidejte knihovny Steamu z SD karty, USB disku nebo SSD a DroidDeck udrží hry pohromadě v Knihovně. 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. 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á. - Komprimovat Steam během hry uvolní RAM na zařízeních s nedostatkem paměti. 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ší. Hra běží pomalu? Omezte snímkovou frekvenci v Quick Access a zkuste jinou verzi Proton nebo jinou předvolbu FEX v komponentách hry. Praskání nebo chybějící zvuk ve hře? Zkuste přepínač DirectAudio pro hry v nastavení Steamu v části Zvuk. @@ -625,20 +624,8 @@ gamescope: fronta GPU v reálném čase Dává prioritu práci GPU kompozitoru. Může vyhladit tempo snímků na úkor her. GPU - Paměť Vypnuto - Výchozí ovladače - Komprimovat Steam během hry - Komprimovat neaktivní paměť hry - 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. - 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čí. - Limit RAM - 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. - Vyžaduje swap zRAM, který toto zařízení nemá. - Limit VRAM - 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. Udržet GPU na nejvyšších taktech - Jen Adreno. Méně zadrhávání, více spotřeby baterie a tepla. Opravy relace Turnip: vykreslování sysmem Platí pro klienta Steam i hry. Vyžadováno na Adreno 710/720/722. @@ -815,7 +802,6 @@ Klávesnice PC Android Druhá obrazovka - Režim Zobrazuje Aplikace Android Spustit aplikaci @@ -2339,6 +2325,17 @@ Neshoda kontrolního součtu; stahování bylo odstraněno Během stahování se spustila relace; před instalací nástrojů kompatibility ji zastavte Instalování %1$s + Experimentální sestavení + Instalovat ze souboru + Archiv obsahuje nebezpečný odkaz nebo cestu + Nepodporovaný nebo neplatný archiv + Pro toto sestavení Proton není dost volného místa + Rozbalování Proton (několik minut) + Rozbalení se nezdařilo (tar %1$d) + Archiv neobsahuje sestavení Proton + Sestavení Proton se nepodařilo umístit + Nepodařilo se úplně odebrat %1$s + Experimentální Proton je nainstalován. Vyberte ho ve Steam → Vlastnosti → Kompatibilita. Instalace %1$s se nezdařila (návratový kód %2$d) Nepodařilo se nainstalovat %1$s Stahování balíčku droiddeck-esync @@ -3391,10 +3388,19 @@ Sdílený prefix Steamu Steam zde spouští své pomocné programy pro Windows Smaže ho (%1$s). Steam si vytvoří nový, až ho bude příště potřebovat. + 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. + Lze uvolnit %1$s + Mezipaměti Linuxu a Steamu + Staré dočasné soubory, stažené balíčky a webová mezipaměť Steamu + Staré dočasné soubory + Stažené balíčky + Webová mezipaměť Steamu + Poškozená stahování Steamu + V případě potřeby se vytvoří znovu + Vymazat Aplikace obchodu a hry, které s ní běží Používá: %1$s Hra mimo Steam %1$s - Nepatří k žádné hře, proto zůstává Odebrat vybrané · %1$s Odinstalovat vybrané · %1$s Prefixy Wine @@ -4145,4 +4151,18 @@ Celé číslo Přizpůsobit Vyhlazování hran - \ No newline at end of file + Vlastní + Vyberte samostatně každou barvu rozhraní. + Pozadí + Panely + Vyvýšené panely + Oddělovače + Ohraničení + Hlavní text + Vedlejší text + Tlačítka a hlavní zvýraznění + Text tlačítek + Zvýraznění + Úspěch + Chyba + diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index f4a816b44..f38a57c7a 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -22,7 +22,6 @@ Tilføj Steam-biblioteker fra et SD-kort, et USB-drev eller en SSD, så samler DroidDeck spillene i dit Bibliotek. 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. 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. - Komprimer Steam, mens et spil kører frigør RAM på enheder med lidt hukommelse. Stryg ind fra højre kant for at åbne sessionsmenuen: touchpad-tilstand, PC-tastatur, Lav forsinkelse, spilprofil og mere. Kører spillet langsomt? Begræns billedfrekvensen i Hurtig adgang, og prøv så en anden Proton-version eller FEX-forudindstilling i spillets komponenter. Knitrende eller manglende lyd i spillet? Prøv kontakten DirectAudio til spil i Steam-indstillingerne under Lyd. @@ -621,20 +620,8 @@ gamescope: realtids-GPU-kø Prioriterer compositorens GPU-arbejde. Kan give jævnere billedtiming på bekostning af spillene. GPU - Hukommelse Fra - Driverstandard - Komprimer Steam, mens et spil kører - Komprimer spillets inaktive hukommelse - 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. - 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. - RAM-grænse - 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. - Kræver zRAM-swap, som denne enhed ikke har. - VRAM-grænse - 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. Hold GPU’en på dens højeste clock - Kun Adreno. Færre hak, mere batteribrug og varme. Sessionsrettelser Turnip: sysmem-rendering Gælder Steam-klienten og spil. Påkrævet på Adreno 710/720/722. @@ -811,7 +798,6 @@ PC-tastatur Android Anden skærm - Tilstand Viser Android-apps Start en app @@ -2287,6 +2273,17 @@ Tjeksum stemmer ikke; downloadet blev slettet En session startede under downloadet; stop den før du installerer kompatibilitetsværktøjer Installerer %1$s + Eksperimentelle builds + Installer fra fil + Arkivet indeholder et usikkert link eller en sti + Ikke-understøttet eller ugyldigt arkiv + Der er ikke nok ledig plads til denne Proton-build + Udpakker Proton (nogle få minutter) + Udpakning mislykkedes (tar %1$d) + Arkivet indeholder ingen Proton-build + Kunne ikke placere Proton-builden + Kunne ikke fjerne %1$s helt + Eksperimentel Proton er installeret. Vælg den i Steam → Egenskaber → Kompatibilitet. Installation af %1$s mislykkedes (afslutningskode %2$d) Kunne ikke installere %1$s Henter droiddeck-esync-pakken @@ -3317,10 +3314,19 @@ Steams delte præfiks Steam kører sine egne Windows-hjælpere her Sletter det (%1$s). Steam opretter et nyt, næste gang det skal bruges. + 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. + %1$s kan ryddes + Linux- og Steam-cache + Gamle midlertidige filer, hentede pakker og Steams webcache + Gamle midlertidige filer + Hentede pakker + Steams webcache + Beskadigede Steam-downloads + Oprettes igen efter behov + Ryd En butiksapp og de spil, der kører med den Bruges af %1$s Ikke-Steam-spil %1$s - Ikke knyttet til et spil, så det bevares Fjern valgte · %1$s Afinstaller valgte · %1$s Wine-prefixer @@ -4065,4 +4071,18 @@ Heltal Tilpas Kantudjævning - \ No newline at end of file + Tilpasset + Vælg hver grænsefladefarve individuelt. + Baggrund + Paneler + Hævede paneler + Skillestreger + Kanter + Primær tekst + Sekundær tekst + Knapper og hovedaccent + Knaptekst + Fremhævninger + Succes + Fejl + diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index fb7ed37e2..c897478fb 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -22,7 +22,6 @@ 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. 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. 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. - Steam komprimieren, während ein Spiel läuft gibt auf Geräten mit knappem Arbeitsspeicher RAM frei. Wische vom rechten Rand nach innen, um das Sitzungsmenü zu öffnen: Touchpad-Modus, PC-Tastatur, Modus mit geringer Latenz, Spielprofil und mehr. 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. Knacken oder fehlender Spielton? Probiere den Schalter DirectAudio für Spiele in den Steam-Einstellungen unter Audio. @@ -621,20 +620,8 @@ gamescope: Echtzeit-GPU-Warteschlange Priorisiert die GPU-Arbeit des Compositors. Kann das Frame-Pacing glätten, kostet Spiele aber etwas Leistung. GPU - Arbeitsspeicher Aus - Treiberstandard - Steam komprimieren, während ein Spiel läuft - Inaktiven Spielspeicher komprimieren - 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. - 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. - RAM-Limit - 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. - Benötigt zRAM-Swap, den dieses Gerät nicht hat. - VRAM-Limit - 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. GPU auf höchstem Takt halten - Nur Adreno. Weniger Ruckler, mehr Akkuverbrauch und Wärme. Sitzungskorrekturen Turnip: Sysmem-Rendering Gilt für den Steam-Client und Spiele. Erforderlich bei Adreno 710/720/722. @@ -811,7 +798,6 @@ PC-Tastatur Android Zweiter Bildschirm - Modus Zeigt Android-Apps App starten @@ -2279,6 +2265,17 @@ Prüfsumme stimmt nicht überein; der Download wurde gelöscht Während des Downloads wurde eine Sitzung gestartet; beende sie, bevor du Kompatibilitätstools installierst %1$s wird installiert + Experimentelle Builds + Aus Datei installieren + Das Archiv enthält einen unsicheren Link oder Pfad + Nicht unterstütztes oder ungültiges Archiv + Nicht genug freier Speicher für diesen Proton-Build + Proton wird entpackt (einige Minuten) + Entpacken fehlgeschlagen (tar %1$d) + Das Archiv enthält keinen Proton-Build + Der Proton-Build konnte nicht abgelegt werden + %1$s konnte nicht vollständig entfernt werden + Experimentelles Proton installiert. Wähle es unter Steam → Eigenschaften → Kompatibilität aus. Installation von %1$s fehlgeschlagen (Exit-Code %2$d) %1$s konnte nicht installiert werden droiddeck-esync-Paket wird abgerufen @@ -3317,10 +3314,19 @@ Gemeinsames Präfix von Steam Steam führt hier eigene Windows-Hilfsprogramme aus Löscht es (%1$s). Steam erstellt ein neues, sobald es wieder eines braucht. + 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. + %1$s können geleert werden + Linux- und Steam-Caches + Alte temporäre Dateien, heruntergeladene Pakete und Steams Web-Cache + Alte temporäre Dateien + Heruntergeladene Pakete + Steam-Web-Cache + Beschädigte Steam-Downloads + Wird bei Bedarf neu erstellt + Leeren Eine Store-App und die Spiele, die damit laufen Verwendet von %1$s Nicht-Steam-Spiel %1$s - Keinem Spiel zugeordnet, daher bleibt es erhalten Auswahl entfernen · %1$s Auswahl deinstallieren · %1$s Wine-Präfixe @@ -4065,4 +4071,18 @@ Ganzzahlig Anpassen Kantenglättung - \ No newline at end of file + Benutzerdefiniert + Wähle jede Farbe der Oberfläche einzeln aus. + Hintergrund + Flächen + Erhöhte Flächen + Trennlinien + Rahmen + Haupttext + Sekundärtext + Schaltflächen und Hauptakzent + Schaltflächentext + Hervorhebungen + Erfolg + Fehler + diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 103d46cac..5f23fee83 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -22,7 +22,6 @@ Προσθέστε βιβλιοθήκες Steam από κάρτα SD, μονάδα USB ή SSD, και το DroidDeck κρατά τα παιχνίδια μαζί στη Βιβλιοθήκη σας. Τα Καταστήματα σάς επιτρέπουν να συνδεθείτε σε Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io και Game Jolt και μετά να εγκαθιστάτε και να ενημερώνετε τα παιχνίδια τους από το DroidDeck. Στοιχεία όπως τα FEX, DXVK και VKD3D-Proton ενημερώνονται μόνα τους, και το Proton Experimental ARM64 είναι το προεπιλεγμένο, ή το Proton 11.0 ARM64 μόλις εγκατασταθεί αυτή η έκδοση. - Η επιλογή Συμπίεση του Steam όσο τρέχει παιχνίδι ελευθερώνει RAM σε συσκευές με λίγη μνήμη. Σύρετε προς τα μέσα από τη δεξιά άκρη για να ανοίξετε το μενού συνεδρίας: λειτουργία πινακίδας αφής, Πληκτρολόγιο PC, Λειτουργία χαμηλής καθυστέρησης, προφίλ παιχνιδιού και άλλα. Το παιχνίδι τρέχει αργά; Περιορίστε τον ρυθμό καρέ στο Quick Access και δοκιμάστε άλλη έκδοση Proton ή άλλη προεπιλογή FEX στα στοιχεία του παιχνιδιού. Κροταλίσματα ή απουσία ήχου στο παιχνίδι; Δοκιμάστε τον διακόπτη DirectAudio για παιχνίδια στις ρυθμίσεις του Steam, στην ενότητα Ήχος. @@ -621,20 +620,8 @@ gamescope: ουρά GPU πραγματικού χρόνου Δίνει προτεραιότητα στην εργασία GPU του compositor. Μπορεί να εξομαλύνει τον ρυθμό καρέ με κάποιο κόστος για τα παιχνίδια. GPU - Μνήμη Ανενεργό - Προεπιλογή προγράμματος οδήγησης - Συμπίεση του Steam όσο τρέχει παιχνίδι - Συμπίεση ανενεργής μνήμης παιχνιδιού - Σελιδοποιεί την ανενεργή μνήμη του παιχνιδιού όταν η RAM είναι χαμηλή. Απενεργοποιήστε το αν τα παιχνίδια παγώνουν για λίγα δευτερόλεπτα περίπου κάθε μισό λεπτό. Ισχύει από την επόμενη έναρξη της συνεδρίας. - 20 s μετά την εκκίνηση ενός παιχνιδιού, ο πελάτης Steam συμπιέζεται στη zRAM για να μείνει περισσότερη μνήμη στο παιχνίδι, και διαβάζεται πίσω όταν το παιχνίδι κλείσει. Απενεργοποιήστε το αν η συνεδρία κλείνει λίγο μετά την εκκίνηση παιχνιδιών. Ένα όριο RAM παραπάνω εξακολουθεί να συμπιέζει το Steam όταν η συνεδρία το ξεπεράσει. - Όριο RAM - Ισχύει όσο τρέχει ο πελάτης Steam, σε λειτουργία Steam ή από την επιφάνεια εργασίας. Όταν η συνεδρία χρησιμοποιεί περισσότερη, το Steam και έπειτα οι άλλες υποστηριζόμενες διεργασίες της συνεδρίας συμπιέζονται στη zRAM. Ήπιο όριο: τίποτα δεν κλείνει, αλλά τα παιχνίδια μπορεί να κολλάνε όσο επιστρέφουν οι σελίδες. - Απαιτεί zRAM swap, που δεν υπάρχει σε αυτή τη συσκευή. - Όριο VRAM - Αναφέρει αυτόν τον προϋπολογισμό μνήμης βίντεο σε παιχνίδια Direct3D 9 έως 12 για να μειωθεί η χρήση μνήμης. Τα παιχνίδια μπορεί να τον υπερβούν· δεν προσθέτει σελιδοποίηση GPU ούτε εγγυάται προστασία από σφάλματα έλλειψης μνήμης. Ισχύει από την επόμενη συνεδρία. Διατήρηση της GPU στη μέγιστη συχνότητά της - Μόνο Adreno. Λιγότερα κολλήματα, μεγαλύτερη χρήση μπαταρίας και θερμότητα. Διορθώσεις συνεδρίας Turnip: απόδοση sysmem Ισχύει για το πρόγραμμα-πελάτη Steam και τα παιχνίδια. Απαιτείται σε Adreno 710/720/722. @@ -811,7 +798,6 @@ Πληκτρολόγιο PC Android Δεύτερη οθόνη - Λειτουργία Εμφανίζει Εφαρμογές Android Εκκίνηση εφαρμογής @@ -2287,6 +2273,17 @@ Αναντιστοιχία αθροίσματος ελέγχου· η λήψη διαγράφηκε Μια συνεδρία ξεκίνησε κατά τη λήψη· διακόψτε την πριν εγκαταστήσετε εργαλεία συμβατότητας Εγκατάσταση %1$s + Πειραματικές εκδόσεις + Εγκατάσταση από αρχείο + Το αρχείο περιέχει μη ασφαλή σύνδεσμο ή διαδρομή + Μη υποστηριζόμενο ή μη έγκυρο αρχείο + Δεν υπάρχει αρκετός ελεύθερος χώρος για αυτήν την έκδοση Proton + Αποσυσκευασία του Proton (λίγα λεπτά) + Η αποσυσκευασία απέτυχε (tar %1$d) + Το αρχείο δεν περιέχει έκδοση Proton + Δεν ήταν δυνατή η τοποθέτηση της έκδοσης Proton + Δεν ήταν δυνατή η πλήρης κατάργηση του %1$s + Το πειραματικό Proton εγκαταστάθηκε. Επιλέξτε το στο Steam → Ιδιότητες → Συμβατότητα. Η εγκατάσταση του %1$s απέτυχε (έξοδος %2$d) Δεν ήταν δυνατή η εγκατάσταση του %1$s Λήψη πακέτου droiddeck-esync @@ -3317,10 +3314,19 @@ Κοινό prefix του Steam Το Steam εκτελεί εδώ τα δικά του βοηθητικά προγράμματα Windows Το διαγράφει (%1$s). Το Steam δημιουργεί νέο την επόμενη φορά που θα το χρειαστεί. + Διαγράφει το πρόθεμα Wine και την cache των shader αυτής της εφαρμογής καταστήματος (%1$s), μαζί με τη σύνδεση και όσες αποθηκεύσεις υπάρχουν μόνο εκεί. Τα παιχνίδια που τρέχουν σε αυτό παίρνουν νέο πρόθεμα και ίσως χρειαστεί να ρυθμίσετε ξανά την εφαρμογή. Οι αποθηκεύσεις στο cloud μένουν στον λογαριασμό σας. + Μπορούν να εκκαθαριστούν %1$s + Cache του Linux και του Steam + Παλιά προσωρινά αρχεία, πακέτα που κατέβηκαν και η cache ιστού του Steam + Παλιά προσωρινά αρχεία + Πακέτα που κατέβηκαν + Cache ιστού του Steam + Κατεστραμμένες λήψεις Steam + Δημιουργούνται ξανά όταν χρειάζεται + Εκκαθάριση Μια εφαρμογή καταστήματος και τα παιχνίδια που τρέχουν με αυτήν Χρησιμοποιείται από %1$s Παιχνίδι εκτός Steam %1$s - Δεν αντιστοιχεί σε παιχνίδι, οπότε διατηρείται Αφαίρεση επιλεγμένων · %1$s Κατάργηση επιλεγμένων · %1$s Prefix Wine @@ -4065,4 +4071,18 @@ Ακέραιος Προσαρμογή Εξομάλυνση ακμών - \ No newline at end of file + Προσαρμοσμένο + Επιλέξτε ξεχωριστά κάθε χρώμα της διεπαφής. + Φόντο + Πλαίσια + Ανυψωμένα πλαίσια + Διαχωριστικά + Περιγράμματα + Κύριο κείμενο + Δευτερεύον κείμενο + Κουμπιά και κύριο χρώμα έμφασης + Κείμενο κουμπιών + Επισημάνσεις + Επιτυχία + Σφάλμα + diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index a4fb131cd..c5c083f7b 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -22,7 +22,6 @@ Añade bibliotecas de Steam desde una tarjeta SD, una unidad USB o un SSD, y DroidDeck mantiene los juegos juntos en tu Biblioteca. 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. 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. - Comprimir Steam mientras se ejecuta un juego libera RAM en dispositivos con poca memoria. 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. ¿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. ¿Audio del juego entrecortado o ausente? Prueba el interruptor DirectAudio para juegos en los ajustes de Steam, en Audio. @@ -623,20 +622,8 @@ gamescope: cola de GPU en tiempo real Da prioridad al trabajo de GPU del compositor. Puede suavizar el ritmo de fotogramas a costa de algo de rendimiento en los juegos. GPU - Memoria Desactivado - Predeterminado del controlador - Comprimir Steam mientras se ejecuta un juego - Comprimir memoria inactiva del juego - 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. - 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. - Límite de RAM - 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. - Requiere swap de zRAM, y este dispositivo no lo tiene. - Límite de VRAM - 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. Mantener la GPU a su reloj máximo - Solo Adreno. Menos tirones, más consumo de batería y calor. Correcciones de sesión Turnip: renderizado sysmem Se aplica al cliente de Steam y a los juegos. Obligatorio en Adreno 710/720/722. @@ -813,7 +800,6 @@ Teclado de PC Android Segunda pantalla - Modo Muestra Apps de Android Abrir una app @@ -2313,6 +2299,17 @@ La suma de verificación no coincide; se eliminó la descarga Se inició una sesión durante la descarga; detenla antes de instalar herramientas de compatibilidad Instalando %1$s + Versiones experimentales + Instalar desde archivo + El archivo contiene un enlace o una ruta no segura + Archivo no compatible o no válido + No hay espacio libre suficiente para esta versión de Proton + Desempaquetando Proton (unos minutos) + Error al desempaquetar (tar %1$d) + El archivo no contiene ninguna versión de Proton + No se pudo colocar la versión de Proton + No se pudo quitar %1$s por completo + Proton experimental instalado. Elígelo en Steam → Propiedades → Compatibilidad. Falló la instalación de %1$s (salida %2$d) No se pudo instalar %1$s Descargando el paquete droiddeck-esync @@ -3354,10 +3351,19 @@ Prefijo compartido de Steam Steam ejecuta aquí sus propias herramientas de Windows Lo borra (%1$s). Steam crea uno nuevo la próxima vez que lo necesite. + 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. + Se pueden liberar %1$s + Cachés de Linux y Steam + Archivos temporales antiguos, paquetes descargados y la caché web de Steam + Archivos temporales antiguos + Paquetes descargados + Caché web de Steam + Descargas dañadas de Steam + Se vuelven a crear cuando hacen falta + Borrar Una app de tienda y los juegos que se ejecutan con ella Usado por %1$s Juego que no es de Steam %1$s - No coincide con ningún juego, así que se conserva Quitar selección · %1$s Desinstalar selección · %1$s Prefijos de Wine @@ -4105,4 +4111,18 @@ Entero Ajustar Suavizado de bordes - \ No newline at end of file + Personalizado + Elige cada color de la interfaz por separado. + Fondo + Paneles + Paneles elevados + Separadores + Bordes + Texto principal + Texto secundario + Botones y color principal + Texto de los botones + Destacados + Éxito + Error + diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 92460d64d..4690cf37e 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -22,7 +22,6 @@ Lisää Steam-kirjastoja SD-kortilta, USB-asemalta tai SSD-levyltä, ja DroidDeck pitää pelit yhdessä Kirjastossasi. 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ä. 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. - Pakkaa Steam pelin ollessa käynnissä vapauttaa RAM-muistia laitteilla, joilla muisti on vähissä. Pyyhkäise oikeasta reunasta sisäänpäin avataksesi istuntovalikon: kosketuslevytila, PC-näppäimistö, matalan viiveen tila, pelin profiili ja muuta. Peli pyörii hitaasti? Rajoita kuvanopeutta Pikavalikossa ja kokeile sitten toista Proton-versiota tai FEX-esiasetusta pelin komponenteissa. Rätisevä tai puuttuva pelin ääni? Kokeile Steamin asetuksissa kohdassa Ääni asetusta DirectAudio peleille. @@ -621,20 +620,8 @@ gamescope: reaaliaikainen GPU-jono Priorisoi kompositorin GPU-työtä. Voi tasoittaa kuvanopeuden tahditusta pelien kustannuksella. GPU - Muisti Pois - Ajurin oletus - Pakkaa Steam pelin ollessa käynnissä - Pakkaa pelin käyttämätöntä muistia - 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. - 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. - RAM-raja - 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. - Vaatii zRAM-swapin, jota tässä laitteessa ei ole. - VRAM-raja - 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. Pidä GPU huippukellotaajuudessaan - Vain Adreno. Vähemmän nykäyksiä, enemmän akun kulutusta ja lämpöä. Istunnon korjaukset Turnip: sysmem-renderöinti Koskee Steam-asiakasohjelmaa ja pelejä. Pakollinen Adreno 710/720/722:lla. @@ -811,7 +798,6 @@ PC-näppäimistö Android Toinen näyttö - Tila Näyttää Android-sovellukset Käynnistä sovellus @@ -2287,6 +2273,17 @@ Tarkistussumma ei täsmää; lataus poistettiin Istunto käynnistyi latauksen aikana; pysäytä se ennen yhteensopivuustyökalujen asentamista Asennetaan %1$s + Kokeelliset versiot + Asenna tiedostosta + Arkisto sisältää vaarallisen linkin tai polun + Arkistoa ei tueta tai se on virheellinen + Tälle Proton-versiolle ei ole tarpeeksi vapaata tilaa + Puretaan Protonia (muutama minuutti) + Purku epäonnistui (tar %1$d) + Arkisto ei sisällä Proton-versiota + Proton-versiota ei voitu sijoittaa + Kohdetta %1$s ei voitu poistaa kokonaan + Kokeellinen Proton asennettu. Valitse se kohdassa Steam → Ominaisuudet → Yhteensopivuus. %1$s-asennus epäonnistui (poistumiskoodi %2$d) Kohdetta %1$s ei voitu asentaa Haetaan droiddeck-esync-pakettia @@ -3317,10 +3314,19 @@ Steamin jaettu etuliite Steam suorittaa täällä omia Windows-apuohjelmiaan Poistaa sen (%1$s). Steam luo uuden, kun tarvitsee sitä seuraavan kerran. + 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. + %1$s voidaan tyhjentää + Linuxin ja Steamin välimuistit + Vanhat väliaikaistiedostot, ladatut paketit ja Steamin verkkovälimuisti + Vanhat väliaikaistiedostot + Ladatut paketit + Steamin verkkovälimuisti + Vioittuneet Steam-lataukset + Luodaan tarvittaessa uudelleen + Tyhjennä Kauppasovellus ja pelit, jotka toimivat sen kanssa Käyttää: %1$s Muu kuin Steam-peli %1$s - Ei vastaa mitään peliä, joten se säilytetään Poista valitut · %1$s Poista valittujen asennus · %1$s Wine-prefixit @@ -4065,4 +4071,18 @@ Kokonaisluku Sovita Reunanpehmennys - \ No newline at end of file + Mukautettu + Valitse käyttöliittymän jokainen väri erikseen. + Tausta + Paneelit + Korotetut paneelit + Erottimet + Reunat + Pääteksti + Toissijainen teksti + Painikkeet ja pääkorostus + Painikkeiden teksti + Korostukset + Onnistuminen + Virhe + diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 043f1bdea..b69318e76 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -22,7 +22,6 @@ 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. 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. 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. - Compresser Steam pendant un jeu libère de la RAM sur les appareils qui en manquent. 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. 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. Audio du jeu qui grésille ou absent ? Essayez l\'option Utiliser DirectAudio pour le jeu dans les paramètres Steam, sous Audio. @@ -623,20 +622,8 @@ gamescope : file d\'attente GPU temps réel 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. GPU - Mémoire Désactivé - Valeur par défaut du pilote - Compresser Steam pendant un jeu - Compresser la mémoire inactive du jeu - 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. - 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. - Limite de RAM - 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. - Nécessite un swap zRAM, dont cet appareil ne dispose pas. - Limite de VRAM - 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. Maintenir le GPU à sa fréquence maximale - Uniquement pour Adreno. Moins de saccades, mais plus de consommation d\'énergie et de chaleur. Correctifs de session Turnip : rendu sysmem S’applique au client Steam et aux jeux. Requis sur Adreno 710/720/722. @@ -813,7 +800,6 @@ Clavier PC Android Deuxième écran - Mode Afficher Applications Android Lancer l\'application @@ -2312,6 +2298,17 @@ Somme de contrôle incorrecte ; le téléchargement a été supprimé Une session a démarré pendant le téléchargement ; arrêtez-la avant d\'installer des outils de compatibilité Installation de %1$s + Versions expérimentales + Installer depuis un fichier + L’archive contient un lien ou chemin dangereux + Archive non prise en charge ou invalide + Espace libre insuffisant pour cette version de Proton + Extraction de Proton (quelques minutes) + Échec de l\'extraction (tar %1$d) + L\'archive ne contient aucune version de Proton + Impossible de placer la version de Proton + Impossible de supprimer entièrement %1$s + Proton expérimental installé. Sélectionnez-le dans Steam → Propriétés → Compatibilité. Échec de l\'installation de %1$s (code %2$d) Impossible d\'installer %1$s Récupération du pack droiddeck-esync @@ -3353,10 +3350,19 @@ Préfixe partagé de Steam Steam y exécute ses propres utilitaires Windows Le supprime (%1$s). Steam en crée un nouveau la prochaine fois qu\'il en a besoin. + 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. + %1$s peuvent être libérés + Caches de Linux et de Steam + Anciens fichiers temporaires, paquets téléchargés et cache web de Steam + Anciens fichiers temporaires + Paquets téléchargés + Cache web de Steam + Téléchargements Steam endommagés + Recréés au besoin + Vider Une app de boutique et les jeux qui tournent avec elle Utilisé par %1$s Jeu hors Steam %1$s - Associé à aucun jeu, il est donc conservé Supprimer la sélection · %1$s Désinstaller la sélection · %1$s Préfixes Wine @@ -4104,4 +4110,18 @@ Entier Ajuster Anticrénelage - \ No newline at end of file + Personnalisé + Choisissez séparément chaque couleur de l’interface. + Arrière-plan + Panneaux + Panneaux surélevés + Séparateurs + Bordures + Texte principal + Texte secondaire + Boutons et accent principal + Texte des boutons + Mises en évidence + Succès + Erreur + diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 5c3801056..7a32cca83 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -22,7 +22,6 @@ SD कार्ड, USB ड्राइव या SSD से Steam लाइब्रेरी जोड़ें, और DroidDeck गेम को आपकी लाइब्रेरी में एक साथ रखता है। स्टोर से आप Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io और Game Jolt में साइन इन कर सकते हैं, फिर DroidDeck से उनके गेम इंस्टॉल और अपडेट कर सकते हैं। FEX, DXVK और VKD3D-Proton जैसे कॉम्पोनेंट खुद अपडेट होते हैं, और डिफ़ॉल्ट Proton Experimental ARM64 है, या वह बिल्ड इंस्टॉल होने पर Proton 11.0 ARM64। - गेम चलते समय Steam को कंप्रेस करें कम RAM वाले डिवाइस पर RAM खाली करता है। सत्र मेनू खोलने के लिए दाएँ किनारे से अंदर की ओर स्वाइप करें: टचपैड मोड, पीसी कीबोर्ड, लो लेटेंसी मोड, गेम प्रोफ़ाइल और बहुत कुछ। गेम धीमा चल रहा है? Quick Access में फ़्रेम रेट सीमित करें, फिर गेम के कॉम्पोनेंट में कोई दूसरा Proton वर्शन या FEX प्रीसेट आज़माएँ। गेम की आवाज़ में खरखराहट है या आवाज़ नहीं आ रही? Steam सेटिंग में ऑडियो के अंतर्गत गेम के लिए DirectAudio टॉगल आज़माएँ। @@ -621,20 +620,8 @@ gamescope: रीयलटाइम GPU क्यू कम्पोज़िटर के GPU काम को प्राथमिकता देता है। गेम की कुछ कीमत पर फ़्रेम पेसिंग को स्मूथ कर सकता है। GPU - मेमोरी बंद - ड्राइवर डिफ़ॉल्ट - गेम चलते समय Steam को कंप्रेस करें - गेम की निष्क्रिय मेमोरी को संपीड़ित करें - RAM कम होने पर गेम की निष्क्रिय मेमोरी को पेज करता है। अगर गेम लगभग हर आधे मिनट में कुछ सेकंड के लिए रुकते हैं, तो इसे बंद करें। अगली बार सत्र शुरू होने पर लागू होता है। - गेम शुरू होने के 20 s बाद, Steam क्लाइंट को zRAM में कंप्रेस किया जाता है ताकि गेम को ज़्यादा मेमोरी मिले, और गेम बंद होने पर वापस पढ़ा जाता है। अगर गेम शुरू होने के कुछ देर बाद सेशन बंद हो जाता है तो इसे बंद करें। ऊपर दी गई RAM सीमा पार होने पर भी Steam कंप्रेस होता है। - RAM सीमा - Steam क्लाइंट चलते समय लागू होती है, Steam मोड में या डेस्कटॉप से। जब सेशन इससे ज़्यादा इस्तेमाल करता है, तो Steam और फिर सेशन की दूसरी समर्थित प्रोसेस zRAM में कंप्रेस होती हैं। यह सॉफ़्ट सीमा है: कुछ बंद नहीं होता, लेकिन पेज वापस आते समय गेम अटक सकते हैं। - zRAM स्वैप चाहिए, जो इस डिवाइस में नहीं है। - VRAM सीमा - मेमोरी का उपयोग कम करने के लिए Direct3D 9 से 12 गेम को यह वीडियो मेमोरी बजट बताता है। गेम इसे पार कर सकते हैं; यह GPU पेजिंग नहीं जोड़ता और मेमोरी खत्म होने से क्रैश रोकने की गारंटी नहीं देता। अगले सत्र से लागू होगा। GPU को उसकी टॉप क्लॉक पर बनाए रखें - सिर्फ़ Adreno के लिए। कम हिचकोले, लेकिन ज़्यादा बैटरी खर्च और गर्मी। सेशन फ़िक्स Turnip: sysmem रेंडरिंग Steam क्लाइंट और गेम पर लागू। Adreno 710/720/722 पर ज़रूरी। @@ -811,7 +798,6 @@ पीसी कीबोर्ड Android दूसरी स्क्रीन - मोड दिखाता है Android ऐप ऐप लॉन्च करें @@ -2287,6 +2273,17 @@ चेकसम मेल नहीं खाया; डाउनलोड हटा दिया गया डाउनलोड के दौरान एक सेशन शुरू हुआ; कम्पैटिबिलिटी टूल इंस्टॉल करने से पहले इसे बंद करें %1$s इंस्टॉल हो रहा है + प्रायोगिक बिल्ड + फ़ाइल से इंस्टॉल करें + आर्काइव में असुरक्षित लिंक या पथ है + असमर्थित या अमान्य आर्काइव + इस Proton बिल्ड के लिए पर्याप्त खाली जगह नहीं है + Proton अनपैक हो रहा है (कुछ मिनट) + अनपैक करना विफल रहा (tar %1$d) + आर्काइव में कोई Proton बिल्ड नहीं है + Proton बिल्ड को रखा नहीं जा सका + %1$s को पूरी तरह हटाया नहीं जा सका + प्रायोगिक Proton इंस्टॉल हो गया। इसे Steam → गुण → संगतता में चुनें। %1$s इंस्टॉलेशन विफल रहा (exit %2$d) %1$s इंस्टॉल नहीं हो सका droiddeck-esync पैक लिया जा रहा है @@ -3317,10 +3314,19 @@ Steam का साझा प्रीफ़िक्स Steam यहाँ अपने Windows हेल्पर चलाता है इसे डिलीट करता है (%1$s)। अगली बार ज़रूरत पड़ने पर Steam नया बना लेता है। + इस स्टोर ऐप का Wine प्रीफ़िक्स और शेडर कैश (%1$s) हटाता है, साथ में इसका साइन-इन और सिर्फ़ वहीं रखे सेव भी। इसमें चलने वाले गेम को नया प्रीफ़िक्स मिलता है, और ऐप को फिर से सेट अप करना पड़ सकता है। क्लाउड सेव आपके खाते में रहते हैं। + %1$s साफ़ किया जा सकता है + Linux और Steam कैश + पुरानी अस्थायी फ़ाइलें, डाउनलोड किए गए पैकेज और Steam का वेब कैश + पुरानी अस्थायी फ़ाइलें + डाउनलोड किए गए पैकेज + Steam वेब कैश + खराब Steam डाउनलोड + ज़रूरत पड़ने पर फिर से बनते हैं + साफ़ करें एक स्टोर ऐप और उसके साथ चलने वाले गेम %1$s द्वारा इस्तेमाल गैर-Steam गेम %1$s - किसी गेम से मेल नहीं खाता, इसलिए रखा जाता है चुने गए हटाएँ · %1$s चुने गए अनइंस्टॉल करें · %1$s Wine प्रीफ़िक्स @@ -4065,4 +4071,18 @@ पूर्णांक फ़िट एंटी-अलियासिंग - \ No newline at end of file + कस्टम + इंटरफ़ेस का हर रंग अलग-अलग चुनें। + पृष्ठभूमि + पैनल + उभरे हुए पैनल + विभाजक + किनारे + मुख्य टेक्स्ट + द्वितीयक टेक्स्ट + बटन और मुख्य हाइलाइट + बटन का टेक्स्ट + हाइलाइट + सफलता + त्रुटि + diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index c7699900a..466f52229 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -22,7 +22,6 @@ 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. 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. 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. - 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. 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. 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. 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. @@ -621,20 +620,8 @@ gamescope: valós idejű GPU-sor 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. GPU - Memória Ki - Illesztőprogram alapértéke - A Steam tömörítése játék közben - Játék inaktív memóriájának tömörítése - 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. - 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. - RAM-korlát - 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. - zRAM swap szükséges, amely ezen az eszközön nincs. - VRAM-korlát - 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. A GPU legmagasabb órajelen tartása - Csak Adreno. Kevesebb akadás, nagyobb akkumulátorhasználat és hőtermelés. Munkamenet-javítások Turnip: sysmem renderelés A Steam kliensre és a játékokra vonatkozik. Adreno 710/720/722-n szükséges. @@ -811,7 +798,6 @@ PC-billentyűzet Android Második képernyő - Mód Megjelenít Android-alkalmazások Alkalmazás indítása @@ -2287,6 +2273,17 @@ Az ellenőrzőösszeg nem egyezik; a letöltés törlésre került Egy munkamenet elindult a letöltés közben; állítsa le a kompatibilitási eszközök telepítése előtt %1$s telepítése + Kísérleti buildek + Telepítés fájlból + Az archívum nem biztonságos hivatkozást vagy útvonalat tartalmaz + Nem támogatott vagy érvénytelen archívum + Nincs elég szabad hely ehhez a Proton-buildhez + A Proton kibontása (néhány perc) + A kibontás nem sikerült (tar %1$d) + Az archívum nem tartalmaz Proton-buildet + Nem sikerült elhelyezni a Proton-buildet + Nem sikerült teljesen eltávolítani: %1$s + A kísérleti Proton telepítve. Válaszd ki a Steam → Tulajdonságok → Kompatibilitás menüben. A %1$s telepítése sikertelen (kilépési kód: %2$d) Nem sikerült telepíteni a %1$s-t droiddeck-esync csomag letöltése @@ -3317,10 +3314,19 @@ A Steam megosztott prefixe A Steam itt futtatja saját Windows-segédprogramjait Törli (%1$s). A Steam újat hoz létre, amikor legközelebb szüksége lesz rá. + 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. + %1$s üríthető + Linux- és Steam-gyorsítótárak + Régi ideiglenes fájlok, letöltött csomagok és a Steam webes gyorsítótára + Régi ideiglenes fájlok + Letöltött csomagok + Steam webes gyorsítótár + Sérült Steam-letöltések + Szükség esetén újra létrejön + Ürítés Egy áruházalkalmazás és a vele futó játékok Használja: %1$s Nem Steam-es játék: %1$s - Nem tartozik játékhoz, ezért megmarad Kijelöltek eltávolítása · %1$s Kijelöltek eltávolítása · %1$s Wine-prefixek @@ -4065,4 +4071,18 @@ Egész szám Igazítás Élsimítás - \ No newline at end of file + Egyéni + Válaszd ki külön a felület minden színét. + Háttér + Panelek + Kiemelt panelek + Elválasztók + Szegélyek + Fő szöveg + Másodlagos szöveg + Gombok és fő kiemelés + Gombok szövege + Kiemelések + Siker + Hiba + diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 03ce7b7eb..ecaf67f00 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -22,7 +22,6 @@ Tambahkan pustaka Steam dari kartu SD, drive USB, atau SSD, dan DroidDeck menyatukan semua gim di Pustaka kamu. 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. 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. - Kompres Steam saat gim berjalan membebaskan RAM pada perangkat yang kekurangan memori. Geser masuk dari tepi kanan untuk membuka menu sesi: mode touchpad, Keyboard PC, Mode latensi rendah, Profil gim, dan lainnya. Gim berjalan lambat? Batasi frame rate di Akses cepat, lalu coba versi Proton lain atau preset FEX lain di komponen gim. Audio gim pecah atau tidak ada? Coba opsi DirectAudio untuk gim di pengaturan Steam pada bagian Audio. @@ -619,20 +618,8 @@ gamescope: antrean GPU realtime Memprioritaskan kerja GPU compositor. Dapat menghaluskan pacing frame dengan sedikit mengorbankan gim. GPU - Memori Nonaktif - Default driver - Kompres Steam saat gim berjalan - Kompres memori game yang tidak aktif - 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. - 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. - Batas RAM - 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. - Memerlukan swap zRAM, yang tidak dimiliki perangkat ini. - Batas VRAM - 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. Pertahankan GPU pada clock tertingginya - Hanya Adreno. Lebih sedikit tersendat, lebih banyak penggunaan baterai dan panas. Perbaikan sesi Turnip: rendering sysmem Berlaku untuk klien Steam dan gim. Diperlukan pada Adreno 710/720/722. @@ -809,7 +796,6 @@ Keyboard PC Android Layar kedua - Mode Menampilkan Aplikasi Android Luncurkan aplikasi @@ -2262,6 +2248,17 @@ Checksum tidak cocok; unduhan telah dihapus Sesi dimulai saat pengunduhan berlangsung; hentikan sesi tersebut sebelum menginstal alat kompatibilitas Menginstal %1$s + Build eksperimental + Instal dari file + Arsip berisi tautan atau jalur yang tidak aman + Arsip tidak didukung atau tidak valid + Ruang kosong tidak cukup untuk build Proton ini + Membuka paket Proton (beberapa menit) + Gagal membuka paket (tar %1$d) + Arsip tidak berisi build Proton + Tidak dapat menempatkan build Proton + Tidak dapat menghapus %1$s sepenuhnya + Proton eksperimental terinstal. Pilih di Steam → Properti → Kompatibilitas. Instalasi %1$s gagal (keluar %2$d) Tidak dapat menginstal %1$s Mengambil paket droiddeck-esync @@ -3288,10 +3285,19 @@ Prefix Steam bersama Steam menjalankan helper Windows-nya sendiri di sini Menghapusnya (%1$s). Steam membuat yang baru saat membutuhkannya lagi. + 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. + %1$s dapat dibersihkan + Cache Linux dan Steam + File sementara lama, paket yang diunduh, dan cache web Steam + File sementara lama + Paket yang diunduh + Cache web Steam + Unduhan Steam yang rusak + Dibuat lagi saat diperlukan + Bersihkan Aplikasi toko dan gim yang berjalan dengannya Dipakai oleh %1$s Gim non-Steam %1$s - Tidak cocok dengan gim mana pun, jadi tetap disimpan Hapus yang dipilih · %1$s Hapus instalasi yang dipilih · %1$s Prefix Wine @@ -4035,4 +4041,18 @@ Bilangan bulat Sesuaikan Anti-aliasing - \ No newline at end of file + Kustom + Pilih setiap warna antarmuka secara terpisah. + Latar belakang + Panel + Panel terangkat + Pemisah + Batas + Teks utama + Teks sekunder + Tombol dan aksen utama + Teks tombol + Sorotan + Berhasil + Kesalahan + diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 23ca6a0a1..3eb592f9d 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -22,7 +22,6 @@ Aggiungi librerie Steam da una scheda SD, un\'unità USB o un SSD, e DroidDeck tiene i giochi insieme nella tua Libreria. 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. 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. - Comprimi Steam durante il gioco libera RAM sui dispositivi che ne hanno poca. 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. 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. Audio del gioco che gracchia o manca? Prova l\'opzione DirectAudio per i giochi nelle impostazioni di Steam, sotto Audio. @@ -623,20 +622,8 @@ gamescope: coda GPU in tempo reale Dà priorità al lavoro GPU del compositor. Può rendere più regolare il frame pacing, a scapito dei giochi. GPU - Memoria Disattivo - Predefinito del driver - Comprimi Steam durante il gioco - Comprimi la memoria inattiva del gioco - 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. - 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. - Limite RAM - 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. - Richiede lo swap zRAM, che questo dispositivo non ha. - Limite VRAM - 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. Mantieni la GPU alla frequenza massima - Solo Adreno. Meno scatti, più consumo di batteria e più calore. Correzioni della sessione Turnip: rendering sysmem Si applica al client Steam e ai giochi. Necessario su Adreno 710/720/722. @@ -813,7 +800,6 @@ Tastiera PC Android Secondo schermo - Modalità Mostra App Android Avvia un\'app @@ -2304,6 +2290,17 @@ Checksum non corrispondente; il download è stato eliminato È stata avviata una sessione durante il download; interrompila prima di installare strumenti di compatibilità Installazione di %1$s + Build sperimentali + Installa da file + L\'archivio contiene un collegamento o percorso non sicuro + Archivio non supportato o non valido + Spazio libero insufficiente per questa build di Proton + Estrazione di Proton (qualche minuto) + Estrazione non riuscita (tar %1$d) + L\'archivio non contiene alcuna build di Proton + Impossibile posizionare la build di Proton + Impossibile rimuovere completamente %1$s + Proton sperimentale installato. Selezionalo in Steam → Proprietà → Compatibilità. Installazione di %1$s non riuscita (uscita %2$d) Impossibile installare %1$s Recupero del pacchetto droiddeck-esync @@ -3353,10 +3350,19 @@ Prefisso condiviso di Steam Steam esegue qui i propri strumenti Windows Lo elimina (%1$s). Steam ne crea uno nuovo la prossima volta che serve. + 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. + Si possono liberare %1$s + Cache di Linux e Steam + Vecchi file temporanei, pacchetti scaricati e cache web di Steam + Vecchi file temporanei + Pacchetti scaricati + Cache web di Steam + Download di Steam danneggiati + Ricreati quando servono + Svuota Un\'app di uno store e i giochi che girano con essa Usato da %1$s Gioco non Steam %1$s - Non associato a nessun gioco, quindi viene conservato Rimuovi selezionati · %1$s Disinstalla selezionati · %1$s Prefissi Wine @@ -4104,4 +4110,18 @@ Intero Adatta Antialiasing - \ No newline at end of file + Personalizzato + Scegli separatamente ogni colore dell’interfaccia. + Sfondo + Pannelli + Pannelli rialzati + Separatori + Bordi + Testo principale + Testo secondario + Pulsanti e colore principale + Testo dei pulsanti + Evidenziazioni + Successo + Errore + diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 266d3c6fa..59a0a7559 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -22,7 +22,6 @@ SDカード、USBドライブ、SSDからSteamライブラリを追加でき、DroidDeckはゲームをライブラリにまとめて表示します。 ストアでは、Epic Games、GOG、Xbox、EA、Battle.net、Ubisoft Connect、Amazon Games、itch.io、Game Joltにサインインして、DroidDeckからそれらのゲームをインストール・更新できます。 FEX、DXVK、VKD3D-Protonなどのコンポーネントは自動で更新されます。既定はProton Experimental ARM64で、Proton 11.0 ARM64がインストールされている場合はそちらになります。 - ゲーム実行中はSteamを圧縮すると、メモリが少ない端末でRAMを確保できます。 画面の右端から内側にスワイプするとセッションメニューが開きます。タッチパッドモード、PCキーボード、低遅延モード、ゲームプロファイルなどがあります。 ゲームが重い場合は、クイックアクセスでフレームレートを制限し、ゲームのコンポーネントで別のProtonバージョンやFEXプリセットを試してください。 ゲームの音が割れる、または出ない場合は、Steam設定のオーディオにある「ゲームでDirectAudioを使用」を試してください。 @@ -619,20 +618,8 @@ gamescope:リアルタイムGPUキュー コンポジタのGPU作業の優先度を上げます。フレームタイムの安定性が向上する場合がありますが、ゲームのパフォーマンスの一部を消費します。 GPU - メモリ オフ - ドライバーのデフォルト - ゲーム実行中はSteamを圧縮 - ゲームのアイドルメモリを圧縮 - RAMが少ないときにゲームのアイドルメモリを圧縮します。ゲームが30秒ごとに数秒止まる場合はオフにしてください。次回のセッション開始時に適用されます。 - ゲーム開始の20秒後、SteamクライアントをzRAMに圧縮してゲームに使えるメモリを増やし、ゲーム終了時に読み戻します。ゲーム開始直後にセッションが終了する場合はオフにしてください。上のRAM上限を設定している場合は、セッションが上限を超えるとSteamは引き続き圧縮されます。 - RAM上限 - Steamモードでもデスクトップからでも、Steamクライアントの実行中に適用されます。セッションの使用量がこの値を超えると、Steam、次にセッション内の対応する他のプロセスがzRAMに圧縮されます。ソフトな上限のため何も終了されませんが、ページの読み戻し中にゲームがカクつくことがあります。 - zRAMスワップが必要ですが、このデバイスにはありません。 - VRAM上限 - Direct3D 9~12のゲームにこのビデオメモリ予算を通知し、メモリ使用量の削減を促します。ゲームは予算を超える場合があります。GPUのページングを追加するものではなく、メモリ不足によるクラッシュの防止は保証されません。次のセッションから有効になります。 GPUを最高クロックに保つ - Adrenoのみ。スタッターは減りますが、消費電力と発熱が増えます。 セッション修正 Turnip:sysmemレンダリング Steamクライアントとゲームに適用。Adreno 710/720/722では必須です。 @@ -809,7 +796,6 @@ PCキーボード Android セカンドスクリーン - モード 表示 Androidアプリ アプリを起動 @@ -2262,6 +2248,17 @@ チェックサムが一致しないため、ダウンロードを削除しました ダウンロード中にセッションが開始されました。停止してから互換性ツールをインストールしてください %1$sをインストール中 + 試験版ビルド + ファイルからインストール + アーカイブに安全でないリンクまたはパスが含まれています + 未対応または無効なアーカイブ + このProtonビルド用の空き容量が足りません + Protonを展開中(数分かかります) + 展開に失敗しました(tar %1$d) + アーカイブにProtonビルドが含まれていません + Protonビルドを配置できませんでした + %1$sを完全に削除できませんでした + 試験版Protonをインストールしました。Steam → プロパティ → 互換性 で選択してください。 %1$sのインストールに失敗しました(終了コード %2$d) %1$sをインストールできませんでした droiddeck-esyncパックを取得中 @@ -3288,10 +3285,19 @@ Steam の共有プレフィックス Steam が独自の Windows ヘルパーをここで実行します 削除します(%1$s)。次に必要になったとき Steam が新しく作成します。 + このストアアプリの Wine プレフィックスとシェーダーキャッシュ(%1$s)を、サインイン情報やそこにしかないセーブデータごと削除します。中で動くゲームは新しいプレフィックスで始まり、アプリの再セットアップが必要になる場合があります。クラウドのセーブデータはアカウントに残ります。 + %1$s を消去できます + Linux と Steam のキャッシュ + 古い一時ファイル、ダウンロード済みパッケージ、Steam のウェブキャッシュ + 古い一時ファイル + ダウンロード済みパッケージ + Steam のウェブキャッシュ + 破損した Steam ダウンロード + 必要なときに再作成されます + 消去 ストアアプリとそれで動くゲーム %1$s が使用 Steam 以外のゲーム %1$s - どのゲームにも一致しないため保持されます 選択項目を削除 · %1$s 選択項目をアンインストール · %1$s Wineプレフィックス @@ -4035,4 +4041,18 @@ 整数 画面に合わせる アンチエイリアス - \ No newline at end of file + カスタム + インターフェースの各色を個別に選択します。 + 背景 + パネル + 浮き上がったパネル + 区切り線 + 境界線 + メインテキスト + サブテキスト + ボタンとメインアクセント + ボタンのテキスト + 強調表示 + 成功 + エラー + diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 63db111b0..192985e19 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -22,7 +22,6 @@ SD 카드, USB 드라이브, SSD에서 Steam 라이브러리를 추가할 수 있으며, DroidDeck이 게임을 라이브러리에 함께 모아 줍니다. 스토어에서는 Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io, Game Jolt에 로그인하고 DroidDeck에서 해당 게임을 설치하고 업데이트할 수 있습니다. FEX, DXVK, VKD3D-Proton 같은 구성 요소는 스스로 업데이트되며, 기본값은 Proton Experimental ARM64이고 Proton 11.0 ARM64 빌드가 설치되면 그쪽이 기본값이 됩니다. - 게임 실행 중 Steam 압축은 메모리가 부족한 기기에서 RAM을 확보해 줍니다. 오른쪽 가장자리에서 안쪽으로 스와이프하면 세션 메뉴가 열립니다. 터치패드 모드, PC 키보드, 저지연 모드, 게임 프로필 등이 있습니다. 게임이 느린가요? 빠른 액세스에서 프레임 레이트를 제한한 다음, 게임의 구성 요소에서 다른 Proton 버전이나 FEX 프리셋을 시도해 보세요. 게임 소리가 지직거리거나 나오지 않나요? Steam 설정의 오디오에서 게임에서 DirectAudio 사용 토글을 시도해 보세요. @@ -619,20 +618,8 @@ gamescope: 실시간 GPU 큐 컴포지터 GPU 작업의 우선순위를 높입니다. 프레임 타임 안정성을 개선할 수 있지만 게임 성능의 일부를 소모합니다. GPU - 메모리 끄기 - 드라이버 기본값 - 게임 실행 중 Steam 압축 - 유휴 게임 메모리 압축 - RAM이 부족할 때 유휴 게임 메모리를 압축합니다. 게임이 약 30초마다 몇 초씩 멈추면 끄세요. 다음 세션을 시작할 때 적용됩니다. - 게임이 시작되고 20초 후 Steam 클라이언트를 zRAM으로 압축해 게임에 더 많은 메모리를 남기고, 게임이 종료되면 다시 읽어 들입니다. 게임 시작 직후 세션이 종료되면 이 옵션을 끄세요. 위의 RAM 제한을 설정하면 세션이 이를 초과할 때 여전히 Steam을 압축합니다. - RAM 제한 - Steam 모드나 데스크톱에서 Steam 클라이언트가 실행되는 동안 적용됩니다. 세션이 이 값보다 많이 사용하면 Steam과 세션의 다른 지원 프로세스를 차례로 zRAM으로 압축합니다. 소프트 제한이므로 종료되는 것은 없지만, 페이지를 다시 읽어 들이는 동안 게임이 끊길 수 있습니다. - zRAM 스왑이 필요하지만 이 기기에는 없습니다. - VRAM 제한 - 메모리 사용량을 줄이도록 Direct3D 9~12 게임에 이 비디오 메모리 예산을 알립니다. 게임은 예산을 초과할 수 있으며, GPU 페이징을 추가하거나 메모리 부족으로 인한 충돌 방지를 보장하지 않습니다. 다음 세션부터 적용됩니다. GPU를 최고 클럭으로 유지 - Adreno에만 해당됩니다. 끊김이 줄어들지만 전력 소모와 발열이 증가합니다. 세션 수정 Turnip: sysmem 렌더링 Steam 클라이언트와 게임에 적용됩니다. Adreno 710/720/722에 필수입니다. @@ -809,7 +796,6 @@ PC 키보드 Android 보조 화면 - 모드 표시 Android 앱 앱 실행 @@ -2262,6 +2248,17 @@ 체크섬이 일치하지 않아 다운로드를 삭제했습니다 다운로드 중에 세션이 시작되었습니다. 호환성 도구를 설치하기 전에 세션을 중지하세요 %1$s 설치 중 + 실험용 빌드 + 파일에서 설치 + 압축 파일에 안전하지 않은 링크 또는 경로가 포함되어 있습니다 + 지원되지 않거나 잘못된 압축 파일 + 이 Proton 빌드를 설치할 여유 공간이 부족합니다 + Proton 풀는 중 (몇 분 소요) + 압축 풀기 실패 (tar %1$d) + 아카이브에 Proton 빌드가 없습니다 + Proton 빌드를 배치할 수 없습니다 + %1$s을(를) 완전히 제거할 수 없습니다 + 실험용 Proton이 설치되었습니다. Steam → 속성 → 호환성에서 선택하세요. %1$s 설치 실패(종료 코드 %2$d) %1$s을(를) 설치할 수 없습니다 droiddeck-esync 팩 받는 중 @@ -3288,10 +3285,19 @@ Steam의 공유 프리픽스 Steam이 자체 Windows 도우미를 여기서 실행합니다 삭제합니다(%1$s). 다음에 필요할 때 Steam이 새로 만듭니다. + 이 스토어 앱의 Wine 접두사와 셰이더 캐시(%1$s)를 로그인 정보 및 그곳에만 있는 저장 데이터와 함께 삭제합니다. 그 안에서 실행되는 게임은 새 접두사를 받으며, 앱을 다시 설정해야 할 수 있습니다. 클라우드 저장 데이터는 계정에 남습니다. + %1$s 정리 가능 + Linux 및 Steam 캐시 + 오래된 임시 파일, 다운로드한 패키지, Steam 웹 캐시 + 오래된 임시 파일 + 다운로드한 패키지 + Steam 웹 캐시 + 손상된 Steam 다운로드 + 필요할 때 다시 만들어집니다 + 지우기 스토어 앱과 이 앱으로 실행되는 게임 사용 중: %1$s Steam이 아닌 게임 %1$s - 일치하는 게임이 없어 유지됩니다 선택 항목 제거 · %1$s 선택 항목 제거 · %1$s Wine 프리픽스 @@ -4035,4 +4041,18 @@ 정수 화면에 맞춤 안티앨리어싱 - \ No newline at end of file + 사용자 지정 + 인터페이스의 각 색상을 개별적으로 선택하세요. + 배경 + 패널 + 돌출 패널 + 구분선 + 테두리 + 기본 텍스트 + 보조 텍스트 + 버튼 및 기본 강조색 + 버튼 텍스트 + 강조 표시 + 성공 + 오류 + diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 90bcde36e..b13c7c7bb 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -22,7 +22,6 @@ Tambah pustaka Steam daripada kad SD, pemacu USB atau SSD, dan DroidDeck menyatukan permainan dalam Pustaka anda. Kedai membolehkan anda log masuk ke Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io dan Game Jolt, kemudian memasang dan mengemas kini permainan mereka daripada DroidDeck. Komponen seperti FEX, DXVK dan VKD3D-Proton mengemas kini sendiri, dan Proton Experimental ARM64 ialah lalai, atau Proton 11.0 ARM64 sebaik sahaja binaan itu dipasang. - Mampatkan Steam semasa permainan berjalan membebaskan RAM pada peranti yang kekurangan memori. Leret masuk dari tepi kanan untuk membuka menu sesi: mod pad sentuh, Papan kekunci PC, Mod kependaman rendah, profil permainan dan banyak lagi. Permainan berjalan perlahan? Hadkan kadar bingkai dalam Akses pantas, kemudian cuba versi Proton atau pratetap FEX lain dalam komponen permainan. Bunyi permainan berderak atau tiada? Cuba togol DirectAudio untuk permainan dalam tetapan Steam di bawah Audio. @@ -619,20 +618,8 @@ gamescope: baris gilir GPU masa nyata Mengutamakan kerja GPU compositor. Boleh melicinkan rentak bingkai dengan sedikit kos kepada permainan. GPU - Memori Mati - Lalai pemacu - Mampatkan Steam semasa permainan berjalan - Mampatkan memori permainan terbiar - Mampatkan memori permainan terbiar apabila RAM rendah. Matikan jika permainan membeku beberapa saat lebih kurang setiap setengah minit. Berkuat kuasa apabila sesi dimulakan seterusnya. - 20 s selepas permainan bermula, klien Steam dimampatkan ke dalam zRAM untuk memberi permainan lebih banyak memori, dan dibaca semula apabila permainan ditutup. Matikan ini jika sesi tertutup sejurus selepas permainan bermula. Had RAM di atas masih memampatkan Steam apabila sesi melebihinya. - Had RAM - Berkuat kuasa semasa klien Steam berjalan, dalam mod Steam atau dari desktop. Apabila sesi menggunakan lebih daripada ini, Steam dan kemudian proses lain sesi yang disokong dimampatkan ke dalam zRAM. Had lembut: tiada apa yang ditutup, tetapi permainan mungkin tersekat-sekat semasa halaman dibaca semula. - Memerlukan swap zRAM, yang tiada pada peranti ini. - Had VRAM - Melaporkan bajet memori video ini kepada permainan Direct3D 9 hingga 12 untuk mengurangkan penggunaan memori. Permainan boleh melebihinya; ini tidak menambah paging GPU atau menjamin perlindungan daripada ranap akibat kehabisan memori. Berkuat kuasa pada sesi seterusnya. Kekalkan GPU pada kelajuan tertinggi - Adreno sahaja. Kurang tersekat-sekat, lebih penggunaan bateri dan haba. Pembetulan sesi Turnip: rendering sysmem Terpakai pada klien Steam dan permainan. Diperlukan pada Adreno 710/720/722. @@ -809,7 +796,6 @@ Papan kekunci PC Android Skrin kedua - Mod Memaparkan Apl Android Lancarkan apl @@ -2262,6 +2248,17 @@ Checksum tidak sepadan; muat turun telah dipadam Sesi dimulakan semasa muat turun; hentikan dahulu sebelum memasang alat keserasian Memasang %1$s + Binaan eksperimen + Pasang daripada fail + Arkib mengandungi pautan atau laluan tidak selamat + Arkib tidak disokong atau tidak sah + Ruang kosong tidak mencukupi untuk binaan Proton ini + Membuka pakej Proton (beberapa minit) + Gagal membuka pakej (tar %1$d) + Arkib tidak mengandungi binaan Proton + Tidak dapat meletakkan binaan Proton + Tidak dapat mengalih keluar %1$s sepenuhnya + Proton eksperimen telah dipasang. Pilihnya di Steam → Sifat → Keserasian. Pemasangan %1$s gagal (keluar %2$d) Tidak dapat memasang %1$s Mengambil pek droiddeck-esync @@ -3288,10 +3285,19 @@ Awalan Steam dikongsi Steam menjalankan pembantu Windowsnya sendiri di sini Memadamnya (%1$s). Steam mencipta yang baharu apabila memerlukannya lagi. + Memadam prefiks Wine dan cache shader apl kedai ini (%1$s), bersama log masuk dan simpanan yang hanya ada di situ. Permainan yang berjalan di dalamnya mendapat prefiks baharu, dan anda mungkin perlu menyediakan apl itu semula. Simpanan awan kekal dalam akaun anda. + %1$s boleh dikosongkan + Cache Linux dan Steam + Fail sementara lama, pakej yang dimuat turun dan cache web Steam + Fail sementara lama + Pakej yang dimuat turun + Cache web Steam + Muat turun Steam yang rosak + Dibuat semula apabila perlu + Kosongkan Aplikasi kedai dan permainan yang berjalan dengannya Digunakan oleh %1$s Permainan bukan Steam %1$s - Tidak sepadan dengan mana-mana permainan, jadi ia disimpan Alih keluar yang dipilih · %1$s Nyahpasang yang dipilih · %1$s Prefix Wine @@ -4035,4 +4041,18 @@ Integer Muat Anti-aliasing - \ No newline at end of file + Tersuai + Pilih setiap warna antara muka secara berasingan. + Latar belakang + Panel + Panel timbul + Pemisah + Sempadan + Teks utama + Teks sekunder + Butang dan aksen utama + Teks butang + Sorotan + Berjaya + Ralat + diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index c10de04c8..8715fddf8 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -22,7 +22,6 @@ Legg til Steam-biblioteker fra et SD-kort, en USB-stasjon eller en SSD, så holder DroidDeck spillene samlet i Biblioteket ditt. Butikker lar deg logge inn på Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io og Game Jolt, og deretter installere og oppdatere spillene deres fra DroidDeck. Komponenter som FEX, DXVK og VKD3D-Proton oppdaterer seg selv, og Proton Experimental ARM64 er standard, eller Proton 11.0 ARM64 når den versjonen er installert. - Komprimer Steam mens et spill kjører frigjør minne på enheter som har lite. Sveip inn fra høyre kant for å åpne øktmenyen: styreflatemodus, PC-tastatur, modus for lav forsinkelse, spillprofil og mer. Kjører spillet tregt? Begrens bildefrekvensen i Hurtigmeny, og prøv deretter en annen Proton-versjon eller FEX-forhåndsinnstilling i spillets komponenter. Knitrende eller manglende spillyd? Prøv bryteren DirectAudio for spill i Steam-innstillingene under Lyd. @@ -621,20 +620,8 @@ gamescope: realtime GPU-kø Prioriterer kompositørens GPU-arbeid. Kan jevne ut bildetakten, på bekostning av spillene. GPU - Minne Av - Driverstandard - Komprimer Steam mens et spill kjører - Komprimer inaktivt spillminne - Komprimerer inaktivt spillminne når RAM er lav. Slå av hvis spill fryser i noen sekunder omtrent hvert halve minutt. Trer i kraft neste gang økten starter. - 20 s etter at et spill starter, komprimeres Steam-klienten til zRAM for å gi spillet mer minne, og leses inn igjen når spillet lukkes. Slå av hvis sesjonen lukkes kort tid etter at spill starter. En RAM-grense ovenfor komprimerer fortsatt Steam når sesjonen går over den. - RAM-grense - Gjelder mens Steam-klienten kjører, i Steam-modus eller fra skrivebordet. Når sesjonen bruker mer enn dette, komprimeres Steam og deretter sesjonens andre støttede prosesser til zRAM. En myk grense: ingenting lukkes, men spill kan hakke mens sider hentes tilbake. - Krever zRAM-swap, som denne enheten ikke har. - VRAM-grense - Rapporterer dette videominnebudsjettet til Direct3D 9 til 12-spill for å redusere minnebruken. Spill kan overskride det; dette legger ikke til GPU-sideveksling og garanterer ikke beskyttelse mot krasj ved minnemangel. Gjelder fra neste økt. Hold GPU-en på toppfrekvens - Bare Adreno. Færre hikk, mer batteribruk og varme. Sesjonsfikser Turnip: sysmem-rendering Gjelder Steam-klienten og spill. Påkrevd på Adreno 710/720/722. @@ -811,7 +798,6 @@ PC-tastatur Android Andre skjerm - Modus Viser Android-apper Start en app @@ -2287,6 +2273,17 @@ Sjekksummen stemmer ikke; nedlastingen ble slettet En sesjon startet under nedlastingen; avslutt den før du installerer kompatibilitetsverktøy Installerer %1$s + Eksperimentelle bygg + Installer fra fil + Arkivet inneholder en utrygg lenke eller bane + Arkivet støttes ikke eller er ugyldig + Ikke nok ledig plass til dette Proton-bygget + Pakker ut Proton (noen få minutter) + Utpakking mislyktes (tar %1$d) + Arkivet inneholder ingen Proton-bygg + Kunne ikke plassere Proton-bygget + Kunne ikke fjerne %1$s helt + Eksperimentell Proton er installert. Velg den i Steam → Egenskaper → Kompatibilitet. Installasjonen av %1$s mislyktes (avslutningskode %2$d) Kunne ikke installere %1$s Henter droiddeck-esync-pakke @@ -3317,10 +3314,19 @@ Steams delte prefiks Steam kjører sine egne Windows-hjelpere her Sletter det (%1$s). Steam oppretter et nytt neste gang det trengs. + Sletter denne butikkappens Wine-prefiks og shader-buffer (%1$s), sammen med innlogging og lagringer som bare finnes der. Spill som kjører i det, får et nytt prefiks, og du må kanskje sette opp appen igjen. Skylagringer blir værende på kontoen din. + %1$s kan tømmes + Linux- og Steam-buffere + Gamle midlertidige filer, nedlastede pakker og Steams nettbuffer + Gamle midlertidige filer + Nedlastede pakker + Steams nettbuffer + Skadede Steam-nedlastinger + Lages på nytt ved behov + Tøm En butikkapp og spillene som kjører med den Brukes av %1$s Ikke-Steam-spill %1$s - Ikke knyttet til et spill, så det beholdes Fjern valgte · %1$s Avinstaller valgte · %1$s Wine-prefikser @@ -4065,4 +4071,18 @@ Heltall Tilpass Kantutjevning - \ No newline at end of file + Egendefinert + Velg hver grensesnittfarge individuelt. + Bakgrunn + Paneler + Hevede paneler + Skillelinjer + Kanter + Hovedtekst + Sekundærtekst + Knapper og hovedfarge + Knappetekst + Uthevinger + Suksess + Feil + diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 1b00b2d21..111332286 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -22,7 +22,6 @@ Voeg Steam-bibliotheken toe vanaf een SD-kaart, USB-stick of SSD, en DroidDeck houdt de games bij elkaar in je Bibliotheek. Met Winkels log je in bij Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io en Game Jolt, en installeer en update je hun games vanuit DroidDeck. Componenten zoals FEX, DXVK en VKD3D-Proton updaten zichzelf, en Proton Experimental ARM64 is de standaard, of Proton 11.0 ARM64 zodra die build is geïnstalleerd. - Steam comprimeren terwijl een game draait maakt RAM vrij op apparaten die weinig geheugen hebben. Veeg vanaf de rechterrand naar binnen om het sessiemenu te openen: touchpadmodus, Pc-toetsenbord, modus voor lage latentie, gameprofiel en meer. Draait een game traag? Begrens de framerate in het Snelmenu en probeer dan een andere Proton-versie of FEX-preset in de componenten van de game. Kraakt de audio of ontbreekt het geluid? Probeer de schakelaar DirectAudio voor games in de Steam-instellingen onder Audio. @@ -621,20 +620,8 @@ gamescope: realtime GPU-wachtrij Geeft het GPU-werk van de compositor voorrang. Kan de framepacing gladder maken, ten koste van wat gameprestaties. GPU - Geheugen Uit - Driverstandaard - Steam comprimeren terwijl een game draait - Inactief gamegeheugen comprimeren - Comprimeert inactief gamegeheugen bij weinig RAM. Zet dit uit als games ongeveer elke halve minuut een paar seconden vastlopen. Geldt vanaf de volgende keer dat de sessie start. - 20 s nadat een game start, wordt de Steam-client in zRAM gecomprimeerd om de game meer geheugen te geven, en teruggelezen als de game sluit. Zet dit uit als de sessie kort na het starten van games sluit. Een RAM-limiet hierboven comprimeert Steam nog steeds als de sessie die overschrijdt. - RAM-limiet - Geldt terwijl de Steam-client draait, in de Steam-modus of vanaf de desktop. Als de sessie meer gebruikt dan dit, worden Steam en daarna de andere ondersteunde processen van de sessie in zRAM gecomprimeerd. Een zachte limiet: er wordt niets gesloten, maar games kunnen haperen terwijl pagina’s terugkomen. - Vereist zRAM-swap, die dit apparaat niet heeft. - VRAM-limiet - Meldt dit videogeheugenbudget aan Direct3D 9- tot 12-games om het geheugengebruik te verlagen. Games kunnen het overschrijden; dit voegt geen GPU-paging toe en garandeert geen bescherming tegen crashes door geheugentekort. Geldt vanaf de volgende sessie. GPU op hoogste kloksnelheid houden - Alleen Adreno. Minder haperingen, meer batterijverbruik en warmte. Sessiefixes Turnip: sysmem-rendering Geldt voor de Steam-client en games. Vereist op Adreno 710/720/722. @@ -811,7 +798,6 @@ Pc-toetsenbord Android Tweede scherm - Modus Toont Android-apps Een app starten @@ -2287,6 +2273,17 @@ Checksum komt niet overeen; de download is verwijderd Er is een sessie gestart tijdens het downloaden; stop die voordat je compatibiliteitstools installeert %1$s installeren + Experimentele builds + Installeren vanuit bestand + Archief bevat een onveilige link of pad + Niet-ondersteund of ongeldig archief + Niet genoeg vrije ruimte voor deze Proton-build + Proton uitpakken (enkele minuten) + Uitpakken mislukt (tar %1$d) + Het archief bevat geen Proton-build + Kan de Proton-build niet plaatsen + Kan %1$s niet volledig verwijderen + Experimentele Proton geïnstalleerd. Kies het in Steam → Eigenschappen → Compatibiliteit. Installeren van %1$s is mislukt (afsluitcode %2$d) Kan %1$s niet installeren Pakket droiddeck-esync ophalen @@ -3317,10 +3314,19 @@ Gedeeld Steam-prefix Steam voert hier eigen Windows-hulpmiddelen uit Verwijdert het (%1$s). Steam maakt een nieuw aan zodra het er weer een nodig heeft. + Verwijdert de Wine-prefix en shadercache van deze winkel-app (%1$s), met de aanmelding en saves die alleen daar staan. Games die erin draaien krijgen een nieuwe prefix, en je moet de app misschien opnieuw instellen. Cloudsaves blijven in je account. + %1$s kan worden gewist + Linux- en Steam-caches + Oude tijdelijke bestanden, gedownloade pakketten en de webcache van Steam + Oude tijdelijke bestanden + Gedownloade pakketten + Steam-webcache + Beschadigde Steam-downloads + Wordt opnieuw gemaakt wanneer nodig + Wissen Een winkel-app en de games die ermee draaien Gebruikt door %1$s Niet-Steam-game %1$s - Niet aan een game gekoppeld, dus het blijft bewaard Selectie verwijderen · %1$s Selectie verwijderen · %1$s Wine-prefixen @@ -4065,4 +4071,18 @@ Geheel getal Passend Anti-aliasing - \ No newline at end of file + Aangepast + Kies elke interfacekleur afzonderlijk. + Achtergrond + Panelen + Verhoogde panelen + Scheidingslijnen + Randen + Hoofdtekst + Secundaire tekst + Knoppen en hoofdkleur + Knoptekst + Accenten + Geslaagd + Fout + diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3c03522f4..ab4f7544e 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -22,7 +22,6 @@ Dodaj biblioteki Steam z karty SD, dysku USB lub SSD, a DroidDeck zbierze gry razem w Twojej Bibliotece. Sklepy pozwalają zalogować się do Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io i Game Jolt, a następnie instalować i aktualizować ich gry z poziomu DroidDeck. Komponenty takie jak FEX, DXVK i VKD3D-Proton aktualizują się same, a domyślny jest Proton Experimental ARM64 albo Proton 11.0 ARM64, gdy ta wersja jest zainstalowana. - Kompresuj Steam podczas gry zwalnia pamięć RAM na urządzeniach, którym jej brakuje. Przesuń palcem od prawej krawędzi, aby otworzyć menu sesji: tryb touchpada, Klawiatura PC, Tryb niskiego opóźnienia, profil gry i więcej. Gra działa wolno? Ogranicz liczbę klatek w menu Szybki dostęp, a potem wypróbuj inną wersję Proton lub inny preset FEX w komponentach gry. Trzaski lub brak dźwięku w grze? Wypróbuj przełącznik DirectAudio dla gier w ustawieniach Steam w sekcji Dźwięk. @@ -625,20 +624,8 @@ gamescope: kolejka GPU czasu rzeczywistego Nadaje priorytet pracy GPU kompozytora. Może wygładzić tempo klatek kosztem części wydajności gier. GPU - Pamięć Wyłączony - Domyślny sterownika - Kompresuj Steam podczas gry - Kompresuj nieużywaną pamięć gry - Kompresuje nieużywaną pamięć gry przy małej ilości RAM. Wyłącz, jeśli gry zawieszają się na kilka sekund mniej więcej co pół minuty. Działa od następnego uruchomienia sesji. - 20 s po starcie gry klient Steam jest kompresowany do zRAM, aby zostawić grze więcej pamięci, i wczytywany z powrotem po zamknięciu gry. Wyłącz, jeśli sesja zamyka się wkrótce po starcie gier. Powyższy limit RAM nadal kompresuje Steam, gdy sesja go przekroczy. - Limit RAM - Działa, gdy działa klient Steam, w trybie Steam lub z pulpitu. Gdy sesja używa więcej, Steam, a następnie inne obsługiwane procesy sesji są kompresowane do zRAM. Miękki limit: nic nie jest zamykane, ale gry mogą się zacinać podczas wczytywania stron z powrotem. - Wymaga swapu zRAM, którego to urządzenie nie ma. - Limit VRAM - Zgłasza ten budżet pamięci wideo grom Direct3D od 9 do 12, aby ograniczyć zużycie pamięci. Gry mogą go przekroczyć; nie dodaje to stronicowania GPU ani nie gwarantuje ochrony przed awariami z powodu braku pamięci. Działa od następnej sesji. Utrzymuj GPU na najwyższym taktowaniu - Tylko Adreno. Mniej przycięć, większe zużycie baterii i więcej ciepła. Poprawki sesji Turnip: renderowanie sysmem Dotyczy klienta Steam i gier. Wymagane na Adreno 710/720/722. @@ -815,7 +802,6 @@ Klawiatura PC Android Drugi ekran - Tryb Pokazuje Aplikacje Android Uruchom aplikację @@ -2339,6 +2325,17 @@ Niezgodna suma kontrolna; pobrany plik usunięto Podczas pobierania uruchomiono sesję; zatrzymaj ją przed instalacją narzędzi zgodności Instalowanie %1$s + Kompilacje eksperymentalne + Instaluj z pliku + Archiwum zawiera niebezpieczne łącze lub ścieżkę + Nieobsługiwane lub nieprawidłowe archiwum + Za mało wolnego miejsca na tę kompilację Proton + Rozpakowywanie Proton (kilka minut) + Rozpakowywanie nie powiodło się (tar %1$d) + Archiwum nie zawiera kompilacji Proton + Nie udało się umieścić kompilacji Proton + Nie udało się całkowicie usunąć %1$s + Eksperymentalny Proton został zainstalowany. Wybierz go w Steam → Właściwości → Zgodność. Instalacja %1$s nie powiodła się (kod %2$d) Nie udało się zainstalować %1$s Pobieranie pakietu droiddeck-esync @@ -3391,10 +3388,19 @@ Współdzielony prefiks Steam Steam uruchamia tu własne narzędzia pomocnicze Windows Usuwa go (%1$s). Steam utworzy nowy, gdy znów będzie potrzebny. + Usuwa prefiks Wine i pamięć podręczną shaderów tej aplikacji sklepu (%1$s) wraz z logowaniem i zapisami przechowywanymi tylko tam. Gry, które w nim działają, dostaną nowy prefiks, a aplikację może trzeba będzie skonfigurować ponownie. Zapisy w chmurze zostają na koncie. + Można wyczyścić %1$s + Pamięć podręczna Linuksa i Steam + Stare pliki tymczasowe, pobrane pakiety i pamięć podręczna stron Steam + Stare pliki tymczasowe + Pobrane pakiety + Pamięć podręczna stron Steam + Uszkodzone pobrania Steam + Tworzone ponownie w razie potrzeby + Wyczyść Aplikacja sklepu i gry, które z nią działają Używany przez: %1$s Gra spoza Steam %1$s - Nie pasuje do żadnej gry, więc zostaje zachowany Usuń wybrane · %1$s Odinstaluj wybrane · %1$s Prefiksy Wine @@ -4145,4 +4151,18 @@ Liczba całkowita Dopasuj Wygładzanie krawędzi - \ No newline at end of file + Niestandardowy + Wybierz osobno każdy kolor interfejsu. + Tło + Panele + Wyniesione panele + Separatory + Obramowania + Tekst główny + Tekst dodatkowy + Przyciski i główny akcent + Tekst przycisków + Wyróżnienia + Sukces + Błąd + diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 3e1e41005..6bcf81188 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -22,7 +22,6 @@ Adicione bibliotecas Steam de um cartão SD, unidade USB ou SSD, e o DroidDeck mantém os jogos juntos na sua Biblioteca. Lojas permite iniciar sessão no Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io e Game Jolt, e depois instalar e atualizar os jogos deles a partir do DroidDeck. Componentes como FEX, DXVK e VKD3D-Proton atualizam-se sozinhos, e o Proton Experimental ARM64 é o predefinido, ou o Proton 11.0 ARM64 quando essa versão estiver instalada. - Comprimir o Steam durante um jogo liberta RAM em dispositivos com pouca memória. Deslize a partir do limite direito para abrir o menu da sessão: modo de painel tátil, Teclado de PC, Modo de baixa latência, perfil do jogo e mais. O jogo está lento? Limite a taxa de fotogramas no Acesso rápido e experimente outra versão do Proton ou outra predefinição do FEX nos componentes do jogo. Áudio do jogo com estalidos ou ausente? Experimente a opção DirectAudio para jogos nas definições do Steam, em Áudio. @@ -623,20 +622,8 @@ gamescope: fila de GPU em tempo real Dá prioridade ao trabalho de GPU do compositor. Pode suavizar o ritmo de fotogramas, com algum custo para os jogos. GPU - Memória Desativado - Predefinição do controlador - Comprimir o Steam durante um jogo - Comprimir memória inativa do jogo - Comprime a memória inativa do jogo quando há pouca RAM. Desative se os jogos bloquearem durante alguns segundos aproximadamente a cada meio minuto. Aplica-se no próximo início da sessão. - 20 s após o início de um jogo, o cliente Steam é comprimido na zRAM para deixar mais memória ao jogo, e é lido de volta quando o jogo fecha. Desative se a sessão fechar pouco depois de os jogos iniciarem. Um limite de RAM acima continua a comprimir o Steam quando a sessão o ultrapassa. - Limite de RAM - Aplica-se enquanto o cliente Steam está em execução, no modo Steam ou a partir do ambiente de trabalho. Quando a sessão utiliza mais do que isto, o Steam e depois os outros processos suportados da sessão são comprimidos na zRAM. Um limite flexível: nada é fechado, mas os jogos podem ter soluços enquanto as páginas são repostas. - Requer swap em zRAM, que este dispositivo não tem. - Limite de VRAM - Comunica este orçamento de memória de vídeo aos jogos Direct3D 9 a 12 para reduzir a utilização de memória. Os jogos podem excedê-lo; isto não adiciona paginação da GPU nem garante proteção contra falhas por falta de memória. Aplica-se na próxima sessão. Manter a GPU na frequência máxima - Apenas Adreno. Menos soluços, mais consumo de bateria e mais calor. Correções da sessão Turnip: renderização em sysmem Aplica-se ao cliente Steam e aos jogos. Obrigatório no Adreno 710/720/722. @@ -813,7 +800,6 @@ Teclado de PC Android Segundo ecrã - Modo Mostra Apps Android Iniciar uma app @@ -1837,6 +1823,20 @@ Saturação Brilho Cor hexadecimal + Personalizado + Escolha individualmente cada cor da interface. + Fundo + Painéis + Painéis elevados + Divisórias + Contornos + Texto principal + Texto secundário + Botões e destaque principal + Texto dos botões + Destaques e indicadores + Sucesso + Erro Esc Ins Del @@ -2304,6 +2304,17 @@ A soma de verificação não corresponde; a transferência foi eliminada Foi iniciada uma sessão durante a transferência; pare-a antes de instalar ferramentas de compatibilidade A instalar %1$s + Versões experimentais + Instalar a partir de ficheiro + O arquivo contém uma ligação ou caminho inseguro + Arquivo não suportado ou inválido + Não há espaço livre suficiente para esta versão do Proton + A desempacotar o Proton (alguns minutos) + Falha ao desempacotar (tar %1$d) + O arquivo não contém nenhuma versão do Proton + Não foi possível colocar a versão do Proton + Não foi possível remover totalmente %1$s + Proton experimental instalado. Escolha-o em Steam → Propriedades → Compatibilidade. Falha na instalação de %1$s (saída %2$d) Não foi possível instalar %1$s A obter o pacote droiddeck-esync @@ -3353,10 +3364,19 @@ Prefixo partilhado do Steam O Steam executa aqui os seus próprios auxiliares do Windows Elimina-o (%1$s). O Steam cria um novo da próxima vez que precisar. + Apaga o prefixo Wine e a cache de shaders desta app de loja (%1$s), com a sessão iniciada e os jogos guardados apenas aí. Os jogos que correm nele recebem um prefixo novo, e poderá ter de configurar a app outra vez. Os jogos guardados na nuvem ficam na sua conta. + É possível libertar %1$s + Caches do Linux e do Steam + Ficheiros temporários antigos, pacotes transferidos e a cache web do Steam + Ficheiros temporários antigos + Pacotes transferidos + Cache web do Steam + Transferências danificadas do Steam + Recriados quando necessário + Limpar Uma app de loja e os jogos que correm com ela Usado por %1$s Jogo não Steam %1$s - Não corresponde a nenhum jogo, por isso é mantido Remover seleção · %1$s Desinstalar seleção · %1$s Prefixos do Wine @@ -4104,4 +4124,4 @@ Inteiro Ajustar Suavização de serrilhado - \ No newline at end of file + diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 2344d779e..c93c0e9a2 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -22,7 +22,6 @@ Adicione bibliotecas da Steam de um cartão SD, pen drive USB ou SSD, e o DroidDeck mantém os jogos juntos na sua Biblioteca. Lojas permite entrar no Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io e Game Jolt, e depois instalar e atualizar os jogos deles pelo DroidDeck. Componentes como FEX, DXVK e VKD3D-Proton se atualizam sozinhos, e o Proton Experimental ARM64 é o padrão, ou o Proton 11.0 ARM64 quando essa versão estiver instalada. - Comprimir a Steam durante o jogo libera RAM em dispositivos com pouca memória. Deslize da borda direita para abrir o menu da sessão: modo touchpad, Teclado de PC, Modo de baixa latência, perfil do jogo e mais. Jogo rodando devagar? Limite a taxa de quadros no Acesso rápido e depois teste outra versão do Proton ou outra predefinição do FEX nos componentes do jogo. Áudio do jogo com chiado ou sem som? Experimente a opção DirectAudio para jogos nas configurações da Steam, em Áudio. @@ -623,20 +622,8 @@ gamescope: fila de GPU em tempo real Prioriza o trabalho de GPU do compositor. Pode suavizar o ritmo dos quadros, com algum custo para os jogos. GPU - Memória Desativado - Padrão do driver - Comprimir a Steam durante o jogo - Comprimir memória inativa do jogo - Comprime a memória inativa do jogo quando há pouca RAM. Desative se os jogos travarem por alguns segundos a cada meio minuto, aproximadamente. Vale a partir do próximo início da sessão. - 20 s após o início de um jogo, o cliente Steam é comprimido na zRAM para deixar mais memória ao jogo, e é lido de volta quando o jogo fecha. Desative se a sessão fechar logo após os jogos iniciarem. Um limite de RAM acima ainda comprime a Steam quando a sessão o ultrapassa. - Limite de RAM - Vale enquanto o cliente Steam está em execução, no modo Steam ou pela área de trabalho. Quando a sessão usa mais que isso, a Steam e depois os outros processos compatíveis da sessão são comprimidos na zRAM. Um limite flexível: nada é fechado, mas os jogos podem travar enquanto as páginas voltam. - Requer swap em zRAM, que este dispositivo não tem. - Limite de VRAM - Informa este orçamento de memória de vídeo aos jogos Direct3D 9 a 12 para reduzir o uso de memória. Os jogos podem excedê-lo; isso não adiciona paginação de GPU nem garante proteção contra falhas por falta de memória. Entra em vigor na próxima sessão. Manter a GPU no clock máximo - Só em Adreno. Menos engasgos, mais gasto de bateria e mais calor. Correções da sessão Turnip: renderização sysmem Aplica-se ao cliente Steam e aos jogos. Obrigatório nas Adreno 710/720/722. @@ -817,7 +804,6 @@ Teclado de PC Android Segunda tela - Modo Mostra Apps Android Abrir um app @@ -1842,6 +1828,20 @@ Saturação Brilho Cor hexadecimal + Personalizado + Escolha individualmente cada cor da interface. + Fundo + Painéis + Painéis elevados + Divisórias + Bordas + Texto principal + Texto secundário + Botões e destaque principal + Texto dos botões + Destaques e indicadores + Sucesso + Erro Esc Ins Del @@ -2309,6 +2309,17 @@ A soma de verificação não confere; o download foi excluído Uma sessão foi iniciada durante o download; pare-a antes de instalar ferramentas de compatibilidade Instalando %1$s + Builds experimentais + Instalar do arquivo + O arquivo contém um link ou caminho inseguro + Arquivo sem suporte ou inválido + Não há espaço livre suficiente para este build do Proton + Desempacotando o Proton (alguns minutos) + Falha ao desempacotar (tar %1$d) + O arquivo não contém nenhum build do Proton + Não foi possível colocar o build do Proton + Não foi possível remover totalmente o %1$s + Proton experimental instalado. Escolha-o em Steam → Propriedades → Compatibilidade. Falha na instalação do %1$s (código de saída %2$d) Não foi possível instalar o %1$s Buscando o pacote droiddeck-esync @@ -3358,10 +3369,19 @@ Prefixo compartilhado da Steam A Steam executa aqui seus próprios auxiliares do Windows Apaga o prefixo (%1$s). A Steam cria um novo na próxima vez que precisar. + Apaga o prefixo do Wine e o cache de shaders deste app de loja (%1$s), com o login e os saves guardados só ali. Os jogos que rodam nele recebem um prefixo novo, e talvez seja preciso configurar o app de novo. Os saves na nuvem continuam na sua conta. + Dá para liberar %1$s + Caches do Linux e da Steam + Arquivos temporários antigos, pacotes baixados e o cache web da Steam + Arquivos temporários antigos + Pacotes baixados + Cache web da Steam + Downloads danificados da Steam + Recriados quando necessário + Limpar Um app de loja e os jogos que rodam com ele Usado por %1$s Jogo não Steam %1$s - Não corresponde a nenhum jogo, então é mantido Remover seleção · %1$s Desinstalar seleção · %1$s Prefixos do Wine @@ -4109,4 +4129,4 @@ Inteiro Ajustar Suavização de serrilhado - \ No newline at end of file + diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index b17267af8..c843890ec 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -22,7 +22,6 @@ Adaugă biblioteci Steam de pe un card SD, o unitate USB sau un SSD, iar DroidDeck păstrează jocurile împreună în Biblioteca ta. Magazine îți permite să te conectezi la Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io și Game Jolt, apoi să instalezi și să actualizezi jocurile lor din DroidDeck. Componente precum FEX, DXVK și VKD3D-Proton se actualizează singure, iar Proton Experimental ARM64 este implicit, sau Proton 11.0 ARM64 odată ce acea versiune este instalată. - Comprimă Steam cât rulează un joc eliberează RAM pe dispozitivele cu memorie puțină. Glisează dinspre marginea dreaptă ca să deschizi meniul sesiunii: mod touchpad, Tastatură de PC, Mod latență redusă, profilul jocului și altele. Jocul rulează greu? Limitează rata de cadre în Acces rapid, apoi încearcă altă versiune de Proton sau alt preset FEX în componentele jocului. Sunet de joc cu pârâituri sau lipsă? Încearcă opțiunea DirectAudio pentru jocuri din setările Steam, la Sunet. @@ -623,20 +622,8 @@ gamescope: coadă GPU în timp real Prioritizează lucrul GPU al compositorului. Poate netezi ritmul cadrelor, cu un cost pentru jocuri. GPU - Memorie Dezactivat - Implicit driver - Comprimă Steam cât rulează un joc - Comprimă memoria inactivă a jocului - Comprimă memoria inactivă a jocului când memoria RAM este redusă. Dezactivează dacă jocurile îngheață câteva secunde aproximativ la fiecare jumătate de minut. Se aplică la următoarea pornire a sesiunii. - La 20 s după pornirea unui joc, clientul Steam este comprimat în zRAM pentru a lăsa jocului mai multă memorie și este citit înapoi când jocul se închide. Dezactivează dacă sesiunea se închide la scurt timp după pornirea jocurilor. O limită RAM de mai sus tot comprimă Steam când sesiunea o depășește. - Limită RAM - Se aplică cât rulează clientul Steam, în modul Steam sau de pe desktop. Când sesiunea folosește mai mult de atât, Steam și apoi celelalte procese acceptate ale sesiunii sunt comprimate în zRAM. O limită flexibilă: nimic nu se închide, dar jocurile pot sacada cât paginile revin. - Necesită swap zRAM, pe care acest dispozitiv nu îl are. - Limită VRAM - Raportează acest buget de memorie video jocurilor Direct3D 9 până la 12 pentru a reduce utilizarea memoriei. Jocurile îl pot depăși; nu adaugă paginare GPU și nu garantează protecție împotriva blocărilor cauzate de lipsa memoriei. Se aplică din sesiunea următoare. Fixează GPU-ul la frecvența maximă - Doar Adreno. Mai puține întreruperi, consum mai mare de baterie și căldură. Remedieri de sesiune Turnip: randare sysmem Se aplică clientului Steam și jocurilor. Necesară pe Adreno 710/720/722. @@ -813,7 +800,6 @@ Tastatură de PC Android Al doilea ecran - Mod Arată Aplicații Android Lansează o aplicație @@ -2313,6 +2299,17 @@ Sumă de control incorectă; descărcarea a fost ștearsă O sesiune a pornit în timpul descărcării; oprește-o înainte de a instala instrumente de compatibilitate Se instalează %1$s + Versiuni experimentale + Instalează din fișier + Arhiva conține o legătură sau o cale nesigură + Arhivă neacceptată sau nevalidă + Nu există suficient spațiu liber pentru această versiune Proton + Se despachetează Proton (câteva minute) + Despachetarea a eșuat (tar %1$d) + Arhiva nu conține nicio versiune Proton + Versiunea Proton nu a putut fi plasată + %1$s nu a putut fi eliminat complet + Proton experimental a fost instalat. Selectează-l în Steam → Proprietăți → Compatibilitate. Instalarea %1$s a eșuat (cod de ieșire %2$d) %1$s nu a putut fi instalat Se obține pachetul droiddeck-esync @@ -3354,10 +3351,19 @@ Prefixul Steam partajat Steam rulează aici propriile utilitare Windows Îl șterge (%1$s). Steam creează unul nou data viitoare când are nevoie. + Șterge prefixul Wine și memoria cache de shadere ale acestei aplicații de magazin (%1$s), cu autentificarea și salvările păstrate doar acolo. Jocurile care rulează în el primesc un prefix nou și poate fi nevoie să configurezi din nou aplicația. Salvările din cloud rămân în cont. + Se pot elibera %1$s + Cache-uri Linux și Steam + Fișiere temporare vechi, pachete descărcate și cache-ul web Steam + Fișiere temporare vechi + Pachete descărcate + Cache web Steam + Descărcări Steam deteriorate + Se recreează când e nevoie + Golește O aplicație de magazin și jocurile care rulează cu ea Folosit de %1$s Joc non-Steam %1$s - Nu corespunde niciunui joc, deci este păstrat Elimină selecția · %1$s Dezinstalează selecția · %1$s Prefixuri Wine @@ -4105,4 +4111,18 @@ Număr întreg Potrivire Antialiasing - \ No newline at end of file + Personalizat + Alege separat fiecare culoare a interfeței. + Fundal + Panouri + Panouri ridicate + Separatoare + Margini + Text principal + Text secundar + Butoane și accent principal + Textul butoanelor + Evidențieri + Succes + Eroare + diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 0714d5669..e76e565d2 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -22,7 +22,6 @@ Добавляйте библиотеки Steam с SD-карты, USB-накопителя или SSD, и DroidDeck соберёт игры вместе в вашей «Библиотеке». «Магазины» позволяют войти в Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io и Game Jolt, а затем устанавливать и обновлять их игры из DroidDeck. Компоненты вроде FEX, DXVK и VKD3D-Proton обновляются сами, а по умолчанию используется Proton Experimental ARM64 или Proton 11.0 ARM64, когда эта сборка установлена. - «Сжимать Steam во время игры» освобождает ОЗУ на устройствах с нехваткой памяти. Проведите от правого края, чтобы открыть меню сеанса: режим тачпада, «Клавиатура ПК», «Режим низкой задержки», профиль игры и другое. Игра тормозит? Ограничьте частоту кадров в меню «Быстрый доступ», затем попробуйте другую версию Proton или другой пресет FEX в компонентах игры. Треск или нет звука в игре? Попробуйте переключатель «DirectAudio для игр» в настройках Steam в разделе «Аудио». @@ -625,20 +624,8 @@ gamescope: очередь GPU в реальном времени Повышает приоритет работы GPU композитора. Может улучшить стабильность времени кадра, но потребляет часть производительности игры. GPU - Память Выкл. - По умолчанию драйвера - Сжимать Steam во время игры - Сжимать неактивную память игры - Сжимает неактивную память игры при нехватке RAM. Отключите, если игры зависают на несколько секунд примерно каждые полминуты. Применяется при следующем запуске сеанса. - Через 20 с после запуска игры клиент Steam сжимается в zRAM, чтобы оставить игре больше памяти, и считывается обратно после закрытия игры. Отключите, если сессия закрывается вскоре после запуска игр. Лимит RAM выше всё равно сжимает Steam, когда сессия его превышает. - Лимит RAM - Действует, пока работает клиент Steam, в режиме Steam или с рабочего стола. Когда сессия использует больше этого значения, Steam, а затем другие поддерживаемые процессы сессии сжимаются в zRAM. Мягкий лимит: ничего не закрывается, но игры могут подтормаживать, пока страницы возвращаются. - Нужен своп zRAM, которого на этом устройстве нет. - Лимит VRAM - Сообщает играм Direct3D 9–12 этот бюджет видеопамяти для снижения её использования. Игры могут его превысить; это не добавляет подкачку памяти GPU и не гарантирует защиту от сбоев из-за нехватки памяти. Действует со следующего сеанса. Поддерживать максимальную частоту GPU - Только для Adreno. Меньше подтормаживаний, но больше энергопотребления и нагрева. Исправления сессии Turnip: рендеринг sysmem Применяется к клиенту Steam и играм. Требуется на Adreno 710/720/722. @@ -815,7 +802,6 @@ Клавиатура ПК Android Второй экран - Режим Показывать Приложения Android Запустить приложение @@ -2339,6 +2325,17 @@ Контрольная сумма не совпадает; загруженный файл удален Во время загрузки запустилась сессия; остановите ее перед установкой инструментов совместимости Установка %1$s + Экспериментальные сборки + Установить из файла + Архив содержит небезопасную ссылку или путь + Неподдерживаемый или недействительный архив + Недостаточно свободного места для этой сборки Proton + Распаковка Proton (несколько минут) + Не удалось распаковать (tar %1$d) + В архиве нет сборки Proton + Не удалось разместить сборку Proton + Не удалось полностью удалить %1$s + Экспериментальная сборка Proton установлена. Выберите её в Steam → Свойства → Совместимость. Ошибка установки %1$s (код выхода %2$d) Не удалось установить %1$s Загрузка пакета droiddeck-esync @@ -3391,10 +3388,19 @@ Общий префикс Steam Steam запускает здесь свои вспомогательные программы Windows Удаляет его (%1$s). Steam создаст новый, когда он снова понадобится. + Удаляет префикс Wine и кеш шейдеров этого приложения магазина (%1$s) вместе со входом в аккаунт и сохранениями, которые есть только там. Игры, работающие в нём, получат новый префикс, а приложение, возможно, придётся настроить заново. Облачные сохранения остаются в аккаунте. + Можно очистить %1$s + Кеши Linux и Steam + Старые временные файлы, скачанные пакеты и веб-кеш Steam + Старые временные файлы + Скачанные пакеты + Веб-кеш Steam + Повреждённые загрузки Steam + Создаются заново при необходимости + Очистить Приложение магазина и игры, которые с ним работают Используется: %1$s Игра не из Steam %1$s - Не сопоставлен с игрой, поэтому сохраняется Удалить выбранные · %1$s Удалить выбранные · %1$s Префиксы Wine @@ -4145,4 +4151,18 @@ Целое число По размеру Сглаживание - \ No newline at end of file + Пользовательская + Выберите каждый цвет интерфейса отдельно. + Фон + Панели + Приподнятые панели + Разделители + Границы + Основной текст + Вторичный текст + Кнопки и основной акцент + Текст кнопок + Выделения + Успех + Ошибка + diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 35a26507e..1d9b64733 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -22,7 +22,6 @@ Lägg till Steam-bibliotek från ett SD-kort, USB-minne eller SSD, så håller DroidDeck ihop spelen i ditt Bibliotek. Butiker låter dig logga in på Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io och Game Jolt och sedan installera och uppdatera deras spel från DroidDeck. Komponenter som FEX, DXVK och VKD3D-Proton uppdaterar sig själva, och Proton Experimental ARM64 är standard, eller Proton 11.0 ARM64 när den versionen är installerad. - Komprimera Steam medan ett spel körs frigör RAM på enheter med lite minne. Svep in från högerkanten för att öppna sessionsmenyn: pekplattsläge, PC-tangentbord, låg latens, spelprofil med mera. Går spelet långsamt? Begränsa bildfrekvensen i Snabbåtkomst och prova sedan en annan Proton-version eller FEX-förinställning i spelets komponenter. Knaster eller saknat ljud i spelet? Prova växlaren DirectAudio för spel i Steam-inställningarna under Ljud. @@ -621,20 +620,8 @@ gamescope: GPU-kö i realtid Prioriterar kompositorns GPU-arbete. Kan jämna ut bildtakten till viss kostnad för spelen. GPU - Minne Av - Drivrutinens standard - Komprimera Steam medan ett spel körs - Komprimera spelets inaktiva minne - Komprimerar spelets inaktiva minne när RAM-minnet är lågt. Stäng av om spel fryser några sekunder ungefär var halvminut. Gäller nästa gång sessionen startar. - 20 s efter att ett spel startat komprimeras Steam-klienten till zRAM för att ge spelet mer minne, och läses tillbaka när spelet stängs. Stäng av om sessionen stängs strax efter att spel startar. En RAM-gräns ovan komprimerar fortfarande Steam när sessionen överskrider den. - RAM-gräns - Gäller medan Steam-klienten körs, i Steam-läge eller från skrivbordet. När sessionen använder mer än detta komprimeras Steam och sedan sessionens övriga processer som stöds till zRAM. En mjuk gräns: inget stängs, men spel kan hacka medan sidor läses tillbaka. - Kräver zRAM-swap, vilket den här enheten saknar. - VRAM-gräns - Rapporterar denna videominnesbudget till Direct3D 9 till 12-spel för att minska minnesanvändningen. Spel kan överskrida den; detta lägger inte till sidväxling av GPU-minne och garanterar inte skydd mot krascher vid minnesbrist. Gäller från nästa session. Håll GPU:n på dess högsta klockfrekvens - Bara Adreno. Färre hack, högre batteriförbrukning och mer värme. Sessionsfixar Turnip: sysmem-rendering Gäller Steam-klienten och spel. Krävs på Adreno 710/720/722. @@ -811,7 +798,6 @@ PC-tangentbord Android Andra skärmen - Läge Visar Android-appar Starta en app @@ -2287,6 +2273,17 @@ Kontrollsumman stämmer inte. Nedladdningen togs bort En session startade under nedladdningen. Stoppa den innan du installerar kompatibilitetsverktyg Installerar %1$s + Experimentella byggen + Installera från fil + Arkivet innehåller en osäker länk eller sökväg + Arkivet stöds inte eller är ogiltigt + Inte tillräckligt med ledigt utrymme för den här Proton-versionen + Packar upp Proton (några minuter) + Uppackningen misslyckades (tar %1$d) + Arkivet innehåller ingen Proton-version + Det gick inte att placera Proton-versionen + Det gick inte att ta bort %1$s helt + Experimentell Proton installerad. Välj den i Steam → Egenskaper → Kompatibilitet. Installationen av %1$s misslyckades (avslutningskod %2$d) Kunde inte installera %1$s Hämtar droiddeck-esync-paket @@ -3317,10 +3314,19 @@ Steams delade prefix Steam kör sina egna Windows-hjälpprogram här Raderar det (%1$s). Steam skapar ett nytt nästa gång det behövs. + Tar bort den här butiksappens Wine-prefix och shadercache (%1$s), med inloggning och sparfiler som bara finns där. Spel som körs i det får ett nytt prefix, och du kan behöva konfigurera appen igen. Molnsparningar finns kvar på ditt konto. + %1$s kan rensas + Linux- och Steam-cacheminnen + Gamla tillfälliga filer, hämtade paket och Steams webbcache + Gamla tillfälliga filer + Hämtade paket + Steams webbcache + Skadade Steam-nedladdningar + Skapas igen vid behov + Rensa En butiksapp och spelen som körs med den Används av %1$s Icke-Steam-spel %1$s - Inte kopplat till något spel, så det behålls Ta bort valda · %1$s Avinstallera valda · %1$s Wine-prefix @@ -4065,4 +4071,18 @@ Heltal Anpassa Kantutjämning - \ No newline at end of file + Anpassat + Välj varje gränssnittsfärg separat. + Bakgrund + Paneler + Upphöjda paneler + Avdelare + Kanter + Huvudtext + Sekundär text + Knappar och huvudaccent + Knapptext + Markeringar + Lyckades + Fel + diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 36cc3dbf2..72d7f7191 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -22,7 +22,6 @@ เพิ่มคลังเกม Steam จากการ์ด SD ไดรฟ์ USB หรือ SSD แล้ว DroidDeck จะรวมเกมไว้ด้วยกันใน ไลบรารี ของคุณ สโตร์ ให้คุณลงชื่อเข้าใช้ Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io และ Game Jolt แล้วติดตั้งและอัปเดตเกมของสโตร์เหล่านั้นจาก DroidDeck ได้ คอมโพเนนต์อย่าง FEX, DXVK และ VKD3D-Proton อัปเดตตัวเอง และค่าเริ่มต้นคือ Proton Experimental ARM64 หรือ Proton 11.0 ARM64 เมื่อติดตั้งบิลด์นั้นแล้ว - บีบอัด Steam ขณะเล่นเกม ช่วยเพิ่ม RAM ว่างบนอุปกรณ์ที่หน่วยความจำเหลือน้อย ปัดเข้าจากขอบขวาเพื่อเปิดเมนูเซสชัน: โหมดทัชแพด แป้นพิมพ์พีซี โหมดหน่วงเวลาต่ำ โปรไฟล์เกม และอื่น ๆ เกมช้าใช่ไหม ลองจำกัดเฟรมเรตใน Quick Access แล้วลองใช้ Proton เวอร์ชันอื่นหรือพรีเซ็ต FEX อื่นในคอมโพเนนต์ของเกม เสียงเกมแตกพร่าหรือไม่มีเสียง ลองเปิดสวิตช์ DirectAudio สำหรับเกม ในการตั้งค่า Steam ภายใต้ เสียง @@ -619,20 +618,8 @@ gamescope: คิว GPU แบบเรียลไทม์ ให้ความสำคัญกับงาน GPU ของตัวประกอบภาพก่อน อาจทำให้การเรียงเฟรมราบรื่นขึ้นโดยแลกกับประสิทธิภาพของเกมบางส่วน GPU - หน่วยความจำ ปิด - ค่าเริ่มต้นของไดรเวอร์ - บีบอัด Steam ขณะเล่นเกม - บีบอัดหน่วยความจำเกมที่ไม่ได้ใช้งาน - บีบอัดหน่วยความจำเกมที่ไม่ได้ใช้งานเมื่อ RAM เหลือน้อย ปิดไว้หากเกมค้างไม่กี่วินาทีทุกประมาณครึ่งนาที มีผลเมื่อเริ่มเซสชันครั้งถัดไป - 20 วินาทีหลังเกมเริ่ม ไคลเอนต์ Steam จะถูกบีบอัดลงใน zRAM เพื่อเหลือหน่วยความจำให้เกมมากขึ้น และอ่านกลับเมื่อปิดเกม ปิดตัวเลือกนี้หากเซสชันปิดไปไม่นานหลังเริ่มเกม ขีดจำกัด RAM ด้านบนยังคงบีบอัด Steam เมื่อเซสชันใช้เกินขีดจำกัด - ขีดจำกัด RAM - มีผลขณะไคลเอนต์ Steam ทำงาน ทั้งในโหมด Steam หรือจากเดสก์ท็อป เมื่อเซสชันใช้เกินค่านี้ Steam และโปรเซสอื่นที่รองรับของเซสชันจะถูกบีบอัดลงใน zRAM ตามลำดับ เป็นขีดจำกัดแบบอ่อน: ไม่มีอะไรถูกปิด แต่เกมอาจกระตุกขณะดึงหน้าหน่วยความจำกลับมา - ต้องใช้ zRAM swap ซึ่งอุปกรณ์นี้ไม่มี - ขีดจำกัด VRAM - แจ้งงบประมาณหน่วยความจำวิดีโอนี้ให้เกม Direct3D 9 ถึง 12 เพื่อลดการใช้หน่วยความจำ เกมอาจใช้เกินงบได้ ฟีเจอร์นี้ไม่ได้เพิ่มการสลับหน้าหน่วยความจำ GPU และไม่รับประกันว่าจะป้องกันการแครชเมื่อหน่วยความจำหมด มีผลในเซสชันถัดไป ตรึง GPU ไว้ที่ความเร็วสัญญาณนาฬิกาสูงสุด - สำหรับ Adreno เท่านั้น สะดุดน้อยลง แต่ใช้แบตเตอรี่และเกิดความร้อนมากขึ้น การแก้ไขเซสชัน Turnip: การเรนเดอร์ sysmem ใช้กับไคลเอนต์ Steam และเกม จำเป็นสำหรับ Adreno 710/720/722 @@ -809,7 +796,6 @@ แป้นพิมพ์พีซี Android หน้าจอที่สอง - โหมด แสดง แอป Android เปิดแอป @@ -2262,6 +2248,17 @@ ค่าตรวจสอบไม่ตรงกัน การดาวน์โหลดถูกลบแล้ว มีเซสชันเริ่มขึ้นระหว่างการดาวน์โหลด หยุดเซสชันก่อนติดตั้งเครื่องมือความเข้ากันได้ กำลังติดตั้ง %1$s + บิลด์ทดลอง + ติดตั้งจากไฟล์ + ไฟล์เก็บถาวรมีลิงก์หรือเส้นทางที่ไม่ปลอดภัย + ไฟล์เก็บถาวรไม่รองรับหรือไม่ถูกต้อง + พื้นที่ว่างไม่เพียงพอสำหรับบิลด์ Proton นี้ + กำลังแตกไฟล์ Proton (ใช้เวลาไม่กี่นาที) + แตกไฟล์ไม่สำเร็จ (tar %1$d) + ไฟล์เก็บถาวรไม่มีบิลด์ Proton + ไม่สามารถวางบิลด์ Proton ได้ + ไม่สามารถลบ %1$s ออกให้หมดได้ + ติดตั้ง Proton รุ่นทดลองแล้ว เลือกได้ที่ Steam → คุณสมบัติ → ความเข้ากันได้ การติดตั้ง %1$s ล้มเหลว (ออกด้วยสถานะ %2$d) ไม่สามารถติดตั้ง %1$s ได้ กำลังดึงแพ็ก droiddeck-esync @@ -3288,10 +3285,19 @@ Prefix Steam ที่ใช้ร่วมกัน Steam รันตัวช่วย Windows ของตัวเองที่นี่ ลบ prefix นี้ (%1$s) Steam จะสร้างใหม่เมื่อต้องใช้ครั้งถัดไป + ลบ Wine prefix และแคชเชเดอร์ของแอปร้านค้านี้ (%1$s) พร้อมการลงชื่อเข้าใช้และเซฟที่อยู่ในนั้นเท่านั้น เกมที่รันในนั้นจะได้ prefix ใหม่ และคุณอาจต้องตั้งค่าแอปอีกครั้ง เซฟบนคลาวด์ยังอยู่ในบัญชีของคุณ + ล้างได้ %1$s + แคชของ Linux และ Steam + ไฟล์ชั่วคราวเก่า แพ็กเกจที่ดาวน์โหลด และแคชเว็บของ Steam + ไฟล์ชั่วคราวเก่า + แพ็กเกจที่ดาวน์โหลด + แคชเว็บของ Steam + ไฟล์ดาวน์โหลด Steam ที่เสียหาย + สร้างใหม่เมื่อจำเป็น + ล้าง แอปสโตร์และเกมที่ทำงานกับแอปนั้น ใช้โดย %1$s เกมนอก Steam %1$s - ไม่ตรงกับเกมใด จึงเก็บไว้ นำรายการที่เลือกออก · %1$s ถอนการติดตั้งรายการที่เลือก · %1$s Wine prefix @@ -4035,4 +4041,18 @@ จำนวนเต็ม พอดีหน้าจอ การลบรอยหยัก - \ No newline at end of file + กำหนดเอง + เลือกสีแต่ละสีของอินเทอร์เฟซแยกกัน + พื้นหลัง + แผง + แผงยกสูง + ตัวแบ่ง + เส้นขอบ + ข้อความหลัก + ข้อความรอง + ปุ่มและสีเน้นหลัก + ข้อความบนปุ่ม + จุดเน้น + สำเร็จ + ข้อผิดพลาด + diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index ce681b142..093ad5af3 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -22,7 +22,6 @@ SD karttan, USB sürücüden veya SSD\'den Steam kütüphaneleri ekle; DroidDeck oyunları Kütüphane\'nde bir arada tutar. Mağazalar, Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io ve Game Jolt\'ta oturum açmanı, ardından oyunlarını DroidDeck\'ten yüklemeni ve güncellemeni sağlar. FEX, DXVK ve VKD3D-Proton gibi bileşenler kendini günceller; varsayılan Proton Experimental ARM64\'tür, Proton 11.0 ARM64 kurulduktan sonra ise o olur. - Oyun çalışırken Steam\'i sıkıştır, belleği az olan cihazlarda RAM boşaltır. Oturum menüsünü açmak için sağ kenardan içeri kaydır: dokunmatik yüzey modu, PC klavyesi, düşük gecikme, oyun profili ve daha fazlası. Oyun yavaş mı çalışıyor? Hızlı erişim\'de kare hızını sınırla, sonra oyunun bileşenlerinde başka bir Proton sürümü veya FEX ön ayarı dene. Oyun sesinde cızırtı var ya da ses yok mu? Steam ayarlarında Ses altındaki Oyunlar için DirectAudio düğmesini dene. @@ -621,20 +620,8 @@ gamescope: gerçek zamanlı GPU kuyruğu Bileştiricinin GPU işine öncelik verir. Oyunlardan biraz feda ederek kare zamanlamasını yumuşatabilir. GPU - Bellek Kapalı - Sürücü varsayılanı - Oyun çalışırken Steam\'i sıkıştır - Oyunun boşta belleğini sıkıştır - RAM azaldığında oyunun boşta belleğini sıkıştırır. Oyunlar yaklaşık her yarım dakikada birkaç saniye donuyorsa kapatın. Oturum bir sonraki başlatıldığında geçerli olur. - Oyun başladıktan 20 sn sonra oyuna daha fazla bellek kalması için Steam istemcisi zRAM\'e sıkıştırılır ve oyun kapanınca geri okunur. Oyunlar başladıktan kısa süre sonra oturum kapanıyorsa bunu kapatın. Yukarıdaki RAM sınırı, oturum onu aştığında Steam\'i yine sıkıştırır. - RAM sınırı - Steam istemcisi Steam oturumunda veya masaüstünden çalışırken uygulanır. Oturum bundan fazlasını kullandığında önce Steam, ardından oturumun desteklenen diğer işlemleri zRAM\'e sıkıştırılır. Yumuşak bir sınırdır: hiçbir şey kapatılmaz, ancak sayfalar geri yüklenirken oyunlar takılabilir. - Bu cihazda olmayan zRAM takası gerekir. - VRAM sınırı - Bellek kullanımını azaltmak için Direct3D 9–12 oyunlarına bu video belleği bütçesini bildirir. Oyunlar bütçeyi aşabilir; GPU sayfalaması eklemez veya bellek yetersizliğinden kaynaklanan çökmeleri önlemeyi garanti etmez. Sonraki oturumda geçerli olur. GPU\'yu en yüksek saat hızında tut - Yalnızca Adreno. Daha az takılma, daha fazla pil tüketimi ve ısınma. Oturum düzeltmeleri Turnip: sysmem işleme Steam istemcisi ve oyunlar için geçerlidir. Adreno 710/720/722\'de gereklidir. @@ -811,7 +798,6 @@ PC klavyesi Android İkinci ekran - Mod Gösterilen Android uygulamaları Uygulama başlat @@ -2279,6 +2265,17 @@ Sağlama toplamı uyuşmuyor; indirme silindi İndirme sırasında bir oturum başladı; uyumluluk araçlarını yüklemeden önce durdurun %1$s yükleniyor + Deneysel sürümler + Dosyadan yükle + Arşiv güvenli olmayan bir bağlantı veya yol içeriyor + Desteklenmeyen veya geçersiz arşiv + Bu Proton sürümü için yeterli boş alan yok + Proton paketten çıkarılıyor (birkaç dakika) + Paketten çıkarma başarısız oldu (tar %1$d) + Arşivde Proton sürümü yok + Proton sürümü yerleştirilemedi + %1$s tamamen kaldırılamadı + Deneysel Proton yüklendi. Steam → Özellikler → Uyumluluk bölümünden seçin. %1$s yüklemesi başarısız oldu (çıkış %2$d) %1$s yüklenemedi droiddeck-esync paketi getiriliyor @@ -3317,10 +3314,19 @@ Steam\'in ortak öneki Steam kendi Windows yardımcılarını burada çalıştırır Siler (%1$s). Steam bir dahaki ihtiyacında yenisini oluşturur. + Bu mağaza uygulamasının Wine önekini ve gölgelendirici önbelleğini (%1$s), oturum açma bilgisi ve yalnızca orada duran kayıtlarla birlikte siler. İçinde çalışan oyunlar yeni bir önek alır ve uygulamayı yeniden kurmanız gerekebilir. Bulut kayıtları hesabınızda kalır. + %1$s temizlenebilir + Linux ve Steam önbellekleri + Eski geçici dosyalar, indirilen paketler ve Steam’in web önbelleği + Eski geçici dosyalar + İndirilen paketler + Steam web önbelleği + Hasarlı Steam indirmeleri + Gerektiğinde yeniden oluşturulur + Temizle Bir mağaza uygulaması ve onunla çalışan oyunlar Kullanan: %1$s Steam dışı oyun %1$s - Bir oyunla eşleşmedi, bu yüzden korunuyor Seçilenleri kaldır · %1$s Seçilenlerin yüklemesini kaldır · %1$s Wine önekleri @@ -4065,4 +4071,18 @@ Tam sayı Sığdır Kenar yumuşatma - \ No newline at end of file + Özel + Arayüzdeki her rengi ayrı ayrı seçin. + Arka plan + Paneller + Yükseltilmiş paneller + Ayırıcılar + Kenarlıklar + Ana metin + İkincil metin + Düğmeler ve ana vurgu + Düğme metni + Vurgular + Başarılı + Hata + diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 4ab72b177..cf87b4103 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -22,7 +22,6 @@ Додавайте бібліотеки Steam із SD-картки, USB-накопичувача чи SSD, і DroidDeck збере ігри разом у вашій «Бібліотеці». «Магазини» дають змогу увійти в Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io і Game Jolt, а потім установлювати й оновлювати їхні ігри з DroidDeck. Компоненти, як-от FEX, DXVK і VKD3D-Proton, оновлюються самі, а типовою є Proton Experimental ARM64 або Proton 11.0 ARM64, щойно цю збірку встановлено. - «Стискати Steam під час гри» звільняє оперативну пам\'ять на пристроях, яким її бракує. Проведіть від правого краю, щоб відкрити меню сеансу: режим сенсорної панелі, «Клавіатура ПК», низька затримка, профіль гри та інше. Гра гальмує? Обмежте частоту кадрів у меню «Швидкий доступ», потім спробуйте іншу версію Proton або набір налаштувань FEX у компонентах гри. Тріск або зникає звук у грі? Спробуйте перемикач «DirectAudio для ігор» у налаштуваннях Steam у розділі «Звук». @@ -625,20 +624,8 @@ gamescope: черга GPU реального часу Надає пріоритет роботі композитора на GPU. Може вирівняти темп кадрів ціною частини продуктивності ігор. GPU - Памʼять Вимк. - Типово для драйвера - Стискати Steam під час гри - Стискати неактивну пам’ять гри - Стискає неактивну пам’ять гри, коли мало RAM. Вимкніть, якщо ігри зависають на кілька секунд приблизно кожні пів хвилини. Застосовується під час наступного запуску сеансу. - Через 20 с після запуску гри клієнт Steam стискається в zRAM, щоб залишити грі більше памʼяті, і зчитується назад, коли гра закривається. Вимкніть, якщо сеанс закривається невдовзі після запуску ігор. Ліміт RAM вище все одно стискає Steam, коли сеанс його перевищує. - Ліміт RAM - Діє, поки працює клієнт Steam, у режимі Steam або з робочого столу. Коли сеанс використовує більше цього значення, Steam, а потім інші підтримувані процеси сеансу стискаються в zRAM. Мʼякий ліміт: нічого не закривається, але ігри можуть підвисати, поки сторінки повертаються. - Потрібен своп zRAM, якого на цьому пристрої немає. - Ліміт VRAM - Повідомляє іграм Direct3D 9–12 цей бюджет відеопам’яті для зменшення її використання. Ігри можуть його перевищити; це не додає підкачку пам’яті GPU й не гарантує захисту від збоїв через нестачу пам’яті. Діє з наступного сеансу. Тримати GPU на максимальній частоті - Лише Adreno. Менше запинок, вища витрата заряду та нагрів. Виправлення сеансу Turnip: рендеринг через sysmem Застосовується до клієнта Steam та ігор. Потрібно для Adreno 710/720/722. @@ -815,7 +802,6 @@ Клавіатура ПК Android Другий екран - Режим Показує Додатки Android Запустити додаток @@ -2339,6 +2325,17 @@ Контрольна сума не збіглася; завантаження видалено Під час завантаження розпочався сеанс; зупиніть його, перш ніж встановлювати інструменти сумісності Встановлення %1$s + Експериментальні збірки + Встановити з файлу + Архів містить небезпечне посилання або шлях + Непідтримуваний або недійсний архів + Недостатньо вільного місця для цієї збірки Proton + Розпакування Proton (кілька хвилин) + Не вдалося розпакувати (tar %1$d) + В архіві немає збірки Proton + Не вдалося розмістити збірку Proton + Не вдалося повністю видалити %1$s + Експериментальну збірку Proton встановлено. Виберіть її в Steam → Властивості → Сумісність. Встановлення %1$s не вдалося (код виходу %2$d) Не вдалося встановити %1$s Отримання пакета droiddeck-esync @@ -3391,10 +3388,19 @@ Спільний префікс Steam Steam запускає тут власні допоміжні програми Windows Видаляє його (%1$s). Steam створить новий, коли він знову знадобиться. + Видаляє префікс Wine і кеш шейдерів цього застосунку крамниці (%1$s) разом із входом в обліковий запис і збереженнями, що є лише там. Ігри, які в ньому працюють, отримають новий префікс, а застосунок, можливо, доведеться налаштувати знову. Хмарні збереження лишаються в обліковому записі. + Можна очистити %1$s + Кеші Linux і Steam + Старі тимчасові файли, завантажені пакети й вебкеш Steam + Старі тимчасові файли + Завантажені пакети + Вебкеш Steam + Пошкоджені завантаження Steam + Створюються знову за потреби + Очистити Застосунок магазину та ігри, які з ним працюють Використовується: %1$s Не-Steam гра %1$s - Не зіставлено з грою, тому зберігається Видалити вибрані · %1$s Видалити вибрані · %1$s Префікси Wine @@ -4145,4 +4151,18 @@ Ціле число За розміром Згладжування - \ No newline at end of file + Власна тема + Виберіть окремо кожен колір інтерфейсу. + Тло + Панелі + Підняті панелі + Роздільники + Межі + Основний текст + Вторинний текст + Кнопки й основний акцент + Текст кнопок + Виділення + Успіх + Помилка + diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 873b7398c..5b7328556 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -22,7 +22,6 @@ Thêm thư viện Steam từ thẻ SD, ổ USB hoặc SSD, và DroidDeck sẽ gom các game lại trong Thư viện của bạn. Cửa hàng cho phép bạn đăng nhập Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io và Game Jolt, rồi cài đặt và cập nhật game của họ ngay từ DroidDeck. Các thành phần như FEX, DXVK và VKD3D-Proton tự cập nhật, và mặc định là Proton Experimental ARM64, hoặc Proton 11.0 ARM64 khi bản dựng đó đã được cài. - Nén Steam khi game đang chạy giúp giải phóng RAM trên các thiết bị thiếu bộ nhớ. Vuốt vào từ mép phải để mở menu phiên: chế độ bàn di chuột, Bàn phím PC, độ trễ thấp, hồ sơ game và nhiều hơn nữa. Game chạy chậm? Hãy giới hạn tốc độ khung hình trong Truy cập nhanh, rồi thử phiên bản Proton khác hoặc bộ cài đặt sẵn FEX khác trong các thành phần của game. Âm thanh game bị rè hoặc mất tiếng? Hãy thử bật DirectAudio cho game trong cài đặt Steam, mục Âm thanh. @@ -619,20 +618,8 @@ gamescope: hàng đợi GPU thời gian thực Ưu tiên công việc GPU của compositor. Có thể làm nhịp khung hình mượt hơn với một phần chi phí cho game. GPU - Bộ nhớ Tắt - Mặc định của driver - Nén Steam khi game đang chạy - Nén bộ nhớ game không hoạt động - Nén bộ nhớ game không hoạt động khi RAM thấp. Tắt nếu game bị đứng vài giây khoảng mỗi nửa phút. Áp dụng từ lần khởi động phiên tiếp theo. - 20 giây sau khi game bắt đầu, client Steam được nén vào zRAM để game có thêm bộ nhớ, và được đọc lại khi game đóng. Tắt nếu phiên bị đóng ngay sau khi game bắt đầu. Giới hạn RAM ở trên vẫn nén Steam khi phiên vượt quá mức đó. - Giới hạn RAM - Áp dụng khi client Steam đang chạy, ở chế độ Steam hoặc từ desktop. Khi phiên dùng nhiều hơn mức này, Steam rồi đến các tiến trình được hỗ trợ khác của phiên sẽ bị nén vào zRAM. Giới hạn mềm: không có gì bị đóng, nhưng game có thể giật khi các trang được nạp lại. - Cần swap zRAM, thiết bị này không có. - Giới hạn VRAM - Báo ngân sách bộ nhớ video này cho các trò chơi Direct3D 9 đến 12 để giảm mức dùng bộ nhớ. Trò chơi có thể vượt ngân sách; tính năng này không bổ sung phân trang GPU hay bảo đảm tránh lỗi do hết bộ nhớ. Có hiệu lực ở phiên tiếp theo. Giữ GPU ở xung nhịp cao nhất - Chỉ dành cho Adreno. Ít giật hơn, dùng nhiều pin và nhiệt hơn. Các bản sửa phiên Turnip: render sysmem Áp dụng cho ứng dụng Steam và trò chơi. Bắt buộc trên Adreno 710/720/722. @@ -809,7 +796,6 @@ Bàn phím PC Android Màn hình thứ hai - Chế độ Hiển thị Ứng dụng Android Khởi chạy một ứng dụng @@ -2262,6 +2248,17 @@ Checksum không khớp; tệp tải xuống đã bị xóa Một phiên đã bắt đầu trong khi tải; hãy dừng nó trước khi cài công cụ tương thích Đang cài %1$s + Bản dựng thử nghiệm + Cài đặt từ tệp + Tệp lưu trữ chứa liên kết hoặc đường dẫn không an toàn + Tệp lưu trữ không được hỗ trợ hoặc không hợp lệ + Không đủ dung lượng trống cho bản dựng Proton này + Đang giải nén Proton (vài phút) + Giải nén thất bại (tar %1$d) + Tệp lưu trữ không chứa bản dựng Proton + Không thể đặt bản dựng Proton + Không thể gỡ hoàn toàn %1$s + Đã cài Proton thử nghiệm. Hãy chọn nó trong Steam → Thuộc tính → Tương thích. Cài %1$s thất bại (mã thoát %2$d) Không thể cài %1$s Đang lấy pack droiddeck-esync @@ -3288,10 +3285,19 @@ Prefix Steam dùng chung Steam chạy các trình hỗ trợ Windows riêng tại đây Xóa prefix này (%1$s). Steam sẽ tạo prefix mới vào lần tới khi cần. + Xóa prefix Wine và bộ nhớ đệm shader của ứng dụng cửa hàng này (%1$s), cùng thông tin đăng nhập và các bản lưu chỉ có ở đó. Trò chơi chạy trong đó sẽ nhận prefix mới, và bạn có thể phải thiết lập lại ứng dụng. Bản lưu trên đám mây vẫn còn trong tài khoản của bạn. + Có thể dọn %1$s + Bộ nhớ đệm của Linux và Steam + Tệp tạm cũ, gói đã tải xuống và bộ nhớ đệm web của Steam + Tệp tạm cũ + Gói đã tải xuống + Bộ nhớ đệm web của Steam + Tệp tải xuống Steam bị hỏng + Được tạo lại khi cần + Dọn Một ứng dụng cửa hàng và các game chạy cùng nó Được dùng bởi %1$s Game ngoài Steam %1$s - Không khớp với game nào nên được giữ lại Gỡ mục đã chọn · %1$s Gỡ cài đặt mục đã chọn · %1$s Prefix Wine @@ -4035,4 +4041,18 @@ Số nguyên Vừa màn hình Khử răng cưa - \ No newline at end of file + Tùy chỉnh + Chọn riêng từng màu của giao diện. + Nền + Bảng + Bảng nổi + Đường phân cách + Đường viền + Văn bản chính + Văn bản phụ + Nút và màu nhấn chính + Văn bản trên nút + Điểm nhấn + Thành công + Lỗi + diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 234847fc5..eeddf20d4 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -22,7 +22,6 @@ 可添加 SD 卡、USB 驱动器或 SSD 上的 Steam 游戏库,DroidDeck 会把这些游戏集中在你的库中。 游戏商店让你登录 Epic Games、GOG、Xbox、EA、Battle.net、Ubisoft Connect、Amazon Games、itch.io 和 Game Jolt,然后在 DroidDeck 中安装和更新它们的游戏。 FEX、DXVK 和 VKD3D-Proton 等组件会自动更新,默认使用 Proton Experimental ARM64,安装 Proton 11.0 ARM64 后则默认使用它。 - “游戏运行时压缩 Steam”可在内存不足的设备上释放 RAM。 从右边缘向内滑动可打开会话菜单:触控板模式、PC 键盘、低延迟、游戏配置档案等。 游戏运行缓慢?先在快捷访问中限制帧率,再到游戏的组件中尝试其他 Proton 版本或 FEX 预设。 游戏音频爆音或没有声音?请在 Steam 设置的“音频”下尝试“游戏使用 DirectAudio”开关。 @@ -619,20 +618,8 @@ gamescope:实时 GPU 队列 优先处理合成器的 GPU 工作。可平滑帧节奏,但会牺牲部分游戏性能。 GPU - 内存 关闭 - 驱动默认 - 游戏运行时压缩 Steam - 压缩游戏闲置内存 - RAM 较低时压缩游戏闲置内存。如果游戏大约每半分钟卡顿几秒,请关闭此项。下次启动会话时生效。 - 游戏启动 20 秒后,Steam 客户端会被压缩到 zRAM 中,为游戏腾出更多内存,并在游戏关闭时读回。如果会话在游戏启动后不久就关闭,请关闭此选项。设置了上方的 RAM 上限时,会话超出上限后仍会压缩 Steam。 - RAM 上限 - 在 Steam 客户端运行时生效,无论是 Steam 模式还是从桌面启动。会话使用量超过此值时,会先将 Steam、再将会话中其他受支持的进程压缩到 zRAM。这是软上限:不会关闭任何进程,但在页面读回时游戏可能卡顿。 - 需要 zRAM 交换空间,但此设备不支持。 - VRAM 上限 - 向 Direct3D 9 至 12 游戏报告此显存预算,以促使游戏减少内存使用。游戏可能超出预算;此功能不提供 GPU 分页,也不保证避免内存不足导致的崩溃。下次会话生效。 把 GPU 锁定在最高频率 - 仅限 Adreno。卡顿更少,但更耗电、更发热。 会话修复 Turnip:sysmem 渲染 适用于 Steam 客户端和游戏。Adreno 710/720/722 必需。 @@ -809,7 +796,6 @@ PC 键盘 Android 副屏 - 模式 显示 Android 应用 启动应用 @@ -2339,6 +2325,17 @@ 校验和不匹配;已删除下载的文件 下载期间有会话启动;请先停止它,再安装兼容性工具 正在安装 %1$s + 实验版本 + 从文件安装 + 压缩包包含不安全的链接或路径 + 不支持或无效的压缩包 + 可用空间不足,无法安装此 Proton 版本 + 正在解包 Proton(需要几分钟) + 解包失败(tar %1$d) + 压缩包中不含 Proton 版本 + 无法放置 Proton 版本 + 无法完全移除 %1$s + 实验版 Proton 已安装。请在 Steam → 属性 → 兼容性 中选择。 %1$s 安装失败(退出代码 %2$d) 无法安装 %1$s 正在获取 droiddeck-esync 包 @@ -3288,10 +3285,19 @@ Steam 的共享前缀 Steam 在此运行其自带的 Windows 辅助程序 删除该前缀(%1$s)。Steam 下次需要时会新建一个。 + 删除此商店应用的 Wine 前缀和着色器缓存(%1$s),包括其登录信息和仅存于其中的存档。在其中运行的游戏会获得新的前缀,你可能需要重新设置该应用。云存档仍保留在你的账户中。 + 可清理 %1$s + Linux 和 Steam 缓存 + 旧临时文件、已下载的软件包和 Steam 网页缓存 + 旧临时文件 + 已下载的软件包 + Steam 网页缓存 + 损坏的 Steam 下载 + 需要时会重新生成 + 清理 商店应用及通过它运行的游戏 由 %1$s 使用 非 Steam 游戏 %1$s - 未匹配到游戏,因此保留 移除所选 · %1$s 卸载所选 · %1$s Wine 前缀 @@ -4035,4 +4041,18 @@ 整数 适应 抗锯齿 - \ No newline at end of file + 自定义 + 分别选择界面的每种颜色。 + 背景 + 面板 + 凸起面板 + 分隔线 + 边框 + 主要文本 + 次要文本 + 按钮和主要强调色 + 按钮文字 + 高亮 + 成功 + 错误 + diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index a2eeb3b08..a194530d5 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -22,7 +22,6 @@ 可加入 SD 卡、USB 隨身碟或 SSD 上的 Steam 遊戲庫,DroidDeck 會把這些遊戲集中在你的收藏庫中。 「商店」讓你登入 Epic Games、GOG、Xbox、EA、Battle.net、Ubisoft Connect、Amazon Games、itch.io 和 Game Jolt,然後在 DroidDeck 中安裝和更新它們的遊戲。 FEX、DXVK 和 VKD3D-Proton 等元件會自動更新,預設使用 Proton Experimental ARM64,安裝 Proton 11.0 ARM64 後則預設使用它。 - 「遊戲執行時壓縮 Steam」可在記憶體不足的裝置上釋放 RAM。 從右邊緣向內滑動可開啟工作階段選單:觸控板模式、電腦鍵盤、低延遲、遊戲設定檔等。 遊戲執行緩慢?先在快速存取中限制影格率,再到遊戲的元件中嘗試其他 Proton 版本或 FEX 預設。 遊戲音訊爆音或沒有聲音?請在 Steam 設定的「音訊」下嘗試「遊戲使用 DirectAudio」開關。 @@ -619,20 +618,8 @@ gamescope:即時 GPU 佇列 優先處理合成器的 GPU 工作。可令幀間隔更平穩,但會犧牲少許遊戲效能。 GPU - 記憶體 關閉 - 驅動程式預設 - 遊戲執行時壓縮 Steam - 壓縮遊戲閒置記憶體 - RAM 偏低時壓縮遊戲閒置記憶體。如果遊戲大約每半分鐘凍結幾秒,請關閉此項。下次啟動工作階段時生效。 - 遊戲啟動 20 秒後,Steam 用戶端會被壓縮到 zRAM,為遊戲騰出更多記憶體,並在遊戲關閉時讀回。如果會話在遊戲啟動後不久就關閉,請關閉此選項。若超過上方的 RAM 上限,會話仍會壓縮 Steam。 - RAM 上限 - 在 Steam 用戶端執行時生效,無論是 Steam 模式或從桌面啟動。當會話的用量超過此值時,會先將 Steam、再將會話中其他受支援的程序壓縮到 zRAM。這是軟性上限:不會關閉任何程式,但在分頁讀回時遊戲可能會卡頓。 - 需要 zRAM 交換空間,但此裝置沒有。 - VRAM 上限 - 向 Direct3D 9 至 12 遊戲報告此顯存預算,以促使遊戲減少記憶體用量。遊戲可能超出預算;此功能不提供 GPU 分頁,也不保證避免因記憶體不足而崩潰。下次工作階段生效。 讓 GPU 保持最高頻率 - 只限 Adreno。減少卡頓,但更耗電、更發熱。 會話修正 Turnip:sysmem 渲染 適用於 Steam 用戶端和遊戲。Adreno 710/720/722 必須開啟。 @@ -809,7 +796,6 @@ 電腦鍵盤 Android 第二螢幕 - 模式 顯示 Android 應用程式 啟動應用程式 @@ -2261,6 +2247,17 @@ 校驗和不符;已刪除下載的檔案 下載期間有會話啟動;請先停止該會話,再安裝兼容性工具 正在安裝 %1$s + 實驗版本 + 從檔案安裝 + 壓縮檔包含不安全的連結或路徑 + 不支援或無效的壓縮檔 + 可用空間不足,無法安裝此 Proton 版本 + 正在解包 Proton(需要幾分鐘) + 解包失敗(tar %1$d) + 壓縮檔中不含 Proton 版本 + 無法放置 Proton 版本 + 無法完全移除 %1$s + 實驗版 Proton 已安裝。請在 Steam → 內容 → 相容性 中選擇。 %1$s 安裝失敗(結束代碼 %2$d) 無法安裝 %1$s 正在下載 droiddeck-esync 套件 @@ -3285,10 +3282,19 @@ Steam 的共用前綴 Steam 在此執行其自帶的 Windows 輔助程式 刪除該前綴(%1$s)。Steam 下次需要時會新建一個。 + 刪除此商店應用程式的 Wine 前綴和著色器快取(%1$s),包括其登入資料和只存於其中的存檔。在其中執行的遊戲會獲得新的前綴,你可能需要重新設定該應用程式。雲端存檔仍會保留在你的帳戶中。 + 可清理 %1$s + Linux 和 Steam 快取 + 舊暫存檔、已下載的套件和 Steam 網頁快取 + 舊暫存檔 + 已下載的套件 + Steam 網頁快取 + 損壞的 Steam 下載 + 需要時會重新建立 + 清理 商店應用程式及透過它執行的遊戲 由 %1$s 使用 非 Steam 遊戲 %1$s - 未配對到任何遊戲,因此保留 移除所選 · %1$s 解除安裝所選 · %1$s Wine 前綴 @@ -4035,4 +4041,18 @@ 整數 配合畫面 抗鋸齒 - \ No newline at end of file + 自訂 + 分別選擇介面的每種顏色。 + 背景 + 面板 + 凸起面板 + 分隔線 + 邊框 + 主要文字 + 次要文字 + 按鈕和主要強調色 + 按鈕文字 + 重點標示 + 成功 + 錯誤 + diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 76d7d67f3..82c63ad01 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -22,7 +22,6 @@ 可加入 SD 卡、USB 隨身碟或 SSD 上的 Steam 遊戲庫,DroidDeck 會把這些遊戲集中在你的收藏庫中。 「遊戲商店」讓你登入 Epic Games、GOG、Xbox、EA、Battle.net、Ubisoft Connect、Amazon Games、itch.io 和 Game Jolt,然後在 DroidDeck 中安裝和更新它們的遊戲。 FEX、DXVK 和 VKD3D-Proton 等元件會自動更新,預設使用 Proton Experimental ARM64,安裝 Proton 11.0 ARM64 後則預設使用它。 - 「遊戲執行時壓縮 Steam」可在記憶體不足的裝置上釋放 RAM。 從右邊緣向內滑動可開啟工作階段選單:觸控板模式、電腦鍵盤、低延遲、遊戲設定檔等。 遊戲執行緩慢?先在快速存取中限制影格率,再到遊戲的元件中嘗試其他 Proton 版本或 FEX 預設。 遊戲音訊爆音或沒有聲音?請在 Steam 設定的「音訊」下嘗試「遊戲使用 DirectAudio」開關。 @@ -619,20 +618,8 @@ gamescope:即時 GPU 佇列 提高合成器 GPU 工作的優先順序。可能改善影格時間穩定性,但會佔用一部分遊戲效能。 GPU - 記憶體 關閉 - 驅動程式預設值 - 遊戲執行時壓縮 Steam - 壓縮遊戲閒置記憶體 - RAM 偏低時壓縮遊戲閒置記憶體。如果遊戲大約每半分鐘凍結幾秒,請關閉此項。下次啟動工作階段時生效。 - 遊戲啟動 20 秒後,Steam 用戶端會被壓縮到 zRAM,為遊戲騰出更多記憶體,並在遊戲關閉時讀回。如果工作階段在遊戲啟動後不久就關閉,請關閉此選項。若超過上方的 RAM 上限,工作階段仍會壓縮 Steam。 - RAM 上限 - 在 Steam 用戶端執行時生效,無論是 Steam 模式或從桌面啟動。當工作階段的用量超過此值時,會先將 Steam、再將工作階段中其他受支援的程序壓縮到 zRAM。這是軟性上限:不會關閉任何程式,但在分頁讀回時遊戲可能會卡頓。 - 需要 zRAM 交換空間,但這部裝置沒有。 - VRAM 上限 - 向 Direct3D 9 至 12 遊戲回報此顯示記憶體預算,以促使遊戲減少記憶體使用量。遊戲可能超出預算;此功能不提供 GPU 分頁,也不保證避免記憶體不足造成的當機。下次工作階段生效。 讓 GPU 保持最高頻率 - 僅適用於 Adreno。卡頓更少,但耗電和發熱更多。 工作階段修復 Turnip:sysmem 渲染 適用於 Steam 用戶端和遊戲。Adreno 710/720/722 必需。 @@ -809,7 +796,6 @@ 電腦鍵盤 Android 第二螢幕 - 模式 顯示 Android 應用程式 啟動應用程式 @@ -2261,6 +2247,17 @@ 校驗碼不符;已刪除下載內容 下載期間有工作階段啟動;請先停止它,再安裝相容性工具 正在安裝 %1$s + 實驗版本 + 從檔案安裝 + 壓縮檔包含不安全的連結或路徑 + 不支援或無效的壓縮檔 + 可用空間不足,無法安裝此 Proton 版本 + 正在解包 Proton(需要幾分鐘) + 解包失敗(tar %1$d) + 壓縮檔中不含 Proton 版本 + 無法放置 Proton 版本 + 無法完全移除 %1$s + 實驗版 Proton 已安裝。請在 Steam → 內容 → 相容性 中選擇。 %1$s 安裝失敗(結束代碼 %2$d) 無法安裝 %1$s 正在取得 droiddeck-esync 套件 @@ -3285,10 +3282,19 @@ Steam 的共用前綴 Steam 在此執行其自帶的 Windows 輔助程式 刪除該前綴(%1$s)。Steam 下次需要時會新建一個。 + 刪除此商店應用程式的 Wine 前置詞和著色器快取(%1$s),包括其登入資訊和僅存於其中的存檔。在其中執行的遊戲會取得新的前置詞,你可能需要重新設定該應用程式。雲端存檔仍會保留在你的帳戶中。 + 可清除 %1$s + Linux 和 Steam 快取 + 舊暫存檔、已下載的套件和 Steam 網頁快取 + 舊暫存檔 + 已下載的套件 + Steam 網頁快取 + 損毀的 Steam 下載 + 需要時會重新建立 + 清除 商店應用程式及透過它執行的遊戲 由 %1$s 使用 非 Steam 遊戲 %1$s - 未配對到任何遊戲,因此保留 移除所選 · %1$s 解除安裝所選 · %1$s Wine 前綴 @@ -4035,4 +4041,18 @@ 整數 符合畫面 抗鋸齒 - \ No newline at end of file + 自訂 + 分別選擇介面的每種顏色。 + 背景 + 面板 + 浮起面板 + 分隔線 + 邊框 + 主要文字 + 次要文字 + 按鈕與主要強調色 + 按鈕文字 + 醒目標示 + 成功 + 錯誤 + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1249173b3..0267b4c09 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -49,7 +49,6 @@ Add Steam libraries from an SD card, USB drive or SSD, and DroidDeck keeps the games together in your Library. Stores lets you sign in to Epic Games, GOG, Xbox, EA, Battle.net, Ubisoft Connect, Amazon Games, itch.io and Game Jolt, then install and update their games from DroidDeck. Components like FEX, DXVK and VKD3D-Proton update themselves, and Proton Experimental ARM64 is the default, or Proton 11.0 ARM64 once that build is installed. - Compress Steam while a game runs frees RAM on devices that run low. Swipe in from the right edge to open the session menu: touchpad mode, PC keyboard, low latency, game profile and more. Game running slow? Cap the frame rate in Quick Access, then try another Proton version or FEX preset in the game\'s components. Crackling or missing game audio? Try the DirectAudio for games toggle in Steam settings under Audio. @@ -677,20 +676,8 @@ gamescope: realtime GPU queue Prioritizes the compositor\'s GPU work. Can smooth frame pacing at some cost to games. GPU - Memory Off - Driver default - Compress Steam while a game runs - Compress idle game memory - Pages out idle game memory when RAM is low. Turn this off if games freeze for a few seconds about every half minute. Applies the next time the session starts. - Compresses Steam while a game runs, starting sooner when memory is tight. Steam is read back after the game closes once enough RAM is available. Turn this off if the session closes shortly after games start. A RAM cap above still compresses Steam when the session goes over it. - RAM cap - Applies while the Steam client runs, in Steam mode or from the desktop. When the session uses more than this, Steam and then the session\'s other supported processes are compressed into zRAM. A soft cap: nothing is closed, but games may stutter while pages come back. - Needs zRAM swap, which this device does not have. - VRAM cap - Reports this video memory budget to Direct3D 9 to 12 games to encourage lower memory use. Games may exceed it; this does not add GPU paging or guarantee protection from out-of-memory crashes. Takes effect at the next session. Hold the GPU at its top clock - Adreno only. Fewer hitches, more battery use and heat. Session fixes Turnip: sysmem rendering Applies to the Steam client and games. Required on Adreno 710/720/722. @@ -896,7 +883,6 @@ PC keyboard Android Second screen - Mode Shows Android apps Launch an app @@ -1795,6 +1781,7 @@ This launcher cannot add shortcuts. Use Copy launch link instead. Invalid game launch link. This game is no longer in your DroidDeck library. + Add this game to DroidDeck first, then start it from your frontend. Stop the current session before launching a Steam game. Could not send the game to Steam. Try launching it again. %1$s is a UWP app. This runtime has no Windows app-model host to start it. @@ -2057,6 +2044,20 @@ Saturation Brightness Hex color + Custom + Choose each interface color independently. + Background + Panels + Raised panels + Dividers + Borders + Main text + Secondary text + Buttons and main accent + Button text + Highlights + Success + Error Esc Ins Del @@ -2255,6 +2256,8 @@ Deck grips + trackpads Dashboard Desktop + Second screen: %1$s + Last used Start the desktop Desktop · %1$s Trackpad @@ -2538,6 +2541,17 @@ Checksum mismatch; the download was deleted A session started during the download; stop it before installing compatibility tools Installing %1$s + Experimental builds + Install from file + Archive contains an unsafe link or path + Unsupported or invalid archive + Not enough free space for this Proton build + Unpacking Proton (a few minutes) + Unpacking failed (tar %1$d) + The archive holds no Proton build + Could not place the Proton build + Could not fully remove %1$s + Experimental Proton installed. Pick it in Steam → Properties → Compatibility. %1$s installation failed (exit %2$d) Could not install %1$s Fetching droiddeck-esync pack @@ -2895,6 +2909,8 @@ Already up to date Sign in to the store to sync saves Saves were not synced + Some saves were not synced · %1$s + Cloud conflict · %1$d files · %2$s installed in your library store @@ -3617,10 +3633,19 @@ Steam’s shared prefix Steam runs its own Windows helpers here Deletes it (%1$s). Steam makes a new one the next time it needs it. + Deletes this store app’s Wine prefix and shader cache (%1$s), with its sign-in and any saves kept only there. Games that run in it get a fresh prefix, and you may need to set the app up again. Cloud saves stay in your account. + %1$s can be cleared + Linux and Steam caches + Old temporary files, downloaded packages and Steam’s web cache + Old temporary files + Downloaded packages + Steam web cache + Damaged Steam downloads + Made again when needed + Clear A store app and the games that run with it Used by %1$s Non-Steam game %1$s - Not matched to a game, so it is kept Remove selected · %1$s Uninstall selected · %1$s Wine prefixes @@ -4262,6 +4287,24 @@ Steam or Desktop options (swipe up) Steam quick menu (•••) Logs + UI zoo + Screens that are hard to reach, shown only when you pick one + Open + Show + Previews change nothing real: nothing is installed, removed or signed out, and the menu\'s switches save nothing. A Library preview stays until you end it from its pill or restart. + Library + Nothing installed + Signed out of every store + Sample games in every store + Preview: %1$s + End preview + Real library + Preview a state + Preview shortcuts + Adds a preview button where a state lives, such as the Library\'s toolbar, to switch states in place + Previews are read-only. End the preview to open games. + In-game menu + In-game menu preview · Back to close Tabs Storage Syncthing @@ -4289,6 +4332,12 @@ Store accounts Sign in Sign out + Manage stores + All games + Custom games + Not signed in + Login expired + Uses an API key Reset Reset tabs Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More. diff --git a/app/src/main/rust/stores/src/ubisoft/ffi.rs b/app/src/main/rust/stores/src/ubisoft/ffi.rs index 30df1ccd4..9cfbb9780 100644 --- a/app/src/main/rust/stores/src/ubisoft/ffi.rs +++ b/app/src/main/rust/stores/src/ubisoft/ffi.rs @@ -75,6 +75,33 @@ fn denuvo(ticket: &str, session: &str, product: u32, challenge: &str) -> Result< }) } +fn cloud_urls(request: &serde_json::Value) -> Result { + let s = |k: &str| request.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); + let product = request.get("productId").and_then(|v| v.as_u64()).unwrap_or(0) as u32; + let method = match s("method").as_str() { + "put" => super::service::CLOUD_PUT, + "get" => super::service::CLOUD_GET, + other => return Err(format!("unknown cloud save method {other}")), + }; + let items: Vec = request.get("items").and_then(|v| v.as_array()).ok_or("no items")?.iter().map(|i| super::service::CloudItem { + name: i.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(), + size: i.get("size").and_then(|v| v.as_u64()).unwrap_or(0), + md5_base64: i.get("md5").and_then(|v| v.as_str()).unwrap_or("").to_string(), + }).collect(); + if items.is_empty() || items.iter().any(|i| i.name.is_empty()) { + return Err("cloud save items need names".into()); + } + let (ticket, session) = (s("ticket"), s("sessionId")); + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())?; + rt.block_on(async { + let mut d = super::demux::Demux::connect(&ticket).await?; + let (mut ownership, _) = super::service::Ownership::open(&mut d, &ticket, &session).await?; + let token = ownership.token(&mut d, product).await?; + let signed = super::service::cloudsave_urls(&mut d, &token, product, method, &items).await?; + Ok(json!({ "requests": signed.iter().map(|r| json!({ "url": r.url, "header": r.header })).collect::>() })) + }) +} + fn call(op: &str, request: &str) -> String { let parsed: serde_json::Value = serde_json::from_str(request).unwrap_or(serde_json::Value::Null); let s = |k: &str| parsed.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); @@ -86,6 +113,7 @@ fn call(op: &str, request: &str) -> String { .and_then(|r| install::chunks(&r)) .map(|m| json!({ "chunks": install::chunks_json(&m.chunks), "setup": install::setup_json(&m) })) .unwrap_or_else(|e| json!({ "error": e })), + "cloud-urls" => cloud_urls(&parsed).unwrap_or_else(|e| json!({ "error": e })), "launch" => launch(&s("ticket"), &s("sessionId"), parsed.get("productId").and_then(|v| v.as_u64()).unwrap_or(0) as u32) .unwrap_or_else(|e| json!({ "error": e })), _ => json!({ "error": format!("unknown operation {op}") }), diff --git a/app/src/main/rust/stores/src/ubisoft/service.rs b/app/src/main/rust/stores/src/ubisoft/service.rs index bfdddc29a..de8e724d0 100644 --- a/app/src/main/rust/stores/src/ubisoft/service.rs +++ b/app/src/main/rust/stores/src/ubisoft/service.rs @@ -204,3 +204,48 @@ pub async fn denuvo_token(d: &mut Demux, ownership_token: &str, challenge: &[u8] let t = pb::fields(pb::sub(&rsp, 3).ok_or("no game token answer")?)?; pb::sub(&t, 1).filter(|b| !b.is_empty()).map(<[u8]>::to_vec).ok_or_else(|| "Ubisoft sent an empty game token".into()) } + +pub struct CloudItem { + pub name: String, + pub size: u64, + pub md5_base64: String, +} + +pub struct SignedRequest { + pub header: String, + pub url: String, +} + +pub const CLOUD_PUT: u64 = 1; +pub const CLOUD_GET: u64 = 2; + +pub async fn cloudsave_urls(d: &mut Demux, ownership_token: &str, product_id: u32, method: u64, items: &[CloudItem]) -> Result, String> { + let conn = d.open("cloudsave_service").await?; + let mut req = Msg::new().text(1, ownership_token).uint(2, product_id as u64).uint(3, method); + for item in items { + let mut entry = Msg::new().text(1, &item.name); + if method == CLOUD_PUT { + entry = entry.msg(2, Msg::new().uint(1, item.size).text(2, &item.md5_base64)); + } + req = req.msg(4, entry); + } + let raw = d.call(conn, Msg::new().msg(1, Msg::new().uint(1, 1).msg(2, req))).await?; + let rsp = pb::fields(pb::sub(&pb::fields(&raw)?, 1).ok_or("no cloud save answer")?)?; + let urls = pb::fields(pb::sub(&rsp, 2).ok_or("no cloud save URLs")?)?; + let status = pb::num(&urls, 1).unwrap_or(0); + if status != 1 { + return Err(format!("Ubisoft's cloud save service refused the request (status {status})")); + } + let mut out = Vec::new(); + for r in pb::subs(&urls, 2) { + let r = pb::fields(r)?; + out.push(SignedRequest { + header: pb::string(&r, 1).unwrap_or_default(), + url: pb::string(&r, 2).ok_or("cloud save URL missing")?, + }); + } + if out.len() != items.len() { + return Err(format!("Ubisoft signed {} of {} cloud save requests", out.len(), items.len())); + } + Ok(out) +} diff --git a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt index 14dbdb833..2e06a6d8f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt @@ -7,6 +7,7 @@ import android.os.Looper import androidx.compose.ui.geometry.Rect import com.droiddeck.launcher.frontend.AutoComponents import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.ExperimentalProtons import com.droiddeck.launcher.session.ProtonExtras import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionPhase @@ -25,7 +26,9 @@ import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import org.robolectric.util.ReflectionHelpers import java.io.File +import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger @RunWith(RobolectricTestRunner::class) @Config(sdk = [28], manifest = Config.NONE) @@ -88,6 +91,67 @@ class ProtonMenuAutoTest { File(this, "proton").apply { writeText(""); setExecutable(true) } } + private fun prerelease(tag: String) = ExperimentalProtons.Release(tag, "$tag.tar.xz", "https://github.com/o/r/releases/download/$tag/$tag.tar.xz", null, 1L) + + private fun recreatedMenu(refreshes: AtomicInteger, tag: String) = ProtonMenu(activity, Handler(Looper.getMainLooper())) { idle }.apply { + installer = menu.installer + latestCheck = { false } + experimentalRefresh = { + refreshes.incrementAndGet() + listOf(prerelease(tag)) + } + } + + @Test + fun aRecreatedMenuJoinsTheRunningRefresh() { + idle = false + val started = CountDownLatch(1) + val gate = CountDownLatch(1) + val refreshes = AtomicInteger() + menu.latestCheck = { false } + menu.experimentalRefresh = { + started.countDown() + gate.await(5, TimeUnit.SECONDS) + listOf(prerelease("first")) + } + menu.checkUpdates() + assertTrue(started.await(5, TimeUnit.SECONDS)) + val recreated = recreatedMenu(refreshes, "second") + recreated.checkUpdates() + gate.countDown() + waitUntil { recreated.experimentalReleases.map { it.tag } == listOf("first") } + assertEquals(0, refreshes.get()) + recreated.checkUpdates() + waitUntil { recreated.experimentalReleases.map { it.tag } == listOf("second") } + assertEquals(1, refreshes.get()) + } + + @Test + fun aFinishedRefreshIsPublishedBeforeTheNextOneStarts() { + idle = false + val finished = CountDownLatch(1) + val refreshes = AtomicInteger() + menu.experimentalReleases = emptyList() + menu.latestCheck = { false } + menu.experimentalRefresh = { + finished.countDown() + listOf(prerelease("older")) + } + menu.checkUpdates() + assertTrue(finished.await(5, TimeUnit.SECONDS)) + val recreated = recreatedMenu(refreshes, "newer") + repeat(20) { + recreated.checkUpdates() + Thread.sleep(10) + } + assertEquals(0, refreshes.get()) + assertTrue(recreated.experimentalReleases.isEmpty()) + waitUntil { recreated.experimentalReleases.map { it.tag } == listOf("older") } + recreated.checkUpdates() + waitUntil { recreated.experimentalReleases.map { it.tag } == listOf("newer") } + assertEquals(1, refreshes.get()) + } + private fun waitUntil(done: () -> Boolean) { val deadline = System.nanoTime() + 5_000_000_000L while (System.nanoTime() < deadline) { diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt index bcae5c8fe..b5f58de79 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt @@ -33,27 +33,64 @@ class GameFilesTest { assertEquals("18446744073709551615", file.readText()) val context = RuntimeEnvironment.getApplication() listOf(Uri.fromFile(file), Uri.parse(file.path)).forEach { uri -> - assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))) + assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))?.id) } val provider = LaunchFileProvider(file) provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend" }) ShadowContentResolver.registerProviderInternal("frontend", provider) val uri = Uri.parse("content://frontend/document/opaque%3A42") - assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))) + assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))?.id) + } + + @Test fun readsIdsFromEveryFrontendFileFormat() { + listOf("8400\n", "steam://rungameid/8400", "droiddeck://game/8400", + "# Daijishou Player Template\n[steamappid] 8400\n", "# DST\n[steamappid] 8400\n", + "[InternetShortcut]\r\nIconIndex=0\r\nURL=steam://rungameid/8400\r\nIconFile=C:\\steam.ico\r\n").forEach { value -> + assertEquals(value, "8400", GameFiles.read(ByteArrayInputStream(value.toByteArray()))) + } } @Test fun rejectsCommandsMalformedIdsLargeFilesAndUnsupportedIntents() { - listOf("", "0", "01", "-1", "18446744073709551616", "steam://rungameid/8400", - "8400\n8401", "droiddeck://game/8400", "droiddeck://game/8400?command=quit", "x".repeat(129)).forEach { value -> + listOf("", "0", "01", "-1", "18446744073709551616", "steam://rungameid/8400?x=1", "steam://run/8400", + "8400\n8401", "droiddeck://game/8400?command=quit", "x".repeat(4097), + "[InternetShortcut]\nURL=https://example.com/8400", "[InternetShortcut]\nURL=8400", + "# Daijishou Player Template\n[epicappid] 8400").forEach { value -> assertNull(value, GameFiles.read(ByteArrayInputStream(value.toByteArray()))) } - assertEquals("8400", GameFiles.read(ByteArrayInputStream("8400\n".toByteArray()))) val context = RuntimeEnvironment.getApplication() assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_SEND, Uri.parse("droiddeck://game/8400")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/8400.steam")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("file://remote/game.steam")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(File(tmp.root, "missing.steam"))))) - assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("droiddeck://game/8400")))) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("droiddeck://game/8400")))?.id) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("8400")))?.id) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("steam://rungameid/8400")))?.id) + } + + @Test fun storeFilesCarryTheirSourceAndTitle() { + val context = RuntimeEnvironment.getApplication() + val epic = File(tmp.root, "Hades II.epic").apply { writeText("17") } + val request = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(epic)))!! + assertEquals("epic", request.source) + assertEquals("Hades II", request.title) + val daijishou = File(tmp.root, "Portal.steamappid").apply { writeText("# Daijishou Player Template\n[steamappid] 400\n") } + val steam = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(daijishou)))!! + assertEquals(Library.SOURCE_STEAM, steam.source) + assertEquals("400", steam.id) + } + + @Test fun programFilesArriveAsPathsNotContents() { + val context = RuntimeEnvironment.getApplication() + val exe = File(tmp.newFolder("Game"), "Game.exe").apply { writeBytes(byteArrayOf(0x4d, 0x5a)) } + val request = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(exe)))!! + assertEquals(exe.canonicalFile, request.program) + assertNull(request.id) + val provider = LaunchFileProvider(exe) + provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend.files" }) + ShadowContentResolver.registerProviderInternal("frontend.files", provider) + val shared = Uri.parse("content://frontend.files/root" + exe.canonicalPath) + assertEquals(exe.canonicalFile, GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, shared))?.program) + assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(File(exe.parentFile, "Missing.exe"))))) } @Test fun exportsGameIconBeforeCapsuleAndPreservesCustomArtwork() { @@ -185,13 +222,32 @@ class GameFilesTest { val file = GameFiles.export(app, folder, game("620", "Portal 2")) assertEquals("Portal 2.steam", file.name) assertEquals("620", file.readText()) - assertEquals("620", GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))) + assertEquals("620", GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))?.id) val added = Library.SteamGame(1, "Added Game", null, Library.ADDED, -1L) val addedFile = GameFiles.export(app, folder, added) assertEquals("Added Game.steam", addedFile.name) assertEquals("18446744073709551615", addedFile.readText()) } + @Test fun storeGamesExportUnderTheirStoreExtensionAndLaunchBack() { + val folder = tmp.newFolder() + val forza = Library.SteamGame(1, "Forza Horizon 5", null, Library.ADDED, -7L, source = "xbox", storeId = "9NKX70BBCDRN") + val steam = File(folder, "Forza Horizon 5.steam").apply { writeText(forza.gameIdString) } + File(folder, ".droiddeck-sync.json").writeText( + """{"format":"droiddeck-game-files-v1","games":{"Forza Horizon 5.steam":"${forza.gameIdString}"}}""") + GameFiles.sync(app, folder, listOf(forza)) + val file = File(folder, "Forza Horizon 5.xbox") + assertEquals(forza.gameIdString, file.readText()) + assertFalse(steam.exists()) + val request = GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))!! + assertEquals("xbox", request.source) + assertSame(forza, request.find(listOf(game("620", "Portal 2"), forza))) + listOf("ubisoft", "ea", "rockstar", "battlenet", "itch", "gamejolt", "epic", "gog", "amazon").forEach { store -> + val game = Library.SteamGame(1, "Game", null, Library.ADDED, -8L, source = store) + assertEquals("Game.$store", GameFiles.filename(game)) + } + } + @Test fun steamSyncDisambiguatesTitlesAndPreservesEditedAndForeignFiles() { val folder = tmp.newFolder() val first = game("620", "A/B") diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt index 002085daf..63b6807c0 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt @@ -14,29 +14,41 @@ class GameLaunchIntentTest { @Test fun acceptsNativeAndExplicitlyRetargetedGameNativeProfiles() { listOf(GameLaunchIntent.ACTION, "app.gamenative.LAUNCH_GAME").forEach { action -> val request = Intent(action).putExtra("app_id", 620).putExtra("game_source", "STEAM") - assertEquals("620", GameLaunchIntent.read(RuntimeEnvironment.getApplication(), request)) - assertEquals("8400", GameLaunchIntent.readId(Intent(action).putExtra("app_id", "8400"))) - assertEquals("620", GameLaunchIntent.readId(request.putExtra("game_source", "steam"))) + assertEquals("620", GameLaunchIntent.read(RuntimeEnvironment.getApplication(), request)?.id) + assertEquals("8400", GameLaunchIntent.readExtras(Intent(action).putExtra("app_id", "8400"))?.id) + assertEquals("620", GameLaunchIntent.readExtras(request.putExtra("game_source", "steam"))?.id) } } - @Test fun stringIdsPreserveUnsignedShortcutIds() { + @Test fun longAndStringIdsPreserveUnsignedShortcutIds() { listOf("2147483648", "18446744073709551615").forEach { id -> - assertEquals(id, GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) + assertEquals(id, GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))?.id) + } + assertEquals("620", GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620L))?.id) + assertEquals("18446744073709551615", GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1L))?.id) + } + + @Test fun storeSourcesComeThroughForLibraryMatching() { + mapOf("EPIC" to "epic", "gog" to "gog", "AMAZON" to "amazon", "XBOX" to "xbox", "UBISOFT" to "ubisoft", + "EA" to "ea", "ROCKSTAR" to "rockstar", "BATTLENET" to "battlenet", "ITCH" to "itch", "GAMEJOLT" to "gamejolt", + "CUSTOM_GAME" to Library.ADDED).forEach { (name, source) -> + val request = GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 1207658924).putExtra("game_source", name)) + assertEquals(name, source, request?.source) + assertEquals("1207658924", request?.id) } } @Test fun rejectsUnsupportedSourcesTypesAndIdsWithoutFallingBackToData() { listOf("", "0", "01", "+1", "-1", "18446744073709551616", "620\n", "steam://rungameid/620").forEach { id -> - assertNull(id, GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) + assertNull(id, GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) } - listOf("EPIC", "GOG", "CUSTOM_GAME", "", "STEAM ").forEach { source -> - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", source))) + listOf("STADIA", "", "STEAM ", "added").forEach { source -> + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", source))) } - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620L))) - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1))) - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", 1))) - assertNull(GameLaunchIntent.readId(Intent(Intent.ACTION_MAIN).putExtra("app_id", 620))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 0L))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", 1))) + assertNull(GameLaunchIntent.readExtras(Intent(Intent.ACTION_MAIN).putExtra("app_id", 620))) assertNull(GameLaunchIntent.read(RuntimeEnvironment.getApplication(), Intent(GameLaunchIntent.ACTION, android.net.Uri.parse("droiddeck://game/620")))) } @@ -44,7 +56,7 @@ class GameLaunchIntentTest { @Test fun deepLinksStillAcceptUnsignedShortcutIds() { val context = RuntimeEnvironment.getApplication() assertEquals("18446744073709551615", GameLaunchIntent.read(context, - Intent(Intent.ACTION_VIEW, android.net.Uri.parse("droiddeck://game/18446744073709551615")))) + Intent(Intent.ACTION_VIEW, android.net.Uri.parse("droiddeck://game/18446744073709551615")))?.id) assertFalse(GameLaunchIntent.accepts(Intent.ACTION_SEND)) assertTrue(GameLaunchIntent.accepts(GameLaunchIntent.ACTION)) } diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt new file mode 100644 index 000000000..d7a50728c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.frontend + +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class GameRequestTest { + @get:Rule val tmp = TemporaryFolder() + + private fun game(id: Long, name: String, source: String = Library.SOURCE_STEAM, storeId: String? = null, files: File? = null, + library: String = "internal", appId: Int = id.toInt()) = + Library.SteamGame(appId, name, null, library, id, gameFiles = files, source = source, storeId = storeId) + + @Test fun steamIdsMatchTheGameIdOrAnAddedGamesSteamAppId() { + val portal = game(400, "Portal") + val added = game(-1L, "Celeste", library = Library.ADDED, source = Library.ADDED, appId = 504230) + val games = listOf(portal, added) + assertSame(portal, GameRequest("400").find(games)) + assertSame(added, GameRequest("18446744073709551615").find(games)) + assertSame(added, GameRequest("504230").find(games)) + assertNull(GameRequest("401").find(games)) + } + + @Test fun titleMatchingWaitsForTheFullScan() { + val cached = game(-2L, "Example", source = "gog", storeId = "111") + assertNull(GameRequest("222", "gog", "Example").find(listOf(cached), byTitle = false)) + assertSame(cached, GameRequest("222", "gog", "Example").find(listOf(cached))) + assertSame(cached, GameRequest("111", "gog", "Other").find(listOf(cached), byTitle = false)) + } + + @Test fun gogMatchesItsProductIdThenTitle() { + val witcher = game(-2L, "The Witcher 3: Wild Hunt", source = "gog", storeId = "1207664663") + val games = listOf(game(292030, "The Witcher 3: Wild Hunt"), witcher) + assertSame(witcher, GameRequest("1207664663", "gog").find(games)) + assertSame(witcher, GameRequest("5", "gog", "The Witcher 3 Wild Hunt").find(games)) + } + + @Test fun storesWithAppLocalIdsMatchByTitleWithinTheirStore() { + val hades = game(-3L, "Hades II", source = "epic", storeId = "Ixion") + val custom = game(-4L, "Cave Story+", library = Library.ADDED, source = Library.ADDED) + val games = listOf(game(1145350, "Hades II"), hades, custom) + assertSame(hades, GameRequest("17", "epic", "hades ii").find(games)) + assertSame(custom, GameRequest("9", Library.ADDED, "Cave Story").find(games)) + assertNull(GameRequest("17", "epic").find(games)) + assertNull(GameRequest("17", "amazon", "Hades II").find(games)) + } + + @Test fun programsStartTheDeepestGameThatOwnsThem() { + val root = tmp.newFolder("Games") + val suite = File(root, "Suite").apply { mkdirs() } + val inner = File(suite, "Episode 2").apply { mkdirs() } + val outer = game(-5L, "Suite", files = suite) + val episode = game(-6L, "Episode 2", files = inner) + val games = listOf(outer, episode) + assertSame(episode, GameRequest(program = File(inner, "bin/game.exe")).find(games)) + assertSame(outer, GameRequest(program = File(suite, "launcher.exe")).find(games)) + assertNull(GameRequest(program = File(root, "Other/other.exe")).find(games)) + assertNull(GameRequest(program = File(root, "Suite2/game.exe")).find(games)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/ClockLogComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/ClockLogComponentTest.kt index 1dc1d6b6a..fed4553bf 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/ClockLogComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/ClockLogComponentTest.kt @@ -3,6 +3,8 @@ package com.droiddeck.launcher.gpu import android.content.Intent import android.os.BatteryManager import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test @@ -40,4 +42,68 @@ class ClockLogComponentTest { clocks = ClockLogComponent(log).also { it.attach(context); it.stop(); it.start() } assertTrue(log.readText(), log.length() == 0L) } + @Test fun gpuStepsAndCeilingAreParsedAndPrinted() { + val table = tmp.newFile("gpu_available_frequencies").apply { writeText("443000000 350000000 285000000 160000000\n") } + val ceiling = tmp.newFile("max_gpuclk").apply { writeText("285000000\n") } + val floor = tmp.newFile("min_clock_mhz").apply { writeText("160\n") } + val clock = tmp.newFile("gpu_clock").apply { writeText("230\n") } + val steps = GpuLimits.first(listOf(tmp.root.path + "/missing", table.path))!! + assertEquals(listOf(160L, 285L, 350L, 443L), steps.mhz) + assertEquals( + listOf( + "gpu steps: 160 285 350 443 MHz from ${table.path}", + "gpu ceiling from: ${ceiling.path}", + "gpu floor: 160 MHz from ${floor.path}", + ), + ClockLogComponent.limitLines(steps, ceiling.path, GpuLimits.first(listOf(floor.path))), + ) + assertEquals(" | gpu 230/285(of 443) MHz", ClockLogComponent.gpuField(clock.path, ceiling.path, steps.mhz.last())) + ceiling.writeText("443000000\n") + assertEquals(" | gpu 230/443 MHz", ClockLogComponent.gpuField(clock.path, ceiling.path, steps.mhz.last())) + } + + @Test fun aZeroCeilingIsNotALimit() { + val clock = tmp.newFile("gpu_clock").apply { writeText("0\n") } + val zero = tmp.newFile("max_gpuclk").apply { writeText("0\n") } + assertEquals(" | gpu 0 MHz", ClockLogComponent.gpuField(clock.path, zero.path, 443)) + assertEquals(listOf("gpu limit ${zero.path}: refused"), ClockLogComponent.probeLines("gpu limit", listOf(zero.path), ClockLogComponent::limit)) + assertEquals(listOf("gpu source ${clock.path}: readable"), ClockLogComponent.probeLines("gpu source", listOf(clock.path))) + assertNull(ClockLogComponent.ceilingSource(listOf(zero.path))) + zero.writeText("285000000\n") + assertEquals(zero.path, ClockLogComponent.ceilingSource(listOf(zero.path))) + assertEquals(" | gpu 0/285(of 443) MHz", ClockLogComponent.gpuField(clock.path, zero.path, 443)) + } + + @Test fun aStepTableWithALeadingZeroIsReadable() { + val steps = tmp.newFile("freq_table_mhz").apply { writeText("0 160000000 285000000\n") } + assertEquals(listOf(160L, 285L), GpuLimits.first(listOf(steps.path))?.mhz) + assertEquals(listOf("gpu limit ${steps.path}: readable"), ClockLogComponent.probeLines("gpu limit", listOf(steps.path), ClockLogComponent::firstStep)) + } + + @Test fun unreadableOrMissingLimitsLeaveTheSampleUnchanged() { + val clock = tmp.newFile("clock_mhz").apply { writeText("230\n") } + val refused = tmp.newFolder("max_clock_mhz") + val missing = tmp.root.path + "/gpu_max_clock" + assertEquals(" | gpu 230 MHz", ClockLogComponent.gpuField(clock.path, null, null)) + assertEquals(" | gpu 230 MHz", ClockLogComponent.gpuField(clock.path, missing, 443)) + assertEquals(" | gpu 230 MHz", ClockLogComponent.gpuField(clock.path, refused.path, 443)) + assertEquals("", ClockLogComponent.gpuField(null, null, null)) + assertNull(GpuLimits.first(listOf(missing, refused.path))) + assertEquals(listOf("gpu limit ${refused.path}: refused"), ClockLogComponent.probeLines("gpu limit", listOf(missing, refused.path))) + assertEquals( + listOf("gpu steps: nothing readable", "gpu ceiling from: nothing readable", "gpu floor: nothing readable"), + ClockLogComponent.limitLines(null, null, null), + ) + } + + @Test fun aCeilingChangeMidSessionShowsInTheNextSample() { + val clock = tmp.newFile("cur_freq").apply { writeText("443000000\n") } + val ceiling = tmp.newFile("max_freq").apply { writeText("443000000\n") } + val first = ClockLogComponent.gpuField(clock.path, ceiling.path, 443) + ceiling.writeText("285000000\n") + clock.writeText("285000000\n") + val second = ClockLogComponent.gpuField(clock.path, ceiling.path, 443) + assertEquals(" | gpu 443/443 MHz", first) + assertEquals(" | gpu 285/285(of 443) MHz", second) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/ExperimentalProtonsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ExperimentalProtonsTest.kt new file mode 100644 index 000000000..cbb1c52c3 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/ExperimentalProtonsTest.kt @@ -0,0 +1,435 @@ +package com.droiddeck.launcher.session + +import java.io.File +import java.io.RandomAccessFile +import java.nio.file.Files +import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry +import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream +import android.app.Activity +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Before +import org.robolectric.Robolectric +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class ExperimentalProtonsTest { + @get:Rule val temp = TemporaryFolder() + private lateinit var activity: Activity + + @Before + fun setup() { + activity = Robolectric.buildActivity(Activity::class.java).setup().get() + } + + @Test + fun fileLabelsDropTheWholeArchiveSuffix() { + assertEquals("Build-12.8-r34", ExperimentalProtons.fileLabel("Build-12.8-r34.tar.xz")) + assertEquals("Build-12.8-r34", ExperimentalProtons.fileLabel("Build-12.8-r34.tar")) + assertEquals("Build-12.8-r34", ExperimentalProtons.fileLabel("Build-12.8-r34.7z")) + assertEquals("Build-12.8-r34", ExperimentalProtons.fileLabel("Build-12.8-r34.tgz")) + assertEquals("Experimental-Build", ExperimentalProtons.dirName("Build", ExperimentalProtons.fileLabel("Build.tar.gz"))) + } + + @Test + fun installedReleasesLeaveTheAvailableRows() { + val rows = listOf("r34", "r35").map { ExperimentalProtons.Release(it, "$it.tar.xz", "https://example.invalid/$it", null, 1L) } + val installed = listOf( + ExperimentalProtons.Installed("Experimental-r34", "r34", "release", "r34"), + ExperimentalProtons.Installed("Experimental-file", "file", "file"), + ) + assertEquals(listOf("r35"), ExperimentalProtons.available(rows, installed).map { it.tag }) + assertEquals(listOf("r34", "r35"), ExperimentalProtons.available(rows, emptyList()).map { it.tag }) + } + + @Test + fun releaseRowsOnlyUsePublishedPrereleaseTarAssets() { + val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN } + val releases = JSONArray(""" + [{"tag_name":"stable","prerelease":false,"published_at":"2026-11-10T00:00:00Z","assets":[{"name":"stable-aarch64.tar.gz","browser_download_url":"https://example/stable"}]}, + {"tag_name":"pre","prerelease":true,"published_at":"2026-11-12T00:00:00Z","assets":[{"name":"pre-aarch64.tar.xz","browser_download_url":"https://example/pre"}]}, + {"tag_name":"superseded","prerelease":true,"published_at":"2026-10-25T00:00:00Z","assets":[{"name":"superseded-aarch64.tar.gz","browser_download_url":"https://example/superseded"}]}, + {"tag_name":"sources","prerelease":true,"published_at":"2026-11-13T00:00:00Z","assets":[{"name":"wine-gecko-x86.tar.xz","browser_download_url":"https://example/sources"}]}, + {"tag_name":"draft","draft":true,"prerelease":true,"published_at":"2026-11-14T00:00:00Z","assets":[{"name":"draft-aarch64.tar.gz","browser_download_url":"https://example/draft"}]}, + {"tag_name":"no-tar","prerelease":true,"published_at":"2026-11-15T00:00:00Z","assets":[{"name":"no-tar.sha512sum","browser_download_url":"https://example/sum"}]}] + """.trimIndent()) + assertEquals(listOf("pre"), ProtonExtras.assets(tool, releases, true).map { it.tag }) + } + + @Test + fun markerRoundTripKeepsReleaseTag() { + val dir = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d/Experimental-pre").apply { mkdirs() } + File(dir, ".droiddeck-experimental.json").writeText(JSONObject().put("label", "Experimental-pre").put("source", "pre").put("releaseTag", "pre").toString()) + assertEquals("pre", ExperimentalProtons.installed(activity).single().releaseTag) + } + + @Test + fun missingReleaseTagsAreAutoRemovedButFileBuildsAreNot() { + val complete = ProtonExtras.ReleaseFetch(JSONArray().put(JSONObject().put("tag_name", "kept").put("prerelease", true)), true) + val partial = ProtonExtras.ReleaseFetch(JSONArray().put(JSONObject().put("tag_name", "gone").put("prerelease", true)), false) + val stable = ProtonExtras.ReleaseFetch(JSONArray().put(JSONObject().put("tag_name", "gone").put("prerelease", false)), false) + assertTrue(ExperimentalProtons.shouldRemove("gone", complete) { true }) + assertFalse(ExperimentalProtons.shouldRemove("gone", complete) { false }) + assertFalse(ExperimentalProtons.shouldRemove("gone", partial) { true }) + assertTrue(ExperimentalProtons.shouldRemove("gone", stable) { false }) + assertFalse(ExperimentalProtons.shouldRemove(null, complete) { true }) + } + + @Test + fun archiveTypeUsesMagicBytes() { + val zip = temp.newFile("wrong-name.bin").apply { writeBytes(byteArrayOf(0x50, 0x4B, 0x03, 0x04)) } + val seven = temp.newFile("seven.data").apply { writeBytes(byteArrayOf(0x37, 0x7A, 0xBC.toByte(), 0xAF.toByte(), 0x27, 0x1C)) } + val tar = temp.newFile("tar.data").apply { RandomAccessFile(this, "rw").use { it.seek(257); it.write("ustar".toByteArray()) } } + assertEquals(ExperimentalProtons.ArchiveType.ZIP, ExperimentalProtons.archiveType(zip)) + assertEquals(ExperimentalProtons.ArchiveType.SEVEN_Z, ExperimentalProtons.archiveType(seven)) + assertEquals(ExperimentalProtons.ArchiveType.TAR, ExperimentalProtons.archiveType(tar)) + } + + @Test + fun namesNeverCollideWithReleasedBuilds() { + val name = ExperimentalProtons.dirName("DroidDeck-Proton-11-12.8-aarch64", "pr34-build") + assertEquals("Experimental-DroidDeck-Proton-11-12.8-aarch64-pr34-build", name) + assertFalse(name.startsWith("DroidDeck-Proton")) + assertEquals("Experimental-DroidDeck-Proton-11-12.8-aarch64", + ExperimentalProtons.dirName("DroidDeck-Proton-11-12.8-aarch64", "DroidDeck-Proton-11-12.8-aarch64")) + } + + @Test + fun buildTreeSkipsLinksOutOfTheArchive() { + val outside = protonTree(temp.newFolder("installed")) + val unpacked = temp.newFolder("unpacked") + Files.createSymbolicLink(File(unpacked, "a-link").toPath(), outside.toPath()) + assertNull(ExperimentalProtons.buildTree(unpacked)) + val real = protonTree(File(unpacked, "b-build")) + assertEquals(real.canonicalFile, ExperimentalProtons.buildTree(unpacked)?.canonicalFile) + } + + @Test + fun buildTreeNeedsWhatTheCatalogNeeds() { + val unpacked = temp.newFolder("unpacked") + val tree = File(unpacked, "build").apply { mkdirs(); File(this, "toolmanifest.vdf").writeText("x") } + assertNull(ExperimentalProtons.buildTree(unpacked)) + File(tree, "proton").writeText("x") + assertNull(ExperimentalProtons.buildTree(unpacked)) + File(tree, "files/lib/wine").mkdirs() + assertEquals(tree.canonicalFile, ExperimentalProtons.buildTree(unpacked)?.canonicalFile) + } + + private fun protonTree(dir: File): File = dir.apply { + File(this, "files/lib/wine").mkdirs() + File(this, "toolmanifest.vdf").writeText("x") + File(this, "proton").writeText("x") + } + + @Test + fun ownFileReplacesALinkWithoutTouchingItsTarget() { + val victim = temp.newFile("compatibilitytool.vdf").apply { writeText("released") } + val tree = temp.newFolder("tree") + Files.createSymbolicLink(File(tree, "compatibilitytool.vdf").toPath(), victim.toPath()) + ExperimentalProtons.ownFile(tree, "compatibilitytool.vdf").writeText("experimental") + assertEquals("released", victim.readText()) + assertFalse(Files.isSymbolicLink(File(tree, "compatibilitytool.vdf").toPath())) + } + + @Test + fun deleteTreeDoesNotFollowLinks() { + val kept = temp.newFolder("kept").apply { File(this, "file").writeText("x") } + val build = temp.newFolder("build") + Files.createSymbolicLink(File(build, "lib").toPath(), kept.toPath()) + assertTrue(ExperimentalProtons.deleteTree(build)) + assertFalse(build.exists()) + assertTrue(File(kept, "file").isFile) + } + + @Test + fun directZipKeepsExecutableModeAndInTreeLinks() { + val archive = temp.newFile("tree.zip") + ZipArchiveOutputStream(archive).use { zip -> + zip.putArchiveEntry(ZipArchiveEntry("build/proton").apply { unixMode = 0x81ED }) + zip.write("binary".toByteArray()) + zip.closeArchiveEntry() + zip.putArchiveEntry(ZipArchiveEntry("build/link").apply { unixMode = 0xA1FF }) + zip.write("proton".toByteArray()) + zip.closeArchiveEntry() + zip.putArchiveEntry(ZipArchiveEntry("build/files/lib/up").apply { unixMode = 0xA1FF }) + zip.write("../../proton".toByteArray()) + zip.closeArchiveEntry() + } + val unpacked = temp.newFolder("direct") + ExperimentalProtons.extractDirect(archive, unpacked, ExperimentalProtons.ArchiveType.ZIP) + assertTrue(File(unpacked, "build/proton").canExecute()) + assertTrue(Files.isSymbolicLink(File(unpacked, "build/link").toPath())) + assertEquals("proton", Files.readSymbolicLink(File(unpacked, "build/link").toPath()).toString()) + assertEquals("../../proton", Files.readSymbolicLink(File(unpacked, "build/files/lib/up").toPath()).toString()) + assertEquals("binary", File(unpacked, "build/files/lib/up").readText()) + } + + @Test + fun directArchivesFillReadOnlyDirectoriesBeforeLockingThem() { + val archive = temp.newFile("locked.zip") + ZipArchiveOutputStream(archive).use { zip -> + zip.putArchiveEntry(ZipArchiveEntry("build/files/").apply { unixMode = 0x416D }) + zip.closeArchiveEntry() + zip.putArchiveEntry(ZipArchiveEntry("build/files/data").apply { unixMode = 0x81A4 }) + zip.write("data".toByteArray()) + zip.closeArchiveEntry() + } + val unpacked = temp.newFolder("locked") + ExperimentalProtons.extractDirect(archive, unpacked, ExperimentalProtons.ArchiveType.ZIP) + val directory = File(unpacked, "build/files") + assertEquals("data", File(directory, "data").readText()) + assertFalse(directory.canWrite()) + directory.setWritable(true) + } + + @Test + fun directSevenZipKeepsExecutableModeAndInTreeLinks() { + val archive = temp.newFile("tree.7z") + SevenZOutputFile(archive).use { seven -> + fun add(name: String, mode: Int, text: String) { + val entry = SevenZArchiveEntry().apply { + this.name = name + hasWindowsAttributes = true + windowsAttributes = (mode shl 16) or 0x8000 + } + seven.putArchiveEntry(entry) + seven.write(text.toByteArray()) + seven.closeArchiveEntry() + } + add("build/proton", 0x81ED, "binary") + add("build/files/lib/up", 0xA1FF, "../../proton") + add("build/plain", 0x81A4, "data") + } + val unpacked = temp.newFolder("seven") + ExperimentalProtons.extractDirect(archive, unpacked, ExperimentalProtons.ArchiveType.SEVEN_Z) + assertTrue(File(unpacked, "build/proton").canExecute()) + assertFalse(File(unpacked, "build/plain").canExecute()) + assertEquals("../../proton", Files.readSymbolicLink(File(unpacked, "build/files/lib/up").toPath()).toString()) + } + + @Test + fun directArchivesAllowCurrentDirectoryBeforeAClimb() { + val archive = temp.newFile("dot.zip") + ZipArchiveOutputStream(archive).use { zip -> + zip.putArchiveEntry(ZipArchiveEntry("build/lib/wine").apply { unixMode = 0x81ED }) + zip.write("binary".toByteArray()) + zip.closeArchiveEntry() + zip.putArchiveEntry(ZipArchiveEntry("build/bin/wine").apply { unixMode = 0xA1FF }) + zip.write("./../lib/wine".toByteArray()) + zip.closeArchiveEntry() + } + val unpacked = temp.newFolder("dot") + ExperimentalProtons.extractDirect(archive, unpacked, ExperimentalProtons.ArchiveType.ZIP) + assertEquals("./../lib/wine", Files.readSymbolicLink(File(unpacked, "build/bin/wine").toPath()).toString()) + assertEquals("binary", File(unpacked, "build/bin/wine").readText()) + } + + @Test + fun directArchivesRejectLinksThatClimbAfterACurrentDirectoryAndAName() { + for (link in listOf("./top/../outside", "./../a/./../..", "top/./../outside")) { + val archive = temp.newFile() + ZipArchiveOutputStream(archive).use { zip -> + zip.putArchiveEntry(ZipArchiveEntry("build/a/b/out").apply { unixMode = 0xA1FF }) + zip.write(link.toByteArray()) + zip.closeArchiveEntry() + } + val result = runCatching { ExperimentalProtons.extractDirect(archive, temp.newFolder(), ExperimentalProtons.ArchiveType.ZIP) } + assertTrue(link, result.exceptionOrNull() is ExperimentalProtons.UnsafeArchiveException) + } + } + + @Test + fun reconcileKeepsBuildsWhenASessionStartsDuringTheLookup() { + val tools = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d") + val dirs = listOf("Experimental-gone-a", "Experimental-gone-b").map { name -> + File(tools, name).apply { + mkdirs() + File(this, ".droiddeck-experimental.json").writeText(JSONObject().put("label", name).put("source", name).put("releaseTag", name).toString()) + } + } + val complete = ProtonExtras.ReleaseFetch(JSONArray(), true) + var lookups = 0 + try { + ExperimentalProtons.reconcile(activity, complete) { + lookups++ + SessionState.running = true + true + } + } finally { + SessionState.running = false + } + assertEquals(1, lookups) + assertTrue(dirs.all { it.isDirectory }) + ExperimentalProtons.reconcile(activity, complete) { true } + assertTrue(dirs.none { it.exists() }) + } + + @Test + fun removeWaitsForAStartingSessionAndThenKeepsTheBuild() { + val tools = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d") + val dir = File(tools, "Experimental-starting").apply { + mkdirs() + File(this, ".droiddeck-experimental.json").writeText(JSONObject().put("label", name).put("source", name).toString()) + File(this, "proton").writeText("build") + } + var removed: Boolean? = null + val removal = Thread { removed = ExperimentalProtons.remove(activity, dir.name) } + try { + synchronized(SessionState.startLock) { + removal.start() + val deadline = System.nanoTime() + 10_000_000_000L + while (removal.state != Thread.State.BLOCKED && System.nanoTime() < deadline) Thread.sleep(5) + assertEquals(Thread.State.BLOCKED, removal.state) + assertTrue(File(dir, "proton").isFile) + SessionState.running = true + } + removal.join(10_000) + assertEquals(false, removed) + assertTrue(File(dir, "proton").isFile) + } finally { + SessionState.running = false + removal.join(10_000) + } + assertTrue(ExperimentalProtons.remove(activity, dir.name)) + assertTrue(!dir.exists()) + assertTrue(File(tools, ".droiddeck-experimental-gone").list().isNullOrEmpty()) + } + + @Test + fun directArchivesRejectLinksThatClimbAfterAName() { + val archive = temp.newFile("climb.zip") + ZipArchiveOutputStream(archive).use { zip -> + zip.putArchiveEntry(ZipArchiveEntry("build/a/b/top").apply { unixMode = 0xA1FF }) + zip.write("../../..".toByteArray()) + zip.closeArchiveEntry() + zip.putArchiveEntry(ZipArchiveEntry("build/a/b/out").apply { unixMode = 0xA1FF }) + zip.write("top/../outside".toByteArray()) + zip.closeArchiveEntry() + } + val result = runCatching { ExperimentalProtons.extractDirect(archive, temp.newFolder("climb-out"), ExperimentalProtons.ArchiveType.ZIP) } + assertTrue(result.exceptionOrNull() is ExperimentalProtons.UnsafeArchiveException) + } + + @Test + fun directZipRejectsEscapingLinksAndEntries() { + val linkArchive = temp.newFile("link.zip") + ZipArchiveOutputStream(linkArchive).use { zip -> + zip.putArchiveEntry(ZipArchiveEntry("build/link").apply { unixMode = 0xA1FF }) + zip.write("../../outside".toByteArray()) + zip.closeArchiveEntry() + } + val entryArchive = temp.newFile("entry.zip") + ZipArchiveOutputStream(entryArchive).use { zip -> + zip.putArchiveEntry(ZipArchiveEntry("../outside")) + zip.write("x".toByteArray()) + zip.closeArchiveEntry() + } + val linkResult = runCatching { ExperimentalProtons.extractDirect(linkArchive, temp.newFolder("link-out"), ExperimentalProtons.ArchiveType.ZIP) } + val entryResult = runCatching { ExperimentalProtons.extractDirect(entryArchive, temp.newFolder("entry-out"), ExperimentalProtons.ArchiveType.ZIP) } + assertTrue(linkResult.exceptionOrNull() is ExperimentalProtons.UnsafeArchiveException) + assertTrue(entryResult.exceptionOrNull() is ExperimentalProtons.UnsafeArchiveException) + } + + @Test + fun staleDownloadCleanupOnlyDeletesItsOwnUnlistedFiles() { + val downloads = File(activity.filesDir, "proton-downloads").apply { mkdirs() } + val stale = File(downloads, "droiddeck-gone-archive.tar.xz").apply { writeText("partial") } + val kept = File(downloads, "droiddeck-kept-archive.tar.xz").apply { writeText("partial") } + val other = File(downloads, "other-archive.tar.xz").apply { writeText("partial") } + ExperimentalProtons.removeStaleDownloads(activity, setOf("kept")) + assertFalse(stale.exists()) + assertTrue(kept.exists()) + assertTrue(other.exists()) + } + + @Test + fun checksumFileWithoutADigestIsRejected() { + assertNull(ExperimentalProtons.checksumIn("not a checksum\n")) + val digest = "a".repeat(128) + assertEquals(digest, ExperimentalProtons.checksumIn("$digest DroidDeck-Proton.tar.gz\n")) + } + + @Test + fun checksumLookupDoesNotSelectTheTarball() { + assertNull(ExperimentalProtons.checksumEntry(listOf("Proton-sha512.tar.gz"), "Proton-sha512.tar.gz")) + assertEquals("Proton-sha512.tar.gz.sha512sum", ExperimentalProtons.checksumEntry( + listOf("Proton-sha512.tar.gz", "Proton-sha512.tar.gz.sha512sum"), "Proton-sha512.tar.gz")) + assertNull(ExperimentalProtons.checksumEntry(listOf("Proton.tar.gz"), "Proton.tar.gz")) + assertEquals("Proton.tar.gz.sha512sum", ExperimentalProtons.checksumEntry( + listOf("Proton-debug.tar.gz.sha512sum", "Proton.tar.gz.sha512sum"), "Proton.tar.gz")) + assertEquals("Proton.sha512sum", ExperimentalProtons.checksumEntry(listOf("Proton.sha512sum"), "Proton.tar.gz")) + assertNull(ExperimentalProtons.checksumEntry(listOf("Proton-debug.tar.gz.sha512sum"), "Proton.tar.gz")) + } + + private fun build(dir: File, marker: String): File = dir.apply { + mkdirs() + File(this, "marker").writeText(marker) + } + + @Test + fun failedPlacementRestoresTheExistingBuild() { + val tools = temp.newFolder("tools") + build(File(tools, "Experimental-A"), "old") + assertFalse(ExperimentalProtons.placeTree(File(tools, "missing"), tools, "Experimental-A") { true }) + assertEquals("old", File(tools, "Experimental-A/marker").readText()) + assertFalse(ExperimentalProtons.placeTree(build(File(tools, "staged"), "new"), tools, "Experimental-A") { false }) + assertEquals("old", File(tools, "Experimental-A/marker").readText()) + assertTrue(tools.walkTopDown().none { it.isFile && it.readText() == "new" }) + } + + @Test + fun aReplacedBuildIsForgottenWhileNeitherBuildIsInstalled() { + val tools = temp.newFolder("tools") + build(File(tools, "Experimental-A"), "old") + val forgotten = ArrayList() + assertTrue(ExperimentalProtons.placeTree(build(File(tools, "staged"), "new"), tools, "Experimental-A") { + assertFalse(File(tools, it).exists()) + forgotten.add(it) + }) + assertEquals(listOf("Experimental-A"), forgotten) + assertEquals("new", File(tools, "Experimental-A/marker").readText()) + assertTrue(ExperimentalProtons.placeTree(build(File(tools, "staged"), "first"), tools, "Experimental-B") { forgotten.add(it) }) + assertEquals(listOf("Experimental-A"), forgotten) + assertEquals(listOf("Experimental-A", "Experimental-B"), tools.walkTopDown().filter { it.name == "marker" }.map { it.parentFile.name }.sorted().toList()) + } + + @Test + fun anInterruptedReplacementIsFinishedWithItsOldStateForgotten() { + val tools = temp.newFolder("tools") + build(File(tools, "Experimental-A"), "old") + build(File(tools, ".droiddeck-experimental-new/Experimental-A"), "new") + build(File(tools, ".droiddeck-experimental-old/Experimental-B"), "old") + build(File(tools, ".droiddeck-experimental-new/Experimental-B"), "new") + build(File(tools, ".droiddeck-experimental-old/Experimental-C"), "old") + build(File(tools, ".droiddeck-experimental-old/Experimental-D"), "old") + build(File(tools, "Experimental-D"), "new") + val forgotten = ArrayList() + ExperimentalProtons.restoreInterrupted(tools) { forgotten.add(it) } + assertEquals(listOf("Experimental-A", "Experimental-B"), forgotten.sorted()) + assertEquals(listOf("new", "new", "old", "new"), listOf("A", "B", "C", "D").map { File(tools, "Experimental-$it/marker").readText() }) + assertTrue(File(tools, ".droiddeck-experimental-old").listFiles().isNullOrEmpty()) + assertTrue(File(tools, ".droiddeck-experimental-new").listFiles().isNullOrEmpty()) + } + + @Test + fun anInterruptedReplacementKeepsTheOldBuildWhenItsStateCannotBeForgotten() { + val tools = temp.newFolder("tools") + build(File(tools, ".droiddeck-experimental-old/Experimental-A"), "old") + build(File(tools, ".droiddeck-experimental-new/Experimental-A"), "new") + ExperimentalProtons.restoreInterrupted(tools) { false } + assertEquals("old", File(tools, "Experimental-A/marker").readText()) + assertTrue(File(tools, ".droiddeck-experimental-new").listFiles().isNullOrEmpty()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/GpuClockPinTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GpuClockPinTest.kt new file mode 100644 index 000000000..3311df050 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/GpuClockPinTest.kt @@ -0,0 +1,34 @@ +package com.droiddeck.launcher.session + +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class GpuClockPinTest { + private val context = RuntimeEnvironment.getApplication() + + @After fun stop() { GpuClockPin.stop(context) } + + @Test fun aToggleOutsideASessionSaysNothing() { + SessionPrefs.setGpuClockPin(context, true) + assertNull(GpuClockPin.sync(context)) + } + + @Test fun aToggleMidSessionReportsTheHoldWithTheStartWording() { + SessionPrefs.setGpuClockPin(context, false) + val started = GpuClockPin.start(context) + assertEquals("gpu clock: governed", started) + SessionPrefs.setGpuClockPin(context, true) + val held = GpuClockPin.sync(context) + assertEquals("gpu clock: no /dev/kgsl-3d0, left governed", held) + SessionPrefs.setGpuClockPin(context, false) + assertEquals(started, GpuClockPin.sync(context)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt index 1261abd54..ad4f169c4 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt @@ -18,6 +18,12 @@ class PipPolicyTest { assertFalse(PipPolicy.eligible(true, false, SessionPhase.SUSPENDED, true, false)) } + @Test fun goingHomeFloatsOnlyGamesDroidDeckLaunchedItself() { + assertTrue(PipPolicy.autoEnter(enabled = true, launchedByAnotherApp = false)) + assertFalse(PipPolicy.autoEnter(enabled = true, launchedByAnotherApp = true)) + assertFalse(PipPolicy.autoEnter(enabled = false, launchedByAnotherApp = false)) + } + @Test fun aspectRatiosStayWithinAndroidLimitsWithoutChangingNormalContent() { assertEquals(1920 to 1080, PipPolicy.aspect(1920, 1080)) assertEquals(239 to 100, PipPolicy.aspect(5760, 1080)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt index 43571a3ff..105205a84 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt @@ -30,7 +30,7 @@ class ProtonExtrasTest { .apply { if (digest != null) put("digest", digest) } private fun release(tag: String, vararg assets: JSONObject, prerelease: Boolean = false, draft: Boolean = false) = JSONObject() - .put("tag_name", tag).put("prerelease", prerelease).put("draft", draft) + .put("tag_name", tag).put("prerelease", prerelease).put("draft", draft).put("published_at", "2026-11-12T00:00:00Z") .put("assets", JSONArray().apply { assets.forEach { put(it) } }) private fun droiddeckRelease(ver: String, prerelease: Boolean = false) = release( @@ -48,6 +48,34 @@ class ProtonExtrasTest { File(this, "proton").apply { writeText(""); setExecutable(true) } } + @Test + fun experimentalRowsUseTheReleaseNameAndTagDetail() { + val current = release("DroidDeck-Bionic-12.8-r34", asset("DroidDeck-Bionic-12.8-r34-aarch64.tar.xz"), prerelease = true) + .put("name", "DroidDeck Bionic 12.8 r34") + val selectedAsset = ProtonExtras.assetOf(tool("droiddeck"), current, experimental = true)!! + val selected = ProtonExtras.assets(tool("droiddeck"), JSONArray().put(current), true).single() + assertEquals("DroidDeck-Bionic-12.8-r34-aarch64.tar.xz", selectedAsset.name) + assertEquals("DroidDeck Bionic 12.8 r34", selected.releaseName) + assertEquals("DroidDeck-Bionic-12.8-r34", selected.tag) + } + + @Test + fun experimentalAssetsIgnoreChecksumSidecars() { + val sidecarOnly = release("DroidDeck-Bionic-12.8-r36", asset("DroidDeck-Bionic-12.8-r36-aarch64.tar.xz.sha512sum")) + assertEquals(null, ProtonExtras.assetOf(tool("droiddeck"), sidecarOnly, experimental = true)) + } + + @Test + fun experimentalAssetsSkipOtherArchitectures() { + val foreign = release("DroidDeck-Bionic-12.8-r37", asset("DroidDeck-Bionic-12.8-r37-x86_64.tar.xz"), asset("DroidDeck-Bionic-12.8-r37-amd64.tar.gz"), prerelease = true) + val mixed = release("DroidDeck-Bionic-12.8-r38", asset("DroidDeck-Bionic-12.8-r38-x86_64.tar.xz"), asset("DroidDeck-Bionic-12.8-r38.tar.xz"), prerelease = true) + val named = release("DroidDeck-Bionic-12.8-r39", asset("DroidDeck-Bionic-12.8-r39-aarch64.tar.xz"), asset("DroidDeck-Bionic-12.8-r39-x86_64.tar.xz"), prerelease = true) + assertEquals(null, ProtonExtras.assetOf(tool("droiddeck"), foreign, experimental = true)) + assertEquals("DroidDeck-Bionic-12.8-r38.tar.xz", ProtonExtras.assetOf(tool("droiddeck"), mixed, experimental = true)!!.name) + assertEquals("DroidDeck-Bionic-12.8-r39-aarch64.tar.xz", ProtonExtras.assetOf(tool("droiddeck"), named, experimental = true)!!.name) + assertTrue(ProtonExtras.assets(tool("droiddeck"), JSONArray().put(foreign), true).isEmpty()) + } + @Test fun theThreeSourcesInOrder() { assertEquals(listOf("ge", "cachyos", "droiddeck"), ProtonExtras.tools.map { it.id }) @@ -72,6 +100,14 @@ class ProtonExtrasTest { assertNull(picked.sha256) } + @Test + fun ownExperimentalReleaseUsesItsCurrentBionicTarballShape() { + val current = release("DroidDeck-Bionic-12.8-r34", asset("DroidDeck-Bionic-12.8-r34-aarch64.tar.xz"), asset("DroidDeck-Bionic-12.8-r34-aarch64.sha512sum"), prerelease = true) + val rows = ProtonExtras.assets(tool("droiddeck"), JSONArray().put(current), prerelease = true) + assertEquals(listOf("DroidDeck-Bionic-12.8-r34"), rows.map { it.tag }) + assertTrue(ProtonExtras.assets(tool("droiddeck"), JSONArray().put(release("DroidDeck-Bionic-12.8-r35", asset("DroidDeck-Bionic-12.8-r35-aarch64.sha512sum"), prerelease = true)), true).isEmpty()) + } + @Test fun githubsDigestIsKeptBesideTheSha512File() { val sum = "ab".repeat(32) @@ -208,8 +244,25 @@ class ProtonExtrasTest { assertFalse(state.getJSONObject("active").has("GE-Proton11-7")) assertFalse(state.getJSONObject("queued").has("GE-Proton11-7")) assertTrue(state.getJSONObject("active").has("GE-Proton11-8")) - ComponentsManager.forgetProton(context, kept.name) + assertTrue(ComponentsManager.forgetProton(context, kept.name)) assertTrue(File(originals, "GE-Proton11-8/GE-Proton11-8/dxvk.wcp").isFile) + val published = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv") + published.appendText("*\tExperimental-Gone\t11\tdxvk\tfiles/lib/wine/dxvk/x86_64-windows/dxgi.dll\t-\t-\n") + File(originals, "Experimental-Gone/11/dxvk.wcp").apply { parentFile?.mkdirs(); writeText("x") } + assertTrue(ComponentsManager.forgetProton(context, "Experimental-Gone")) + assertFalse(published.readLines().any { "Experimental-Gone" in it }) + assertFalse(File(originals, "Experimental-Gone").exists()) + + val store = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/store") + File(originals, "Experimental-Stale/11/dxvk.wcp").apply { parentFile?.mkdirs(); writeText("x") } + val stale = File(store, "original-Experimental-Stale-11-dxvk").apply { mkdirs(); File(this, ".complete").writeText("1\n") } + val other = File(store, "original-Experimental-Stale-2-11-dxvk").apply { mkdirs(); File(this, ".complete").writeText("1\n") } + File(originals, "Experimental-Stale/2-11/dxvk.wcp").apply { parentFile?.mkdirs(); writeText("x") } + published.appendText("*\tExperimental-Stale-2\t11\tdxvk\tfiles/a.dll\t0\t/root/.local/share/droiddeck-components/store/${other.name}/files/a.dll\n") + assertTrue(ComponentsManager.forgetProton(context, "Experimental-Stale")) + assertFalse(stale.exists()) + assertTrue(File(other, ".complete").isFile) + assertFalse(File(originals, "Experimental-Stale").exists()) } @Test @@ -242,4 +295,76 @@ class ProtonExtrasTest { assertNull(ProtonExtras.missing(context, tool("droiddeck"))) assertEquals("DroidDeck-Proton-11-11.4", ProtonExtras.update(context, tool("droiddeck"))) } + + @Test + fun laterPagesAreReadOnlyUntilAStableBaselineIsFound() { + val tool = tool("droiddeck") + val pages = mapOf( + 1 to JSONArray().apply { repeat(15) { put(droiddeckRelease("11-12.${10 - it}", prerelease = true)) } }, + 2 to JSONArray().put(droiddeckRelease("11-12.8")), + 3 to JSONArray().put(droiddeckRelease("11-12.7")), + ) + val asked = mutableListOf() + val all = ProtonExtras.releases(tool) { asked += it; pages[it] ?: JSONArray() }!! + assertEquals(listOf(1, 2), asked) + assertEquals("DroidDeck-Proton-11-12.8", ProtonExtras.pickAsset(tool, all)!!.tag) + + asked.clear() + ProtonExtras.releases(tool) { asked += it; pages.getValue(2) } + assertEquals(listOf(1), asked) + + asked.clear() + assertEquals(0, ProtonExtras.releases(tool) { asked += it; JSONArray() }!!.length()) + assertEquals(listOf(1), asked) + assertNull(ProtonExtras.releases(tool) { null }) + + asked.clear() + assertNull(ProtonExtras.releases(tool) { page -> + asked += page + if (page == 1) JSONArray().apply { repeat(15) { put(droiddeckRelease("11-12.${10 - it}", prerelease = true)) } } else null + }) + assertEquals(listOf(1, 2), asked) + } + + @Test + fun anOldTestButtonInstallRemainsAUsableInstalledBuild() { + val context = RuntimeEnvironment.getApplication() + val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d") + val installed = installTool(tools, "DroidDeck-Proton 11-12.9") + val releases = File(context.filesDir, "proton-extras.json") + releases.writeText(JSONObject().put(installed.name, "DroidDeck-Proton-11-12.9").toString()) + assertEquals(listOf(installed.name), ProtonExtras.installedAll(context, tool("droiddeck"))) + assertEquals(listOf("DroidDeck-Proton-11-12.9"), ProtonExtras.installedTags(context, tool("droiddeck"))) + } + + @Test + fun malformedReleaseEntriesAreSkipped() { + val releases = JSONArray("[null, 5, {\"tag_name\": \"x\", \"assets\": [null]}]").put(droiddeckRelease("11-12.8")) + assertEquals("DroidDeck-Proton-11-12.8", ProtonExtras.pickAsset(tool("droiddeck"), releases)!!.tag) + assertNull(ProtonExtras.pickAsset(tool("droiddeck"), JSONArray("[null]"))) + } + + @Test + fun failedOrPartialReleaseFetchDoesNotPretendMissingBuildsAreGone() { + val tool = tool("droiddeck") + assertNull(ProtonExtras.releasesForRemoval(tool) { null }) + val asked = mutableListOf() + val result = ProtonExtras.releasesForRemoval(tool) { page -> + asked += page + if (page == 1) JSONArray().apply { repeat(15) { put(droiddeckRelease("11-12.${10 - it}", prerelease = true)) } } else null + } + assertNull(result) + assertEquals(listOf(1, 2), asked) + } + + @Test + fun aShortReleasePageCompletesTheRemovalLookup() { + val asked = mutableListOf() + val result = ProtonExtras.releasesForRemoval(tool("droiddeck")) { page -> + asked += page + JSONArray().put(droiddeckRelease("11-12.8", prerelease = true)) + } + assertTrue(result!!.complete) + assertEquals(listOf(1), asked) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt index 7d2087f6f..66b68631f 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt @@ -35,7 +35,8 @@ class SessionSuspendControllerTest { val urgent = fixture.signals.filter { it.signal == URG } assertEquals(listOf(GAME), urgent.map { it.pid }) assertTrue(fixture.signals.indexOfFirst { it.signal == URG } < fixture.signals.indexOfFirst { it.signal == STOP }) - assertEquals("1", fixture.control.readText()) + assertEquals(listOf("1"), fixture.held) + assertEquals("0", fixture.control.readText()) assertEquals(listOf(Triple(1, 1_000_000L, 3_000_000L)), fixture.pagedOut) assertEquals(0, fixture.unacknowledged) assertTrue(fixture.game.threads.all { it.state == 't' }) @@ -56,6 +57,22 @@ class SessionSuspendControllerTest { assertEquals(0, fixture.unacknowledged) } + @Test fun aTrimAcknowledgementIsNotTakenForAFinishedPageOut() { + val fixture = fixture(17) + fixture.control.writeText("0") + fixture.handlerStalls = true + val ack = File(fixture.control.parentFile, ".dd-zram.ack.$GAME") + var stoppedEarly = false + fixture.afterSleep = { + if (fixture.now == 3000L) fixture.handlerStalls = false + if (fixture.handlerStalls && fixture.signals.any { it.signal == URG }) ack.writeText("4096") + if (fixture.handlerStalls && fixture.signals.any { it.signal == STOP }) stoppedEarly = true + } + fixture.controller.freeze(pageOut = true) { assertTrue(it) } + assertFalse(stoppedEarly) + assertEquals(0, fixture.unacknowledged) + } + @Test fun replacedHandlerIsNotWaitedForPastTheStartWindow() { val fixture = fixture(17) fixture.control.writeText("0") @@ -107,6 +124,17 @@ class SessionSuspendControllerTest { assertEquals(1, fixture.pagedIn.size) } + @Test fun theMonitorIsHeldOffWhilePagingOutAndReadingBack() { + val fixture = fixture(17) + fixture.control.writeText("0") + val hold = File(fixture.control.parentFile, ".dd-zram.hold") + fixture.controller.freeze(pageOut = true) { assertTrue(it) } + assertFalse(hold.exists()) + fixture.controller.resume { assertTrue(it) } + assertFalse(hold.exists()) + assertEquals(listOf("1", "0"), fixture.held) + } + @Test fun noReadBackAfterAFreezeWithoutPageOut() { val fixture = fixture(17) fixture.control.writeText("0") @@ -116,6 +144,18 @@ class SessionSuspendControllerTest { assertTrue(fixture.pagedIn.isEmpty()) } + @Test fun aTrimRequestInTheControlFileDoesNotReplaceThePageOut() { + val fixture = fixture(17) + fixture.control.writeText("0") + fixture.afterSleep = { fixture.control.writeText("2 4096\n") } + fixture.controller.freeze(pageOut = true) { assertTrue(it) } + fixture.controller.resume { assertTrue(it) } + assertEquals(listOf("1", "0"), fixture.held) + assertEquals("2 4096\n", fixture.control.readText()) + assertEquals(listOf(Triple(1, 1_000_000L, 3_000_000L)), fixture.pagedOut) + assertEquals(listOf(Triple(1, 0L, 3_000_000L)), fixture.pagedIn) + } + @Test fun readBackIsSkippedWhenAvailableMemoryCannotTakeIt() { val fixture = fixture(17) fixture.control.writeText("0") @@ -124,7 +164,7 @@ class SessionSuspendControllerTest { val before = fixture.signals.size fixture.controller.resume { assertTrue(it) } assertFalse(fixture.signals.drop(before).any { it.signal == URG }) - assertEquals("1", fixture.control.readText()) + assertEquals(listOf("1"), fixture.held) assertEquals(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn) } @@ -151,18 +191,6 @@ class SessionSuspendControllerTest { assertEquals(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn) } - @Test fun noReadBackWithARamCap() { - val fixture = fixture(17) - fixture.control.writeText("0") - fixture.readBackAllowed = false - fixture.controller.freeze(pageOut = true) { assertTrue(it) } - val before = fixture.signals.size - fixture.controller.resume { assertTrue(it) } - assertFalse(fixture.signals.drop(before).any { it.signal == URG }) - assertEquals("1", fixture.control.readText()) - assertEquals(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn) - } - @Test fun cancelledFreezeReadsBackWhatThePageOutAlreadyMoved() { val fixture = fixture(17) fixture.control.writeText("0") @@ -170,7 +198,7 @@ class SessionSuspendControllerTest { fixture.controller.freeze(pageOut = true) { assertFalse(it) } assertFalse(fixture.signals.any { it.signal == STOP }) assertEquals(2, fixture.signals.count { it.signal == URG }) - assertEquals("0", fixture.control.readText()) + assertEquals(listOf("1", "0"), fixture.held) assertEquals(1, fixture.pagedIn.single().first) assertEquals(0L, fixture.pagedIn.single().second) assertTrue(fixture.pagedIn.single().third > 0L) @@ -183,7 +211,7 @@ class SessionSuspendControllerTest { fixture.afterSleep = { if (fixture.now >= 500) fixture.controller.cancelFreeze() } fixture.controller.freeze(pageOut = true) { assertFalse(it) } assertEquals(2, fixture.signals.count { it.signal == URG }) - assertEquals("0", fixture.control.readText()) + assertEquals(listOf("1", "0"), fixture.held) assertEquals(Triple(1, 0L, 0L), fixture.pagedIn.single()) } @@ -467,6 +495,7 @@ class SessionSuspendControllerTest { val groups = mutableListOf(root, game) val helpers = mutableListOf() val signals = mutableListOf() + val held = mutableListOf() var rootPid = ROOT var now = 0L var audioSuspends = 0 @@ -486,7 +515,6 @@ class SessionSuspendControllerTest { val pagedIn = mutableListOf>() var availableKb = 8_000_000L var totalKb = 16_000_000L - var readBackAllowed = true private var gameResidentKb = 4_000_000L private var gameSwapKb = 0L private var pagingOut = false @@ -506,7 +534,6 @@ class SessionSuspendControllerTest { pagedOut += Triple(processes, resident, swap) this.unacknowledged = unacknowledged }, - readBackAllowed = { readBackAllowed }, pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) }, ) @@ -514,6 +541,8 @@ class SessionSuspendControllerTest { private fun signal(pid: Int, signal: Int) { signals += SentSignal(pid, signal) + val request = if (signal == URG) File(control.parentFile, "${control.name}.hold").takeIf { it.isFile }?.readText() else null + if (signal == URG) held += request val group = groups.first { it.pid == pid } if (signal == STOP) { continuing = false @@ -522,7 +551,7 @@ class SessionSuspendControllerTest { it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last()) }?.state = 't' } else if (signal == URG) { - if (control.readText() == "0") { pagingOut = false; pagingIn = true } else pagingOut = true + if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true } else if (signal == CONT) { if (clockAtContinue == null && clock.isFile) { clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long diff --git a/app/src/test/java/com/droiddeck/launcher/session/ShaderPrecachePrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ShaderPrecachePrefsTest.kt index b4d8d81f8..92eef3092 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ShaderPrecachePrefsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ShaderPrecachePrefsTest.kt @@ -20,9 +20,9 @@ class ShaderPrecachePrefsTest { SessionPrefs.steamRoot(context, SessionPrefs.steamClientArch(context)).deleteRecursively() } - @Test fun clientWithoutConfigStartsWithPrecachingOff() { - assertEquals(false, SessionPrefs.pendingShaderPrecache(context)) - assertEquals(false, SessionPrefs.shaderPrecache(context)) + @Test fun clientWithoutConfigStartsWithPrecachingOn() { + assertEquals(true, SessionPrefs.pendingShaderPrecache(context)) + assertEquals(true, SessionPrefs.shaderPrecache(context)) } @Test fun existingConfigKeepsTheClientsChoice() { diff --git a/app/src/test/java/com/droiddeck/launcher/storage/KeptPrefixRemovalTest.kt b/app/src/test/java/com/droiddeck/launcher/storage/KeptPrefixRemovalTest.kt new file mode 100644 index 000000000..f4412a41c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/storage/KeptPrefixRemovalTest.kt @@ -0,0 +1,42 @@ +package com.droiddeck.launcher.storage + +import com.droiddeck.launcher.stores.InstalledStoreGame +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreGameSidecar +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = android.app.Application::class) +class KeptPrefixRemovalTest { + private val compat = File("/rootfs/root/.local/share/Steam/steamapps/compatdata") + + private fun kept(id: String, owner: PrefixOwner) = KeptPrefix(File(compat, id), owner, null, 1L shl 30, "Internal", false) + + private fun report(kept: List, storeFolders: List = emptyList()) = StorageReport( + 0, 0, 0, emptyMap(), 0, 0, 0, 0, emptyList(), emptyList(), emptyList(), emptyList(), 0, emptyList(), emptyList(), 0, + kept, true, storeFolders.map { StoreGameUsage(InstalledStoreGame(StoreGameSidecar(Store.BATTLENET, "pro", "Game", "Game.exe"), it), -1, false) }, + ) + + @Test fun launcherAndUnknownPrefixesCanBeRemoved() { + val launcher = kept("2929927072", PrefixOwner.LAUNCHER) + val unknown = kept("1234", PrefixOwner.UNKNOWN) + val r = report(listOf(launcher, unknown)) + assertTrue(StorageState.keptRemovable(r, launcher)) + assertTrue(StorageState.keptRemovable(r, unknown)) + assertTrue(StorageState.keptRemovable(r, kept("0", PrefixOwner.SHARED))) + } + + @Test fun aLauncherPrefixHoldingAnInstalledGameStays() { + val bnet = kept("2611429436", PrefixOwner.LAUNCHER) + val inside = File(bnet.dir, "pfx/drive_c/Program Files (x86)/Overwatch") + assertFalse(StorageState.keptRemovable(report(listOf(bnet), listOf(inside)), bnet)) + val elsewhere = File(compat, "2611429436-other/Overwatch") + assertTrue(StorageState.keptRemovable(report(listOf(bnet), listOf(elsewhere)), bnet)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/storage/StorageSummaryTest.kt b/app/src/test/java/com/droiddeck/launcher/storage/StorageSummaryTest.kt new file mode 100644 index 000000000..0139a3b87 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/storage/StorageSummaryTest.kt @@ -0,0 +1,27 @@ +package com.droiddeck.launcher.storage + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = android.app.Application::class) +class StorageSummaryTest { + @Test fun theSavedOverviewReadsBackAsWritten() { + val buckets = Bucket.entries.mapIndexed { i, b -> b to (i + 1) * 1_000_000_000L }.toMap() + val s = StorageSummary(42, 103L shl 30, 49L shl 30, buckets, 234L shl 20, 3, 1, 7L shl 30, 9L shl 20, 350L shl 20, + 12, 226L shl 20, 8, 73L shl 20, 0, 0, 105L shl 20, 9L shl 20, 8L shl 30) + val back = StorageSummary.fromJson(s.toJson())!! + assertEquals(s.toJson(), back.toJson()) + assertEquals(buckets, back.buckets) + assertEquals(s.droiddeck, back.droiddeck) + } + + @Test fun anOtherVersionOrDamagedFileReadsAsNone() { + assertNull(StorageSummary.fromJson("{\"v\":0}")) + assertNull(StorageSummary.fromJson("not json")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/storage/SystemCachesTest.kt b/app/src/test/java/com/droiddeck/launcher/storage/SystemCachesTest.kt new file mode 100644 index 000000000..4c0ed681c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/storage/SystemCachesTest.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.storage + +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class SystemCachesTest { + @get:Rule val tmp = TemporaryFolder() + + private val now = 10L * 24 * 60 * 60 * 1000 + private val old = now - SystemCaches.TEMP_IDLE_MS - 1000 + + private fun file(path: String, modified: Long) = File(tmp.root, path).apply { parentFile!!.mkdirs(); writeText("x"); setLastModified(modified) } + + @Test fun onlyIdleVisibleTemporaryFilesAreCleared() { + file("rootfs/tmp/old.deb", old) + file("rootfs/tmp/oldDir/a", old).parentFile!!.setLastModified(old) + file("rootfs/tmp/busyDir/a", old) + file("rootfs/tmp/busyDir/b", now - 1000).parentFile!!.setLastModified(old) + file("rootfs/tmp/.X11-unix/X0", old).parentFile!!.setLastModified(old) + file("rootfs/tmp/fresh.log", now) + val found = SystemCaches.find(File(tmp.root, "rootfs"), emptyList(), now) + assertEquals(listOf("old.deb", "oldDir"), found.getValue(SystemCache.TEMP).map { it.name }.sorted()) + } + + @Test fun packagesAndSteamCachesAreFound() { + file("rootfs/var/cache/apt/archives/git_1_arm64.deb", now) + file("rootfs/var/cache/apt/archives/lock", now) + file("rootfs/var/cache/apt/archives/partial/perl.deb", now) + val steam = File(tmp.root, "rootfs/root/.local/share/Steam") + file("rootfs/root/.local/share/Steam/config/htmlcache/Cache/data_0", now) + file("rootfs/root/.local/share/Steam/steamapps/corrupt/1_2_ab_corrupt.chunk", now) + val found = SystemCaches.find(File(tmp.root, "rootfs"), listOf(steam, File(tmp.root, "missing")), now) + assertEquals(listOf("git_1_arm64.deb", "perl.deb"), found.getValue(SystemCache.PACKAGES).map { it.name }.sorted()) + assertEquals(listOf(File(steam, "config/htmlcache")), found.getValue(SystemCache.STEAM_WEB)) + assertEquals(listOf(File(steam, "steamapps/corrupt")), found.getValue(SystemCache.STEAM_CORRUPT)) + } + + @Test fun checkoutsAndTheirWorktreeRecordsAreFound() { + val rootfs = File(tmp.root, "rootfs") + File(rootfs, "root/DroidDeck/.git/worktrees/dd-pet").mkdirs() + file("rootfs/root/dd-pet/.git", now).writeText("gitdir: /root/DroidDeck/.git/worktrees/dd-pet\n") + file("rootfs/root/own/.git/HEAD", now) + file("rootfs/root/notes/readme", now) + file("rootfs/root/bad/.git", now).writeText("gitdir: /root/DroidDeck/.git/worktrees/../../../etc\n") + assertEquals(listOf("bad", "dd-pet", "own"), SystemCaches.checkouts(rootfs).map { it.name }.sorted()) + assertEquals(File(rootfs, "root/DroidDeck/.git/worktrees/dd-pet"), SystemCaches.worktreeRecord(rootfs, File(rootfs, "root/dd-pet"))) + assertEquals(null, SystemCaches.worktreeRecord(rootfs, File(rootfs, "root/own"))) + assertEquals(null, SystemCaches.worktreeRecord(rootfs, File(rootfs, "root/bad"))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt index 9f1dcd2b0..f3944a803 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt @@ -1,5 +1,8 @@ package com.droiddeck.launcher.stores +import com.droiddeck.launcher.stores.ubisoft.MemorySlots +import com.droiddeck.launcher.stores.ubisoft.UbisoftCloud +import com.droiddeck.launcher.stores.ubisoft.UbisoftCloudTransport import java.io.File import java.util.concurrent.Executor import org.junit.Assert.assertArrayEquals @@ -20,10 +23,18 @@ class CloudSavesTest { private class Memory : CloudTransport { val files = HashMap>() val puts = ArrayList() + var onGet: (CloudFile) -> Unit = {} + var raceAfter = Int.MAX_VALUE override fun list() = files.map { (k, v) -> CloudFile(k, v.second, CloudSaves.md5(v.first)) } - override fun get(file: CloudFile) = files.getValue(file.name) - override fun put(files: Map, modifiedMs: Map): Map = - files.mapValues { (k, v) -> puts += k; this.files[k] = v to 99_000L; 99_000L } + override fun get(file: CloudFile) = files.getValue(file.name).also { onGet(file) } + override fun put(files: Map, modifiedMs: Map): Map { + val sent = LinkedHashMap() + for ((k, v) in files) { + if (sent.size >= raceAfter) throw CloudChanged(sent, files.keys.filter { it !in sent }) + puts += k; this.files[k] = v to 99_000L; sent[k] = 99_000L + } + return sent + } } private fun dir() = File(app.filesDir, "saves-${System.nanoTime()}").apply { mkdirs() } @@ -50,6 +61,72 @@ class CloudSavesTest { assertEquals("v1", File(kept, "slot0.sav").readText()) } + @Test fun aFolderAliasNeverHidesTheRealSaveFromARestore() { + val game = id; val dir = dir() + File(dir, "SaveData").mkdirs(); File(dir, "SaveData/slot.sav").writeText("local") + val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "Cache").toPath(), File(dir, "SaveData").toPath()) } + org.junit.Assume.assumeTrue(link.isSuccess) + val memory = Memory().apply { files["SaveData/slot.sav"] = "cloud".toByteArray() to 1000L } + val cloud = object : CloudTransport by memory { + override fun wants(name: String) = name.startsWith("SaveData/") + } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true) + assertEquals("cloud", File(dir, "SaveData/slot.sav").readText()) + val kept = File(app.filesDir, "stores/cloud-backups/gog-$game").listFiles { f -> f.name.startsWith("local-") }!!.single() + assertEquals("local", File(kept, "SaveData/slot.sav").readText()) + } + + @Test fun aSaveReachedOnlyThroughAFolderAliasStillGoesUp() { + val game = id; val dir = dir() + File(dir, "Actual").mkdirs(); File(dir, "Actual/slot.sav").writeText("played") + val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "SaveData").toPath(), File(dir, "Actual").toPath()) } + org.junit.Assume.assumeTrue(link.isSuccess) + java.nio.file.Files.createSymbolicLink(File(dir, "Actual/loop").toPath(), dir.toPath()) + val memory = Memory() + val cloud = object : CloudTransport by memory { + override fun wants(name: String) = name.startsWith("SaveData/") + } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("uploaded", r.reason) + assertEquals(listOf("SaveData/slot.sav"), memory.puts) + assertEquals("played", String(memory.files.getValue("SaveData/slot.sav").first)) + } + + @Test fun onlySelectedSavesCanCollideByCase() { + val names = listOf("Logs/A.txt", "Logs/a.txt", "SaveGame/1") + assertFalse(CloudSaves.caseCollision(names) { !it.startsWith("Logs/") }) + assertTrue(CloudSaves.caseCollision(names) { true }) + assertTrue(CloudSaves.caseCollision(listOf("SaveGame/1", "savegame/1")) { it.lowercase().startsWith("savegame/") }) + } + + @Test fun aSavedConflictWhoseSidesNowMatchIsCleared() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + cloud.files["slot0.sav"] = "v2".toByteArray() to 50_000L + File(dir, "slot0.sav").writeText("v2") + com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav").apply() + assertEquals("up-to-date", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false).reason) + assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty()) + com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav").apply() + CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty()) + } + + @Test fun aDownloadTheLaunchStoppedWaitingForWritesNothing() { + val game = id; val dir = dir() + File(dir, "slot0.sav").writeText("local") + val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L } + val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true, claim = { false }) + assertEquals("skipped", r.result); assertEquals("launch-moved-on", r.reason) + assertEquals("local", File(dir, "slot0.sav").readText()) + assertFalse(File(app.filesDir, "stores/cloud-backups/gog-$game").exists()) + var claimed = 0 + assertEquals("ok", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true, claim = { claimed++; true }).result) + assertEquals(1, claimed); assertEquals("v1", File(dir, "slot0.sav").readText()) + } + @Test fun aFileChangedOnBothSidesIsLeftForTheUser() { val game = id; val dir = dir() val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L } @@ -65,6 +142,134 @@ class CloudSavesTest { assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty()) } + @Test fun aSlotTheGameRewritesDuringADownloadIsKeptAndNamedAsAConflict() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + cloud.files["slot0.sav"] = "cloud v2".toByteArray() to 50_000L + cloud.onGet = { File(dir, "slot0.sav").writeText("game wrote") } + val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("partial", r.result); assertEquals("changed-locally", r.reason); assertEquals(1, r.conflicts) + assertTrue(r.detail.contains("slot0.sav")) + assertEquals("game wrote", File(dir, "slot0.sav").readText()) + assertEquals(listOf("slot0.sav"), CloudSaves.conflicts(app, Store.GOG, game)) + } + + @Test fun aCloudNameOutsideTheSaveFolderIsBlockedNotAConflict() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["../escape.sav"] = "x".toByteArray() to 1000L } + val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("partial", r.result); assertEquals("blocked-path", r.reason); assertEquals(0, r.conflicts) + assertTrue(r.detail.contains("../escape.sav")) + assertFalse(File(dir.parentFile, "escape.sav").exists()) + assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty()) + } + + @Test fun anUploadStoppedByANewerCloudWriteKeepsTheRestAsConflicts() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["a.sav"] = "a1".toByteArray() to 1000L; files["b.sav"] = "b1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + File(dir, "a.sav").writeText("a2"); File(dir, "b.sav").writeText("b2") + cloud.raceAfter = 1 + val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("partial", r.result); assertEquals("changed-in-cloud", r.reason); assertEquals(1, r.files) + val unsent = listOf("a.sav", "b.sav").single { it !in cloud.puts } + assertEquals(listOf(unsent), CloudSaves.conflicts(app, Store.GOG, game)) + } + + @Test fun aForcedUploadKeepsConflictsForSlotsItDidNotSend() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L; files["slot1.sav"] = "w1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + File(dir, "slot0.sav").writeText("local v2"); File(dir, "slot1.sav").delete() + cloud.files["slot0.sav"] = "cloud v2".toByteArray() to 50_000L + com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav\nslot1.sav").apply() + CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = true) + assertEquals("local v2", String(cloud.files.getValue("slot0.sav").first)) + assertEquals(listOf("slot1.sav"), CloudSaves.conflicts(app, Store.GOG, game)) + } + + private fun ubisoftDir(user: String, root: File = File(app.filesDir, "ubi-${System.nanoTime()}")) = File(root, "$user/77").apply { mkdirs() } + + @Test fun aSlotBothSidesSavedAlikeIsNotAConflictWhenTheCloudNamesOnlyAVersion() { + val game = id; val dir = ubisoftDir("u1") + val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) } + assertEquals("ok", CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false).result) + File(dir, "1.save").writeBytes(MemorySlots.save("a2")) + slots.store("1", MemorySlots.save("a2")) + val down = CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + assertEquals(0, down.conflicts) + assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, dir).isEmpty()) + val up = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + assertEquals("up-to-date", up.reason); assertEquals(0, up.conflicts) + File(dir, "1.save").writeBytes(MemorySlots.save("a3 local")) + slots.store("1", MemorySlots.save("a3 cloud")) + assertEquals(1, CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false).conflicts) + } + + @Test fun aNewUbisoftSaveWithAnEmptyIdentifierIsStampedAndUploaded() { + val game = id; val dir = ubisoftDir("u1") + val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) } + CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + File(dir, "2.save").writeBytes("UBISAVE0".toByteArray() + ByteArray(32) + "fresh slot".toByteArray()) + File(dir, "3.save").writeBytes("UBISAVE0".toByteArray() + "not-an-identifier-but-not-empty!".toByteArray()) + val up = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + assertEquals("uploaded", up.reason) + val stamped = UbisoftCloud.mark(File(dir, "2.save").readBytes()) + assertTrue(stamped != null) + assertEquals("fresh slot", String(File(dir, "2.save").readBytes().copyOfRange(40, 50))) + assertEquals(stamped, UbisoftCloud.mark(slots.data.getValue("2"))) + assertFalse("3" in slots.data) + assertEquals("not-an-identifier-but-not-empty!", String(File(dir, "3.save").readBytes().copyOfRange(8, 40))) + } + + @Test fun aSlotCommittedBeforeALaterOneFailsReachesTheBaseline() { + val game = id; val dir = ubisoftDir("u1") + val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")); store("2", MemorySlots.save("b1")) } + CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + File(dir, "1.save").writeBytes(MemorySlots.save("a2")); File(dir, "2.save").writeBytes(MemorySlots.save("b2")) + slots.uploadsLeft = 1 + assertTrue(runCatching { CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) } + .exceptionOrNull() is java.io.IOException) + val base = CloudSaves.baseline(app, Store.UBISOFT, CloudSaves.scope(Store.UBISOFT, game, dir))!! + val sent = listOf("1", "2").single { slots.data.getValue(it).contentEquals(MemorySlots.save(if (it == "1") "a2" else "b2")) } + val kept = if (sent == "1") "2" else "1" + assertEquals(CloudSaves.md5(File(dir, "$sent.save")), base.getValue("$sent.save").localMd5) + assertEquals(CloudSaves.md5(MemorySlots.save(if (kept == "1") "a1" else "b1")), base.getValue("$kept.save").localMd5) + slots.uploadsLeft = Int.MAX_VALUE + val r = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + assertEquals("ok", r.result); assertEquals(1, r.files); assertEquals(0, r.conflicts) + } + + @Test fun ubisoftConflictsBelongToTheAccountAndProductThatHadThem() { + val game = id; val root = File(app.filesDir, "ubi-${System.nanoTime()}") + val a = ubisoftDir("uA", root); val b = ubisoftDir("uB", root) + val cloudB = Memory().apply { files["slot0.save"] = "b1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.UBISOFT, game, b, cloudB, force = false) + File(b, "slot0.save").writeText("b local") + val cloudA = Memory().apply { files["slot0.save"] = "a1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.UBISOFT, game, a, cloudA, force = false) + File(a, "slot0.save").writeText("a local") + cloudA.files["slot0.save"] = "a2".toByteArray() to 50_000L + assertEquals(1, CloudSaves.downWith(app, Store.UBISOFT, game, a, cloudA, force = false).conflicts) + assertEquals(listOf("slot0.save"), CloudSaves.conflicts(app, Store.UBISOFT, game, a)) + assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, b).isEmpty()) + CloudSaves.downWith(app, Store.UBISOFT, game, b, cloudB, force = true) + assertEquals("b local", File(b, "slot0.save").readText()) + com.droiddeck.launcher.stores.epic.EpicPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.save").apply() + assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, ubisoftDir("uC", root)).isEmpty()) + assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game).isEmpty()) + } + + @Test fun aUbisoftGameAddedFromAnotherFolderIsFoundForCloudSaves() { + val game = id + val folder = File(app.filesDir, "Elsewhere/Anno-$game").apply { mkdirs() } + File(folder, "Anno.exe").writeText("MZ") + StoreGameSidecar(Store.UBISOFT, game, "Anno", "Anno.exe", extra = mapOf("productId" to "77")).write(folder) + com.droiddeck.launcher.session.SessionPrefs.followStoreGame(app, "ubisoft:$game", folder.path) { true } + assertEquals("not-signed-in", CloudSaves.status(app, Store.UBISOFT, game).reason) + } + @Test fun aDirtyMarkStaysUntilAnUploadGoesThroughOrIsSkippedForGood() { val gameId = "1207664643" val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN-mark").apply { mkdirs() } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/download/DownloadEntryTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/download/DownloadEntryTest.kt index 46b38647c..914089a2c 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/download/DownloadEntryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/download/DownloadEntryTest.kt @@ -24,4 +24,45 @@ class DownloadEntryTest { assertFalse(e.passed(DownloadStage.INSTALL)) assertTrue(e.copy(state = DownloadState.INSTALLED).passed(DownloadStage.INSTALL)) } + + @Test fun streamingInstallKeepsDownloadAndInstallProgressApart() { + val installBit = 1 shl DownloadStage.INSTALL.ordinal + val installing = base.copy(stage = DownloadStage.INSTALL, bytesDone = 10, bytesTotal = 100, stageDone = 25, stageTotal = 100) + assertTrue(installing.streaming) + assertEquals(0.10f, installing.downloadFraction, 0.001f) + assertEquals(0.25f, installing.installFraction, 0.001f) + val backToDownload = installing.copy(stage = DownloadStage.DOWNLOAD, stagesPassed = installBit) + assertTrue(backToDownload.streaming) + assertEquals(0.25f, backToDownload.installFraction, 0.001f) + assertFalse(base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 10, bytesTotal = 100).streaming) + assertTrue(installing.copy(bytesDone = 99_950, bytesTotal = 100_000).streaming) + assertTrue(installing.copy(bytesDone = 99_999_999, bytesTotal = 100_000_000).streaming) + assertFalse(installing.copy(bytesDone = 100).streaming) + assertFalse(installing.copy(state = DownloadState.PAUSED).streaming) + } + + @Test fun overallProgressOnlyGrowsAcrossSequentialAndStreamingStages() { + val installBit = 1 shl DownloadStage.INSTALL.ordinal + val downloadBit = 1 shl DownloadStage.DOWNLOAD.ordinal + val sequential = listOf( + base.copy(stage = DownloadStage.MANIFEST), + base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 50, bytesTotal = 100), + base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 100, bytesTotal = 100), + base.copy(stage = DownloadStage.INSTALL, bytesDone = 100, bytesTotal = 100, stagesPassed = downloadBit, stageDone = 0, stageTotal = 10), + base.copy(stage = DownloadStage.INSTALL, bytesDone = 100, bytesTotal = 100, stagesPassed = downloadBit, stageDone = 10, stageTotal = 10), + base.copy(state = DownloadState.INSTALLED), + ).map { it.overallFraction } + assertEquals(sequential, sequential.sorted()) + assertEquals(1f, sequential.last(), 0f) + val streaming = listOf( + base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 10, bytesTotal = 100), + base.copy(stage = DownloadStage.INSTALL, bytesDone = 20, bytesTotal = 100, stageDone = 15, stageTotal = 100), + base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 40, bytesTotal = 100, stageDone = 15, stageTotal = 100, stagesPassed = installBit), + base.copy(stage = DownloadStage.INSTALL, bytesDone = 60, bytesTotal = 100, stageDone = 55, stageTotal = 100, stagesPassed = installBit), + base.copy(stage = DownloadStage.DOWNLOAD, bytesDone = 100, bytesTotal = 100, stageDone = 60, stageTotal = 100, stagesPassed = installBit), + base.copy(stage = DownloadStage.INSTALL, bytesDone = 100, bytesTotal = 100, stageDone = 80, stageTotal = 100, stagesPassed = installBit or downloadBit), + ).map { it.overallFraction } + assertEquals(streaming, streaming.sorted()) + } } + diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt index b9deb11a1..2a3ed5ce6 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.stores.ea import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.CloudSaves import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreLaunch @@ -413,4 +414,190 @@ class EaTest { assertTrue(!EaAuth.storeRefreshed(app, "late", 3600, "r3")) assertNull(EaAuth.load(app)) } + + private fun tokenServer(status: String, error: String = "invalid_grant"): java.net.ServerSocket { + val server = java.net.ServerSocket(0) + Thread { + runCatching { + server.accept().use { socket -> + val input = socket.getInputStream() + val head = StringBuilder() + while (!head.endsWith("\r\n\r\n")) head.append(input.read().takeIf { it >= 0 }?.toChar() ?: break) + val length = Regex("(?i)content-length: *(\\d+)").find(head)?.groupValues?.get(1)?.toInt() ?: 0 + repeat(length) { input.read() } + val body = """{"error":"$error"}""".toByteArray() + socket.getOutputStream().apply { + write("HTTP/1.1 $status\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray()) + write(body) + flush() + } + } + } + }.apply { isDaemon = true; start() } + return server + } + + @Test fun aRejectedRefreshAsksForSignInWhileAnUnreachableOneKeepsTheSessionForARetry() { + val app = org.robolectric.RuntimeEnvironment.getApplication() + val real = EaAuth.tokenUrl + try { + com.droiddeck.launcher.stores.StoreAccounts.write(app, Store.EA, + JSONObject().put("access_token", "old").put("refresh_token", "r").put("expires_at", 1L).put("user_id", "1")) + EaAuth.tokenUrl = "http://127.0.0.1:1/" + assertNull(EaAuth.accessToken(app)) + assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn) + tokenServer("503 Service Unavailable", "temporarily_unavailable").use { server -> + EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/" + assertNull(EaAuth.accessToken(app)) + } + assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn) + tokenServer("400 Bad Request", "invalid_client").use { server -> + EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/" + assertNull(EaAuth.accessToken(app)) + } + assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn) + tokenServer("400 Bad Request").use { server -> + EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/" + assertNull(EaAuth.accessToken(app)) + } + assertFalse(CloudSaves.status(app, Store.EA, "x").signedIn) + assertTrue(EaAuth.storeRefreshed(app, "new", 3600, "r2")) + assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn) + } finally { + EaAuth.tokenUrl = real + EaAuth.signOut(app) + } + } + + private val heat = """ +%Documents%/Need for Speed Heat/SaveGame/savegame/ +%Documents%/Need for Speed Heat/SaveGame/wraps/ +%Documents%/Need for Speed Heat/settings/PROFILEOPTIONS +""" + + @Test fun rulesFindTheFolderTheyShareAndPickOnlyTheirFiles() { + val rules = EaSaveRules.parse(heat)!! + assertEquals("%Documents%/Need for Speed Heat/", rules.base()) + assertEquals("%DOCUMENTS%/Need for Speed Heat/", EaSaveRules.template(rules.base()!!)) + assertTrue(rules.matches("%Documents%/Need for Speed Heat/SaveGame/savegame/1")) + assertTrue(rules.matches("%documents%\\need for speed heat\\settings\\PROFILEOPTIONS")) + assertFalse(rules.matches("%Documents%/Need for Speed Heat/settings/PROFILEOPTIONS.bak")) + assertFalse(rules.matches("%Documents%/Need for Speed Heat/Logs/crash.txt")) + } + + @Test fun globsStayInsideTheirFolderAndExcludesWin() { + val bf = EaSaveRules.parse("""%Documents%/Battlefield 6/settings/*.xml + %Documents%/Battlefield 6/settings/*.sav""")!! + assertEquals("%Documents%/Battlefield 6/settings/", bf.base()) + assertTrue(bf.matches("%Documents%/Battlefield 6/settings/a.sav")) + assertFalse(bf.matches("%Documents%/Battlefield 6/settings/sub/a.sav")) + val le = EaSaveRules.parse(""" + %Documents%/BioWare/Mass Effect Legendary Edition/Config/ + %Documents%/BioWare/Mass Effect Legendary Edition/""")!! + assertTrue(le.matches("%Documents%/BioWare/Mass Effect Legendary Edition/Save/ME1/x.pcsav")) + assertFalse(le.matches("%Documents%/BioWare/Mass Effect Legendary Edition/Config/GamerSettings.ini")) + assertNull(EaSaveRules.parse("")) + assertNull(EaSaveRules.parse("""C:/Games/x/""")!!.base()) + } + + @Test fun rulesApplyInTheirOrderAndTheFirstMatchDecides() { + val rules = EaSaveRules.parse(""" +%Documents%/Game/Config/ +%Documents%/Game/Config/keys.ini +%Documents%/Game/""")!! + assertTrue(rules.matches("%Documents%/Game/Config/keys.ini")) + assertFalse(rules.matches("%Documents%/Game/Config/video.ini")) + assertTrue(rules.matches("%Documents%/Game/Save/1.sav")) + } + + @Test fun aBarePatternMatchesFileNamesInsideTheSaveFolder() { + val dig = EaSaveRules.parse(""" +%Documents%/My Games/SteamWorld Dig/controls.cfg +%Documents%/My Games/SteamWorld Dig/settings.xml +*.xml +%Documents%/My Games/SteamWorld Dig/profile.dat""")!! + assertEquals("%Documents%/My Games/SteamWorld Dig/", dig.base()) + assertTrue(dig.matches("%Documents%/My Games/SteamWorld Dig/profile1.xml")) + assertFalse(dig.matches("%Documents%/My Games/SteamWorld Dig/settings.xml")) + assertFalse(dig.matches("%Documents%/Other Game/profile1.xml")) + val witness = EaSaveRules.parse("""%AppData%/The Witness/**.png""")!! + assertEquals("%AppData%/The Witness/", witness.base()) + assertTrue(witness.matches("%AppData%/The Witness/shot.png")) + } + + @Test fun localLowAndInstallFoldersResolveToTheirTemplates() { + val fe = EaSaveRules.parse("""%LocalLowAppData%/Zoink Games/Fe/SystemSettings.sav +%LocalLowAppData%/Zoink Games/Fe/Save1.sav""")!! + assertEquals("%APPLICATION_DATA_LOCAL_LOW%/Zoink Games/Fe/", EaSaveRules.template(fe.base()!!)) + val castle = EaSaveRules.parse("""%InstallDir%/x86/Lost_Castle_Data/lc_game_data +%InstallDir%/x64/Lost_Castle_Data/lc_game_data""")!! + assertEquals("%INSTALL%/", EaSaveRules.template(castle.base()!!)) + assertTrue(castle.matches("%InstallDir%/x64/Lost_Castle_Data/lc_game_data")) + assertFalse(castle.matches("%InstallDir%/x64/Lost_Castle_Data/other")) + } + + @Test fun aManifestWithSingleQuotedAttributesKeepsEveryField() { + val m = EaCloud.parse(""" + %Documents%/A & B/1 + s1""") + val f = m.files.single() + assertEquals(12L, f.size); assertEquals("content/12-ab", f.href); assertEquals("q+w==", f.md5) + assertEquals("2022-10-17T23:51:04ZZ", f.created); assertEquals("2022-10-18T00:00:00ZZ", f.modified) + assertEquals("%Documents%/A & B/1", f.localName) + assertEquals("{1}", m.lineage); assertEquals(listOf("s1"), m.snapshots) + assertTrue(runCatching { EaCloud.parse("") }.isFailure) + } + + @Test fun aManifestKeepsItsFilesSnapshotsAndEaTimestampsThroughAWrite() { + val xml = """ + + %Documents%/Need for Speed Heat/SaveGame/savegame/1 + + 80cmnqT/rIKQRmciINSVhQ== +""" + val m = EaCloud.parse(xml) + assertEquals(1, m.files.size) + assertEquals("c7996be80a6e38d1f8ef28866b114f8b", EaCloud.hex(m.files[0].md5)) + assertEquals(1666050664000L, EaCloud.parseTime(m.files[0].modified)) + assertEquals("2022-10-17T23:51:04ZZ", EaCloud.stamp(1666050664123L)) + val again = EaCloud.parse(EaCloud.write(m)) + assertEquals(m.files.single().localName, again.files.single().localName) + assertEquals(m.files.single().href, again.files.single().href) + assertEquals(m.files.single().created, again.files.single().created) + assertEquals(m.files.single().modified, again.files.single().modified) + assertEquals(m.files.single().size, again.files.single().size) + assertEquals(m.files.single().md5, again.files.single().md5) + assertEquals(listOf("80cmnqT/rIKQRmciINSVhQ=="), again.snapshots) + assertEquals(m.lineage, again.lineage) + } + + @Test fun commentedRulesAreIgnoredAndNamesKeepTheirSpaces() { + val rules = EaSaveRules.parse(""" + + %Documents%/Game/ """)!! + assertEquals(listOf("%Documents%/Game/"), rules.includes) + assertTrue(rules.excludes.isEmpty()) + assertTrue(rules.matches("%Documents%/Game/Config/a.ini")) + assertEquals("%Documents%/Game/slot.sav ", EaSaveRules.normalize("%Documents%\\Game\\slot.sav ")) + } + + @Test fun aTruncatedManifestIsRefused() { + val cut = runCatching { EaCloud.parse("""""") } + assertTrue(cut.isFailure) + val open = runCatching { EaCloud.parse("""%Documents%/a""") } + assertTrue(open.isFailure) + } + + @Test fun snapshotEntitiesAreDecodedOnceAndWrittenBackTheSame() { + val m = EaCloud.parse("""abc+def""") + assertEquals(listOf("abc+def"), m.snapshots) + assertEquals(listOf("abc+def"), EaCloud.parse(EaCloud.write(m)).snapshots) + } + + @Test fun cloudKeysFollowTheMultiplayerId() { + assertEquals(listOf("195133_195133"), EaCloud.keys("195133", "195133")) + assertEquals(listOf("52209", "52209_52209"), EaCloud.keys("52209", "")) + assertEquals("https://x/y?a=1&b=2", EaCloud.manifestUrl("https://x/y?a=1&b=2")) + assertTrue(CloudSaves.supports(Store.EA)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/MemorySlots.kt b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/MemorySlots.kt new file mode 100644 index 000000000..e32909ee7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/MemorySlots.kt @@ -0,0 +1,43 @@ +package com.droiddeck.launcher.stores.ubisoft + +import com.droiddeck.launcher.stores.CloudSaves +import org.json.JSONArray +import org.json.JSONObject +import java.time.Instant + +internal class MemorySlots : UbisoftSlots { + private var record = JSONObject().put("entityId", "e1").put("name", UbisoftCloud.entityName(77L)).put("revision", 1) + .put("obj", JSONObject().put("slots", JSONArray())) + private var clock = 1_700_000_000_000L + val data = HashMap() + var uploadsLeft = Int.MAX_VALUE + var afterUpdate: (JSONArray) -> Unit = {} + + override fun entity() = UbisoftCloud.Entity(JSONObject(record.toString())) + + override fun upload(slot: String, data: ByteArray) { + if (uploadsLeft-- <= 0) throw java.io.IOException("upload failed") + this.data[slot] = data + } + + override fun update(entity: UbisoftCloud.Entity, slots: JSONArray) { + afterUpdate(slots) + record = JSONObject(record.toString()).put("revision", record.getInt("revision") + 1).put("obj", JSONObject().put("slots", slots)) + } + + override fun download(slot: String) = data[slot] + + fun store(slot: String, bytes: ByteArray) { + data[slot] = bytes + val slots = JSONArray(record.getJSONObject("obj").getJSONArray("slots").toString()) + val entry = (0 until slots.length()).map { slots.getJSONObject(it) }.firstOrNull { it.optString("filename") == slot } + ?: JSONObject().put("filename", slot).put("id", slot.toInt()).also { slots.put(it) } + clock += 60_000L + entry.put("hash", UbisoftCloud.mark(bytes)).put("size", bytes.size).put("lastModified", Instant.ofEpochMilli(clock).toString()) + record = JSONObject(record.toString()).put("revision", record.getInt("revision") + 1).put("obj", JSONObject().put("slots", slots)) + } + + companion object { + fun save(tag: String): ByteArray = ("UBISAVE0" + CloudSaves.md5(tag.toByteArray()) + tag).toByteArray() + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt index aecf4ca77..75e2df58c 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt @@ -5,6 +5,7 @@ import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreLaunch import org.json.JSONArray +import java.io.File import org.json.JSONObject import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals @@ -39,6 +40,23 @@ class UbisoftTest { assertEquals("Steam", UbisoftLibrary.thirdParty(steamConfig)) } + @Test fun gamesTheProfileLeavesOutTakeTheirArtFromTheConfiguration() { + val config = "version: 2.0\r\nroot:\r\n name: l1\r\n thumb_image: THUMBIMAGE\r\n background_image: 'b4c1.jpg'\r\n" + + " installer:\r\n thumb_image: nested.jpg\r\nlocalizations:\r\n default:\r\n l1: \"Assassin's Creed\u2122\"\r\n THUMBIMAGE: a3a6.jpg\r\n" + val owned = JSONObject().put("games", JSONArray() + .put(JSONObject().put("productId", 109).put("spaceId", "space-sc").put("productType", 0).put("owned", true).put("manifest", "AB").put("configuration", config)) + .put(JSONObject().put("productId", 82).put("spaceId", "space-ac").put("productType", 0).put("owned", true).put("manifest", "CD").put("configuration", config))) + val art = CatalogItem(Store.UBISOFT, "space-sc", "Splinter Cell", "https://x/wide.jpg", tallImageUrl = "https://x/tall.jpg", owned = true, extra = mapOf("spaceId" to "space-sc")) + val games = UbisoftLibrary.assemble(listOf(art), owned) + val assets = "https://static3.cdn.ubi.com/orbit/uplay_launcher_3_0/assets/" + val unlisted = games.first { it.id == "space-ac" } + assertEquals("Assassin's Creed\u2122", unlisted.title) + assertEquals(assets + "b4c1.jpg", unlisted.imageUrl) + assertEquals(assets + "a3a6.jpg", unlisted.tallImageUrl) + assertEquals("https://x/wide.jpg", games.first { it.id == "space-sc" }.imageUrl) + assertNull(UbisoftLibrary.image("root:\n thumb_image: THUMBIMAGE\n", "thumb_image")) + } + @Test fun withoutAnOwnershipAnswerTheProfileListStays() { val profile = listOf(listed("space-sc", "Splinter Cell"), listed("space-gone", "Free Weekend")) assertEquals(listOf("space-gone", "space-sc"), UbisoftLibrary.assemble(profile, JSONObject().put("error", "demux closed")).map { it.id }) @@ -98,4 +116,74 @@ class UbisoftTest { assertArrayEquals(bytes, UbisoftActivation.unhex("00017fff802a")) assertNull(UbisoftActivation.unhex("abc")) } + + @Test fun aSaveNamesItsUbisoftIdentifierInItsHeader() { + val mark = "4ef5bf634b40daa577aaeaa52c2283a9" + val save = byteArrayOf(0x24, 2, 0, 0, 0, 0, 0, 0) + mark.toByteArray() + ByteArray(64) { it.toByte() } + assertEquals(mark, UbisoftCloud.mark(save)) + assertNull(UbisoftCloud.mark(ByteArray(8) + ByteArray(32) + ByteArray(16))) + assertNull(UbisoftCloud.mark(ByteArray(39))) + } + + @Test fun cloudSaveBodiesSurviveTheZlibHop() { + val save = ByteArray(200_000) { (it % 251).toByte() } + assertArrayEquals(save, UbisoftCloud.inflate(UbisoftCloud.deflate(save))) + assertEquals(0x78, UbisoftCloud.deflate(save)[0].toInt()) + val packed = UbisoftCloud.deflate(save) + val cut = runCatching { UbisoftCloud.inflate(packed.copyOf(packed.size / 2)) } + assertTrue(cut.isFailure) + } + + @Test fun aSlotVersionChangesWithItsSizeTimeOrIdentifier() { + val a = UbisoftCloud.Slot(1, "1", "4ef5bf634b40daa577aaeaa52c2283a9", 2414, 1_689_224_156_000) + assertEquals("2414:1689224156000:4ef5bf634b40daa577aaeaa52c2283a9", UbisoftCloud.version(a)) + assertTrue(UbisoftCloud.version(a) != UbisoftCloud.version(UbisoftCloud.Slot(1, "1", a.hash, 2414, a.modifiedMs + 1))) + } + + @Test fun aSlotCommitCountsOnlyWhenNoOtherSlotMovedAndOursLanded() { + fun entity(revision: Int, vararg slots: Triple) = UbisoftCloud.Entity(JSONObject().put("revision", revision) + .put("obj", JSONObject().put("slots", JSONArray().apply { + for ((name, hash, size) in slots) put(JSONObject().put("filename", name).put("hash", hash).put("size", size).put("lastModified", "2026-01-01T00:00:00Z")) + }))) + val a = "4ef5bf634b40daa577aaeaa52c2283a9"; val b = "0123456789abcdef0123456789abcdef"; val c = "fedcba9876543210fedcba9876543210" + val before = entity(4, Triple("1", a, 10), Triple("2", b, 20)) + assertEquals(c, UbisoftCloudTransport.committedSlot(before, entity(5, Triple("1", c, 11), Triple("2", b, 20)), "1", c, 11)?.hash) + assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", c, 11), Triple("2", a, 21)), "1", c, 11)) + assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", b, 30), Triple("2", b, 20)), "1", c, 11)) + assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", c, 11)), "1", c, 11)) + } + + @Test fun aSlotTheCloudRewritesBeforeItIsVerifiedStaysUnsent() { + val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) } + val transport = UbisoftCloudTransport(slots, "u1") + transport.list() + slots.afterUpdate = { list -> list.getJSONObject(0).put("hash", UbisoftCloud.mark(MemorySlots.save("other device"))) } + val changed = runCatching { transport.put(mapOf("1.save" to MemorySlots.save("a2"))) }.exceptionOrNull() as com.droiddeck.launcher.stores.CloudChanged + assertTrue(changed.sent.isEmpty()) + assertEquals(listOf("1.save"), changed.unsent) + assertNull(transport.committed("1.save")) + } + + @Test fun ubisoftCloudSavesAreSupported() { + assertTrue(com.droiddeck.launcher.stores.CloudSaves.supports(Store.UBISOFT)) + assertTrue(!com.droiddeck.launcher.stores.CloudSaves.supports(Store.AMAZON)) + } + + @Test fun keptGameTokensBelongToOneAccountAndProductUntilDropped() { + val root = kotlin.io.path.createTempDirectory().toFile() + val dir = File(root, "cache") + val cache = UbisoftActivation.TokenCache(dir) + assertNull(cache.get("u-1", 109)) + assertTrue(cache.put("u-1", 109, byteArrayOf(1, 2, 3))) + assertArrayEquals(byteArrayOf(1, 2, 3), cache.get("u-1", 109)) + assertNull(cache.get("u-1", 82)) + assertNull(cache.get("u-2", 109)) + assertTrue(cache.put("../u-1", 82, byteArrayOf(4))) + assertEquals(listOf("cache"), root.list()!!.toList()) + assertTrue(dir.listFiles()!!.all { it.parentFile == dir }) + assertTrue(cache.drop("u-1", 109)) + assertNull(cache.get("u-1", 109)) + assertTrue(cache.drop("u-1", 109)) + root.deleteRecursively() + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/BottomScreenBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/BottomScreenBarTest.kt index 97389fa28..2af8942ca 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/BottomScreenBarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/BottomScreenBarTest.kt @@ -1,8 +1,11 @@ package com.droiddeck.launcher.ui import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState import org.junit.After @@ -75,4 +78,35 @@ class BottomScreenBarTest { compose.onNodeWithContentDescription(context.getString(R.string.drawer_steam_menu)).assertDoesNotExist() compose.onNodeWithContentDescription(context.getString(R.string.drawer_open_qam)).assertDoesNotExist() } + + @Test fun thePanelNameOpensTheScreenPickerInsteadOfAMenuButton() { + var menus = 0 + val picked = mutableListOf() + val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL, SecondScreenMode.CUSTOM_CONTROLS) + compose.setContent { + DroidDeckTheme { + BottomScreenBar(BottomBarModel("Trackpad", {}, { menus++ }, null, null, + picker = ScreenPicker(modes, SecondScreenMode.KEYBOARD_TRACKPAD, { picked += it }, onMenu = { menus++ }))) + } + } + compose.onNodeWithTag("bottom-bar-menu").assertDoesNotExist() + compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertExists() + compose.onNodeWithTag("bottom-bar-screen").performClick() + compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").performClick() + compose.waitForIdle() + assertEquals(listOf(SecondScreenMode.TERMINAL), picked) + compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-screen").performClick() + compose.onNodeWithTag("screen-picker-menu").performClick() + compose.waitForIdle() + assertEquals(1, menus) + } + + @Test fun focusStartsOnTheMenuFromAPanelAndOnThePanelFromTheMenu() { + val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) + assertNull(ScreenPicker(modes, SecondScreenMode.TERMINAL, {}, onMenu = {}).focusTarget()) + assertEquals(SecondScreenMode.TERMINAL, ScreenPicker(modes, SecondScreenMode.TERMINAL, {}, onMenu = {}, menuShown = true).focusTarget()) + assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, ScreenPicker(modes, SecondScreenMode.NONE, {}, onMenu = {}, menuShown = true).focusTarget()) + assertEquals(SecondScreenMode.TERMINAL, ScreenPicker(modes, SecondScreenMode.TERMINAL, {}).focusTarget()) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CloudMessageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CloudMessageTest.kt index 2bf7360ed..0ada7eba2 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CloudMessageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CloudMessageTest.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.CloudSaves import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -25,6 +26,15 @@ class CloudMessageTest { assertEquals(ctx.getString(R.string.cloud_not_synced), msg("failed", 0, 0, "SocketTimeoutException")) } + @Test fun aPartialSyncNamesTheSlotsItLeft() { + fun partial(conflicts: Int, detail: String) = cloudMessage(ctx, CloudSaves.Result("partial", 0, 0L, "blocked-path", conflicts, detail)) + assertEquals(ctx.getString(R.string.cloud_partial, "outside the save folder: ../x.save"), partial(0, "outside the save folder: ../x.save")) + assertEquals(ctx.getString(R.string.cloud_conflict_files_detail, 2, "changed locally: 1.save, 2.save"), partial(2, "changed locally: 1.save, 2.save")) + assertTrue(partial(1, "changed locally: 1.save").contains("1.save")) + assertEquals(ctx.getString(R.string.cloud_conflict_files, 1), partial(1, "")) + assertEquals(ctx.getString(R.string.cloud_not_synced), partial(0, "")) + } + @Test fun okResultsSayWhatHappened() { assertEquals(ctx.getString(R.string.cloud_up_to_date), msg("ok", 0, 0, "up-to-date")) assertEquals(ctx.getString(R.string.cloud_done, 3), msg("ok", 3, 0, "uploaded")) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryColumnsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryColumnsTest.kt new file mode 100644 index 000000000..3d0340e06 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryColumnsTest.kt @@ -0,0 +1,13 @@ +package com.droiddeck.launcher.ui + +import org.junit.Assert.assertEquals +import org.junit.Test + +class LibraryColumnsTest { + @Test fun everySizeStepChangesTheColumnCountUntilOne() { + val phone = (0..4).map { libraryColumns(width = 1080, base = 450, gap = 30, level = it) } + assertEquals(listOf(4, 3, 2, 1, 1), phone) + val tablet = (0..4).map { libraryColumns(width = 2400, base = 450, gap = 30, level = it) } + assertEquals(listOf(7, 6, 5, 4, 3), tablet) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt index 7674ab242..772578ea3 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt @@ -82,6 +82,25 @@ class LibraryEntriesTest { assertEquals(listOf("steam", "xbox", "epic", "gog", "added"), librarySources(entries, listOf("xbox", "epic", "gog"))) } + @Test fun theLibrarysOwnTabsSitAfterTheTabTheyFollow() { + val entries = listOf("added", "gog", "steam", "epic", "xbox").map { LibraryEntry(it, it, it, null, null, true) } + val order = listOf("xbox", "epic", "gog") + assertEquals(listOf("steam", "xbox", "added", "epic", "gog"), librarySources(entries, order, places = listOf("added" to "xbox"))) + assertEquals(listOf("added", "steam", "xbox", "epic", "gog"), librarySources(entries, order, places = listOf("added" to "", "favorites" to "added", "steam" to "favorites"))) + assertEquals(listOf("xbox", "epic", "steam", "gog", "added"), librarySources(entries, order, places = listOf("favorites" to "epic", "steam" to "favorites", "added" to "nope"))) + } + + @Test fun hidingTheTabALibraryTabFollowsKeepsItInPlace() { + val entries = listOf("added", "gog", "epic", "xbox").map { LibraryEntry(it, it, it, null, null, true) } + assertEquals(listOf("xbox", "added", "gog"), librarySources(entries, listOf("xbox", "epic", "gog"), places = listOf("added" to "epic"), offStores = setOf("epic"))) + } + + @Test fun placesRoundTripThroughTheirOrder() { + val order = listOf("epic", "steam", "favorites", "gog", "xbox", "added") + assertEquals(order, placeLibraryTabs(listOf("epic", "gog", "xbox"), libraryPlacesOf(order))) + assertEquals(listOf("favorites", "steam", "epic", "gog", "added"), placeLibraryTabs(listOf("epic", "gog"), emptyList())) + } + @Test fun librarySourcesIgnoreUnknownAndDuplicateOrderEntriesAndAppendNewStores() { val entries = listOf("epic", "gog", "battlenet").map { LibraryEntry(it, it, it, null, null, false) } assertEquals(listOf("epic", "gog", "battlenet"), librarySources(entries, listOf("missing", "epic", "epic", "amazon"))) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt index 699ca0372..c2ce77dbf 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt @@ -50,4 +50,9 @@ class LibraryFavoritesTest { assertEquals(listOf(LIBRARY_FAVORITES, "steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"))) assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:999"))) } + + @Test fun aHiddenFavoritesTabStaysHiddenWithHeartedGames() { + val entries = listOf(steam(440, "Team Fortress 2"), owned("123", "Witcher")) + assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"), offTabs = setOf(LIBRARY_FAVORITES))) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt index ac5835c2a..0cea327e8 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt @@ -30,10 +30,16 @@ class LibraryHiddenTest { assertFalse(inLibrarySource(LIBRARY_HIDDEN, cs, emptySet(), hidden)) } - @Test fun theHiddenTabIsLastAndOnlyWhenEnabled() { + @Test fun theHiddenTabIsLastAndOnlyWhenTurnedOn() { val entries = listOf(tf2, cs) assertEquals(listOf(Library.SOURCE_STEAM), librarySources(entries, emptyList(), hidden = hidden)) - assertEquals(listOf(Library.SOURCE_STEAM, LIBRARY_HIDDEN), librarySources(entries, emptyList(), hidden = hidden, showHidden = true)) + assertEquals(listOf(Library.SOURCE_STEAM, LIBRARY_HIDDEN), librarySources(entries, emptyList(), hidden = hidden, offTabs = emptySet())) + } + + @Test fun theHiddenTabSortsLastUnlessMoved() { + assertEquals(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, "epic", Library.ADDED, LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic"), DEFAULT_LIBRARY_PLACES)) + val moved = placeLibraryTabs(listOf("epic"), listOf(LIBRARY_HIDDEN to "epic")) + assertEquals(listOf("epic", LIBRARY_HIDDEN), moved.filter { it == "epic" || it == LIBRARY_HIDDEN }) } @Test fun aStoreTabWithOnlyHiddenGamesDisappears() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt index f6085e512..2630a3314 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt @@ -76,52 +76,41 @@ class LibraryVisibilityTest { LibraryView.focusFirst = false } - @Test fun uninstalledGamesAreHiddenUntilSelectedInTheFilterAndTheChoiceSurvivesReopeningLibrary() { + @Test fun uninstalledGamesStayFoldedUnderTheirRowAndTheChoiceSurvivesReopeningLibrary() { show() compose.onNodeWithText("Installed Steam game").assertExists() compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() - chooseVisibility(true) + compose.onNodeWithText("NOT INSTALLED · 2").assertExists() + toggleNotInstalled(true) compose.onNodeWithText("Uninstalled GOG").assertExists() - assertTrue(SessionPrefs.libraryShowUninstalled(ctx)) compose.runOnIdle { generation++; Snapshot.sendApplyNotifications() } compose.mainClock.advanceTimeBy(2_000) compose.onNodeWithText("Uninstalled GOG").assertExists() - chooseVisibility(false) + toggleNotInstalled(false) compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() - assertFalse(SessionPrefs.libraryShowUninstalled(ctx)) } - @Test fun theFilterExpandsBesideSortWithoutChangingTheSelectionOnOpen() { + @Test fun theNotInstalledRowReplacesTheFilterButtonAndSortStillOpens() { show() - val filter = compose.onNodeWithContentDescription("Filter · Installed only") - val sort = compose.onNodeWithContentDescription("Sort") - assertTrue(filter.fetchSemanticsNode().boundsInRoot.right <= sort.fetchSemanticsNode().boundsInRoot.left) - filter.performClick() - compose.mainClock.advanceTimeBy(2_000) - compose.onNodeWithText("Installed only").assertIsDisplayed() - compose.onNodeWithText("All owned games").assertIsDisplayed() - compose.onAllNodesWithText("Filter").assertCountEquals(1) - compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() + compose.onNodeWithContentDescription("Filter · Installed only").assertDoesNotExist() + compose.onNodeWithTag("library-not-installed").assertExists() assertFalse(SessionPrefs.libraryShowUninstalled(ctx)) - compose.runOnIdle { Steps.fold(); Snapshot.sendApplyNotifications() } - compose.mainClock.advanceTimeBy(1_000) - sort.performClick() + compose.onNodeWithContentDescription("Sort").performClick() compose.mainClock.advanceTimeBy(2_000) compose.onAllNodesWithText("Sort").assertCountEquals(1) compose.onNodeWithText("Recently played").assertIsDisplayed() } - @Test fun theXboxAccessChoicesShareTheLibraryFilter() { + @Test fun theXboxFilterOnlyOffersTheXboxAccessChoices() { StoreAccounts.write(ctx, Store.XBOX, JSONObject().put("username", "Library test")) StoresState.accounts[Store.XBOX] = "Library test" StoresState.library[Store.XBOX] = listOf(CatalogItem(Store.XBOX, "owned", "Uninstalled Xbox", null, owned = true)) LibraryView.source = Store.XBOX.id try { show() - compose.onNodeWithContentDescription("Filter · Installed only").performClick() + compose.onNodeWithContentDescription("Filter · All").performClick() compose.mainClock.advanceTimeBy(2_000) - compose.onNodeWithText("Installed only").assertIsDisplayed() - compose.onNodeWithText("All owned games").assertIsDisplayed() + compose.onNodeWithText("Installed only").assertDoesNotExist() compose.onNodeWithText("Game Pass").assertIsDisplayed().performClick() compose.mainClock.advanceTimeBy(1_000) assertEquals(XboxLibraryFilter.GAME_PASS, XboxLibraryFilter.current) @@ -131,31 +120,64 @@ class LibraryVisibilityTest { } } - @Test fun aSearchWithOnlyUninstalledMatchesOffersToRevealThem() { + @Test fun aSearchWithOnlyUninstalledMatchesShowsTheFoldedRowToRevealThem() { LibraryView.query = "Uninstalled GOG" show() compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() - compose.onNodeWithTag("library-browse-owned").performClick() + compose.onNodeWithText("No installed games match these filters", substring = true).assertDoesNotExist() + compose.onNodeWithTag("library-not-installed").performClick() compose.mainClock.advanceTimeBy(1_000) compose.onNodeWithText("Uninstalled GOG").assertExists() assertEquals("Uninstalled GOG", LibraryView.query) + compose.onNodeWithTag("library-not-installed").performClick() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() + compose.onNodeWithTag("library-not-installed").assertExists() } - @Test fun aHiddenStoreRemainsReachableInLibraryInItsConfiguredOrder() { + @Test fun aSwitchedOffStoreLeavesTheChipsButItsGamesStayUnderAll() { SessionPrefs.setStoresTabOrder(ctx, listOf("epic", "gog")) SessionPrefs.setStoresTabHidden(ctx, setOf("gog")) show() val steam = compose.onNodeWithTag("library-source-steam").fetchSemanticsNode().boundsInRoot.left val epic = compose.onNodeWithTag("library-source-epic").fetchSemanticsNode().boundsInRoot.left - val gog = compose.onNodeWithTag("library-source-gog").fetchSemanticsNode().boundsInRoot.left - assertTrue(steam < epic && epic < gog) - compose.onNodeWithTag("library-source-gog").performClick() - compose.mainClock.advanceTimeBy(1_000) - compose.onNodeWithTag("library-browse-owned").assertIsDisplayed().performClick() + assertTrue(steam < epic) + compose.onNodeWithTag("library-source-gog").assertDoesNotExist() + compose.onNodeWithTag("library-not-installed").performClick() compose.mainClock.advanceTimeBy(1_000) compose.onNodeWithText("Uninstalled GOG").assertExists() } + @Test fun anEmptyLibraryStillShowsItsChipsSoCustomGamesAndSignInAreReachable() { + for (store in listOf(Store.GOG, Store.EPIC)) StoreAccounts.clear(ctx, store) + StoresState.library.clear() + StoresState.accounts.clear() + compose.mainClock.autoAdvance = false + compose.setContent { + DroidDeckTheme { + CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) { + FocusGlideHost { Box(Modifier.fillMaxSize()) { + LibraryPage(state(emptyList()), actions(), "games", {}, Modifier.fillMaxSize()) + } } + } + } + } + compose.mainClock.advanceTimeBy(2_000) + compose.onNodeWithTag("library-source-added").performClick() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithTag("library-custom-empty").assertExists() + } + + @Test fun theCustomGamesTabIsAlwaysThereAndOffersToAddWhenEmpty() { + show() + compose.onNodeWithTag("library-source-added").performClick() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithTag("library-custom-empty").assertExists() + compose.onNodeWithTag("library-custom-add").performClick() + assertTrue(GamesDialogState.adding) + GamesDialogState.adding = false + } + @Test fun theStoresOwnedGamesLinkRevealsOwnedGamesDespiteTheSavedInstalledOnlyView() { assertFalse(SessionPrefs.libraryShowUninstalled(ctx)) LibraryView.showOwned(ctx, Store.GOG) @@ -188,22 +210,17 @@ class LibraryVisibilityTest { compose.mainClock.advanceTimeBy(2_000) } - private fun chooseVisibility(show: Boolean) { - compose.onNodeWithContentDescription("Filter · " + if (SessionPrefs.libraryShowUninstalled(ctx)) "All owned games" else "Installed only") - .performClick() - compose.mainClock.advanceTimeBy(2_000) - assertTrue(Steps.open) - compose.onNodeWithText(if (show) "All owned games" else "Installed only") - .performClick() + private fun toggleNotInstalled(show: Boolean) { + compose.onNodeWithTag("library-not-installed").performClick() compose.mainClock.advanceTimeBy(1_000) assertEquals(show, SessionPrefs.libraryShowUninstalled(ctx)) } - private fun state() = FrontEndState( + private fun state(games: List = listOf(Library.SteamGame(440, "Installed Steam game", null, "internal"))) = FrontEndState( installed = "r9", ready = true, available = null, busy = false, stage = "", percent = -1, desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "", romsDir = null, logsEnabled = false, - steamGames = listOf(Library.SteamGame(440, "Installed Steam game", null, "internal")), + steamGames = games, emulators = emptyList(), running = null, ) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt index 477984315..a2e7f61c3 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt @@ -76,9 +76,10 @@ class SecondScreenBarTest { return (0 until root.childCount).map { root.getChildAt(it) } } - @Test fun trackpadPanelHasTheBarWithTheKeyboardToggleState() { + @Test fun trackpadPanelHasTheBarWithTheKeyboardToggleStateAndSwap() { SessionState.mode = SessionService.MODE_STEAM - val panel = presentation() + var swaps = 0 + val panel = presentation { swaps++ } try { panel.show() panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD) @@ -89,11 +90,15 @@ class SecondScreenBarTest { assertEquals(context.getString(R.string.second_mode_keyboard_trackpad), bar.title) assertNotNull(bar.onClose); assertNotNull(bar.onMenu); assertNotNull(bar.onSteam); assertNotNull(bar.onQam) assertNull(bar.tabs) - val keyboard = bar.extras.single() + assertEquals(listOf("bottom-keyboard", "bottom-swap"), bar.extras.map { it.tag }) + val keyboard = bar.extras.first() assertEquals(context.getString(R.string.second_show_keyboard), keyboard.description) assertFalse(keyboard.active) + bar.extras.last().onClick() + assertEquals(1, swaps) + assertEquals(listOf("bottom-keyboard", "bottom-swap"), panel.barModel(SecondScreenMode.TERMINAL)!!.extras.map { it.tag }) ReflectionHelpers.getField>(panel, "keyboardShown").value = true - val shown = panel.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.single() + val shown = panel.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.first() assertEquals(context.getString(R.string.second_hide_keyboard), shown.description) assertTrue(shown.active) } finally { panel.closeControls() } @@ -130,6 +135,8 @@ class SecondScreenBarTest { noSwap.show() noSwap.showMode(SecondScreenMode.DECK_CONTROLS) assertTrue(noSwap.barModel(SecondScreenMode.DECK_CONTROLS)!!.extras.isEmpty()) + assertEquals(listOf("bottom-keyboard"), noSwap.barModel(SecondScreenMode.TERMINAL)!!.extras.map { it.tag }) + assertEquals(listOf("bottom-keyboard"), noSwap.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.map { it.tag }) } finally { noSwap.closeControls() } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index 58b8ba055..adbbbe248 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -4,33 +4,29 @@ import org.junit.Assert.* import org.junit.Test class SessionDrawerPageTest { - @Test fun singleScreenNavigationStartsWithControllerAndSkipsSecondScreen() { - val pages = sessionDrawerPages(false, hasAgent = false) + @Test fun navigationStartsWithControllerAndGoesStraightToDisplay() { + val pages = sessionDrawerPages(hasAgent = false) assertEquals(SessionDrawerPage.CONTROLLER, pages.first()) - assertFalse(SessionDrawerPage.SECOND_SCREEN in pages) assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1)) assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1)) assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1)) + assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) + assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) + assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1)) + assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1)) + assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1)) } - @Test fun connectedSecondaryDisplayAddsItsPageAfterControllerAndPreservesOtherPages() { - val connected = sessionDrawerPages(true, hasAgent = false) - assertEquals(SessionDrawerPage.SECOND_SCREEN, connected.step(SessionDrawerPage.CONTROLLER, 1)) - assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1)) - assertEquals(sessionDrawerPages(false, hasAgent = false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN }) - for (pages in listOf(connected, sessionDrawerPages(false, hasAgent = false))) { - assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) - assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) - assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1)) - assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1)) - assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1)) - } + @Test fun glassesAddTheirPageAfterController() { + val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false) + assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1)) + assertEquals(sessionDrawerPages(hasAgent = false), pages.filter { it != SessionDrawerPage.GLASSES }) } @Test fun theAgentPageComesBeforeSessionOnlyWhenTheTabIsShown() { - val with = sessionDrawerPages(false, hasAgent = true) + val with = sessionDrawerPages(hasAgent = true) assertEquals(SessionDrawerPage.AGENT, with.step(SessionDrawerPage.GAMES, 1)) assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1)) - assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(false, hasAgent = false)) + assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false)) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt index f88a8d008..8085debe1 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -80,7 +80,7 @@ class SessionSecondScreenTest { var selected = SecondScreenMode.CUSTOM_CONTROLS compose.setContent { DroidDeckTheme { - SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(true, listOf(SecondScreenDisplay(1, "Bottom screen")), onClose = { closes++ }, select = { selected = it }), docked = true) } @@ -90,18 +90,47 @@ class SessionSecondScreenTest { assertEquals(SecondScreenMode.CUSTOM_CONTROLS, selected) } - @Test fun desktopWithoutASecondDisplayFallsBackToController() { + @Test fun desktopWithoutASecondDisplayHasNoScreenPicker() { SessionState.mode = SessionService.MODE_DESKTOP - var page = SessionDrawerPage.SECOND_SCREEN compose.setContent { DroidDeckTheme { - SessionDrawer(true, page, false, { page = it }, actions(false, emptyList())) + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(false, emptyList())) } } - compose.runOnIdle { assertEquals(SessionDrawerPage.CONTROLLER, page) } + compose.onNodeWithTag("drawer-screen-picker").assertDoesNotExist() compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertDoesNotExist() } + @Test fun dockedMenuPickerReturnsToThePanelAndHasNoMenuButton() { + SessionState.mode = SessionService.MODE_STEAM + val selected = mutableListOf() + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, + actions(true, listOf(SecondScreenDisplay(1, "Bottom screen")), mode = SecondScreenMode.TERMINAL) { selected += it }, + docked = true) + } + } + compose.onNodeWithTag("bottom-bar-menu").assertDoesNotExist() + compose.onNodeWithContentDescription(context.getString(R.string.screen_picker_description, + context.getString(R.string.touch_droiddeck_menu))).performClick() + compose.onNodeWithTag("screen-picker-menu").assertExists() + compose.onNodeWithTag("screen-picker:${SecondScreenMode.TERMINAL.id}").performClick() + assertEquals(listOf(SecondScreenMode.TERMINAL), selected) + } + + @Test fun displayPageCarriesTheGameScreenAndDisplayChoices() { + SessionState.mode = SessionService.MODE_STEAM + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.DISPLAY, false, {}, + actions(true, listOf(SecondScreenDisplay(1, "Bottom screen"), SecondScreenDisplay(2, "Monitor")), gameSwap = true)) + } + } + compose.onNodeWithText(context.getString(R.string.swap_game_screen)).performScrollTo().assertIsDisplayed() + compose.onNodeWithText("Bottom screen").performScrollTo().assertIsDisplayed() + } + @Test fun provisionalBottomScreenPanelSettlesOnlyOnceTheSessionIsInFront() { SessionState.mode = SessionService.MODE_STEAM val previousMode = SessionState.secondScreenMode @@ -233,7 +262,7 @@ class SessionSecondScreenTest { state("drawerOpenState").value = true state("drawerControllerActive").value = true state>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen")) - for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.SECOND_SCREEN, + for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.DISPLAY, KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) { assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0, device.id, 0, 0, InputDevice.SOURCE_GAMEPAD))) @@ -311,14 +340,16 @@ class SessionSecondScreenTest { val displays = listOf(SecondScreenDisplay(1, "Bottom screen")) compose.setContent { DroidDeckTheme { - SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, actions(steam, displays) { selected += it }) + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(steam, displays) { selected += it }) } } val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL, SecondScreenMode.CUSTOM_CONTROLS) for (mode in modes) { - compose.onNodeWithText(context.getString(mode.label)).performScrollTo().assertIsDisplayed().performClick() + compose.onNodeWithTag("drawer-screen-picker").performClick() + compose.onNodeWithTag("screen-picker-menu").assertDoesNotExist() + compose.onNodeWithTag("screen-picker:${SecondScreenMode.DECK_CONTROLS.id}").assertDoesNotExist() + compose.onNodeWithTag("screen-picker:${mode.id}").assertIsDisplayed().performClick() } - compose.onNodeWithText(context.getString(SecondScreenMode.DECK_CONTROLS.label)).assertDoesNotExist() assertEquals(modes, selected) } @@ -330,7 +361,7 @@ class SessionSecondScreenTest { private fun actions(steam: Boolean, displays: List, micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {}, desktop: Boolean = !steam, direct: Boolean = false, onInputSelection: (InputRole?) -> Unit = {}, - onClose: () -> Unit = {}, + onClose: () -> Unit = {}, mode: SecondScreenMode = SecondScreenMode.NONE, gameSwap: Boolean = false, select: (SecondScreenMode) -> Unit = {}) = DrawerActions(steam = steam, desktop = desktop, direct = direct, onInputSelection = onInputSelection, isHomeApp = false, androidApps = emptyList(), hudOn = false, @@ -338,7 +369,7 @@ class SessionSecondScreenTest { frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never", suspendPolicy = "auto", backActionsInverted = false, touchMode = "auto", touchAuto = "trackpad", fexPreset = "default", - secondScreenMode = SecondScreenMode.NONE, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1, + secondScreenMode = mode, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1, gameSwapAvailable = gameSwap, onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {}, onTouch = {}, onFexPreset = {}, onSecondScreenMode = select, onSecondScreenDisplay = {}, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt new file mode 100644 index 000000000..c295f5305 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt @@ -0,0 +1,55 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.stores.Store +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = android.app.Application::class) +class StoreTabsStateTest { + private val ctx get() = RuntimeEnvironment.getApplication() + + @Before fun clear() { + ctx.getSharedPreferences("session", 0).edit().clear().commit() + StoreTabsState.load(ctx) + } + + @Test fun aReorderIsSavedForTheStoresTabAndTheLibrary() { + val ids = StoreTabsState.tabs.map { it.store.id } + val moved = listOf(ids[1], ids[0]) + ids.drop(2) + StoreTabsState.reorder(ctx, moved) + assertEquals(moved, StoreTabsState.tabs.map { it.store.id }) + StoreTabsState.load(ctx) + assertEquals(moved, StoreTabsState.tabs.map { it.store.id }) + } + + @Test fun hidingIsSavedButTheLastShownStoreStays() { + assertTrue(StoreTabsState.setShown(ctx, Store.GOG, false)) + assertTrue(Store.GOG.id in SessionPrefs.storesTabHidden(ctx)) + for (tab in StoreTabsState.tabs.filter { it.shown }.dropLast(1)) StoreTabsState.setShown(ctx, tab.store, false) + val last = StoreTabsState.tabs.single { it.shown }.store + assertFalse(StoreTabsState.setShown(ctx, last, false)) + assertTrue(StoreTabsState.tabs.single { it.store == last }.shown) + } + + @Test fun theHiddenTabStartsOffAndItsSwitchSurvivesAReload() { + assertTrue(LIBRARY_HIDDEN in StoreTabsState.libraryHidden) + StoreTabsState.setLibraryShown(ctx, LIBRARY_HIDDEN, true) + assertTrue(SessionPrefs.libraryShowHidden(ctx)) + StoreTabsState.load(ctx) + assertFalse(LIBRARY_HIDDEN in StoreTabsState.libraryHidden) + StoreTabsState.setLibraryShown(ctx, LIBRARY_FAVORITES, false) + assertEquals(setOf(LIBRARY_FAVORITES), SessionPrefs.libraryTabsHidden(ctx)) + StoreTabsState.setLibraryShown(ctx, LIBRARY_HIDDEN, false) + StoreTabsState.load(ctx) + assertEquals(setOf(LIBRARY_FAVORITES, LIBRARY_HIDDEN), StoreTabsState.libraryHidden) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/ThemeColorsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/ThemeColorsTest.kt index 2f2cc3cd3..b98d0f1ee 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/ThemeColorsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/ThemeColorsTest.kt @@ -188,4 +188,45 @@ class ThemeColorsTest { SessionPrefs.setTheme(app, Themes.TRUE_BLACK) assertEquals(Color(0xFFFF8800), Themes.current(app).primary) } + + @Test fun customThemeRestoresIndependentColorsAndUsesASolidAccent() { + val chosen = CustomThemeColors( + background = 0xFF101112.toInt(), + surface = 0xFF202122.toInt(), + surfaceVariant = 0xFF303132.toInt(), + line = 0xFF404142.toInt(), + line2 = 0xFF505152.toInt(), + onBackground = 0xFFF1F2F3.toInt(), + onSurfaceVariant = 0xFFD1D2D3.toInt(), + primary = 0xFF336699.toInt(), + onPrimary = 0xFFFFFFFF.toInt(), + signal = 0xFFFFAA00.toInt(), + good = 0xFF00CC66.toInt(), + error = 0xFFFF4433.toInt(), + ) + + Themes.setCustomColors(app, CustomThemeColors()) + SessionPrefs.setCustomThemeColors(app, chosen) + SessionPrefs.setTheme(app, Themes.CUSTOM) + + assertEquals(chosen, SessionPrefs.customThemeColors(app)) + + val palette = Themes.current(app) + assertEquals(Themes.CUSTOM, palette.id) + assertEquals(Color(chosen.background), palette.background) + assertEquals(Color(chosen.surface), palette.surface) + assertEquals(Color(chosen.surfaceVariant), palette.surfaceVariant) + assertEquals(Color(chosen.line), palette.line) + assertEquals(Color(chosen.line2), palette.line2) + assertEquals(Color(chosen.onBackground), palette.onBackground) + assertEquals(Color(chosen.onSurfaceVariant), palette.onSurfaceVariant) + assertEquals(Color(chosen.primary), palette.primary) + assertEquals(Color(chosen.primary), palette.primary2) + assertEquals(Color(chosen.onPrimary), palette.onPrimary) + assertEquals(Color(chosen.signal), palette.signal) + assertEquals(Color(chosen.good), palette.good) + assertEquals(Color(chosen.error), palette.error) + assertTrue(Themes.all.any { it.id == Themes.CUSTOM }) + } + } diff --git a/app/src/testDebug/java/com/droiddeck/launcher/ui/PreviewRenderTest.kt b/app/src/testDebug/java/com/droiddeck/launcher/ui/PreviewRenderTest.kt new file mode 100644 index 000000000..f84e55526 --- /dev/null +++ b/app/src/testDebug/java/com/droiddeck/launcher/ui/PreviewRenderTest.kt @@ -0,0 +1,63 @@ +package com.droiddeck.launcher.ui + +import android.app.Application +import android.graphics.Bitmap +import android.graphics.Canvas +import android.view.inspector.WindowInspector +import androidx.compose.ui.test.junit4.createComposeRule +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.ParameterizedRobolectricTestRunner +import org.robolectric.ParameterizedRobolectricTestRunner.Parameters +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import java.io.File + +/** + * Draws every preview case with Robolectric's native graphics and saves it as a PNG under app/build/preview-renders/, + * so UI changes can be looked at without a device. Fails on a preview that throws or draws a single flat colour. + */ +@RunWith(ParameterizedRobolectricTestRunner::class) +@Config(sdk = [34], application = Application::class, qualifiers = "w960dp-h540dp-land-xhdpi") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +internal class PreviewRenderTest(private val case: PreviewCase) { + @get:Rule val compose = createComposeRule() + + @Test fun handheld() = render("handheld") + + @Test @Config(qualifiers = "w540dp-h960dp-port-xhdpi") + fun portrait() = render("portrait") + + private fun render(size: String) { + compose.mainClock.autoAdvance = false + compose.setContent { case.content() } + // The clock is paused, so step it while waiting: navigation and the loads that make a case ready run in frames. + compose.waitUntil(timeoutMillis = 15_000) { compose.mainClock.advanceTimeByFrame(); case.ready() } + // Entrance animations settle well within this. + compose.mainClock.advanceTimeBy(2_000) + compose.waitForIdle() + compose.runOnIdle { save(size) } + } + + private fun save(size: String) { + // A dialog has its own window; the last one is on top. + val view = WindowInspector.getGlobalWindowViews().last() + assertTrue("${case.name}: empty bounds", view.width > 0 && view.height > 0) + val image = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) + view.draw(Canvas(image)) + val pixels = IntArray(image.width * image.height) + image.getPixels(pixels, 0, image.width, 0, 0, image.width, image.height) + assertTrue("${case.name}: drew one flat colour", pixels.any { it != pixels.first() }) + val out = File("build/preview-renders/$size/${case.name}.png") + out.parentFile?.mkdirs() + out.outputStream().use { image.compress(Bitmap.CompressFormat.PNG, 100, it) } + image.recycle() + } + + companion object { + @JvmStatic @Parameters(name = "{0}") + fun cases(): List> = previewCases.map { arrayOf(it) } + } +} diff --git a/docs/agent-control.md b/docs/agent-control.md index ed9fbcf1e..13bf1c232 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -122,9 +122,12 @@ tools/droiddeckctl stop tools/droiddeckctl resume tools/droiddeckctl launch 489830 --wait +tools/droiddeckctl library --source xbox +tools/droiddeckctl launch --game "dead space" --wait tools/droiddeckctl wait focused 489830 tools/droiddeckctl wait game tools/droiddeckctl quit 489830 +tools/droiddeckctl quit tools/droiddeckctl focus tools/droiddeckctl input key ENTER @@ -145,6 +148,10 @@ tools/droiddeckctl ui click --match "Play" tools/droiddeckctl ui set-text some-field --text abc tools/droiddeckctl guest -- xprop -root GAMESCOPE_FOCUSED_APP +tools/droiddeckctl native -- ls /usr/local/lib/droiddeck-xbox +tools/droiddeckctl xodus --timeout 60 -- resolve-package 9N51S9QZMSB6 --json --market US +tools/droiddeckctl cloud down ubisoft 92c79ab6-a69a-411d-ba2b-625ab104235d +tools/droiddeckctl cloud up ea DR:105641400 --force tools/droiddeckctl cdp targets tools/droiddeckctl cdp eval 'SteamClient.Apps.GetMyRunningApps?.()' tools/droiddeckctl env set DXVK_HUD=fps @@ -209,9 +216,24 @@ every 10 s until the battery is under that temperature, so runs being compared s `input` needs a session that has drawn its first frame. Pad input goes through the session screen's virtual pad, the same one the on-screen controls drive, so games that ignore touch still respond. -`launch`, `quit` and `cdp` need a Steam session; `focus` and `wait focused` need gamescope (every +`launch` with an app id and `cdp` need a Steam session; `focus` and `wait focused` need gamescope (every mode except the desktop). +Store and added games (Xbox, EA, Ubisoft, GOG, Epic, Battle.net, Rockstar, a folder added by hand) are +launched by their library id, the same `droiddeck://game/` link a home screen shortcut opens, so +they go through the front end's own launch path and start a session when none is running. `library` +lists the ids with each game's name, source, store id and folder (`--query` and `--source` narrow it), +and `launch --game` takes an id or a unique part of a name; an ambiguous name exits with +`GAME_AMBIGUOUS` and lists the matches. With `--wait` it returns once a game other than the Steam +client has focus. `quit` without an id quits the focused game, so store games close the same way. + +`xodus` runs the Xbox backend with the app's own credentials and runtime, as the Xbox store does, +and returns its exit code with the last 160 KiB of stdout and stderr (`--timeout` stops it). +`cloud down|up ` syncs one game's cloud saves now, without launching it, with the +`result`, `files`, `bytes`, `reason`, `conflicts` and `detail` the game page shows; `--force` takes +that side over conflicts. The store id is the one in the game's install record (`library` shows +it). Both need Setup > Developer > Debugging tools. + `input pen` does not go through the app. It registers a virtual pen with `adb shell uinput -`, so Android's own input reader makes the stylus events, as for a built-in pen, and it works on whatever is on screen, without a session or Setup > Developer > Debugging tools. Positions are fractions of @@ -402,6 +424,7 @@ Automator show them: | Tag | Where | |---|---| | `rail-steam`, `rail-games` (the Library), `rail-desktop`, `rail-store`, `rail-components`, `rail-android-apps`, `rail-setup`, `rail-updates` | the front end's rail | +| `dual-rail-` (`dual-rail-games`, `dual-rail-downloads`, ...) | the rail on the second screen of a dual-screen device | | `play-steam` | Play on the Steam page, and on the Library when it has no games | | `library-source-` | the Library's source filter chips (`all`, `steam`, `gog`, ...) | | `game-tab-` | the open tab of a game page | diff --git a/docs/compose-previews.md b/docs/compose-previews.md new file mode 100644 index 000000000..1aa505956 --- /dev/null +++ b/docs/compose-previews.md @@ -0,0 +1,36 @@ +# Compose previews + +Previews show production composables with sample data, without a device, the Linux runtime or a network. Use them in two +ways: + +- **Android Studio:** select the `debug` build variant and open `app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt` + in Split or Design view. +- **Rendered to PNG files**, with no Studio or device needed (also how an agent can look at a UI change): + + ```sh + ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest' + ``` + + Each preview is drawn with Robolectric's native graphics at handheld (960x540 dp at xhdpi, the Duo's top screen, + 1920x1080 px) and portrait (540x960 dp) sizes, into `app/build/preview-renders/{handheld,portrait}/.png`. The test + fails if a preview throws, or draws a single flat colour. + +## Files + +| File | What | +| --- | --- | +| `app/src/debug/.../ui/PreviewSupport.kt` | `PreviewHost` (the production theme), `@DroidDeckPreviews` (the two sizes), sample `FrontEndState`, no-op `FrontEndActions` and `DrawerActions`, sample games | +| `app/src/debug/.../ui/LauncherPreviews.kt` | The previews, and `previewCases`, the list the render test draws | +| `app/src/testDebug/.../ui/PreviewRenderTest.kt` | The render test | + +Previews cover the launcher on each tab (Steam, Library, Library with no games, Stores, Downloads, Settings, Settings with +no runtime) and the in-game menu's pages (Controller, Display, HUD, Session, and the Desktop menu). + +## Adding one + +Write the preview in `LauncherPreviews.kt` (or a new file beside it) with `@DroidDeckPreviews`, wrapping the content in +`PreviewHost`. Add a `PreviewCase` to `previewCases` so it is rendered and checked too. The launcher opens on a tab via +`sampleState(navigate = "")`. + +Everything here is in the debug source sets, so none of it ships in release builds. Sample art is left out, so cards use +their fallback gradients. Previews check layout and look; they do not exercise launching, input or the runtime. diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index 434aa2267..218d1fd8e 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -1,42 +1,121 @@ -# Low-memory reclaim and userspace compression +# Automatic memory management -The Steam session monitor uses the existing `libddsession.so` page-out request to reclaim -private anonymous launcher memory. The default remains a request 20 seconds after game focus, -with five minutes between requests. With client compression enabled, low system headroom can -also trigger a request while a game is loading, before its first focused window. +The Steam session keeps enough memory free on its own. There are no memory settings: the +session monitor in `droiddeck-session` measures how much memory is available and how fast it is +being taken, and compresses just enough idle memory into zRAM to stay ahead of it. -Every five seconds the monitor reads `MemAvailable`, swap headroom and memory PSI. Low -headroom means less than one fifth of total RAM (bounded to 512–1536 MiB), or at least 1% -`some avg10` memory stall with less than one third of RAM available. Pressure requests target -only the launcher processes already recognized by the monitor, never the game. They require -at least 128 MiB launcher RSS and enough free swap to cover its anonymous RSS while leaving -one fifth of swap (at least 256 MiB) free. File-backed resident pages do not consume this -budget: the page-out helper targets private anonymous mappings. If `RssAnon` is absent from a -process's status, its full RSS is used instead. The regular automatic client request uses the -same swap guard. An explicit session RAM cap retains its existing behavior. +## What the monitor measures -Pressure requests are at least 30 seconds apart. Reclaiming less than 16 MiB doubles the -retry delay, up to five minutes. After game exit, speculative launcher readback is deferred -until the session is under any explicit RAM cap, pressure has subsided, and available RAM -can cover twice the launcher's swap while leaving the headroom reserve. Normal demand paging -continues while readback is deferred; Steam does not have to wait for the monitor to recover. -The same readback runs while the game is still running once the client has been in front of it -for five seconds (a game stuck on a black screen and left through Steam, or a long stay in the -Steam menu), under the same memory checks and only without an explicit RAM cap. Missing or -unreadable focus data never counts as the client in front. Demand paging -alone left the Steam library and menus blank for about half a minute in that case. The -client is compressed again 20 seconds after the game is back in front. -Missing memory counters disable automatic pressure reclaim and speculative readback. Missing -PSI alone still permits the `MemAvailable` fallback. No root settings, swap sizes, compression -algorithms, Android process priorities or game-specific settings are changed. +Each pass reads four things: + +- `MemAvailable` from `/proc/meminfo`. +- The fall rate: how much `MemAvailable` dropped since the last pass, plus what the monitor + itself freed in between, per second. A peak decays by a quarter per pass, so one burst keeps + the monitor alert for a few seconds without holding it there. +- Memory stall: the change in the `some` total of `/proc/pressure/memory`, as a percentage of + the time between passes. A missing PSI file reads as no stall. +- zRAM room and saving: free space on the zRAM swap devices in `/proc/swaps` after a reserve + of one eighth of zRAM (at least 128 MiB), and the measured saving per compressed byte from + `/sys/block/zram0/mm_stat` (bounded to 1.2:1–6:1, 2.5:1 before 64 MiB has been stored). + Disk swap is not counted as room: paging to storage is what causes long stalls. + +The monitor sleeps five seconds between passes while more than two fifths of RAM is available +and memory is steady, and one second otherwise. + +## Levels + +| Level | Value | Meaning | +| --- | --- | --- | +| Floor | one eighth of RAM, bounded to 640–1280 MiB | Below this the system is close to killing the session. `lmkd` ended a session on a 7.5 GiB device with 490 MiB available. | +| Target | floor + ten seconds of the fall rate | Where the monitor wants available memory to stay. | +| Burst | two seconds of the fall rate, when that is at least 64 MiB and less than two fifths of RAM is available | Memory that will be taken before the next passes can react. | + +The amount to free is the distance to the target or the burst, whichever is larger. The hard +part of it is what available memory is short of the floor, and nothing when it is above. With +a memory stall of at least 1% the hard part is two seconds of the fall rate when that is +larger, whatever the size of the fall and however much memory is available. + +## What gets compressed, in order + +1. The Steam client and hidden launchers, while a game is running and the client is not known + to be in front (unreadable focus data counts as not in front), or at any time when there is + a hard need. Without a hard need the client is left alone for 30 seconds after + it was read back. +2. Processes of the session that loaded `libddsession.so` (the game, Wine and its services), + largest first, only for the hard part that the client did not cover. One pass moves at + most 256 MiB. + +Both use the preload's cold-only request (`2 `): each process pages out only memory it has +not touched recently and stops at the budget, so memory in use stays in RAM and is not read +straight back. The budget is the amount to free divided by the measured saving, limited to the +zRAM room. With less than half the floor available the request ignores heat (`3 `), moves +up to 1 GiB, and runs at most once every ten seconds. + +Two things keep memory from going in and out of zRAM. The preload remembers each 1 MiB chunk +it paged out: when a quarter or more of those pages are resident again at the next visit, the +chunk is hot and is passed over for the next 64 visits, then 128, then 255. And the monitor +reads `pswpin` from `/proc/vmstat`: what was read back from swap, fading over half a minute, +is taken off what one pass may move (1 GiB in all, at most 256 MiB of it from the session). A device +whose working set does not fit therefore stops being trimmed and is left to the kernel, until +the forced level is reached. + +A pass that gives back less than a quarter of what the floor is short by is followed by a wait: +five seconds, doubling after each such pass up to a minute. The wait ends early when available +memory drops another eighth of the floor or reaches the forced level, and is forgotten after a +pass that gives back enough or once nothing is needed. + +Requests go to one process at a time. The monitor waits for that process's acknowledgement +(the kB it paged out) before the next, reads `MemAvailable` again, and stops once the budget is +met or available memory is back at the level the pass was started for. A process that has not +started within half a second, or has not finished when the pass (client and session together) +has waited five seconds in total or six seconds have gone by since it began, is skipped for a +minute, and a late answer from it is discarded. A process is known by its number and start time, so a new process that got the +number of a skipped one is asked. Processes with less +than 8 MiB of anonymous memory are skipped. While the app pages the session out for suspend, or +reads it back on resume, it holds the monitor off with `/tmp/.dd-zram.hold` and writes its own +request (`1` to page out, `0` to read back) into that file. A signalled process reads the hold +file first and the control file only when the hold file is missing or empty, so a trim request +the monitor wrote at the same moment cannot replace the app's. The suspend page-out answers `1` +in `/tmp/.dd-zram.ack.` and a trim answers its kB in `/tmp/.dd-zram.trim.`, so the +monitor never removes or reads an answer the app is waiting for, and the app never takes a +trim's answer for its own. A trim budget smaller than a chunk covers the stretch of the chunk +that holds that many resident pages, and the next request continues from where it ended. With less than 64 MiB of zRAM room nothing is requested and the +session log says so once a minute. + +With no shortage nothing is compressed. A game that fits in memory is never touched, and Steam +is no longer compressed on a timer. + +## Reading the client back + +Once the client has been compressed, it is read back in one request when the game has exited, +or the client has been in front of the game for five seconds, and at least 30 seconds have +passed since the last request, and available memory covers the client's swap plus the target +and the floor. Missing or unreadable focus data never counts as the client in front. Demand +paging alone left the Steam library and menus blank for about half a minute in that case. +Suspending the session while it is asleep, hidden or the screen is off still pages everything +out, and resuming reads it back when available memory is at least twice what those processes +have in swap at that moment and, after it, 1 GiB or a tenth of RAM, whichever is larger, stays +available. + +## Threads + +Page-out never runs on a thread of the game. The preload's signal handler only wakes its +`zr-worker` thread, which does the `madvise` calls. A forked process +without a worker trims inline in steps of at most 32 MiB per request and looks at no more +than 512 MiB of its address space each time. The page-out for a suspend and the read-back +after it are not limited there: they run once, while the process is being stopped or +started, and cover all of it. The monitor is a +shell loop in the session, outside every game process. + +The session log gets a line once at least 16 MiB has moved since the last one, at most every +five seconds: +`memory: available N MB, falling N MB/s, compressed N MB of the client and N MB of the session`. + +No root settings, swap sizes, compression algorithms, Android process priorities or +game-specific settings are changed. + +## Measurements behind the levels -A bounded live test of the pressure helper on the FIT during Caravan SandWitch loading -requested page-out at 20:52:37 UTC, 18 seconds before the installed timed reclaimer. Aggregate -launcher RSS fell from 608 to 283 MiB across that request; this is summed process RSS, not a -measurement of net physical RAM saved. The game reached its main menu at 60 FPS. The test ran -the candidate monitor functions alongside the old APK's monitor, not a newly built APK; -the old monitor's later request is visible separately at 20:52:55 in the session log. This -does not establish gameplay performance or resolve Stellar Blade's larger memory failure. Continuing an existing Caravan save reproduced a whole-session low-memory kill with the pressure helper running. Android recorded `ApplicationExitInfo` reason `LOW_MEMORY`, and @@ -49,39 +128,6 @@ reduced aggregate launcher RSS only from 263 to 255 MiB and backed off. Thus lau does not resolve this load failure, and this run did not exhaust swap. The unevictable/shmem growth needs allocation attribution before treating it as a driver or GPU-memory diagnosis. -## Pressure reclaim: compressing idle game memory - -The monitor also compresses the game session itself when observed pressure approaches the -system kill boundary. There is no RAM-size gate. The trigger is absolute real headroom, not a -percentage: Android's `lmkd` killed a session on a 7.5 GiB device with -490 MiB still available, so a 95% used threshold (about 400 MiB left on 8 GB) is already past the -kill. A world load added 1 GiB of GPU memory in about ten seconds, and compressing 1.4 GiB took -2.6 seconds, so the request has to leave room for both. - -Performance > Compress idle game memory turns this off (`DD_ZRAM_IDLE=0`); launcher compression -and the RAM cap are unaffected. - -The session request runs when real headroom falls below a quarter of RAM (bounded to -768–2560 MiB), or below one and a half times that with at least 1% `some` or `full avg10` -memory stall. Real headroom subtracts positive growth in KGSL allocation, `Unevictable`, and -`Shmem` from `MemAvailable`; a rapid fall also qualifies below twice the headroom or two fifths of RAM, whichever is larger (a 15 GB Thor Max was killed with 5.3 GB still available while memory fell about 400 MB per tick). The monitor -may first request page-out of idle Steam and hidden launchers, subject to the Performance -setting and client reclaim limits. When both qualify, both requests are sent before waiting -for either to complete, so a slow launcher acknowledgement does not delay the game request. Until the client -request finishes, its anonymous RSS remains reserved from the session's swap budget. Completion -and backoff are measured against the processes that received each request, even if a later scan -finds different processes. The session request targets processes that loaded -`libddsession.so`: the game, Wine and its services, and excludes Steam and hidden launchers. -Requests are at least 30 seconds apart and need the same -swap reserve as launcher requests. When the session has read back more than half of what the -previous request compressed, that memory is in use: the request is skipped and the wait doubles, -up to five minutes. A completed request must also raise `MemAvailable` by at least one -sixteenth of the tier headroom, with a 16 MiB minimum; otherwise the same wait doubles because -the pass did not provide meaningful system headroom. A request whose memory stayed compressed or -whose available memory recovers resets the wait to 30 seconds. Below half the headroom the wait -is ignored and only the 30-second spacing applies, so critical pressure can still trigger a -request. The state resets when the game exits. - Measured on a Retroid Pocket Duo (7.5 GiB, kernel 6.6, 6 GiB lzo-rle zram plus a 4 GiB swap file) entering the world in World of Warcraft: Forever, one run each: @@ -99,20 +145,6 @@ allocation, not swap capacity. Little Nightmares at the same settings compressed the following minute at its menu and 440 MiB while loading the next area; frame rate stayed at 44–46 FPS with one or two short frame-time spikes. These are single runs, not averages. -On the PR build without any manual step, the monitor compressed WoW before character select and -again during the load; the game entered the world and stayed there at 33 FPS. Once in the world, -available memory settled near 1 GiB, under the headroom, and the first version of the policy -compressed 200–400 MiB every 30 seconds while the game read back about 15 MiB/s. The -read-back check therefore compares against the last request instead of all compressed memory. - -A second run on that build showed the trigger arriving too late: character select sat at -1.5–1.6 GiB available, just above the original one-fifth headroom, so nothing was compressed -there. During the load, available memory crossed the headroom 9 seconds after Enter World, but the -launcher check ran first and waited 12 seconds for acknowledgements; the game request started at -21 seconds, moved about 200 MiB, and `lmkd` ended the session at 30 seconds. The quarter-of-RAM -level starts reclaim earlier. Sending both requests before waiting removes the launcher -acknowledgement delay; it does not guarantee that reclaim can keep up with every loading peak. - Without root an app cannot write its memory cgroup's `memory.reclaim` (owned by `system`), `process_madvise` on another process returns `EPERM`, `PAGEMAP_SCAN` is absent before Linux 6.7, and KGSL's per-process GPU reclaim `state` is root-only. Page-out therefore runs inside each diff --git a/docs/development/memory-guard-ab.md b/docs/development/memory-guard-ab.md new file mode 100644 index 000000000..4ac8d1a21 --- /dev/null +++ b/docs/development/memory-guard-ab.md @@ -0,0 +1,90 @@ +# Keep-top guard A/B on dual screens + +`KeepTopActivity` (#2763) covers every other display while a session is on top, so that +display's home is not its top activity. On the Thor, lmkd kills the bottom home under memory +pressure, Android relaunches it to the front (`wm_task_to_front`), the session loses the top +spot, drops to adj 50 and is killed in lmkd's next pass. + +Android gives a translucent activity that is alone in its task an `ActivityRecordInputSink` +that consumes every touch inside the task bounds, whatever the window's flags say +(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`, on for DroidDeck's target SDK; see +`services/core/java/com/android/server/wm/ActivityRecordInputSink.java`). The guard's +`FLAG_NOT_TOUCHABLE` therefore did nothing: with the dual-screen panel closed, the bottom +screen took no touch until the session ended, and the guard also stayed over it after Home. + +The guard now takes touches itself. A touch removes it from that display. It comes back when +the session is top-resumed again, or after 5 s if the session kept the top spot (one touch on +the bottom screen, then back to the game). Stopping or entering PiP removes the guards. + +## Tool + +`tools/memory_guard_ab.py` drives a rooted dual-screen device over adb (`su` required) with a +build that has the debugging tools: + +```sh +python3 tools/memory_guard_ab.py --label main --apk main.apk states +python3 tools/memory_guard_ab.py --label fix --apk fix.apk states +python3 tools/memory_guard_ab.py --label fix pressure --stop-mb 650 --hold 30 --runs 3 +python3 tools/memory_guard_ab.py --label fix summarize ~/.cache/droiddeck-memory-guard-ab/fix-stop650-1-events.txt +``` + +Results are JSON lines in `~/.cache/droiddeck-memory-guard-ab/