diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 08cb6341be..3816c1a52c 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 cb5b882ec7..c271f963b9 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 0000000000..e0003e1348 --- /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 0000000000..fc83727e11 --- /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 c15996d8fe..d286cce1f5 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -875,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) @@ -947,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 { @@ -1202,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 @@ -1220,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) } diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 618452d028..be228331ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -1028,7 +1028,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) @@ -1759,10 +1761,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 -> @@ -3497,7 +3496,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 +4231,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 +4252,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pad = padBridge, onKeyboardClosed = ::bottomKeyboardClosed, onMenu = { drawerOpen = true }, + picker = ::bottomScreenPicker, onMenuTouched = { if (drawerPinned) { drawerPinned = false @@ -5615,6 +5628,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() @@ -5657,6 +5675,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) @@ -5686,6 +5707,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 @@ -5700,6 +5722,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 @@ -5783,6 +5806,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) { @@ -5796,13 +5832,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()) { @@ -6483,6 +6523,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/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index e917e36605..df90f6f86b 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/frontend/GameFiles.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt index 63b5f6b4dc..3ab8928920 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 6f71475cf9..3e5d4ae0dd 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 0000000000..a6baf2d70f --- /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/session/KeepTopActivity.kt b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt index 849c0aafcc..109f6d282a 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 d2d4d49bd9..cef3489a37 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/SessionPipController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt index f32fe2abbf..503b8c743e 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 5c9d0eb178..a0208ec727 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) { 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 57f07742cf..115e0b1132 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 917b2c0ba1..4ceb4278bf 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) { 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 d430d11434..90138c5255 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/ui/BottomDesktopPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt index a0033d81a7..c9e8362c4d 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 7ad576f956..7c33334a26 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 2d2e401fa7..b51aec8bf1 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 e4715b6a15..0fbbcf3f3e 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/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt new file mode 100644 index 0000000000..21057d1dea --- /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/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 191956c170..adf55c4b1b 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/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index c35f3d10df..5503ef22a1 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 ef414c4eb0..2267bef930 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 8815ea43ac..b7976c89dd 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 @@ -595,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() } 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 6d360d7357..6bc4fd2149 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 9697fc289d..3b93f06527 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 @@ -482,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) { @@ -497,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) } @@ -1146,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 2b10c7902e..0000000000 --- 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 a0fb74ef6f..c50a6c8978 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 272f42840c..d901b1a68f 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 0000000000..7e732d4fe4 --- /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 f7f4319d29..1a674da7f6 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/RailSettingsPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt index debc0f86b4..d25f723651 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 62f3c61f6c..6944d5a302 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 @@ -301,7 +302,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 } @@ -318,15 +320,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 d65852ece2..3751702897 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 c92485c892..3ccf279bbe 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 @@ -166,7 +165,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 +177,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 @@ -386,7 +383,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 @@ -460,8 +457,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) @@ -510,7 +505,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), @@ -520,7 +516,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() } @@ -543,7 +548,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 @@ -650,6 +655,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, @@ -796,9 +802,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) }) } } - 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 { @@ -1284,43 +1287,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)) { - Text(stringResource(R.string.input_second_mode_hint), Modifier.padding(14.dp), - style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant) - 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/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 7f2d0cb0c1..20dd2c2807 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/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 440541dda4..a54c7f9bfb 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 6d4605785a..efe8a808bc 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/res/values-ar/input_library.xml b/app/src/main/res/values-ar/input_library.xml index 68f65da57e..4a94939081 100644 --- a/app/src/main/res/values-ar/input_library.xml +++ b/app/src/main/res/values-ar/input_library.xml @@ -103,7 +103,6 @@ رجوع · مرتان في Steam ومرة في سطح المكتب في وضع Steam. الاستمرار بالضغط على رجوع يفتح الوصول السريع أيضًا. الاستعادة إلى الافتراضي - يتم تذكر اختيار اللوحة. يفتح سطح المكتب مساحة عمل ثانية؛ ولا يغيّر الجلسة أو ملف تعريف الإدخال. وحدة تحكم افتراضية نوع وحدة التحكم التي يراها Steam أو اللعبة. شاشة لمس diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 52c5f64a1e..6433943918 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -812,7 +812,6 @@ لوحة مفاتيح الكمبيوتر Android الشاشة الثانية - الوضع يعرض تطبيقات Android تشغيل تطبيق diff --git a/app/src/main/res/values-b+es+419/input_library.xml b/app/src/main/res/values-b+es+419/input_library.xml index 7769845d32..82305bea9d 100644 --- a/app/src/main/res/values-b+es+419/input_library.xml +++ b/app/src/main/res/values-b+es+419/input_library.xml @@ -103,7 +103,6 @@ Atrás · dos veces en Steam, una en escritorio En modo Steam. Mantener Atrás también abre el acceso rápido. Restaurar valores predeterminados - Tu elección de panel se recuerda. Escritorio abre un segundo espacio de trabajo; no cambia la sesión ni su perfil de entrada. Control virtual El tipo de control que ven Steam o el juego. Pantalla táctil 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 6bb03b842b..922b1407f3 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -830,7 +830,6 @@ Teclado de PC Android Segunda pantalla - Modo Muestra Apps de Android Abrir una app diff --git a/app/src/main/res/values-bg/input_library.xml b/app/src/main/res/values-bg/input_library.xml index 53f2103152..31967ac490 100644 --- a/app/src/main/res/values-bg/input_library.xml +++ b/app/src/main/res/values-bg/input_library.xml @@ -103,7 +103,6 @@ Назад · два пъти в Steam, веднъж в работен плот В режим Steam. Задържането на Назад отваря и бързия достъп. Връщане към подразбирането - Изборът на панел се запомня. Работният плот отваря второ работно пространство; не сменя сесията или профила ѝ за вход. Виртуален контролер Типът контролер, който Steam или играта виждат. Сензорен екран diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index cc99224c93..57566ec959 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -804,7 +804,6 @@ Клавиатура за компютър Android Втори екран - Режим Показва Приложения за Android Стартиране на приложение diff --git a/app/src/main/res/values-cs/input_library.xml b/app/src/main/res/values-cs/input_library.xml index 10783695ce..6ba6584e5e 100644 --- a/app/src/main/res/values-cs/input_library.xml +++ b/app/src/main/res/values-cs/input_library.xml @@ -103,7 +103,6 @@ Zpět · dvakrát v Steam, jednou na ploše V režimu Steam. Podržením Zpět se také otevře rychlý přístup. Obnovit výchozí - Volba panelu se pamatuje. Plocha otevře druhý pracovní prostor; nepřepíná relaci ani její vstupní profil. Virtuální ovladač Typ ovladače, který vidí Steam nebo hra. Dotyková obrazovka diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 15df9624b9..c2b89c6e12 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -808,7 +808,6 @@ Klávesnice PC Android Druhá obrazovka - Režim Zobrazuje Aplikace Android Spustit aplikaci diff --git a/app/src/main/res/values-da/input_library.xml b/app/src/main/res/values-da/input_library.xml index f3fd6e80ac..3ba74431ee 100644 --- a/app/src/main/res/values-da/input_library.xml +++ b/app/src/main/res/values-da/input_library.xml @@ -103,7 +103,6 @@ Tilbage · to gange i Steam, én gang på skrivebordet I Steam-tilstand. Hvis du holder Tilbage, åbnes hurtigadgang også. Gendan standard - Dit panelvalg huskes. Skrivebord åbner et andet arbejdsområde; det skifter ikke sessionen eller dens inputprofil. Virtuel controller Den controllertype, som Steam eller spillet ser. Berøringsskærm diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 4a5dac730f..67037ab952 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -804,7 +804,6 @@ PC-tastatur Android Anden skærm - Tilstand Viser Android-apps Start en app diff --git a/app/src/main/res/values-de/input_library.xml b/app/src/main/res/values-de/input_library.xml index 8ba2b07f50..754679261f 100644 --- a/app/src/main/res/values-de/input_library.xml +++ b/app/src/main/res/values-de/input_library.xml @@ -103,7 +103,6 @@ Zurück · zweimal in Steam, einmal im Desktop Im Steam-Modus. Halten von Zurück öffnet auch den Schnellzugriff. Auf Standard zurücksetzen - Ihre Panel-Auswahl wird gespeichert. Desktop öffnet einen zweiten Arbeitsbereich; es wechselt weder die Sitzung noch ihr Eingabeprofil. Virtueller Controller Der von Steam oder dem Spiel erkannte Controller-Typ. Touchscreen diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 068f519c59..c913e57c78 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -804,7 +804,6 @@ PC-Tastatur Android Zweiter Bildschirm - Modus Zeigt Android-Apps App starten diff --git a/app/src/main/res/values-el/input_library.xml b/app/src/main/res/values-el/input_library.xml index c9f40579e3..d100812712 100644 --- a/app/src/main/res/values-el/input_library.xml +++ b/app/src/main/res/values-el/input_library.xml @@ -103,7 +103,6 @@ Πίσω · δύο φορές στο Steam, μία στην επιφάνεια εργασίας Σε λειτουργία Steam. Το κράτημα του Πίσω ανοίγει και τη γρήγορη πρόσβαση. Επαναφορά στις προεπιλογές - Η επιλογή πίνακα απομνημονεύεται. Η επιφάνεια εργασίας ανοίγει δεύτερο χώρο εργασίας· δεν αλλάζει τη συνεδρία ούτε το προφίλ εισόδου της. Εικονικό χειριστήριο Ο τύπος χειριστηρίου που βλέπουν το Steam ή το παιχνίδι. Οθόνη αφής diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index f4873ceb7c..c1e1ffcb79 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -804,7 +804,6 @@ Πληκτρολόγιο PC Android Δεύτερη οθόνη - Λειτουργία Εμφανίζει Εφαρμογές Android Εκκίνηση εφαρμογής diff --git a/app/src/main/res/values-es/input_library.xml b/app/src/main/res/values-es/input_library.xml index fe2ee17896..a2271204a7 100644 --- a/app/src/main/res/values-es/input_library.xml +++ b/app/src/main/res/values-es/input_library.xml @@ -103,7 +103,6 @@ Atrás · dos veces en Steam, una en escritorio En modo Steam. Mantener Atrás también abre el acceso rápido. Restaurar valores predeterminados - Tu elección de panel se recuerda. Escritorio abre un segundo espacio de trabajo; no cambia la sesión ni su perfil de entrada. Mando virtual El tipo de mando que ven Steam o el juego. Pantalla táctil diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index e39fae7b8a..124192c1a2 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -806,7 +806,6 @@ Teclado de PC Android Segunda pantalla - Modo Muestra Apps de Android Abrir una app diff --git a/app/src/main/res/values-fi/input_library.xml b/app/src/main/res/values-fi/input_library.xml index 846dae260f..8fd745f70a 100644 --- a/app/src/main/res/values-fi/input_library.xml +++ b/app/src/main/res/values-fi/input_library.xml @@ -103,7 +103,6 @@ Takaisin · kahdesti Steamissa, kerran työpöydällä Steam-tilassa. Takaisin-painikkeen pitäminen avaa myös pikakäytön. Palauta oletukset - Paneelivalintasi muistetaan. Työpöytä avaa toisen työtilan; se ei vaihda istuntoa tai sen syöttöprofiilia. Virtuaaliohjain Ohjaintyyppi, jonka Steam tai peli näkee. Kosketusnäyttö diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index e9dacd8e0f..2d7ea36c72 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -804,7 +804,6 @@ PC-näppäimistö Android Toinen näyttö - Tila Näyttää Android-sovellukset Käynnistä sovellus diff --git a/app/src/main/res/values-fr/input_library.xml b/app/src/main/res/values-fr/input_library.xml index 4e899b637f..0dbdf5dbca 100644 --- a/app/src/main/res/values-fr/input_library.xml +++ b/app/src/main/res/values-fr/input_library.xml @@ -103,7 +103,6 @@ Retour · deux fois dans Steam, une fois sur le bureau En mode Steam. Maintenir Retour ouvre aussi l\'accès rapide. Rétablir par défaut - Votre choix de panneau est mémorisé. Le bureau ouvre un second espace de travail ; il ne change ni la session ni son profil d\'entrée. Manette virtuelle Le type de manette vu par Steam ou le jeu. Écran tactile diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e76d3e6dab..f21ab1e3a2 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -806,7 +806,6 @@ Clavier PC Android Deuxième écran - Mode Afficher Applications Android Lancer l\'application diff --git a/app/src/main/res/values-hi/input_library.xml b/app/src/main/res/values-hi/input_library.xml index 81147024d8..7ba5438500 100644 --- a/app/src/main/res/values-hi/input_library.xml +++ b/app/src/main/res/values-hi/input_library.xml @@ -103,7 +103,6 @@ वापस · Steam में दो बार, डेस्कटॉप में एक बार Steam मोड में। वापस दबाए रखने से क्विक एक्सेस भी खुलता है। डिफ़ॉल्ट पर पुनर्स्थापित करें - आपका पैनल चयन याद रखा जाता है। डेस्कटॉप दूसरा कार्यक्षेत्र खोलता है; यह सत्र या उसका इनपुट प्रोफ़ाइल नहीं बदलता। वर्चुअल कंट्रोलर Steam या गेम द्वारा देखा जाने वाला कंट्रोलर प्रकार। टचस्क्रीन diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 2f5d3957fc..d322fa0d01 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -804,7 +804,6 @@ पीसी कीबोर्ड Android दूसरी स्क्रीन - मोड दिखाता है Android ऐप ऐप लॉन्च करें diff --git a/app/src/main/res/values-hu/input_library.xml b/app/src/main/res/values-hu/input_library.xml index ceeaeaf94e..a02e758852 100644 --- a/app/src/main/res/values-hu/input_library.xml +++ b/app/src/main/res/values-hu/input_library.xml @@ -103,7 +103,6 @@ Vissza · kétszer Steam módban, egyszer asztali módban Steam módban. A Vissza nyomva tartása a gyorselérést is megnyitja. Visszaállítás alapértelmezettre - A panelválasztás megjegyződik. Az asztali mód második munkateret nyit; nem váltja a munkamenetet vagy annak beviteli profilját. Virtuális vezérlő A Steam vagy a játék által látott vezérlőtípus. Érintőképernyő diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 50d616a3ca..4f7ad2c7c6 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -804,7 +804,6 @@ PC-billentyűzet Android Második képernyő - Mód Megjelenít Android-alkalmazások Alkalmazás indítása diff --git a/app/src/main/res/values-in/input_library.xml b/app/src/main/res/values-in/input_library.xml index f24780d5cc..28025b1073 100644 --- a/app/src/main/res/values-in/input_library.xml +++ b/app/src/main/res/values-in/input_library.xml @@ -103,7 +103,6 @@ Kembali · dua kali di Steam, sekali di desktop Di mode Steam. Menahan Kembali juga membuka akses cepat. Pulihkan ke bawaan - Pilihan panel Anda diingat. Desktop membuka ruang kerja kedua; tidak mengganti sesi atau profil inputnya. Pengontrol virtual Jenis pengontrol yang dilihat Steam atau game. Layar sentuh diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 1191dc3ac7..4ea3788f5f 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -802,7 +802,6 @@ Keyboard PC Android Layar kedua - Mode Menampilkan Aplikasi Android Luncurkan aplikasi diff --git a/app/src/main/res/values-it/input_library.xml b/app/src/main/res/values-it/input_library.xml index 87061db293..b825c1fb96 100644 --- a/app/src/main/res/values-it/input_library.xml +++ b/app/src/main/res/values-it/input_library.xml @@ -103,7 +103,6 @@ Indietro · due volte in Steam, una su desktop In modalità Steam. Tenere premuto Indietro apre anche l\'accesso rapido. Ripristina i valori predefiniti - La scelta del pannello viene ricordata. Desktop apre un secondo spazio di lavoro; non cambia la sessione né il suo profilo di input. Controller virtuale Il tipo di controller visto da Steam o dal gioco. Touchscreen diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 66fcd52a17..4e7fdf08d1 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -806,7 +806,6 @@ Tastiera PC Android Secondo schermo - Modalità Mostra App Android Avvia un\'app diff --git a/app/src/main/res/values-ja/input_library.xml b/app/src/main/res/values-ja/input_library.xml index ecf218c491..f4294982be 100644 --- a/app/src/main/res/values-ja/input_library.xml +++ b/app/src/main/res/values-ja/input_library.xml @@ -103,7 +103,6 @@ 戻る · Steam では 2 回、デスクトップでは 1 回 Steam モード時。戻るを長押しするとクイックアクセスも開きます。 既定に戻す - パネルの選択は記憶されます。デスクトップは 2 つ目のワークスペースを開くだけで、セッションやその入力プロファイルを切り替えません。 仮想コントローラー Steam またはゲームが認識するコントローラーの種類。 タッチスクリーン diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index a274e0c638..e74e3e706a 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -802,7 +802,6 @@ PCキーボード Android セカンドスクリーン - モード 表示 Androidアプリ アプリを起動 diff --git a/app/src/main/res/values-ko/input_library.xml b/app/src/main/res/values-ko/input_library.xml index d19c198c7e..c5030b8290 100644 --- a/app/src/main/res/values-ko/input_library.xml +++ b/app/src/main/res/values-ko/input_library.xml @@ -103,7 +103,6 @@ 뒤로 · Steam에서는 두 번, 데스크톱에서는 한 번 Steam 모드에서. 뒤로를 길게 누르면 빠른 액세스도 열립니다. 기본값으로 복원 - 패널 선택이 기억됩니다. 데스크톱은 두 번째 작업 공간을 열 뿐 세션이나 입력 프로필을 전환하지 않습니다. 가상 컨트롤러 Steam 또는 게임이 인식하는 컨트롤러 유형입니다. 터치스크린 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index c3bd68537b..557cabab25 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -802,7 +802,6 @@ PC 키보드 Android 보조 화면 - 모드 표시 Android 앱 앱 실행 diff --git a/app/src/main/res/values-ms/input_library.xml b/app/src/main/res/values-ms/input_library.xml index bd4b455121..e14f8a4252 100644 --- a/app/src/main/res/values-ms/input_library.xml +++ b/app/src/main/res/values-ms/input_library.xml @@ -103,7 +103,6 @@ Kembali · dua kali dalam Steam, sekali di desktop Dalam mod Steam. Menahan Kembali juga membuka akses pantas. Pulihkan kepada lalai - Pilihan panel anda diingati. Desktop membuka ruang kerja kedua; ia tidak menukar sesi atau profil inputnya. Pengawal maya Jenis pengawal yang dilihat oleh Steam atau permainan. Skrin sentuh diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 134f1702c0..168ceaa971 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -802,7 +802,6 @@ Papan kekunci PC Android Skrin kedua - Mod Memaparkan Apl Android Lancarkan apl diff --git a/app/src/main/res/values-nb/input_library.xml b/app/src/main/res/values-nb/input_library.xml index e810fed5a4..340337947a 100644 --- a/app/src/main/res/values-nb/input_library.xml +++ b/app/src/main/res/values-nb/input_library.xml @@ -103,7 +103,6 @@ Tilbake · to ganger i Steam, én gang på skrivebordet I Steam-modus. Å holde Tilbake åpner også hurtigtilgang. Tilbakestill til standard - Panelvalget ditt huskes. Skrivebord åpner et andre arbeidsområde; det bytter ikke økten eller inndataprofilen. Virtuell kontroller Kontrollertypen som Steam eller spillet ser. Berøringsskjerm diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index de0bac7fc6..e5115e83aa 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -804,7 +804,6 @@ PC-tastatur Android Andre skjerm - Modus Viser Android-apper Start en app diff --git a/app/src/main/res/values-nl/input_library.xml b/app/src/main/res/values-nl/input_library.xml index 80f96a853b..48db0c68ed 100644 --- a/app/src/main/res/values-nl/input_library.xml +++ b/app/src/main/res/values-nl/input_library.xml @@ -103,7 +103,6 @@ Terug · twee keer in Steam, één keer op bureaublad In spelmodus Steam. Terug ingedrukt houden opent ook snelle toegang. Terugzetten naar standaard - Je paneelkeuze wordt onthouden. Bureaublad opent een tweede werkruimte; het wisselt de sessie of het invoerprofiel niet. Virtuele controller Het controllertype dat Steam of het spel ziet. Touchscreen diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 16b5a74ec8..9151d3b212 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -804,7 +804,6 @@ Pc-toetsenbord Android Tweede scherm - Modus Toont Android-apps Een app starten diff --git a/app/src/main/res/values-pl/input_library.xml b/app/src/main/res/values-pl/input_library.xml index 1193c2a125..02c4db578b 100644 --- a/app/src/main/res/values-pl/input_library.xml +++ b/app/src/main/res/values-pl/input_library.xml @@ -103,7 +103,6 @@ Wstecz · dwa razy w Steam, raz na pulpicie W trybie Steam. Przytrzymanie Wstecz otwiera też szybki dostęp. Przywróć domyślne - Wybór panelu jest zapamiętywany. Pulpit otwiera drugą przestrzeń roboczą; nie przełącza sesji ani jej profilu wejścia. Wirtualny kontroler Typ kontrolera widziany przez Steam lub grę. Ekran dotykowy diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 8b624db10e..31742655ac 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -808,7 +808,6 @@ Klawiatura PC Android Drugi ekran - Tryb Pokazuje Aplikacje Android Uruchom aplikację diff --git a/app/src/main/res/values-pt-rPT/input_library.xml b/app/src/main/res/values-pt-rPT/input_library.xml index 498a7442e0..ec88357260 100644 --- a/app/src/main/res/values-pt-rPT/input_library.xml +++ b/app/src/main/res/values-pt-rPT/input_library.xml @@ -103,7 +103,6 @@ Voltar · duas vezes no Steam, uma no ambiente de trabalho No modo Steam. Manter Voltar também abre o acesso rápido. Repor predefinições - A sua escolha de painel é memorizada. O ambiente de trabalho abre um segundo espaço de trabalho; não muda a sessão nem o seu perfil de entrada. Comando virtual O tipo de comando visto pelo Steam ou pelo jogo. Ecrã tátil diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 732df24c4c..a5745195b4 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -806,7 +806,6 @@ Teclado de PC Android Segundo ecrã - Modo Mostra Apps Android Iniciar uma app diff --git a/app/src/main/res/values-pt/input_library.xml b/app/src/main/res/values-pt/input_library.xml index ae84ba99ce..93dd70368e 100644 --- a/app/src/main/res/values-pt/input_library.xml +++ b/app/src/main/res/values-pt/input_library.xml @@ -103,7 +103,6 @@ Voltar · duas vezes no Steam, uma no desktop No modo Steam. Manter Voltar também abre o acesso rápido. Restaurar o padrão - Sua escolha de painel é lembrada. O desktop abre um segundo espaço de trabalho; não troca a sessão nem o perfil de entrada. Controle virtual O tipo de controle visto pelo Steam ou pelo jogo. Tela sensível ao toque diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index f0814f45b2..f5eca4b046 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -813,7 +813,6 @@ Teclado de PC Android Segunda tela - Modo Mostra Apps Android Abrir um app diff --git a/app/src/main/res/values-ro/input_library.xml b/app/src/main/res/values-ro/input_library.xml index 5a3648d509..7f2b804916 100644 --- a/app/src/main/res/values-ro/input_library.xml +++ b/app/src/main/res/values-ro/input_library.xml @@ -103,7 +103,6 @@ Înapoi · de două ori în Steam, o dată pe desktop În modul Steam. Ținerea butonului Înapoi deschide și accesul rapid. Restabilește implicit - Alegerea panoului este reținută. Desktopul deschide un al doilea spațiu de lucru; nu schimbă sesiunea sau profilul ei de intrare. Controller virtual Tipul de controller văzut de Steam sau de joc. Ecran tactil diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index c228979545..cc7a55a184 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -806,7 +806,6 @@ Tastatură de PC Android Al doilea ecran - Mod Arată Aplicații Android Lansează o aplicație diff --git a/app/src/main/res/values-ru/input_library.xml b/app/src/main/res/values-ru/input_library.xml index d02df2ffe6..b4b9cfd9f6 100644 --- a/app/src/main/res/values-ru/input_library.xml +++ b/app/src/main/res/values-ru/input_library.xml @@ -103,7 +103,6 @@ Назад · дважды в Steam, один раз в рабочем столе В режиме Steam. Удержание «Назад» также открывает быстрый доступ. Вернуть по умолчанию - Выбор панели запоминается. Рабочий стол открывает второе рабочее пространство; он не переключает сеанс или его профиль ввода. Виртуальный контроллер Тип контроллера, который видят Steam или игра. Сенсорный экран diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 58a3c4e745..a5f31948ad 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -808,7 +808,6 @@ Клавиатура ПК Android Второй экран - Режим Показывать Приложения Android Запустить приложение diff --git a/app/src/main/res/values-sv/input_library.xml b/app/src/main/res/values-sv/input_library.xml index dfe4102366..15e3e12e03 100644 --- a/app/src/main/res/values-sv/input_library.xml +++ b/app/src/main/res/values-sv/input_library.xml @@ -103,7 +103,6 @@ Tillbaka · två gånger i Steam, en gång på skrivbordet I Steam-läge. Att hålla Tillbaka öppnar även snabbåtkomst. Återställ till standard - Ditt panelval kommer ihåg. Skrivbord öppnar en andra arbetsyta; det byter inte sessionen eller dess inmatningsprofil. Virtuell handkontroll Den handkontrolltyp som Steam eller spelet ser. Pekskärm diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 73c1f9dbe0..9bc129df9a 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -804,7 +804,6 @@ PC-tangentbord Android Andra skärmen - Läge Visar Android-appar Starta en app diff --git a/app/src/main/res/values-th/input_library.xml b/app/src/main/res/values-th/input_library.xml index 944a4aaa79..ef2ae2702a 100644 --- a/app/src/main/res/values-th/input_library.xml +++ b/app/src/main/res/values-th/input_library.xml @@ -103,7 +103,6 @@ ย้อนกลับ · สองครั้งใน Steam หนึ่งครั้งบนเดสก์ท็อป ในโหมด Steam การกดย้อนกลับค้างจะเปิดการเข้าถึงด่วนด้วย คืนค่าเริ่มต้น - ตัวเลือกแผงของคุณจะถูกจำไว้ เดสก์ท็อปจะเปิดพื้นที่ทำงานที่สอง ไม่ได้สลับเซสชันหรือโปรไฟล์อินพุต คอนโทรลเลอร์เสมือน ชนิดคอนโทรลเลอร์ที่ Steam หรือเกมมองเห็น หน้าจอสัมผัส diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 43c49d86fa..2402c15f86 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -802,7 +802,6 @@ แป้นพิมพ์พีซี Android หน้าจอที่สอง - โหมด แสดง แอป Android เปิดแอป diff --git a/app/src/main/res/values-tr/input_library.xml b/app/src/main/res/values-tr/input_library.xml index 12d264ee81..563657c5d4 100644 --- a/app/src/main/res/values-tr/input_library.xml +++ b/app/src/main/res/values-tr/input_library.xml @@ -103,7 +103,6 @@ Geri · Steam\'de iki kez, masaüstünde bir kez Steam modunda. Geri tuşunu basılı tutmak hızlı erişimi de açar. Varsayılana sıfırla - Panel seçiminiz hatırlanır. Masaüstü ikinci bir çalışma alanı açar; oturumu veya giriş profilini değiştirmez. Sanal denetleyici Steam veya oyunun gördüğü denetleyici türü. Dokunmatik ekran diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 7fd0d204d3..bdcb3b8b0f 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -804,7 +804,6 @@ PC klavyesi Android İkinci ekran - Mod Gösterilen Android uygulamaları Uygulama başlat diff --git a/app/src/main/res/values-uk/input_library.xml b/app/src/main/res/values-uk/input_library.xml index f2504dde51..9993d25a57 100644 --- a/app/src/main/res/values-uk/input_library.xml +++ b/app/src/main/res/values-uk/input_library.xml @@ -103,7 +103,6 @@ Назад · двічі в Steam, один раз у робочому столі У режимі Steam. Утримання «Назад» також відкриває швидкий доступ. Відновити типове - Ваш вибір панелі запам\'ятовується. Робочий стіл відкриває другий робочий простір; він не перемикає сеанс або його профіль введення. Віртуальний контролер Тип контролера, який бачать Steam або гра. Сенсорний екран diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index be20c1fb05..6259160400 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -808,7 +808,6 @@ Клавіатура ПК Android Другий екран - Режим Показує Додатки Android Запустити додаток diff --git a/app/src/main/res/values-vi/input_library.xml b/app/src/main/res/values-vi/input_library.xml index 6b75fe7fd8..71e6b034cc 100644 --- a/app/src/main/res/values-vi/input_library.xml +++ b/app/src/main/res/values-vi/input_library.xml @@ -103,7 +103,6 @@ Quay lại · hai lần trong Steam, một lần trên máy tính Ở chế độ Steam. Giữ Quay lại cũng mở truy cập nhanh. Khôi phục mặc định - Lựa chọn bảng của bạn được ghi nhớ. Máy tính mở không gian làm việc thứ hai; không chuyển phiên hay hồ sơ đầu vào của nó. Tay cầm ảo Loại tay cầm mà Steam hoặc trò chơi thấy. Màn hình cảm ứng diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 33796ad9c4..424ff42df2 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -802,7 +802,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 diff --git a/app/src/main/res/values-zh-rCN/input_library.xml b/app/src/main/res/values-zh-rCN/input_library.xml index 00c716c4cc..921f57c80d 100644 --- a/app/src/main/res/values-zh-rCN/input_library.xml +++ b/app/src/main/res/values-zh-rCN/input_library.xml @@ -103,7 +103,6 @@ 返回 · Steam 里两下,桌面上一下 Steam 模式下。按住返回也会打开快捷菜单。 恢复默认 - 面板选择会被记住。桌面会打开第二个工作区,不切换会话或它的输入配置。 虚拟手柄 Steam 或游戏看到的手柄类型。 触摸屏 diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 667f1cb9c1..4343a946ba 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -802,7 +802,6 @@ PC 键盘 Android 副屏 - 模式 显示 Android 应用 启动应用 diff --git a/app/src/main/res/values-zh-rHK/input_library.xml b/app/src/main/res/values-zh-rHK/input_library.xml index 20930002a7..d997b2e0ca 100644 --- a/app/src/main/res/values-zh-rHK/input_library.xml +++ b/app/src/main/res/values-zh-rHK/input_library.xml @@ -103,7 +103,6 @@ 返回 · Steam 裡兩下,桌面上一下 Steam 模式下。按住返回也會開啟快速選單。 恢復預設 - 面板選擇會被記住。桌面會開啟第二個工作區,不切換工作階段或其輸入設定檔。 虛擬控制器 Steam 或遊戲看到的控制器類型。 觸控螢幕 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 2ec673e61b..71ec80c4d0 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -802,7 +802,6 @@ 電腦鍵盤 Android 第二螢幕 - 模式 顯示 Android 應用程式 啟動應用程式 diff --git a/app/src/main/res/values-zh-rTW/input_library.xml b/app/src/main/res/values-zh-rTW/input_library.xml index 20930002a7..d997b2e0ca 100644 --- a/app/src/main/res/values-zh-rTW/input_library.xml +++ b/app/src/main/res/values-zh-rTW/input_library.xml @@ -103,7 +103,6 @@ 返回 · Steam 裡兩下,桌面上一下 Steam 模式下。按住返回也會開啟快速選單。 恢復預設 - 面板選擇會被記住。桌面會開啟第二個工作區,不切換工作階段或其輸入設定檔。 虛擬控制器 Steam 或遊戲看到的控制器類型。 觸控螢幕 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index d6d0037309..105d095c98 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -802,7 +802,6 @@ 電腦鍵盤 Android 第二螢幕 - 模式 顯示 Android 應用程式 啟動應用程式 diff --git a/app/src/main/res/values/input_library.xml b/app/src/main/res/values/input_library.xml index 27d018b6e8..b2969a042b 100644 --- a/app/src/main/res/values/input_library.xml +++ b/app/src/main/res/values/input_library.xml @@ -103,7 +103,6 @@ Back · twice in Steam, once in Desktop In Steam mode. Holding Back also opens quick access. Restore to default - Your panel choice is remembered. Desktop opens a second workspace; it does not switch the session or its input profile. Virtual controller The controller type seen by Steam or the game. Touchscreen diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 965ab2322e..a2e6d905e8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -865,7 +865,6 @@ PC keyboard Android Second screen - Mode Shows Android apps Launch an app @@ -1774,6 +1773,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. @@ -2259,6 +2259,8 @@ Deck grips + trackpads Dashboard Desktop + Second screen: %1$s + Last used Start the desktop Desktop · %1$s Trackpad @@ -4288,6 +4290,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 @@ -4316,6 +4336,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/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt index bcae5c8fec..b5f58de79a 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 002085daf8..63b6807c0f 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 0000000000..d7a50728c7 --- /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/session/PipPolicyTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PipPolicyTest.kt index 1261abd542..ad4f169c44 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/stores/download/DownloadEntryTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/download/DownloadEntryTest.kt index 46b38647c9..914089a2ca 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/ui/BottomScreenBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/BottomScreenBarTest.kt index 97389fa285..2af8942ca2 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/LibraryColumnsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryColumnsTest.kt new file mode 100644 index 0000000000..3d0340e064 --- /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 7674ab242d..772578ea37 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 699ca03720..c2ce77dbf7 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 ac5835c2a5..0cea327e82 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 f6085e5126..2630a3314d 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 4779843153..a2e7f61c31 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 58b8ba055b..adbbbe248a 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 dc2ff1cc6c..c45b32d234 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -83,7 +83,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) } @@ -93,18 +93,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 @@ -236,7 +265,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))) @@ -351,14 +380,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) } @@ -370,7 +401,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, @@ -378,7 +409,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 0000000000..c295f5305d --- /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/testDebug/java/com/droiddeck/launcher/ui/PreviewRenderTest.kt b/app/src/testDebug/java/com/droiddeck/launcher/ui/PreviewRenderTest.kt new file mode 100644 index 0000000000..f84e55526a --- /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/compose-previews.md b/docs/compose-previews.md new file mode 100644 index 0000000000..1aa5059563 --- /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/memory-guard-ab.md b/docs/development/memory-guard-ab.md new file mode 100644 index 0000000000..4ac8d1a214 --- /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/