From df48a85a710ca0904d98b3c0971c3ecc012fb1e9 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:40:55 -0500 Subject: [PATCH] feat(library): Library chips and toolbar like the Stores tab, a Custom games tab, and one Manage stores sheet (#2897) * feat(stores): one Manage stores sheet for order, visibility and accounts Store order, which stores show, and signing in or out now live in one slide-over, the same one Edit tabs uses, with the same sorter: drag the handle, or Y to grab and the d-pad to move, A to show or hide. - The Library's chip row opens it from a sliders chip at its start, in place of the Store accounts button at the end of the row. The Stores tab's Arrange tabs opens the same sheet instead of rearranging the chip row in place. - Each store row shows its account and one action: Sign in, Sign out, Reconnect when the login expired, or Add key for itch.io. - A switched-off store leaves the Library's chips too; its games stay under All. A shown store that is signed out keeps its chip, and picking it shows the Stores tab's sign-in card in the Library. - The Stores tab, the Library's chips and the sheet share one store order. EditTabsSheet and the new sheet share SideSheet, and the tab and store lists share SortableRows. Sign-in from the Stores tab, the sheet and the Library goes through startStoreSignIn. * feat(library): Library chips match the Stores tab, cards fade in on a store change, and the sheet only arranges The Library's chip row uses the Stores tab's chips, store-colored theme and sliding fill. Switching store fades and lifts the visible cards in, staggered, and still when animations are off. Sign-in now lives on each store's own tab, so Manage stores drops its account buttons and keeps order and show or hide, with each account as a line of text. * feat(library): chips at the top, the chosen chip's toolbar under them, and a Custom games tab The Library drops its title row and game count. The store chips are the top row, and under them the chosen chip's name sits beside search, display, sort, view and the game file actions, as in the Stores tab. The add button that sat in every header becomes a Custom games chip that is always there: empty, it opens on a card that adds a game file or a folder of games; with games in it, its toolbar has the add button. * feat(library): store-colored focus in the Library, an aligned All chip, and sign out from a store's toolbar The Library's grid takes the chosen store's theme, so focus rings and accents use its color as on the Stores tab's pages. All gets a grid mark where the other chips have a dot, so its label lines up, and the Manage stores chip matches the chips' height. A signed-in store's toolbar has an account button that asks before signing out, with the Stores tab's wording. * feat(library): drop the chosen store's name from the toolbar The chip above already names it, so the toolbar starts with search. * fix(library): an empty library keeps its chips, so Custom games and a store's sign-in stay reachable With no games and no store signed in, the Library used to switch to a separate empty page without chips. It now shows the chips and toolbar like any other library, with the empty-library note under All games. * fix(library): no toolbar between the chips and a sign-in or empty Custom games card The search, display, sort and view row has nothing to act on there, so the card sits right under the chips, as it does in the Stores tab, and Down from the chip reaches its button. * fix(library): sign-in and empty Custom games cards fill the space under the chips They were a fixed 300 dp, which left the bottom of the screen empty once the toolbar above them was gone. They now take the grid's height minus the chip row. * fix(library): drop the Installed label and lighten the cards' left fade The Not installed row already divides the two sections, so the Installed label above the first games goes. The dark fade on the left of the store sign-in card and the Steam tab's art wall is lighter, so more of the art shows while the title stays readable. * Library: share the hero wall card and wall fade; icon handle for sign out The Custom games splash is now built from the same card as the store sign-in splash, with a drifting wall of the library's covers instead of a flat gradient and no hint text. The sign-in card and the Steam tab share one wall fade. The sign-out step shows the account icon as its handle, like the other toolbar steps, instead of a truncated label. * Library: sort the Custom games tab in Manage stores; keep search reachable Opened from the Library, the Manage stores sheet lists Custom games among the stores so it can be grabbed and moved like them. Its place is saved as the store it follows, so hiding that store or a new store arriving keeps it where it was. It has no switch: the tab is always there. The Custom games splash no longer replaces the toolbar while a search is active, so a search that matches nothing can still be cleared. * Manage stores: sort Favorites, Steam and Custom games; hide Favorites and Custom games Opened from the Library, the sheet lists the Library's own tabs among the stores. Each one's place is saved as the tab it follows, so hiding a store or a new store arriving leaves it where it was. Favorites and Custom games have a switch; Steam can be moved but not hidden. The sheet takes focus only in controller mode, so opening it by touch no longer switches to controller focus and its ring. Picking up a controller while it is open moves focus into it. Hidden games stay off the Custom games cover wall. * Library: keep an expired store's tab and offer sign-in when nothing is cached An expired account no longer drops its Library tab when it has no cached games: the tab stays and opens on the sign-in card, as on the Stores tab. With cached games it keeps listing them. --- .../launcher/session/SessionPrefs.kt | 19 + .../droiddeck/launcher/ui/FrontEndContent.kt | 10 +- .../droiddeck/launcher/ui/LibraryAccounts.kt | 171 --------- .../com/droiddeck/launcher/ui/LibraryPage.kt | 279 ++++++++++---- .../com/droiddeck/launcher/ui/ManageStores.kt | 358 ++++++++++++++++++ .../launcher/ui/RailSettingsPages.kt | 61 +-- .../com/droiddeck/launcher/ui/SteamHome.kt | 14 +- .../com/droiddeck/launcher/ui/StoresPage.kt | 238 +++--------- .../com/droiddeck/launcher/ui/TabsSettings.kt | 186 ++++----- app/src/main/res/values/strings.xml | 6 + .../launcher/ui/LibraryEntriesTest.kt | 19 + .../launcher/ui/LibraryFavoritesTest.kt | 5 + .../launcher/ui/LibraryVisibilityTest.kt | 48 ++- .../launcher/ui/StoreTabsStateTest.kt | 42 ++ 14 files changed, 860 insertions(+), 596 deletions(-) delete mode 100644 app/src/main/java/com/droiddeck/launcher/ui/LibraryAccounts.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt 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 5c9d0eb17..e7c7f5f2b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -352,6 +352,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/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 191956c17..c81f19dc5 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,17 @@ 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()) + ManageStoresSheet() + } return } if (selected == "desktop") { 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 c79337e85..000000000 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryAccounts.kt +++ /dev/null @@ -1,171 +0,0 @@ -package com.droiddeck.launcher.ui - -import androidx.compose.foundation.LocalIndication -import androidx.compose.foundation.background -import androidx.compose.foundation.basicMarquee -import androidx.compose.foundation.clickable -import androidx.compose.foundation.hoverable -import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ManageAccounts -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.ManageAccounts, 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.ManageAccounts, 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/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index b1fd672a6..dab63bec1 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,16 @@ 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 @@ -167,9 +177,12 @@ 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 }, showHidden: Boolean = false, offStores: Set = emptySet(), + places: List> = DEFAULT_LIBRARY_PLACES, offTabs: Set = emptySet(), +): 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 + LIBRARY_HIDDEN) .filter { source -> when (source) { LIBRARY_HIDDEN -> showHidden @@ -177,6 +190,7 @@ internal fun librarySources( else -> source in always || entries.any { it.source == source && !hidden(it) } } } +} internal object LibraryDisplay { const val DEFAULT_LEVEL = 2 @@ -345,10 +359,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) emptySet() else storeTabs + .filter { it.shown && StoresState.backend(it.store) != null && 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(), + 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, LibraryDisplay.hidden && !soundMode, + 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) emptySet() else StoreTabsState.libraryHidden, ) val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL val q = LibraryView.query.trim().lowercase() @@ -370,7 +392,6 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, } val collectionItems = collectionId?.let { if (source == Store.GAMEJOLT.id) GameJoltCollections.gamesOf(it) else ItchCollections.gamesOf(it) } val pool = if (collectionId == null) all else collectionEntries(all, collectionItems.orEmpty(), Store.byId(source) ?: Store.ITCH) - val libraryTotal = if (soundMode) 0 else all.count { inLibrarySource(LIBRARY_ALL, it, favorites, concealed) } val matching = pool.filter { inLibrarySource(source, it, favorites, concealed) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it) } @@ -491,7 +512,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 } @@ -514,8 +535,8 @@ 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( - s, a, grid, visible, split, if (soundMode) visible.size else libraryTotal, sources, source, sizesPending, syncing, + 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, onSource = { LibraryView.source = it }, @@ -528,15 +549,19 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, 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 && (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) @@ -558,7 +583,7 @@ private fun LibraryEmpty(s: FrontEndState, a: FrontEndActions, modifier: Modifie if (s.steamGamesX64) ClientTag() if (!s.shortcutPicker) { AddGameButton { GamesDialogState.adding = true } - StoreAccountsButton() + ManageStoresChip() } } } @@ -580,6 +605,7 @@ 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" @@ -589,7 +615,12 @@ private fun LibraryGrid( 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 { @@ -600,14 +631,14 @@ private fun LibraryGrid( } val itemIndex: (Int) -> Int = { i -> headerItems + i + when { - split > 0 -> if (i < split) 1 else 2 + 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 + 1 + ToggleAt.SPLIT -> headerItems + split else -> headerItems + visible.size } val gapPx = with(density) { 10.dp.toPx() } @@ -620,6 +651,7 @@ private fun LibraryGrid( } } 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 -> @@ -652,7 +684,17 @@ private fun LibraryGrid( } 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 = { @@ -681,7 +723,7 @@ private fun LibraryGrid( } NotInstalledRow(notInstalled, expanded, keys, onFocus = { rowFocused = it }) { rowFocused = false - val landing = if (expanded) headerItems + split else headerItems + visible.size + 1 + 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 { } @@ -699,16 +741,20 @@ private fun LibraryGrid( modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup().bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }).onSizeChanged { val gap = with(density) { 10.dp.roundToPx() } 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) @@ -723,13 +769,19 @@ private fun LibraryGrid( } } val empty = emptyText - if (split == 0) { + 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) } } + } + 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 { - item(key = "installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_installed)) } libraryGrid(visible.take(split), empty, tile) item(key = NOT_INSTALLED_ROW, span = { GridItemSpan(maxLineSpan) }) { if (toggleAt == ToggleAt.SPLIT) toggleRow() else SectionLabel(stringResource(R.string.stores_section_not_installed)) @@ -800,22 +852,23 @@ 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) DisplayButton() @@ -824,63 +877,143 @@ private fun LibraryHeader( SortButton(s, a) ViewButton(s, a) if (!soundMode) GameFileFolderActions(s, a) - if (!s.shortcutPicker) AddGameButton { if (soundMode) onAddSoundtrack() else GamesDialogState.adding = true } + Store.byId(source)?.takeIf { !soundMode && 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 (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 + } +} + +@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? { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt new file mode 100644 index 000000000..c56ac4a43 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -0,0 +1,358 @@ +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) + } + + /** [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 + SessionPrefs.setLibraryTabsHidden(context, libraryHidden) + } + + 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 and Custom games can be hidden. */ +internal val LIBRARY_OWN_TABS = listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, Library.ADDED) +internal val LIBRARY_HIDEABLE_TABS = setOf(LIBRARY_FAVORITES, Library.ADDED) + +/** Favorites, then Steam, ahead of the stores; Custom games 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) + +/** + * 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) + else -> stringResource(R.string.source_steam) + } + val dot = if (id == LIBRARY_FAVORITES) FavoritesColours.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/RailSettingsPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt index debc0f86b..d25f72365 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt @@ -105,62 +105,19 @@ private fun ResetTabsRow() { } } } -@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) @Composable internal fun EditTabsSheet(s: FrontEndState, a: FrontEndActions) { - val pal = LocalPalette.current - BackHandler(enabled = MoreTabs.editing) { MoreTabs.editing = false } androidx.compose.runtime.DisposableEffect(Unit) { onDispose { MoreTabs.editing = false } } - var wasOpen by remember { mutableStateOf(false) } - val closeInput = androidx.compose.ui.platform.LocalInputModeManager.current - LaunchedEffect(MoreTabs.editing) { - if (MoreTabs.editing) wasOpen = true - else if (wasOpen && closeInput.inputMode == androidx.compose.ui.input.InputMode.Keyboard) focusSoon { MoreTabs.button } - } - Box(Modifier.fillMaxSize()) { - AnimatedVisibility(MoreTabs.editing, enter = fadeIn(), exit = fadeOut()) { - Box( - Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.45f)) - .focusProperties { canFocus = false } - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { MoreTabs.editing = false }, - ) - } - BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) { - val width = minOf(560.dp, maxWidth * 0.92f) - AnimatedVisibility(MoreTabs.editing, enter = slideInHorizontally { it } + fadeIn(), exit = slideOutHorizontally { it } + fadeOut()) { - val inside = remember { FocusRequester() } - var holds by remember { mutableStateOf(false) } - val openInput = androidx.compose.ui.platform.LocalInputModeManager.current - // The launcher only takes focus in controller mode, so opening by touch switches to it like startup does. - LaunchedEffect(Unit) { - repeat(60) { - androidx.compose.runtime.withFrameNanos { } - if (holds || !MoreTabs.editing) return@LaunchedEffect - if (openInput.inputMode != androidx.compose.ui.input.InputMode.Keyboard) openInput.requestInputMode(androidx.compose.ui.input.InputMode.Keyboard) - runCatching { inside.requestFocus() } - } - } - Column( - Modifier.width(width).fillMaxHeight() - .onFocusChanged { holds = it.hasFocus } - .focusRequester(inside) - .focusProperties { exit = { if (MoreTabs.editing) FocusRequester.Cancel else FocusRequester.Default } } - .focusGroup() - .background(MaterialTheme.colorScheme.background) - .border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag("edit-tabs-sheet"), - ) { - PageHeader(stringResource(R.string.more_edit_tabs)) { - Spacer(Modifier.weight(1f)) - SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.onSurfaceVariant) { - MoreTabs.editing = false - } - } - Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) { - TabsSettingsGroup(rememberMenuHost(), s, a) - if (!NavTabs.isDefault()) ResetTabsRow() - } - } + SideSheet(MoreTabs.editing, onClose = { MoreTabs.editing = false }, returnFocus = MoreTabs.button, tag = "edit-tabs-sheet") { + PageHeader(stringResource(R.string.more_edit_tabs)) { + Spacer(Modifier.weight(1f)) + SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.onSurfaceVariant) { + MoreTabs.editing = false } } + Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) { + TabsSettingsGroup(rememberMenuHost(), s, a) + if (!NavTabs.isDefault()) ResetTabsRow() + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 7f2d0cb0c..20dd2c280 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -186,19 +186,19 @@ internal fun Modifier.overhang(by: androidx.compose.ui.unit.Dp = 4.dp): Modifier } @Composable -internal fun WallFade() { +internal fun WallFade(modifier: Modifier = Modifier.fillMaxSize().overhang()) { val colors = MaterialTheme.colorScheme Box( - Modifier.fillMaxSize().overhang().background( + modifier.background( Brush.horizontalGradient( - 0f to colors.background.copy(alpha = 0.97f), - 0.34f to colors.background.copy(alpha = 0.86f), - 0.68f to colors.background.copy(alpha = 0.25f), - 1f to colors.background.copy(alpha = 0.1f), + 0f to colors.background.copy(alpha = 0.86f), + 0.34f to colors.background.copy(alpha = 0.6f), + 0.68f to colors.background.copy(alpha = 0.14f), + 1f to colors.background.copy(alpha = 0.04f), ), ), ) - Box(Modifier.fillMaxSize().overhang().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to colors.background.copy(alpha = 0.9f)))) + Box(modifier.background(Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f)))) } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 2a8e8e67a..edea48ea7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -154,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 @@ -262,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) } @@ -317,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 }) }, ) } } @@ -493,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) @@ -511,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() } @@ -628,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 @@ -663,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) @@ -711,56 +571,59 @@ internal fun CountPill(count: Int) { @Composable -private fun SignInCard(store: Store, height: Dp) { +internal fun SignInCard(store: Store, height: Dp) { 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) } +} + +/** 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() } } } } @@ -774,12 +637,7 @@ 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) - } + startStoreSignIn(ctx, store, placed[0]?.takeIf { it.isAttached }?.boundsInRoot(), colors.primary) { askKey = true } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt index 6d4605785..efe8a808b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt @@ -81,7 +81,6 @@ internal fun TabsSettingsGroup(host: MenuHost, s: FrontEndState, a: FrontEndActi androidx.compose.runtime.withFrameNanos { } reveal.bringIntoView() } - val pad = LocalInputModeManager.current.inputMode == InputMode.Keyboard val state by rememberUpdatedState(s) val rows = { val keys = NavTabs.listed(state) @@ -95,98 +94,113 @@ internal fun TabsSettingsGroup(host: MenuHost, s: FrontEndState, a: FrontEndActi NavTabs.setHidden(ctx, key, !show) } + Box(Modifier.bringIntoViewRequester(reveal)) { + SettingsGroup(stringResource(R.string.setup_group_tabs)) { + SortableRows( + rows = rows, commit = commit, movable = { it != MORE_LINE }, rowHeight = TAB_ROW, handleWidth = TAB_HANDLE, + onActivate = { tab -> if (NavTabs.hideable(tab)) setShown(tab, NavTabs.place(state, tab) == TabPlace.HIDDEN) }, + ) { tab, held, offset, hint, modifier, onFocus -> + if (tab == MORE_LINE) MoreLine() + else TabRow( + tab, NavTabs.place(s, tab) != TabPlace.HIDDEN, NavTabs.hideable(tab), held, offset, hint, modifier, onFocus, + ) { host.open = null; setShown(tab, it) } + } + } + } +} + +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) +@Composable +internal fun SortableRows( + rows: () -> List, + commit: (List) -> Unit, + movable: (String) -> Boolean, + rowHeight: androidx.compose.ui.unit.Dp, + handleWidth: androidx.compose.ui.unit.Dp, + onActivate: (String) -> Unit, + row: @Composable (key: String, held: Boolean, offset: Float, hint: String?, modifier: Modifier, onFocus: (Boolean) -> Unit) -> Unit, +) { + val pad = LocalInputModeManager.current.inputMode == InputMode.Keyboard var dragging by remember { mutableStateOf(null) } var dragOffset by remember { mutableFloatStateOf(0f) } var grabbed by remember { mutableStateOf(null) } var before by remember { mutableStateOf>(emptyList()) } var focused by remember { mutableStateOf(null) } - val rowPx = with(LocalDensity.current) { TAB_ROW.toPx() } - val handlePx = with(LocalDensity.current) { TAB_HANDLE.toPx() } + val rowPx = with(LocalDensity.current) { rowHeight.toPx() } + val handlePx = with(LocalDensity.current) { handleWidth.toPx() } val list = rows() - - Box(Modifier.bringIntoViewRequester(reveal)) { - SettingsGroup(stringResource(R.string.setup_group_tabs)) { - Column( - Modifier.fillMaxWidth().pointerInput(Unit) { - awaitEachGesture { - val down = awaitFirstDown(requireUnconsumed = false) - val start = (down.position.y / rowPx).toInt() - val key = rows().getOrNull(start) - if (key == null || key == MORE_LINE || down.position.x > handlePx || grabbed != null) return@awaitEachGesture - down.consume() - dragging = key - dragOffset = 0f - while (true) { - val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break - change.consume() - if (!change.pressed) break - val travel = change.position.y - down.position.y - val current = rows() - val target = (start + (travel / rowPx).roundToInt()).coerceIn(0, current.lastIndex) - var at = current.indexOf(key) - var next = current - while (target != at) { - next = moveTabRow(next, key, if (target > at) 1 else -1) ?: break - at = next.indexOf(key) + Column( + Modifier.fillMaxWidth().pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + val start = (down.position.y / rowPx).toInt() + val key = rows().getOrNull(start) + if (key == null || !movable(key) || down.position.x > handlePx || grabbed != null) return@awaitEachGesture + down.consume() + dragging = key + dragOffset = 0f + while (true) { + val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break + change.consume() + if (!change.pressed) break + val travel = change.position.y - down.position.y + val current = rows() + val target = (start + (travel / rowPx).roundToInt()).coerceIn(0, current.lastIndex) + var at = current.indexOf(key) + var next = current + while (target != at) { + next = moveTabRow(next, key, if (target > at) 1 else -1) ?: break + at = next.indexOf(key) + } + if (next !== current) commit(next) + dragOffset = travel - (at - start) * rowPx + } + dragging = null + dragOffset = 0f + } + }, + ) { + list.forEachIndexed { index, item -> + key(item) { + if (!movable(item)) row(item, false, 0f, null, Modifier) {} + else { + val bring = remember { BringIntoViewRequester() } + LaunchedEffect(index, grabbed) { if (grabbed == item) bring.bringIntoView() } + row( + item, item == dragging || item == grabbed, if (item == dragging) dragOffset else 0f, + if (pad && focused == item) stringResource(if (grabbed == item) R.string.hud_hint_drop else R.string.hud_hint_grab) else null, + Modifier.bringIntoViewRequester(bring).onPreviewKeyEvent { event -> + val e = event.nativeKeyEvent + val down = e.action == KeyEvent.ACTION_DOWN + val first = down && e.repeatCount == 0 + val mine = grabbed == item + when (e.keyCode) { + KeyEvent.KEYCODE_BUTTON_Y -> { + if (first) { + if (mine) grabbed = null + else if (grabbed == null) { before = rows(); grabbed = item } + } + true + } + KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> { + if (mine && down) moveTabRow(rows(), item, if (e.keyCode == KeyEvent.KEYCODE_DPAD_UP) -1 else 1)?.let(commit) + mine + } + KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> mine + KeyEvent.KEYCODE_BUTTON_B, KeyEvent.KEYCODE_BACK -> { + if (mine && first) { commit(before); grabbed = null } + mine + } + KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_SPACE -> { + if (first) { + if (mine) grabbed = null else onActivate(item) + } + true + } + else -> false } - if (next !== current) commit(next) - dragOffset = travel - (at - start) * rowPx - } - dragging = null - dragOffset = 0f - } - }, - ) { - list.forEachIndexed { index, tab -> - key(tab) { - if (tab == MORE_LINE) { - MoreLine() - } else { - val shown = NavTabs.place(s, tab) != TabPlace.HIDDEN - val held = tab == dragging || tab == grabbed - val bring = remember { BringIntoViewRequester() } - LaunchedEffect(index, grabbed) { if (grabbed == tab) bring.bringIntoView() } - TabRow( - tab, shown, NavTabs.hideable(tab), held, - offset = if (tab == dragging) dragOffset else 0f, - hint = if (pad && focused == tab) stringResource(if (grabbed == tab) R.string.hud_hint_drop else R.string.hud_hint_grab) else null, - modifier = Modifier.bringIntoViewRequester(bring) - .onPreviewKeyEvent { event -> - val e = event.nativeKeyEvent - val down = e.action == KeyEvent.ACTION_DOWN - val first = down && e.repeatCount == 0 - val mine = grabbed == tab - when (e.keyCode) { - KeyEvent.KEYCODE_BUTTON_Y -> { - if (first) { - if (mine) grabbed = null - else if (grabbed == null) { before = rows(); grabbed = tab } - } - true - } - KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> { - if (mine && down) moveTabRow(rows(), tab, if (e.keyCode == KeyEvent.KEYCODE_DPAD_UP) -1 else 1)?.let(commit) - mine - } - KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> mine - KeyEvent.KEYCODE_BUTTON_B, KeyEvent.KEYCODE_BACK -> { - if (mine && first) { commit(before); grabbed = null } - mine - } - KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_SPACE -> { - if (first) { - if (mine) grabbed = null - else if (NavTabs.hideable(tab)) setShown(tab, !shown) - } - true - } - else -> false - } - }, - onFocus = { if (it) focused = tab else if (focused == tab) { focused = null; if (grabbed == tab) grabbed = null } }, - ) { host.open = null; setShown(tab, it) } - } - } + }, + ) { if (it) focused = item else if (focused == item) { focused = null; if (grabbed == item) grabbed = null } } } } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 965ab2322..4ee7cd776 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -4316,6 +4316,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/ui/LibraryEntriesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt index 7674ab242..772578ea3 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt @@ -82,6 +82,25 @@ class LibraryEntriesTest { assertEquals(listOf("steam", "xbox", "epic", "gog", "added"), librarySources(entries, listOf("xbox", "epic", "gog"))) } + @Test fun theLibrarysOwnTabsSitAfterTheTabTheyFollow() { + val entries = listOf("added", "gog", "steam", "epic", "xbox").map { LibraryEntry(it, it, it, null, null, true) } + val order = listOf("xbox", "epic", "gog") + assertEquals(listOf("steam", "xbox", "added", "epic", "gog"), librarySources(entries, order, places = listOf("added" to "xbox"))) + assertEquals(listOf("added", "steam", "xbox", "epic", "gog"), librarySources(entries, order, places = listOf("added" to "", "favorites" to "added", "steam" to "favorites"))) + assertEquals(listOf("xbox", "epic", "steam", "gog", "added"), librarySources(entries, order, places = listOf("favorites" to "epic", "steam" to "favorites", "added" to "nope"))) + } + + @Test fun hidingTheTabALibraryTabFollowsKeepsItInPlace() { + val entries = listOf("added", "gog", "epic", "xbox").map { LibraryEntry(it, it, it, null, null, true) } + assertEquals(listOf("xbox", "added", "gog"), librarySources(entries, listOf("xbox", "epic", "gog"), places = listOf("added" to "epic"), offStores = setOf("epic"))) + } + + @Test fun placesRoundTripThroughTheirOrder() { + val order = listOf("epic", "steam", "favorites", "gog", "xbox", "added") + assertEquals(order, placeLibraryTabs(listOf("epic", "gog", "xbox"), libraryPlacesOf(order))) + assertEquals(listOf("favorites", "steam", "epic", "gog", "added"), placeLibraryTabs(listOf("epic", "gog"), emptyList())) + } + @Test fun librarySourcesIgnoreUnknownAndDuplicateOrderEntriesAndAppendNewStores() { val entries = listOf("epic", "gog", "battlenet").map { LibraryEntry(it, it, it, null, null, false) } assertEquals(listOf("epic", "gog", "battlenet"), librarySources(entries, listOf("missing", "epic", "epic", "amazon"))) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt index 699ca0372..c2ce77dbf 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt @@ -50,4 +50,9 @@ class LibraryFavoritesTest { assertEquals(listOf(LIBRARY_FAVORITES, "steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"))) assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:999"))) } + + @Test fun aHiddenFavoritesTabStaysHiddenWithHeartedGames() { + val entries = listOf(steam(440, "Team Fortress 2"), owned("123", "Witcher")) + assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"), offTabs = setOf(LIBRARY_FAVORITES))) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt index ecefb57d4..2630a3314 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt @@ -81,9 +81,7 @@ class LibraryVisibilityTest { compose.onNodeWithText("Installed Steam game").assertExists() compose.onNodeWithText("Uninstalled GOG").assertDoesNotExist() compose.onNodeWithText("NOT INSTALLED · 2").assertExists() - compose.onNodeWithText("3 games").assertExists() toggleNotInstalled(true) - compose.onNodeWithText("3 games").assertExists() compose.onNodeWithText("Uninstalled GOG").assertExists() compose.runOnIdle { generation++; Snapshot.sendApplyNotifications() } compose.mainClock.advanceTimeBy(2_000) @@ -137,27 +135,47 @@ class LibraryVisibilityTest { 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-not-installed").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 theHeaderCountsTheWholeLibraryWhicheverStoreIsPicked() { - show() - compose.onNodeWithText("3 games").assertExists() - compose.onNodeWithTag("library-source-gog").performClick() + @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.onNodeWithText("3 games").assertExists() + 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() { @@ -198,11 +216,11 @@ class LibraryVisibilityTest { 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/StoreTabsStateTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt new file mode 100644 index 000000000..e159f5185 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreTabsStateTest.kt @@ -0,0 +1,42 @@ +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) + } +}