Stores: GOG, Epic Games and Amazon Games libraries, installs and cloud saves (#476)

A Stores section (rail, under Games; Setup › Stores gate) with each store's sign-in,
library, storefront shelves and a download queue. Each store has two tabs, Store and
Library, and Library filters to All or Installed; libraries open from a saved copy
and refresh in the background, with install sizes on every card. Games install to internal storage,
or a card chosen at Install time, and are registered in the Steam client as non-Steam
games, so they launch through Steam and droiddeck-proton from either the front end or
the client.

- Downloads: GOG, Epic and Amazon engines in Rust (app/src/main/rust/stores, built by
  cargo-ndk, nothing compiled in the tree). One adaptive fetch core with a latency
  brake, stalled-host handoff and every CDN a store offers. Per-stage progress,
  pause/resume, two-step cancel that deletes, failed downloads kept for retry, a
  foreground service with Wi-Fi and wake locks and notification controls.
- Games tab: store source chips (Steam, GOG, Epic, Amazon, Custom) and store art.
- Epic: per-launch exchange code from the app and from Steam's Play button,
  "Epic sign-in (EOS)", "Launch offline", and a game's web links opened in Android's
  browser for EOS consent. The EOS overlay crashed games and is left out.
- Cloud saves (GOG, Epic): pulled before launch, pushed after the game or the session
  ends, no upload before a first download, conflicts never overwritten, backups both
  ways.
- Logs: every store line redacted; the engine log goes to daily files.
This commit is contained in:
The412Banner authored and GitHub committed 2026-10-09 11:08:17 -04:00
1 parent fe71084f23
commit e99d5f9505
141 files changed
+25539 -73

No files matched your search

@@ -83,6 +83,7 @@ import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
@@ -312,7 +313,7 @@ internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolea
@Composable
internal fun AppDialog(
shown: MutableTransitionState<Boolean>, close: () -> Unit, label: String, wide: Boolean,
modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier, maxWidth: Dp? = null, content: @Composable ColumnScope.() -> Unit,
) {
val pal = LocalPalette.current
// The page's ring stays out of sight behind it.
@@ -335,7 +336,7 @@ internal fun AppDialog(
verticalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier
.padding(12.dp)
.widthIn(max = if (wide) 860.dp else 560.dp)
.widthIn(max = maxWidth ?: if (wide) 860.dp else 560.dp)
.fillMaxWidth()
.heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp)
.shadow(24.dp, Shape16, ambientColor = Color.Black, spotColor = Color.Black)
@@ -230,6 +230,11 @@ private fun Content(
StorePage(s, a, modifier)
return
}
// Stores (GOG, Epic, Amazon) takes the whole pane: chips, shelves and a game's page inside it.
if (selected == "stores" && s.gameStoresEnabled) {
StoresPage(s, a, modifier)
return
}
// The Games tab lays out its own list and detail.
if (selected == "games" || selected.startsWith("app:")) {
GamesPage(s, a, selected, onSelect, modifier)
@@ -197,15 +197,19 @@ private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndA
}
}
Box {
SecondaryButton(stringResource(R.string.games_manage_saves), compact = true) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = stringResource(R.string.games_saves), note = summary) { first ->
MenuItem(stringResource(R.string.games_import_saves), checked = false, detail = stringResource(R.string.games_import_saves_hint), focusRequester = first) {
// A GOG or Epic game's saves are its cloud saves: the one place for them, named so.
val cloudGame = com.droiddeck.launcher.stores.Store.byId(g.source).let { it == com.droiddeck.launcher.stores.Store.GOG || it == com.droiddeck.launcher.stores.Store.EPIC }
val label = stringResource(if (cloudGame) R.string.store_cloud_saves else R.string.games_manage_saves)
SecondaryButton(label, compact = true) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = if (cloudGame) label else stringResource(R.string.games_saves), note = summary) { first ->
if (cloudGame) CloudRows(g, open, first)
MenuItem(stringResource(R.string.games_import_saves), checked = false, focusRequester = if (cloudGame) null else first) {
open = false; a.onSaveImport(g)
}
MenuItem(stringResource(R.string.games_export_gamehub), checked = false, detail = stringResource(R.string.games_export_gamehub_hint)) {
MenuItem(stringResource(R.string.games_export_gamehub), checked = false) {
open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.GAMEHUB)
}
MenuItem(stringResource(R.string.games_export_winlator), checked = false, detail = stringResource(R.string.games_export_winlator_hint)) {
MenuItem(stringResource(R.string.games_export_winlator), checked = false) {
open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.WINLATOR)
}
found?.firstOrNull()?.let { d ->
@@ -217,14 +221,74 @@ private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndA
}
}
/**
* A GOG or Epic game's cloud saves: the Cloud saves switch, Upload and Download - three rows from
* the first frame, so nothing moves under the pad while the cloud is checked. Until the check is
* back the two actions are disabled and read "…"; then only their subtitles change: the last sync,
* "No cloud saves", or a conflict, when Upload and Download become Keep local and Keep cloud.
*/
@Composable
private fun CloudRows(g: Library.SteamGame, open: Boolean, first: androidx.compose.ui.focus.FocusRequester) {
val store = com.droiddeck.launcher.stores.Store.byId(g.source)?.takeIf { it != com.droiddeck.launcher.stores.Store.AMAZON } ?: return
val id = g.storeId ?: return
val context = androidx.compose.ui.platform.LocalContext.current.applicationContext
var busy by remember(g.gameId) { androidx.compose.runtime.mutableStateOf<String?>(null) }
var tick by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(0) }
val status by androidx.compose.runtime.produceState<com.droiddeck.launcher.stores.CloudSaves.Status?>(null, g.gameId, open, tick) {
if (open) value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.stores.CloudSaves.status(context, store, id) }.getOrNull()
}
}
// The game's own switch (sidecar "cloud"), known locally: right from the first frame.
val folder = g.gameFiles
var enabled by remember(g.gameId, open) { androidx.compose.runtime.mutableStateOf(folder?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it)?.cloud } ?: true) }
val st = status
val supported = st?.supported ?: true
val conflict = st != null && st.conflicts.isNotEmpty()
fun sync(up: Boolean, force: Boolean = false) {
if (busy != null) return
busy = if (up) "up" else "down"
Thread({
val r = if (up) com.droiddeck.launcher.stores.CloudSaves.upload(context, store, id, force) else com.droiddeck.launcher.stores.CloudSaves.download(context, store, id, force)
com.droiddeck.launcher.stores.StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, if (r.ok) context.getString(R.string.cloud_done, r.files) else r.reason, android.widget.Toast.LENGTH_SHORT).show() }
}, "cloud-manual").start()
}
MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported, focusRequester = first,
detail = if (!supported) stringResource(R.string.cloud_none) else null) {
val f = folder ?: return@MenuItem
val next = !enabled
Thread({
val written = runCatching { com.droiddeck.launcher.stores.StoreGameSidecar.updateCloud(f, next) }.getOrNull()
com.droiddeck.launcher.stores.StoresState.post { enabled = written?.cloud ?: enabled }
}, "cloud-switch").start()
}
val ready = st != null && supported && busy == null
val pending = stringResource(R.string.cloud_pending)
val summary = when {
st == null || busy != null -> pending
!supported -> stringResource(R.string.cloud_none)
conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size)
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
else -> stringResource(R.string.cloud_never)
}
// A conflict turns the two actions into its two answers; the rows stay where they are.
MenuItem(stringResource(if (conflict) R.string.cloud_keep_local else R.string.cloud_upload), checked = false, enabled = ready, detail = summary) { sync(up = true, force = conflict) }
MenuItem(stringResource(if (conflict) R.string.cloud_keep_cloud else R.string.cloud_download), checked = false, enabled = ready, detail = if (st == null || busy != null) pending else null) { sync(up = false, force = conflict) }
}
/** When it was last played (or where it is, if never) over its name, then room for Launch. */
@Composable
private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
Text(
(lastPlayedText(g.lastPlayed) ?: libraryLabel(g.library)).uppercase(),
fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = LocalPalette.current.signal,
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SourceChip(g.source)
// A Custom game's chip already says what its eyebrow would; the line then stays empty.
val eyebrow = lastPlayedText(g.lastPlayed) ?: libraryLabel(g)
if (eyebrow.isNotEmpty()) Text(
eyebrow.uppercase(),
fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = LocalPalette.current.signal,
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
Text(
g.name, fontSize = titleSize, lineHeight = titleSize * 1.15f, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis,
@@ -277,10 +341,14 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni
}
Column(modifier = Modifier.weight(1f)) {
Text(g.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
playedSpan(g.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
// Where it came from beside when it was played: a store's games sit among Steam's own.
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SourceChip(g.source, small = true)
Text(
playedSpan(g.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
}
}
}
@@ -329,11 +397,15 @@ private fun playedSpan(lastPlayed: Long): String? {
).toString()
}
/**
* Where a never-played game lives, beside its source chip: Steam's library, the Games storage for
* a store install (the chip names the store), "Custom game" for a folder the user added.
*/
@Composable
private fun libraryLabel(library: String): String = when (library) {
"internal" -> stringResource(R.string.games_internal)
Library.ADDED -> stringResource(R.string.games_added)
else -> library
private fun libraryLabel(g: Library.SteamGame): String = when {
g.library != Library.ADDED -> if (g.library == "internal") stringResource(R.string.games_internal) else g.library
g.source != Library.ADDED -> stringResource(R.string.games_store_storage)
else -> ""
}
/**
@@ -44,6 +44,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.LocalMall
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material.icons.outlined.SystemUpdate
@@ -57,6 +58,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
@@ -101,7 +103,7 @@ internal fun SideRail(
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
) {
// Every section on screen at once: items shrink (to 44dp, still a touch target) before the rail scrolls.
val count = 6 + (if (s.storeEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0)
val count = 6 + (if (s.storeEnabled) 1 else 0) + (if (s.gameStoresEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0)
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
Column(
@@ -112,6 +114,9 @@ internal fun SideRail(
RailItem(stringResource(R.string.rail_steam), Icons.Outlined.SportsEsports, "steam", selected == "steam", compact, iconOnly, fit, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
// Always there, so the items below it never move; an empty library says how to fill it.
RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, fit, onFocus = { onFocusSelect("games") }) { onSelect("games") }
// The game stores, right under Games: what they install lands there. Its badge counts
// the downloads in flight, so a download started here is never out of sight.
if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", selected == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, fit, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
if (s.storeEnabled) RailItem(stringResource(R.string.rail_store), Icons.Outlined.Storefront, "store", selected == "store", compact, iconOnly, fit, onFocus = { onFocusSelect("store") }) { onSelect("store") }
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", selected == "components", compact, iconOnly, fit, onFocus = { onFocusSelect("components") }) { onSelect("components") }
@@ -134,7 +139,10 @@ internal fun SideRail(
@Composable
private fun RailItem(
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp,
badge: Boolean = false, onFocus: () -> Unit = {}, onClick: () -> Unit,
badge: Boolean = false,
/** A number on the item (downloads in flight); 0 shows nothing. */
count: Int = 0,
onFocus: () -> Unit = {}, onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -182,6 +190,12 @@ private fun RailItem(
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 7.dp else 8.dp, end = if (iconOnly) 9.dp else 18.dp)
.size(8.dp).clip(CircleShape).background(AttentionAmber),
)
if (count > 0) Text(
if (count > 9) "9+" else count.toString(),
fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.onSignal, maxLines = 1,
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 4.dp else 6.dp, end = if (iconOnly) 5.dp else 12.dp)
.clip(RoundedCornerShape(8.dp)).background(pal.signal).padding(horizontal = 5.dp, vertical = 1.dp),
)
}
}
@@ -129,6 +129,17 @@ class FrontEndState(
val animationsEnabled: Boolean = true,
/** The Flathub Store, a beta the user turns on in Setup. */
val storeEnabled: Boolean = false,
/** The Stores section (GOG, Epic Games, Amazon Games), turned on in Setup. */
val gameStoresEnabled: Boolean = false,
/** Setup › Stores: the download engine's speed tier (stores/download/StoreDownloadTier ids). */
val gameStoresSpeedTier: String = "fast",
/** Setup › Stores: the tab a signed-in store opens on (SessionPrefs.STORES_OPEN_LIBRARY / STORE). */
val storesOpenTab: String = SessionPrefs.STORES_OPEN_LIBRARY,
/** A page to open once: "stores:downloads", or a selection such as "app:<id>" (a notification's tap). */
val navigate: String? = null,
val storesShowMature: Boolean = false,
/** Downloads queued, running or paused across the three stores; the rail item's badge. */
val storeDownloadsActive: Int = 0,
/** The Updates page: DroidDeck's own builds and the channel followed. */
val updates: UpdatesState = UpdatesState(),
)
@@ -179,6 +190,13 @@ class FrontEndActions(
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onStoreEnabled: (Boolean) -> Unit = {},
val onGameStoresEnabled: (Boolean) -> Unit = {},
val onGameStoresSpeedTier: (String) -> Unit = {},
val onStoresOpenTab: (String) -> Unit = {},
val onNavigated: () -> Unit = {},
val onStoresShowMature: (Boolean) -> Unit = {},
/** The Games list rebuilt now: a store install or removal changed what is on disk. */
val onLibraryChanged: () -> Unit = {},
val onHomeApp: () -> Unit = {},
val onHomeScreen: (Boolean) -> Unit = {},
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
@@ -356,6 +374,11 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
var selected by rememberSaveable { mutableStateOf(if (s.shortcutPicker) "games" else "steam") }
LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" }
LaunchedEffect(s.navigate) {
val target = s.navigate ?: return@LaunchedEffect
if (target == "stores:downloads") { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" } else selected = target
a.onNavigated()
}
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
@@ -391,8 +414,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop"
}
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
// The Store turned off in Setup takes its page with it.
// The Store turned off in Setup takes its page with it; so does Stores.
LaunchedEffect(s.storeEnabled) { if (!s.storeEnabled && selected == "store") selected = "steam" }
LaunchedEffect(s.gameStoresEnabled) { if (!s.gameStoresEnabled && selected == "stores") selected = "games" }
// The last game uninstalled leaves the Games tab on its empty state.
LaunchedEffect(s.steamGames.isEmpty()) {
if (s.steamGames.isEmpty() && selected.startsWith("app:")) selected = "games"
@@ -76,6 +76,7 @@ import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.R
// The Setup page: runtime and device checks, tools, frame generation and launch settings.
@@ -367,6 +368,24 @@ internal fun SetupPanel(
s.storeEnabled,
) { a.onStoreEnabled(it) }
}
SettingsGroup(stringResource(R.string.setup_stores)) {
ToggleRow(
host, "stores-enabled", stringResource(R.string.setup_stores_show),
null, s.gameStoresEnabled,
) { a.onGameStoresEnabled(it) }
// The same rows as the Stores page's own cog, for whoever looks here first.
SettingsRow(stringResource(R.string.setup_stores_open_on), null) {
SegmentedTabs(
listOf(SessionPrefs.STORES_OPEN_LIBRARY to stringResource(R.string.stores_tab_library), SessionPrefs.STORES_OPEN_STORE to stringResource(R.string.stores_tab_store)),
s.storesOpenTab,
) { a.onStoresOpenTab(it) }
}
ToggleRow(host, "stores-show-mature", stringResource(R.string.stores_show_mature), null, s.storesShowMature) { a.onStoresShowMature(it) }
SettingsRow(stringResource(R.string.setup_stores_speed), null) {
SegmentedTabs(StoreDownloadTier.ALL.map { it.id to stringResource(it.label) }, s.gameStoresSpeedTier) { a.onGameStoresSpeedTier(it) }
}
StoresEngineRow()
}
}
}
}
@@ -456,6 +475,15 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
// An Epic game's own launch choices, kept in its sidecar so a launch from the Steam client
// honours them too (droiddeck-store-launch reads the same file).
// Epic's launch choices; cloud saves live in the game's Cloud saves view, so a GOG game has no card.
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC }
if (cardStore != null && game?.gameFiles != null) add { m ->
Box(m) {
StoreLaunchCard(host, game.gameFiles!!, cardStore)
}
}
if (wincompKey != null) add { m ->
SettingCard(
stringResource(R.string.wincomp_title),
@@ -479,6 +507,53 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
/** Epic's account page behind its sign-in: signing in there presents any step the account still owes. */
private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
/** The Epic card: the sign-in and offline switches, read from and written to the game's sidecar, and Resolve Epic sign-in. */
@Composable
private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) {
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
var sidecar by remember(folder) { mutableStateOf(com.droiddeck.launcher.stores.StoreGameSidecar.read(folder)) }
val options = sidecar?.epic ?: com.droiddeck.launcher.stores.EpicOptions()
val epic = store == com.droiddeck.launcher.stores.Store.EPIC
val key = "store-" + store.id
val value = buildList {
if (epic && options.offline) add(stringResource(R.string.epic_card_offline))
else if (epic && options.eos) add(stringResource(R.string.epic_card_eos))
}.ifEmpty { listOf(stringResource(R.string.epic_card_none)) }.joinToString(" · ")
// Each switch goes straight to the sidecar on disk - both launch paths read it there - and the
// card shows what was read back, so a write that did not take is never shown as done.
fun set(change: (com.droiddeck.launcher.stores.EpicOptions) -> com.droiddeck.launcher.stores.EpicOptions) {
Thread({
val written = runCatching { com.droiddeck.launcher.stores.StoreGameSidecar.updateEpic(folder, change) }
.onFailure { android.util.Log.w("EpicLaunchCard", "could not write ${folder.name}: ${it.message}") }.getOrNull()
if (written != null) android.util.Log.i("EpicLaunchCard", "epic options ${written.id} eos=${written.epic.eos} offline=${written.epic.offline}")
else android.util.Log.w("EpicLaunchCard", "epic options not saved for ${folder.name}")
com.droiddeck.launcher.stores.StoresState.post { sidecar = written ?: com.droiddeck.launcher.stores.StoreGameSidecar.read(folder) }
}, "epic-options").start()
}
SettingCard(store.shortLabel, value, "card:$key", Modifier.fillMaxSize()) {
host.open = if (host.open == key) null else key
}
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = store.shortLabel) { first ->
if (epic) {
MenuItem(stringResource(R.string.epic_eos), checked = options.eos, focusRequester = first) { set { it.copy(eos = !it.eos) } }
MenuItem(stringResource(R.string.epic_offline), checked = options.offline) { set { it.copy(offline = !it.offline) } }
}
if (epic) {
// Epic asks some accounts to accept something once (privacy policy, EULA) before a game may
// sign in - EOS's "corrective action". Signing in on Epic's site shows it.
MenuItem(stringResource(R.string.epic_resolve), checked = false) {
host.open = null
runCatching {
appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(EPIC_RESOLVE_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
}
}
}
@Composable
private fun SettingCard(label: String, value: String, id: String, modifier: Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -233,6 +233,19 @@ class MenuHost {
@Composable
fun rememberMenuHost(): MenuHost = remember { MenuHost() }
/** Under the anchor with left edges aligned, kept on screen: a dropdown that belongs to a tab. */
private class BelowStartProvider(private val gap: Int) : PopupPositionProvider {
override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {
var x = anchorBounds.left
if (x + popupContentSize.width > windowSize.width - 8) x = windowSize.width - 8 - popupContentSize.width
if (x < 8) x = 8
var y = anchorBounds.bottom + gap
if (y + popupContentSize.height > windowSize.height - 8) y = anchorBounds.top - gap - popupContentSize.height
if (y < 8) y = 8
return IntOffset(x, y)
}
}
private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {
var x = anchorBounds.right - popupContentSize.width
@@ -245,7 +258,12 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
}
@Composable
fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.(FocusRequester) -> Unit) {
fun AnchoredMenu(
open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null,
/** A tab's dropdown: under its anchor, left edges aligned, as wide as its entries (within [minWidth]..260 dp). */
compact: Boolean = false, minWidth: androidx.compose.ui.unit.Dp = 120.dp,
content: @Composable ColumnScope.(FocusRequester) -> Unit,
) {
val state = remember { MutableTransitionState(false) }
state.targetState = open
if (!state.currentState && !state.targetState && state.isIdle) return
@@ -259,14 +277,14 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no
}
}
val gap = with(LocalDensity.current) { 6.dp.roundToPx() }
val provider = remember(gap) { BelowEndProvider(gap) }
val provider = remember(gap, compact) { if (compact) BelowStartProvider(gap) else BelowEndProvider(gap) }
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Popup(popupPositionProvider = provider, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) {
AnimatedVisibility(
visibleState = state,
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f, transformOrigin = TransformOrigin(1f, 0f)),
exit = fadeOut(Motion.tw(140)) + scaleOut(Motion.tw(140), targetScale = 0.96f, transformOrigin = TransformOrigin(1f, 0f)),
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f, transformOrigin = TransformOrigin(if (compact) 0f else 1f, 0f)),
exit = fadeOut(Motion.tw(140)) + scaleOut(Motion.tw(140), targetScale = 0.96f, transformOrigin = TransformOrigin(if (compact) 0f else 1f, 0f)),
label = "menu",
) {
// A long list (a driver menu with its downloads) must not run off the screen: the menu is
@@ -274,7 +292,7 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no
val maxHeight = (androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp * 0.86f).dp
Column(
modifier = Modifier
.widthIn(min = 220.dp, max = 340.dp)
.then(if (compact) Modifier.widthIn(min = minWidth, max = 260.dp).width(androidx.compose.foundation.layout.IntrinsicSize.Max) else Modifier.widthIn(min = 220.dp, max = 340.dp))
.heightIn(max = maxHeight)
.shadow(24.dp, RowShape, ambientColor = Color.Black, spotColor = Color.Black)
.clip(RowShape)
@@ -0,0 +1,71 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.Store
// Where a game came from, as a small coloured chip: Steam, one of the stores, or an added folder.
/** The chip's colours per source: a tinted ground and a readable ink on it, one pair per store. */
internal class SourceColours(val fill: Color, val ink: Color, val dot: Color)
internal fun sourceColours(source: String): SourceColours = when (source) {
Store.GOG.id -> SourceColours(Color(0xFF3A1A3C), Color(0xFFE6A3EA), Color(0xFFC25BC8))
Store.EPIC.id -> SourceColours(Color(0xFF2A2A2A), Color(0xFFDDDDDD), Color(0xFFBDBDBD))
Store.AMAZON.id -> SourceColours(Color(0xFF3A2A0A), Color(0xFFFFC266), Color(0xFFFF9900))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
}
@Composable
internal fun sourceLabel(source: String): String = when (source) {
Library.SOURCE_STEAM -> stringResource(R.string.source_steam)
Store.GOG.id -> Store.GOG.label
Store.EPIC.id -> Store.EPIC.label
Store.AMAZON.id -> Store.AMAZON.label
else -> stringResource(R.string.source_added)
}
/** The source chip itself; [small] for a list row, the regular size for a hero or a card. */
@Composable
internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifier = Modifier) {
val c = sourceColours(source)
Text(
sourceLabel(source), fontSize = if (small) 10.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.4.sp,
color = c.ink, maxLines = 1,
modifier = modifier.clip(RoundedCornerShape(6.dp)).background(c.fill)
.padding(horizontal = if (small) 6.dp else 8.dp, vertical = if (small) 1.dp else 2.dp),
)
}
/** A status chip in the stores' colours: green for done ("Installed"), blue for busy, amber for a warning. */
@Composable
internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false) {
val pal = LocalPalette.current
val (fill, ink) = when (tone) {
ChipTone.OK -> Color(0xFF16321F) to pal.good
ChipTone.BUSY -> pal.signal.copy(alpha = 0.18f) to pal.signal
ChipTone.WARN -> Color(0xFF3A2E10) to Color(0xFFFFC24D)
ChipTone.DEAL -> Color(0xFF1E3A1A) to Color(0xFF9BE27A)
ChipTone.PLAIN -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant
}
Text(
text, fontSize = if (small) 9.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.3.sp, color = ink, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(fill).padding(horizontal = if (small) 5.dp else 8.dp, vertical = if (small) 1.dp else 2.dp),
)
}
internal enum class ChipTone { OK, BUSY, WARN, DEAL, PLAIN }
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
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.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
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.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
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 coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
// A store game's own page: hero, the one main action, how it is launched and where it lives.
@Composable
internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: FrontEndActions, onBack: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val id = key.substringAfter(':')
val item = (StoresState.library[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
val installed = StoresState.installedGame(store, id)
val download = StoresState.download("${store.id}:$id")?.takeIf { it.isActive }
// Removal asks twice: one stray press of A should not cost a download.
var confirmRemove by remember(key) { mutableStateOf(false) }
LaunchedEffect(confirmRemove) { if (confirmRemove) { kotlinx.coroutines.delay(4000); confirmRemove = false } }
val title = item?.title ?: installed?.sidecar?.title ?: id
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.padding(bottom = 12.dp)) {
BackLink(store.label, compact = true, onClick = onBack)
SourceChip(store.id)
}
}
Rise(1) {
Box(Modifier.fillMaxWidth().heightIn(min = if (narrow) 150.dp else 180.dp).clip(Shape16).background(artBrush(hueOf(title)))) {
val art = item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover
if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.5f to colors.background.copy(alpha = 0.55f), 1f to Color.Transparent)))
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp)) {
// An install names where it went (internal storage, the card), a download where it is going.
val state = when {
installed != null -> stringResource(R.string.stores_eyebrow_installed) + " · " + com.droiddeck.launcher.stores.StoreInstallRoot.labelFor(ctx, installed.folder)
download != null && download.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + download.location
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
else -> stringResource(R.string.stores_eyebrow_store)
}
val size = (item?.sizeBytes ?: 0L).takeIf { it > 0 }?.let { " · " + formatBytes(it) } ?: ""
Text((state + size).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = pal.signal)
Text(title, fontSize = if (narrow) 24.sp else 30.sp, lineHeight = if (narrow) 27.sp else 33.sp, fontWeight = FontWeight.Black, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
Actions {
when {
installed != null -> {
// Launching, the prefix and the files belong to the Games tab, where every
// installed game has them; here an install only says it is in Steam and
// offers the one thing Games does not: removing it.
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
SecondaryButton(if (confirmRemove) stringResource(R.string.stores_uninstall_confirm) else stringResource(R.string.stores_uninstall), enabled = download == null) {
if (!confirmRemove) confirmRemove = true
else { confirmRemove = false; StoresState.uninstall(ctx, installed) { StoresState.refresh(ctx); a.onLibraryChanged() }; onBack() }
}
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { com.droiddeck.launcher.stores.download.DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) { com.droiddeck.launcher.stores.download.DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { com.droiddeck.launcher.stores.download.DownloadQueue.cancel(ctx, download.key) }
}
item?.owned == true && StoresState.isUnfinished(item) -> {
PrimaryButton(stringResource(R.string.stores_resume_install), main = true) { StoresState.requestInstall(ctx, item) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
}
item?.owned == true -> PrimaryButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install), main = true,
) { StoresState.requestInstall(ctx, item) }
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(if (item.hasPrice && item.finalPrice.isNotBlank()) stringResource(R.string.stores_buy_price, item.finalPrice) else stringResource(R.string.stores_view_on, store.shortLabel), main = true) { openStoreUrl(ctx, item) }
}
BusyChip(s)
}
}
}
}
// Plain text only, and nothing at all when the store sent a template key instead of words.
// A description that is only the title again (some stores fill it so) is no description.
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
if (description.isNotBlank()) Rise(2) {
Text(description, fontSize = 13.sp, lineHeight = 19.sp, color = colors.onSurfaceVariant, maxLines = 6, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 12.dp))
}
}
@@ -0,0 +1,328 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.draw.alpha
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.clickable
import androidx.compose.material.icons.automirrored.outlined.Undo
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Pause
import coil.compose.AsyncImage
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.graphics.Brush
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
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.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
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.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.formatSpeed
// The Downloads chip: one queue for the three stores, its settings and the engine log.
@Composable
internal fun StoresDownloadsPane(s: FrontEndState, a: FrontEndActions) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 700.dp
val list: @Composable () -> Unit = { DownloadList(s, a) }
val side: @Composable () -> Unit = { DownloadSettings(s, a) }
if (wide) Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) {
Box(Modifier.weight(3f)) { list() }
Box(Modifier.weight(2f)) { side() }
} else Column { list(); side() }
}
}
@Composable
private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
val colors = MaterialTheme.colorScheme
val entries = StoresState.downloads
if (entries.isEmpty()) {
Box(Modifier.fillMaxWidth().padding(vertical = 40.dp), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.stores_downloads_empty), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
return
}
// Under way on top; finished below a line whose X clears them all (rows only - a failed
// download's kept files stay until its game page's Clear).
val (active, finished) = entries.partition { it.isActive }
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
// The list changes only when rows come, go or change state; each row reads its own progress.
active.forEachIndexed { i, row -> key(row.key) { Rise(1 + i.coerceAtMost(5)) { DownloadCard(StoresState.download(row.key) ?: row, s, a) } } }
if (finished.isNotEmpty()) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = if (active.isEmpty()) 0.dp else 4.dp)) {
Box(Modifier.weight(1f).height(1.dp).background(LocalPalette.current.line))
RoundAction(Icons.Outlined.Close, stringResource(R.string.stores_dl_clear_all), size = 30.dp) { DownloadQueue.dismissFinished() }
}
finished.forEach { row ->
key(row.key) {
val d = StoresState.download(row.key) ?: row
if (d.state == DownloadState.FAILED) DownloadCard(d, s, a) else FinishedRow(d, s, a)
}
}
}
}
}
/** A finished download: its name and store, and Play when it installed. */
@Composable
private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface).padding(horizontal = 12.dp, vertical = 6.dp),
) {
Text(d.name, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
SourceChip(d.store.id, small = true)
Text(stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.weight(1f))
if (d.state == DownloadState.INSTALLED) RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
}
}
/**
* A row's action as a round icon button - the label is its description - sized like the old
* compact buttons and focusable by pad. [primary] fills it with the accent, [danger] in red.
*/
@Composable
internal fun RoundAction(
icon: androidx.compose.ui.graphics.vector.ImageVector, description: String, primary: Boolean = false, danger: Boolean = false,
enabled: Boolean = true, size: androidx.compose.ui.unit.Dp = 36.dp, onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hot = rememberHot(src)
val fill = when { danger -> Color(0xFFD9443B); primary -> pal.signal; else -> colors.surface.copy(alpha = 0.85f) }
val tint = if (primary || danger) Color.White else if (hot) pal.signal else colors.onBackground
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(size).clip(androidx.compose.foundation.shape.CircleShape).background(fill)
.glideBorder(hot, androidx.compose.foundation.shape.CircleShape, if (primary || danger) colors.onBackground else pal.signal, pal.line)
.alpha(if (enabled) 1f else 0.4f)
.hoverable(src).clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, enabled = enabled, role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick),
) { androidx.compose.material3.Icon(icon, description, tint = tint, modifier = Modifier.size(size * 0.5f)) }
}
/** Cancel in two taps: the stop icon, then a red delete and a keep that undoes it (back by itself after a few seconds). */
@Composable
private fun CancelAction(onDelete: () -> Unit) {
var armed by remember { mutableStateOf(false) }
androidx.compose.runtime.LaunchedEffect(armed) { if (armed) { kotlinx.coroutines.delay(4000); armed = false } }
if (!armed) RoundAction(Icons.Outlined.Close, stringResource(R.string.stores_dl_cancel)) { armed = true }
else {
RoundAction(Icons.Outlined.Delete, stringResource(R.string.stores_dl_cancel_confirm), danger = true) { armed = false; onDelete() }
RoundAction(Icons.AutoMirrored.Outlined.Undo, stringResource(R.string.stores_notification_keep)) { armed = false }
}
}
@Composable
private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val ink = Color.White
val dim = Color.White.copy(alpha = 0.72f)
// The game's wide art is the row: cropped to it, a dark wash from the left so the copy reads
// in white there, the art clear on the right.
Box(Modifier.fillMaxWidth().heightIn(min = 88.dp).clip(Shape12).background(Color(0xFF101318)).border(1.dp, pal.line, Shape12)) {
if (!d.cover.isNullOrEmpty()) AsyncImage(model = d.cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
else Spacer(Modifier.matchParentSize().background(artBrush(hueOf(d.name))))
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to Color.Black.copy(alpha = 0.92f), 0.5f to Color.Black.copy(alpha = 0.7f), 1f to Color.Black.copy(alpha = 0.15f))))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp)) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(d.name, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
SourceChip(d.store.id, small = true)
val where = listOfNotNull(d.location.takeIf { it.isNotBlank() }, d.diskBytes.takeIf { it > 0 }?.let { formatBytes(it) }).joinToString(" · ")
if (where.isNotEmpty()) Text(where, fontSize = 11.sp, color = dim, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
StageBar(d)
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
val meta = when (d.state) {
DownloadState.INSTALLED -> stringResource(R.string.stores_installed_chip)
DownloadState.CANCELLED -> stringResource(R.string.stores_dl_cancelled)
// The reason is in the engine log; the row only says what is kept for Resume.
DownloadState.FAILED -> if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone)) else stringResource(R.string.stores_dl_failed)
DownloadState.PAUSED -> stringResource(R.string.stores_dl_paused)
DownloadState.QUEUED -> if (d.queuePosition > 0) stringResource(R.string.stores_dl_queued_at, d.queuePosition) else stringResource(R.string.stores_dl_queued)
DownloadState.RUNNING -> {
val head = downloadLabel(d)
when {
d.stage == DownloadStage.DOWNLOAD && d.bytesTotal > 0 -> stringResource(R.string.stores_dl_with, head, stringResource(R.string.stores_dl_amount, formatBytes(d.bytesDone), formatBytes(d.bytesTotal)))
d.stageItemsTotal > 0 -> stringResource(R.string.stores_dl_with, head, stringResource(R.string.stores_dl_items, d.stageItems, d.stageItemsTotal))
else -> head
}
}
}
Text(meta, fontSize = 12.sp, color = dim, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
if (d.state == DownloadState.RUNNING && (d.stage == DownloadStage.DOWNLOAD || d.stage == DownloadStage.INSTALL) && d.speedBps > 0) {
Text(formatSpeed(d.speedBps), fontSize = 12.sp, color = dim, maxLines = 1)
if (d.etaSeconds >= 0) Text(eta(d.etaSeconds), fontSize = 12.sp, color = dim, maxLines = 1)
}
}
}
// The row's actions on the right, over the art: icons, their labels as descriptions.
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
when (d.state) {
DownloadState.RUNNING, DownloadState.QUEUED -> {
RoundAction(Icons.Filled.Pause, stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(d.key) }
CancelAction { DownloadQueue.cancel(ctx, d.key) }
}
DownloadState.PAUSED -> {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
CancelAction { DownloadQueue.cancel(ctx, d.key) }
}
DownloadState.FAILED -> RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
DownloadState.INSTALLED -> RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
DownloadState.CANCELLED -> {}
}
}
}
}
}
/**
* One segment per stage - Manifest, Download, Verify, Install - equal widths: a passed or skipped
* stage full, the active one filling with its own progress (a sliver while it has nothing to count),
* the rest empty.
*/
@Composable
private fun StageBar(d: DownloadEntry) {
val stages = listOf(DownloadStage.MANIFEST, DownloadStage.DOWNLOAD, DownloadStage.VERIFY, DownloadStage.INSTALL)
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth()) {
for (st in stages) {
val active = d.state != DownloadState.INSTALLED && d.stage == st
val fill = when {
active -> d.stageFraction.let { if (it < 0f) 0.04f else it }
// A stage a store skips or folds into another (Epic checks chunks while it fetches,
// Amazon writes while it downloads) reads complete once a later one has started.
d.passed(st) || st.ordinal < d.stage.ordinal || d.stage == DownloadStage.DONE -> 1f
else -> 0f
}
Box(Modifier.weight(1f)) {
ProgressBarThin(
fill, paused = active && d.state == DownloadState.PAUSED, verify = active && st == DownloadStage.VERIFY,
height = 6.dp, done = !active && fill >= 1f,
)
}
}
}
}
private fun eta(seconds: Long): String = when {
seconds < 60 -> "<1 min"
seconds < 3600 -> "~${seconds / 60} min"
else -> "~${seconds / 3600} h ${(seconds % 3600) / 60} m"
}
/** The queue's settings beside it: speed tier, downloads at a time, and the engine log. */
@Composable
private fun DownloadSettings(s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
SectionTitle(stringResource(R.string.stores_download_manager), null)
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface).border(1.dp, pal.line, Shape12).padding(horizontal = 14.dp, vertical = 10.dp)) {
DownloadControls(s, a)
}
}
/**
* The queue's two knobs on one line - the speed tier on the left, downloads at a time on the
* right; the same control sits in the cog's popup. A narrow page puts them on two tight lines.
*/
@Composable
internal fun DownloadControls(s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
var parallel by remember { mutableStateOf(DownloadQueue.parallel(ctx)) }
val tier: @Composable () -> Unit = {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(stringResource(R.string.setup_stores_speed), fontSize = 12.sp, color = colors.onSurfaceVariant)
SegmentedTabs(StoreDownloadTier.ALL.map { it.id to stringResource(it.label) }, s.gameStoresSpeedTier) { a.onGameStoresSpeedTier(it) }
}
}
val count: @Composable () -> Unit = {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(stringResource(R.string.stores_parallel), fontSize = 12.sp, color = colors.onSurfaceVariant)
SegmentedTabs(listOf(1 to "1", 2 to "2", 3 to "3"), parallel) { parallel = it; DownloadQueue.setParallel(ctx, it) }
}
}
BoxWithConstraints(Modifier.fillMaxWidth()) {
if (maxWidth >= 460.dp) Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Bottom) { tier(); count() }
else Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { tier(); count() }
}
}
/**
* The chip row's cog: the section's own settings in a small card - which tab a store opens on
* and the speed tier. Setup › Stores repeats them under its gate. Every install is added to Steam;
* that is not a choice.
*/
@Composable
internal fun StoresSettingsDialog(s: FrontEndState, a: FrontEndActions, onDismiss: () -> Unit) {
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
AppDialog(shown, close, "storesSettings", wide = false, maxWidth = 440.dp) {
DialogHeader(stringResource(R.string.stores_settings_eyebrow), stringResource(R.string.stores_title))
Rise(1) {
Column {
SettingsRow(stringResource(R.string.setup_stores_open_on), null) {
SegmentedTabs(
listOf(SessionPrefs.STORES_OPEN_LIBRARY to stringResource(R.string.stores_tab_library), SessionPrefs.STORES_OPEN_STORE to stringResource(R.string.stores_tab_store)),
s.storesOpenTab,
) { a.onStoresOpenTab(it) }
}
SettingsRow(stringResource(R.string.stores_show_mature), null) {
ToggleSwitch(s.storesShowMature, label = stringResource(R.string.stores_show_mature)) { a.onStoresShowMature(it) }
}
// The queue's two knobs as one compact row, the same control the Downloads page has.
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { DownloadControls(s, a) }
}
}
Rise(2) { Actions { SecondaryButton(stringResource(R.string.common_ok), onClick = close) } }
}
}
@@ -0,0 +1,109 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.SdCard
import androidx.compose.material.icons.outlined.Smartphone
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.remember
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.platform.LocalContext
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.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.formatBytes
/**
* "Install <game>:" over one row per place - internal storage, the card - each the action
* itself: icon, name, free space. Asked only when a card is there. The row picked last time
* starts focused, so a pad confirms the usual place with one press; nothing is chosen for the user.
*/
@Composable
internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val targets = remember { StoreInstallRoot.targets(ctx) }
val remembered = remember { SessionPrefs.storesInstallTarget(ctx) }
val defaultIndex = targets.indexOfFirst { it.root.absolutePath == remembered }.coerceAtLeast(0)
val focus = remember { List(targets.size) { FocusRequester() } }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { focus[defaultIndex] } }
AppDialog(shown, close, "installWhere", wide = false, maxWidth = 440.dp) {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Text(
stringResource(R.string.stores_install_title, item.title), fontSize = 15.sp, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
Text(
stringResource(R.string.common_cancel), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant,
modifier = Modifier.clip(Shape12).clickable(role = Role.Button, onClick = close).padding(horizontal = 10.dp, vertical = 6.dp),
)
}
}
Rise(1) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
targets.forEachIndexed { i, t ->
TargetRow(
label = if (t.removable) t.label else stringResource(R.string.stores_target_internal),
free = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
removable = t.removable, focus = focus[i],
) {
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
StoresState.install(ctx, item, t.root)
close()
}
}
}
}
}
}
@Composable
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, onPick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth().focusRequester(focus).clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface.copy(alpha = 0.6f))
.glideBorder(hot, Shape12, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onPick)
.controllerConfirm(onClick = onPick)
.padding(horizontal = 14.dp, vertical = 10.dp),
) {
Icon(if (removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(22.dp))
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(free, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
@@ -0,0 +1,686 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.draw.blur
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
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.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Download
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.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
// The Stores section: GOG, Epic Games and Amazon Games libraries and storefronts, and one
// download queue for the three, in a single full-width pane.
/** The chip row's fourth entry, beside the three stores. */
private const val DOWNLOADS = "downloads"
private val TABS = listOf("store", "library")
/**
* The tabs a store has: Store and Library (whose dropdown filters All / Installed). Amazon has no
* public catalog, so Library alone.
*/
internal fun tabsFor(store: Store?): List<String> = if (store == Store.AMAZON) listOf("library") else TABS
/** [tab] if [store] has it, else Library (the open-on Store choice, or an old Installed / All, falls back there). */
internal fun tabFor(store: Store?, tab: String): String = if (tab in tabsFor(store)) tab else "library"
@Composable
internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
val ctx = LocalContext.current
val narrow = LocalNarrowPane.current
val padH = if (narrow) 14.dp else 22.dp
var chip by rememberSaveable { mutableStateOf(Store.GOG.id) }
var tab by rememberSaveable { mutableStateOf(if (SessionPrefs.storesOpenTab(ctx) == SessionPrefs.STORES_OPEN_STORE) "store" else "library") }
var query by rememberSaveable { mutableStateOf("") }
var openGame by rememberSaveable { mutableStateOf<String?>(null) }
var settings by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(StoresState.openDownloads) { if (StoresState.openDownloads) { chip = DOWNLOADS; StoresState.openDownloads = false } }
val store = Store.byId(chip)
// A tab this store does not have (Store or All on Amazon) reads as Library.
val shownTab = tabFor(store, tab)
LaunchedEffect(Unit) { StoresState.refresh(ctx) }
// A store the account is signed into fills itself when its chip is on screen.
LaunchedEffect(chip, StoresState.accounts[store]) { if (store != null && StoresState.isSignedIn(store)) StoresState.open(ctx, store) }
// A pad's focus sits on something the page is about to replace - the card that opens a game,
// a tab's contents - and would be lost with it, leaving the next press to land on the rail.
// Each move says where focus goes next: into the game page's main action, back to the card
// it was opened from, or onto the first card of a tab or store just picked.
val ff = LocalFrontFocus.current
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
var focusMove by remember { mutableStateOf<Pair<String, Int>?>(null) }
var lastOpened by remember { mutableStateOf<String?>(null) }
fun move(kind: String) { focusMove = kind to (focusMove?.second ?: 0) + 1 }
fun open(key: String) { lastOpened = key; openGame = key; move("detail") }
fun closeGame() { openGame = null; move("card") }
fun switchTab(to: String) { tab = to; move("first") }
// Picking a chip opens the tab Setup says (Library or Store); a tab the user switches to
// afterwards stays until another chip is picked.
val pickChip: (String) -> Unit = { id ->
chip = id; openGame = null; query = ""
if (id != DOWNLOADS) tab = tabFor(Store.byId(id), if (s.storesOpenTab == SessionPrefs.STORES_OPEN_STORE) "store" else "library")
move("first")
}
BackHandler(enabled = openGame != null) { closeGame() }
val scroll = rememberScrollState()
LaunchedEffect(chip, tab, openGame) { scroll.scrollTo(0) }
LaunchedEffect(focusMove, openGame) {
if (inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard || ff == null) return@LaunchedEffect
val target = when {
openGame != null -> if (ff.primaryAttached > 0) ff.primary else ff.items["back:${store?.label}"]
focusMove?.first == "card" -> lastOpened?.let { ff.items["card:$it"] } ?: ff.firstTile.takeIf { ff.firstTileAttached > 0 }
focusMove?.first == "first" -> ff.firstTile.takeIf { ff.firstTileAttached > 0 }
else -> null
} ?: return@LaunchedEffect
var landed = false
focusWithinFrames({ landed }) { target.also { landed = runCatching { it.requestFocus() }.isSuccess } }
}
Column(
modifier = modifier.padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp)
.bumpers(
onPrevious = { if (openGame == null && chip != DOWNLOADS) { val t = tabsFor(store); switchTab(t[(t.indexOf(shownTab) + t.size - 1) % t.size]) } },
onNext = { if (openGame == null && chip != DOWNLOADS) { val t = tabsFor(store); switchTab(t[(t.indexOf(shownTab) + 1) % t.size]) } },
),
) {
// The chip row stays put and paints nothing - the page's background shows through it. What
// scrolls is clipped at the row's lower edge and, once scrolled, faded out there: the
// content's own alpha, not a colour laid over it.
Box(Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
Rise(0) { StoreChips(chip, s.storeDownloadsActive, onPick = pickChip, onSettings = { settings = true }) }
}
val fade = with(androidx.compose.ui.platform.LocalDensity.current) { 14.dp.toPx() }
Box(
Modifier.fillMaxWidth().weight(1f, fill = false).clipToBounds()
.graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }
.drawWithContent {
drawContent()
if (scroll.value > 0 && size.height > fade) drawRect(
Brush.verticalGradient(0f to Color.Transparent, fade / size.height to Color.Black),
blendMode = androidx.compose.ui.graphics.BlendMode.DstIn,
)
},
) {
Column(modifier = Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) {
when {
chip == DOWNLOADS -> StoresDownloadsPane(s, a)
store == null -> {}
// Signed out, or a sign-in that ran out (a launch could not get its code): sign in again.
!StoresState.isSignedIn(store) || StoresState.expired[store] == true -> Rise(1) { SignInCard(store) }
// One focus group, so the pad walks the page's own controls - back, the hero's
// actions, the cards - and reaches the rail only with Left from them.
openGame != null -> Column(Modifier.fillMaxWidth().focusGroup()) { StoreGameDetail(store, openGame!!, s, a, onBack = { closeGame() }) }
else -> Storefront(store, shownTab, query, s, a, onTab = { switchTab(it) }, onQuery = { query = it }, onOpen = { open(it) })
}
}
}
}
if (settings) StoresSettingsDialog(s, a) { settings = false }
StoresState.pendingInstall?.let { item -> InstallWhereDialog(item) { StoresState.pendingInstall = null } }
}
// ---- the chip row -------------------------------------------------------------------------------
/** Four equal chips - the stores with a signed-in dot, Downloads with its count - and the cog. */
@Composable
private fun StoreChips(selected: String, active: Int, onPick: (String) -> Unit, onSettings: () -> Unit) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
for (store in Store.entries) {
StoreChip(
label = store.shortLabel, on = selected == store.id, key = store.id, modifier = Modifier.weight(1f),
lead = {
val c = sourceColours(store.id)
Box(Modifier.size(12.dp).clip(CircleShape).background(c.dot).alpha(if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f))
},
description = store.label + if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) "" else " " + stringResource(R.string.stores_chip_signed_out),
) { onPick(store.id) }
}
StoreChip(
label = stringResource(R.string.stores_tab_downloads), on = selected == DOWNLOADS, key = DOWNLOADS, modifier = Modifier.weight(1f),
lead = { Icon(Icons.Outlined.Download, null, modifier = Modifier.size(18.dp)) },
trail = if (active > 0) { { CountPill(active) } } else null,
) { onPick(DOWNLOADS) }
IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings), onSettings)
}
}
@Composable
private fun StoreChip(
label: String, on: Boolean, key: String, modifier: Modifier, lead: @Composable () -> Unit,
trail: (@Composable () -> Unit)? = null, description: String? = null, onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(99.dp)
val ink = if (on) colors.onBackground else if (hot) colors.onBackground else colors.onSurfaceVariant
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
modifier = modifier.paneItem("storechip:$key").heightIn(min = 44.dp).clip(shape)
.background(if (on) pal.signal.copy(alpha = 0.16f) else colors.surface)
.glideBorder(hot, shape, pal.signal, if (on) pal.signal.copy(alpha = 0.7f) else pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.then(if (description != null) Modifier.semantics { contentDescription = description } else Modifier)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
androidx.compose.runtime.CompositionLocalProvider(androidx.compose.material3.LocalContentColor provides ink) { lead() }
Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis)
trail?.invoke()
}
}
/** The chip row's cog: icon only, the chips' height; opens the section's settings. */
@Composable
private fun IconChip(icon: androidx.compose.ui.graphics.vector.ImageVector, description: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("storechip:settings").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, onClick = onClick)
.controllerConfirm(onClick = onClick),
) { Icon(icon, description, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp)) }
}
@Composable
internal fun CountPill(count: Int) {
val pal = LocalPalette.current
Text(
count.toString(), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = pal.onSignal, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(8.dp)).background(pal.signal).padding(horizontal = 6.dp, vertical = 1.dp),
)
}
// ---- sign-in -----------------------------------------------------------------------------------
/** No account for this store yet: who it signs in as, and the button that opens its login page. */
@Composable
private fun SignInCard(store: Store) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(18.dp),
modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp),
) {
StoreLogo(store, 56.dp)
Column(modifier = Modifier.weight(1f)) {
Text(store.label, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
}
if (!narrow) PrimaryButton(stringResource(R.string.stores_signin), main = true) { StoresState.signIn(ctx, store) }
}
if (narrow) Actions { PrimaryButton(stringResource(R.string.stores_signin), main = true) { StoresState.signIn(ctx, store) } }
}
}
/** A square in the store's colour with its name on it: the stores ship no logo this app may bundle. */
@Composable
internal fun StoreLogo(store: Store, size: Dp) {
val c = sourceColours(store.id)
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(size).clip(Shape14).background(c.fill).border(1.dp, c.dot.copy(alpha = 0.5f), Shape14)) {
Text(store.shortLabel, fontSize = (size.value / 4).sp, fontWeight = FontWeight.Black, color = c.ink, maxLines = 1)
}
}
// ---- storefront --------------------------------------------------------------------------------
@Composable
private fun Storefront(
store: Store, tab: String, query: String, s: FrontEndState, a: FrontEndActions,
onTab: (String) -> Unit, onQuery: (String) -> Unit, onOpen: (String) -> Unit,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val library = StoresState.library[store] ?: emptyList()
val shelves = StoresState.shelves[store]
// The Installed tab, its count and every card's installed mark come from the installs on disk.
val installedItems = remember(StoresState.installed, library) { com.droiddeck.launcher.stores.installedCards(store, StoresState.installed, library) }
val installedKeys = remember(installedItems) { installedItems.map { it.id }.toSet() + StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id } }
val q = query.trim().lowercase()
fun matches(i: CatalogItem) = q.isEmpty() || i.title.lowercase().contains(q)
// The storefront leaves out what the store rates or tags as adult unless the user shows it; owned games always show.
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.owned
fun shelf(l: List<CatalogItem>?) = l?.filter(::shown)
// The Store tab's search: the catalog the shelves brought and the library, each title once.
val everything = remember(library, shelves) { (library + (shelves?.all ?: emptyList())).distinctBy { it.id } }
// Library's dropdown: All (every owned game, the default) or Installed.
var installedOnly by rememberSaveable(store) { mutableStateOf(false) }
var filterOpen by remember { mutableStateOf(false) }
val libraryLabel = if (installedOnly) stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_installed), installedItems.size)
else stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_library), library.size)
Rise(1) {
SubTabs(
listOf("store" to stringResource(R.string.stores_tab_store), "library" to libraryLabel).filter { it.first in tabsFor(store) },
tab,
onPick = { key -> if (key == "library") { if (tab == "library") filterOpen = !filterOpen else onTab(key) } else onTab(key) },
menuFor = { key, tabWidth ->
if (key == "library") AnchoredMenu(filterOpen, onDismiss = { filterOpen = false }, compact = true, minWidth = tabWidth) { first ->
MenuItem(stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_all), library.size), checked = !installedOnly, focusRequester = first) { installedOnly = false; filterOpen = false; onTab("library") }
MenuItem(stringResource(R.string.stores_tab_count, stringResource(R.string.stores_tab_installed), installedItems.size), checked = installedOnly) { installedOnly = true; filterOpen = false; onTab("library") }
}
},
trailing = {
// A purchase made elsewhere shows on a refresh; otherwise the library refreshes itself every six hours.
SmallTextButton(stringResource(R.string.stores_refresh)) { StoresState.open(ctx, store, force = true) }
val name = StoresState.accounts[store] ?: ""
SmallTextButton(stringResource(R.string.stores_signout_named, name)) { StoresState.signOut(ctx, store) }
},
)
}
Rise(2) {
SearchField(
query, onQuery,
placeholder = when {
tab == "store" -> stringResource(R.string.stores_search_catalog, store.label)
installedOnly -> stringResource(R.string.stores_search_installed)
else -> stringResource(R.string.stores_search_library)
},
)
}
StoresState.status[store]?.let { line -> Rise(3) { SyncBar(line) } }
StoresState.problems[store]?.let { Rise(3) { Box(Modifier.padding(bottom = 8.dp)) { Note(it) } } }
// The first card drawn on the tab is where a pad lands after a tab or chip change.
var firstPlaced = false
val card: @Composable (CatalogItem) -> Unit = { item ->
val first = !firstPlaced
firstPlaced = true
GameCard(item, store, s, a, installedKeys, onOpen, first)
}
when (tab) {
"library" -> if (installedOnly) Grid(installedItems.filter(::matches), stringResource(R.string.stores_installed_empty), card)
else Grid(library.filter(::matches), if (library.isEmpty() && StoresState.status[store] != null) stringResource(R.string.stores_library_loading) else stringResource(R.string.stores_nothing_matches), card)
else -> {
if (q.isNotEmpty()) Grid(everything.filter { matches(it) && shown(it) }, stringResource(R.string.stores_nothing_matches), card)
else {
Shelf(stringResource(R.string.stores_shelf_new), shelf(shelves?.whatsNew), card)
Shelf(stringResource(R.string.stores_shelf_deals), shelf(shelves?.deals), card)
Shelf(stringResource(R.string.stores_shelf_free), shelf(shelves?.free), card)
Shelf(stringResource(R.string.stores_shelf_trending), shelf(shelves?.trending), card)
Shelf(stringResource(R.string.stores_shelf_library), library, card)
if (shelves == null && library.isEmpty()) Rise(4) { Note(if (StoresState.status[store] != null) stringResource(R.string.stores_library_loading) else stringResource(R.string.stores_shelves_loading)) }
else if (shelves != null && shelves.isEmpty && store == Store.AMAZON) Rise(4) { Note(stringResource(R.string.stores_amazon_no_catalog)) }
}
}
}
}
/** Underlined tabs as the preview draws them, with [trailing] (the account) at the right. */
@Composable
private fun SubTabs(
tabs: List<Pair<String, String>>, selected: String, onPick: (String) -> Unit,
menuFor: @Composable (String, androidx.compose.ui.unit.Dp) -> Unit = { _, _ -> }, trailing: @Composable () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.weight(1f).horizontalScroll(rememberScrollState())) {
for ((key, label) in tabs) {
val on = key == selected
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pick = { onPick(key) }
val density = androidx.compose.ui.platform.LocalDensity.current
var width by remember { mutableStateOf(0.dp) }
Box(Modifier.onSizeChanged { width = with(density) { it.width.toDp() } }) {
Column(
modifier = Modifier.paneItem("storetab:$key").clip(RoundedCornerShape(8.dp))
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, RoundedCornerShape(8.dp), pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = if (on) colors.onBackground else colors.onSurfaceVariant, maxLines = 1)
Box(Modifier.padding(top = 4.dp).fillMaxWidth().height(2.dp).background(if (on) pal.signal else Color.Transparent))
}
// A tab's own dropdown (Library's filter), anchored under it.
menuFor(key, width)
}
}
}
trailing()
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
@Composable
private fun SmallTextButton(text: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Text(
text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = if (hot) colors.onBackground else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.paneItem("btn:$text").clip(RoundedCornerShape(8.dp)).glideBorder(hot, RoundedCornerShape(8.dp), pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick).padding(horizontal = 8.dp, vertical = 6.dp),
)
}
@Composable
private fun SearchField(query: String, onQuery: (String) -> Unit, placeholder: String) {
AdbTextField(
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = placeholder, compact = true, modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),
)
}
/** A horizontal row of cards under a title; nothing at all when the list is empty or not here yet. */
@Composable
private fun Shelf(title: String, items: List<CatalogItem>?, card: @Composable (CatalogItem) -> Unit) {
if (items.isNullOrEmpty()) return
val colors = MaterialTheme.colorScheme
Text(title, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 14.dp, bottom = 6.dp))
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(vertical = 2.dp)) {
for (item in items.take(24)) key(item.key) { Box(Modifier.width(CardWidth)) { card(item) } }
}
}
/** Cards in rows that fill the width; [empty] when there are none. */
@Composable
private fun Grid(items: List<CatalogItem>, empty: String, card: @Composable (CatalogItem) -> Unit) {
if (items.isEmpty()) { Box(Modifier.padding(vertical = 32.dp).fillMaxWidth(), contentAlignment = Alignment.Center) { Text(empty, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) }; return }
BoxWithConstraints(Modifier.fillMaxWidth().padding(top = 10.dp)) {
val gap = 10.dp
val cols = ((maxWidth + gap) / (CardWidth + gap)).toInt().coerceAtLeast(1)
val w = (maxWidth - gap * (cols - 1)) / cols
Column(verticalArrangement = Arrangement.spacedBy(gap)) {
for (row in items.chunked(cols)) Row(horizontalArrangement = Arrangement.spacedBy(gap), modifier = Modifier.fillMaxWidth()) {
for (item in row) key(item.key) { Box(Modifier.width(w)) { card(item) } }
}
}
}
}
/**
* A card's least width: shelf cards are this wide and a grid fits as many columns as the width
* allows at it (the columns then share the leftover), so a display-density setting changes the
* column count rather than the cards' size. 25% under the first 150 dp: five columns where there
* were four on the Pocket FIT.
*/
private val CardWidth = 112.dp
/**
* One title: its wide art, the title, a price or status line and one button that says the one
* thing to do next - Install with its size, Play, the download's progress, Get for free, or View
* on the store. Tapping the card itself opens the game's page.
*/
@Composable
private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: FrontEndActions, installedKeys: Set<String>, onOpen: (String) -> Unit, first: Boolean = false) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.985f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "cardScale")
val installed = item.id in installedKeys
val download = StoresState.download("${store.id}:${item.id}")?.takeIf { it.isActive }
val open = { onOpen(item.key) }
// A size the library did not give is looked up once the card is on screen or close to it.
val screen = with(androidx.compose.ui.platform.LocalDensity.current) { androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp.toPx() }
val ahead = screen / 2
Column(
modifier = Modifier.fillMaxWidth()
.onGloballyPositioned { c ->
if (item.owned && item.sizeBytes <= 0) {
val b = c.boundsInWindow()
if (b.bottom > -ahead && b.top < screen + ahead && b.width > 0f) com.droiddeck.launcher.stores.StoreSizes.request(ctx, item)
}
}
.paneItem("card:${item.key}").then(if (first) Modifier.firstTile() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale }
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open),
) {
CardFace(item, download) { CardMarker(item, installed, download) }
}
}
/** A store's sync as a thin bar and its count ("25/55"); a moving bar when it has no count yet. */
@Composable
private fun SyncBar(line: String) {
val count = Regex("(\\d+)\\s*/\\s*(\\d+)").find(line)
val done = count?.groupValues?.get(1)?.toIntOrNull()
val total = count?.groupValues?.get(2)?.toIntOrNull()?.takeIf { it > 0 }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
Box(Modifier.weight(1f)) {
if (done != null && total != null) androidx.compose.material3.LinearProgressIndicator(progress = { (done.toFloat() / total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth().height(3.dp))
else androidx.compose.material3.LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(3.dp))
}
if (done != null && total != null) Text("$done/$total", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
}
}
/** How tall the card's one line is, over the blurred foot of its art. */
private val CardStrip = 26.dp
/**
* The card is its art: sharp above, and under the one line a blurred, darkened copy of the same
* picture, placed so the two meet without a seam. Blur needs API 31; below it the copy is only
* darkened, more strongly.
*/
@Composable
private fun CardFace(item: CatalogItem, download: com.droiddeck.launcher.stores.download.DownloadEntry?, marker: @Composable () -> Unit) {
val url = item.imageUrl ?: item.tallImageUrl
val blurs = android.os.Build.VERSION.SDK_INT >= 31
BoxWithConstraints(Modifier.fillMaxWidth()) {
val total = maxWidth * 9f / 16f + CardStrip
Box(Modifier.fillMaxWidth().height(total).background(Color(0xFF101318)).then(if (url == null) Modifier.background(artBrush(hueOf(item.title))) else Modifier)) {
if (url != null) AsyncImage(model = url, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(CardStrip).clipToBounds()) {
if (url != null) AsyncImage(
model = url, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth().wrapContentHeight(Alignment.Bottom, unbounded = true).height(total).blur(24.dp),
)
Spacer(Modifier.matchParentSize().background(Color.Black.copy(alpha = if (blurs) 0.45f else 0.7f)))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.matchParentSize().padding(horizontal = 8.dp),
) {
Text(item.title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
marker()
}
}
// A soft edge where the sharp art meets the strip.
Spacer(Modifier.align(Alignment.BottomCenter).padding(bottom = CardStrip).fillMaxWidth().height(14.dp).background(Brush.verticalGradient(0f to Color.Transparent, 1f to Color.Black.copy(alpha = 0.35f))))
if (download != null) Box(Modifier.align(Alignment.BottomCenter).padding(start = 6.dp, end = 6.dp, bottom = CardStrip + 5.dp)) {
ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY)
}
}
}
}
/** The card's right-hand value: done, resume, progress, size, or the price. */
@Composable
private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droiddeck.launcher.stores.download.DownloadEntry?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val small = 10.sp
when {
// Installed: its size on disk and a small check after it.
installed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
val ctx = LocalContext.current
val game = StoresState.installedGame(item.store, item.id)
if (game != null) androidx.compose.runtime.LaunchedEffect(item.key) { com.droiddeck.launcher.stores.StoreSizes.requestDisk(ctx, item.key, game) }
com.droiddeck.launcher.stores.StoreSizes.onDisk[item.key]?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.size(11.dp))
}
download != null -> Text("${download.percent}%", fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
item.owned && StoresState.isUnfinished(item) -> Text(stringResource(R.string.stores_resume), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
// The size in the title's own type; nothing until it is known.
item.owned -> com.droiddeck.launcher.stores.StoreSizes.size(item).takeIf { it > 0 }?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
item.isFree -> Text(stringResource(R.string.stores_free), fontSize = small, fontWeight = FontWeight.Bold, color = pal.good, maxLines = 1)
item.isDiscounted -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
StateChip("-${item.discountPercent}%", ChipTone.DEAL, small = true)
Text(item.finalPrice, fontSize = small, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
}
item.hasPrice -> Text(item.finalPrice, fontSize = small, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
}
}
@Composable
internal fun CardArt(item: CatalogItem, modifier: Modifier) {
val url = item.imageUrl ?: item.tallImageUrl
val colors = MaterialTheme.colorScheme
// A dark ground under the image, so art with transparency never ends in white, and a quiet
// fade into the card's surface at the foot.
Box(modifier.background(colors.surfaceVariant).then(if (url == null) Modifier.background(artBrush(hueOf(item.title))) else Modifier)) {
if (url != null) AsyncImage(model = url, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
else Text(item.title, fontSize = 10.sp, fontWeight = FontWeight.Black, color = Color.White, maxLines = 3, overflow = TextOverflow.Ellipsis, modifier = Modifier.align(Alignment.BottomStart).padding(6.dp))
Spacer(Modifier.matchParentSize().background(androidx.compose.ui.graphics.Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.surface.copy(alpha = 0.85f))))
}
}
@Composable
internal fun ProgressBarThin(fraction: Float, paused: Boolean = false, verify: Boolean = false, height: Dp = 4.dp, done: Boolean = false) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val fill = when { done -> pal.good; paused -> Color(0xFFFFC24D); verify -> Color(0xFF9B6DFF); else -> pal.signal }
// The fill glides to each new value over a quarter second - progress arrives a few times a second
// and in steps - and is read only while drawing, so the bar animates without relayout.
val shown = androidx.compose.animation.core.animateFloatAsState(
fraction.coerceIn(0f, 1f), androidx.compose.animation.core.tween(250, easing = androidx.compose.animation.core.LinearEasing), label = "bar",
)
Box(
Modifier.fillMaxWidth().height(height).clip(RoundedCornerShape(height / 2)).background(colors.surfaceVariant)
.drawBehind { drawRect(fill, size = androidx.compose.ui.geometry.Size(size.width * shown.value, size.height)) },
)
}
@Composable
internal fun downloadLabel(d: com.droiddeck.launcher.stores.download.DownloadEntry): String = when (d.state) {
DownloadState.PAUSED -> stringResource(R.string.stores_dl_paused)
DownloadState.QUEUED -> stringResource(R.string.stores_dl_queued)
else -> if (d.stageFraction >= 0f) stringResource(R.string.stores_dl_active_percent, activeStageLabel(d), d.percent) else activeStageLabel(d)
}
/** The active stage as the row and the page name it: Checking (files already there), Downloading, Verifying, Installing. */
@Composable
internal fun activeStageLabel(d: com.droiddeck.launcher.stores.download.DownloadEntry): String = when (d.stage) {
DownloadStage.MANIFEST -> if (d.stageItemsTotal > 0) stringResource(R.string.stores_stage_checking) else stringResource(R.string.stores_stage_manifest)
DownloadStage.DOWNLOAD -> stringResource(R.string.stores_stage_downloading)
DownloadStage.VERIFY -> stringResource(R.string.stores_stage_verifying)
DownloadStage.INSTALL -> stringResource(R.string.stores_stage_installing)
DownloadStage.DONE -> stringResource(R.string.stores_stage_done)
}
/** Two taps: the first arms it ([confirm] shows), the second acts; it disarms itself after a few seconds. */
@Composable
internal fun ConfirmButton(label: String, confirm: String, compact: Boolean = false, onConfirm: () -> Unit) {
var armed by remember { mutableStateOf(false) }
LaunchedEffect(armed) { if (armed) { kotlinx.coroutines.delay(4000); armed = false } }
SecondaryButton(if (armed) confirm else label, compact = compact) { if (!armed) armed = true else { armed = false; onConfirm() } }
}
@Composable
internal fun stageLabel(stage: DownloadStage): String = when (stage) {
DownloadStage.MANIFEST -> stringResource(R.string.stores_stage_manifest)
DownloadStage.DOWNLOAD -> stringResource(R.string.stores_stage_download)
DownloadStage.VERIFY -> stringResource(R.string.stores_stage_verify)
DownloadStage.INSTALL -> stringResource(R.string.stores_stage_install)
DownloadStage.DONE -> stringResource(R.string.stores_stage_done)
}
/** The game's web page, in the device's browser: this app buys nothing and claims nothing itself. */
internal fun openStoreUrl(ctx: android.content.Context, item: CatalogItem) {
val url = item.storeUrl.ifBlank { return }
runCatching { ctx.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
/**
* Launches an installed store game the way the Games tab does: through its Steam shortcut. The
* shortcut exists once the client has (re)started since the install; until then the user is told.
*/
internal fun launchStoreGame(ctx: android.content.Context, store: Store, id: String, s: FrontEndState, a: FrontEndActions) {
val game = s.steamGames.firstOrNull { it.source == store.id && it.storeId == id }
if (game == null) {
android.widget.Toast.makeText(ctx, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
return
}
com.droiddeck.launcher.stores.StoreLaunch.prepare(ctx, store, id) { a.onSteamGame(game) }
}
@@ -0,0 +1,20 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.StoresNative
// Controls the Stores section and its Setup group share.
/** Whether the native download engine is in this build, said where the stores are turned on. */
@Composable
internal fun StoresEngineRow() {
val version = StoresNative.version
SettingsRow(
stringResource(R.string.setup_stores_engine),
version,
) {
Chip(if (version != null) stringResource(R.string.setup_stores_engine_chip_ready) else stringResource(R.string.setup_stores_engine_chip_missing), ok = version != null)
}
}