Merge current main while preserving subscription access and game logos

This commit is contained in:
xXJsonDeruloXx committed 2026-10-22 10:41:17 -04:00
commit e6265c1262
509 files changed
+36029 -2264

No files matched your search

@@ -23,6 +23,8 @@ import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
@@ -305,6 +307,7 @@ internal fun AppDialog(
modifier: Modifier = Modifier, maxWidth: Dp? = null,
width: Dp? = null, fitContent: Boolean = false,
back: (() -> Unit)? = null,
scrollable: Boolean = true,
content: @Composable ColumnScope.() -> Unit,
) {
val pal = LocalPalette.current
@@ -314,7 +317,7 @@ internal fun AppDialog(
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().imePadding()
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = close),
.tapOutside(close),
) {
AnimatedVisibility(
visibleState = shown,
@@ -339,10 +342,10 @@ internal fun AppDialog(
.clip(Shape16)
.background(pal.surfaceVariant.copy(alpha = 0.97f))
.border(1.dp, pal.signal.copy(alpha = 0.22f), Shape16)
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
.blockTouches()
.controllerBack(back ?: close)
.then(modifier)
.verticalScroll(rememberScrollState())
.then(if (scrollable) Modifier.verticalScroll(rememberScrollState()) else Modifier)
.padding(horizontal = 18.dp, vertical = 16.dp),
content = content,
)
@@ -492,7 +495,7 @@ private fun IconSuggestions(repo: String, selected: String?, onPick: (String) ->
if (list != null && list.isEmpty()) return
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.height(44.dp)) {
Small(stringResource(if (list == null) R.string.add_app_icon_searching else R.string.add_app_icon_suggestions))
if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) {
if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState()).selectableGroup()) {
list.forEachIndexed { i, url -> Rise(i) { SuggestedIcon(url, url == selected) { onPick(url) } } }
}
}
@@ -509,7 +512,7 @@ private fun SuggestedIcon(url: String, selected: Boolean, onClick: () -> Unit) {
contentAlignment = Alignment.Center,
modifier = Modifier.size(44.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.hoverable(src).selectable(selected = selected, role = androidx.compose.ui.semantics.Role.RadioButton, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick),
) {
AsyncImage(model = ImageRequest.Builder(LocalContext.current).data(url).crossfade(true).build(), contentDescription = stringResource(R.string.add_app_icon), contentScale = ContentScale.Fit, modifier = Modifier.size(34.dp))
@@ -40,6 +40,12 @@ 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.foundation.gestures.detectTapGestures
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import android.content.Context
@@ -502,7 +508,7 @@ private fun ArtChooserDialog(
sgdb = found?.sgdb ?: SteamGridDb.Status.SERVER
}
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } }
LaunchedEffect(options != null) { focusWithinFrames({ false }) { first } }
val apply: (AddedGameArt.Option) -> Unit = { option ->
scope.launch {
val saved = withContext(Dispatchers.IO) { target.set(app, slot, option) }
@@ -624,14 +630,23 @@ private fun SgdbSearchDialog(
}
}
LaunchedEffect(Unit) { search() }
AppDialog(shown, back, "sgdbSearch", wide = false, maxWidth = 460.dp) {
val firstItem = remember { FocusRequester() }
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
val leaveField = { focusManager.clearFocus(); keyboardController?.hide() }
val keyboard = LocalInputModeManager.current.inputMode == InputMode.Keyboard
LaunchedEffect(picked?.id, matches?.size, images.size, busy) {
val ready = if (picked != null) images.isNotEmpty() else !matches.isNullOrEmpty()
if (keyboard && !busy && ready) focusSoon { firstItem }
}
AppDialog(shown, back, "sgdbSearch", wide = false, maxWidth = 460.dp, modifier = Modifier.pointerInput(Unit) { detectTapGestures { leaveField() } }) {
DialogTitleRow(stringResource(R.string.art_sgdb_title, slotName), onClose = { onCloseAll() }, leading = {
SmallIconButton(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.common_back), colors.onBackground, onClick = back)
})
androidx.compose.material3.OutlinedTextField(
query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.art_sgdb_search_label)) },
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onSearch = { search() }),
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onSearch = { leaveField(); search() }),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Search),
)
val maxHeight = (LocalConfiguration.current.screenHeightDp * 0.6f).dp
@@ -643,24 +658,24 @@ private fun SgdbSearchDialog(
val chosenGame = picked
val list = matches.orEmpty()
if (chosenGame == null) {
for (match in list) key(match.id) { PickerRow(null, match.name, null) { showImages(match) } }
list.forEachIndexed { i, match -> key(match.id) { PickerRow(null, match.name, null, focus = if (i == 0) firstItem else null) { leaveField(); showImages(match) } } }
if (matches != null && list.isEmpty() && !busy && status == SteamGridDb.Status.OK) {
Text(stringResource(R.string.art_sgdb_none), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 4.dp))
}
} else {
Text(chosenGame.name, fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 4.dp))
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (option in images) key(option.full) {
images.forEachIndexed { i, option -> key(option.full) {
ArtOption(
slot, option, selected = current?.chosen == true && option.full == chosenRef, focus = null,
slot, option, selected = current?.chosen == true && option.full == chosenRef, focus = if (i == 0) firstItem else null,
description = "${artSourceLabel(AddedGameArt.SGDB)} $slotName",
) { onPick(option) }
}
} }
}
if (images.isEmpty() && !busy && status == SteamGridDb.Status.OK) {
Text(stringResource(R.string.art_sgdb_none), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 4.dp))
}
if (list.size > 1) PickerRow(null, stringResource(R.string.art_sgdb_other_games), null) { picked = null }
if (list.size > 1) PickerRow(null, stringResource(R.string.art_sgdb_other_games), null) { leaveField(); picked = null }
}
if (busy) androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 8.dp))
}
@@ -0,0 +1,717 @@
package com.droiddeck.launcher.ui
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.horizontalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
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.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateMapOf
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.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.selected
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.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.net.Uri
import android.view.Surface
import android.view.TextureView
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.viewinterop.AndroidView
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.BootMovie
import com.droiddeck.launcher.session.BootMovieLibrary
import com.droiddeck.launcher.session.BootMovieReport
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamDeckRepo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
private enum class MovieTab { INSTALLED, IMPORT, REPO, SOUND }
/** Downloads run here rather than in a tab, so switching tabs or closing the settings does not cancel one halfway. */
private val installScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
/** The downloads under way, by post id and percent; kept here so they are still known when the tab or the settings come back. */
private val installProgress = mutableStateMapOf<String, Int>()
/** What the movie list looks like right now: every movie and the one Steam will play. */
private class MovieSnapshot(val entries: List<BootMovieLibrary.Entry>, val selected: String)
/** The movie list, read again every couple of seconds so a movie picked, added or removed inside Steam shows up here too. */
@Composable
private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieSnapshot? {
val app = LocalContext.current.applicationContext
var snapshot by remember { mutableStateOf<MovieSnapshot?>(null) }
val changed by androidx.compose.runtime.rememberUpdatedState(onSelectionChanged)
LaunchedEffect(refresh) {
while (true) {
val before = snapshot?.selected
snapshot = withContext(Dispatchers.IO) {
BootMovie.syncFromSteam(app)
MovieSnapshot(BootMovieLibrary.list(app), BootMovie.choice(app))
}
if (before != null && before != snapshot?.selected) changed()
delay(2_000)
}
}
return snapshot
}
@Composable
private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(8.dp)
Box(
contentAlignment = Alignment.Center,
modifier = modifier.clip(shape)
.background(if (selected) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f))
.border(if (selected) 2.dp else 1.dp, if (selected) pal.signal else pal.line, shape)
.glideBorder(hot, shape, pal.signal)
.hoverable(src)
.clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = label; this.selected = selected }
.padding(horizontal = 10.dp, vertical = 8.dp),
) {
Text(label, fontSize = 12.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
/** The "Boot movie" settings group: Installed movies, Import your own movies, SteamDeckRepo and Sound. */
@Composable
internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
var tab by rememberSaveable { mutableStateOf(MovieTab.INSTALLED) }
SettingsGroup(stringResource(R.string.boot_movie)) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) {
TabChip(stringResource(R.string.boot_movie_tab_installed), tab == MovieTab.INSTALLED, Modifier.weight(1f)) { tab = MovieTab.INSTALLED }
TabChip(stringResource(R.string.boot_movie_tab_import), tab == MovieTab.IMPORT, Modifier.weight(1f)) { tab = MovieTab.IMPORT }
TabChip(stringResource(R.string.boot_movie_tab_repo), tab == MovieTab.REPO, Modifier.weight(1f)) { tab = MovieTab.REPO }
TabChip(stringResource(R.string.boot_movie_tab_sound), tab == MovieTab.SOUND, Modifier.weight(1f)) { tab = MovieTab.SOUND }
}
when (tab) {
MovieTab.INSTALLED -> InstalledTab(a)
MovieTab.IMPORT -> ImportTab(s, a)
MovieTab.REPO -> RepoTab(a)
MovieTab.SOUND -> SoundTab(s, a, host)
}
}
}
@Composable
private fun InstalledTab(a: ModeSettingsActions) {
var browsing by remember { mutableStateOf(false) }
val snapshot = rememberMovies(0, a.onBootMovieChanged)
val current = snapshot?.let { snap -> snap.entries.firstOrNull { it.id == snap.selected }?.title }
val hint = current ?: stringResource(R.string.common_working)
SettingsRow(stringResource(R.string.boot_movie_installed), hint) {
SecondaryButton(stringResource(R.string.boot_movie_browse), onClick = { browsing = true })
}
Text(
stringResource(R.string.boot_movie_note), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp).padding(bottom = 12.dp),
)
val app = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
var saving by remember { mutableStateOf(false) }
// The report is for bug reports, so it shows only while Debugging tools is on (read each time this tab opens).
val debugging = remember { com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(app) }
if (debugging) {
SettingsRow(stringResource(R.string.boot_movie_report), stringResource(R.string.boot_movie_report_hint)) {
SecondaryButton(stringResource(R.string.boot_movie_report_save), enabled = !saving, onClick = {
saving = true
scope.launch {
val file = withContext(Dispatchers.IO) { BootMovieReport.write(app) }
saving = false
Toast.makeText(
app,
file?.let { app.getString(R.string.boot_movie_report_saved, it.path) } ?: app.getString(R.string.boot_movie_report_failed),
Toast.LENGTH_LONG,
).show()
}
})
}
}
if (browsing) InstalledMoviesDialog(a) { browsing = false }
}
@Composable
private fun MovieCover(entry: BootMovieLibrary.Entry, modifier: Modifier = Modifier) {
val app = LocalContext.current.applicationContext
val cover by androidx.compose.runtime.produceState<File?>(null, entry.id, entry.title) {
value = withContext(Dispatchers.IO) { BootMovieLibrary.cover(app, entry) }
}
Box(modifier.aspectRatio(16f / 9f).clip(RoundedCornerShape(8.dp)).background(Color(0xFF0E1218))) {
cover?.let { AsyncImage(model = it, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) }
}
}
@Composable
private fun movieSourceLabel(source: String): String = stringResource(
when (source) {
BootMovieLibrary.SOURCE_DROIDDECK -> R.string.boot_movie_source_droiddeck
BootMovieLibrary.SOURCE_REPO -> R.string.boot_movie_source_repo
BootMovieLibrary.SOURCE_IMPORT -> R.string.boot_movie_source_import
BootMovieLibrary.SOURCE_POINTSHOP -> R.string.boot_movie_source_pointshop
else -> R.string.boot_movie_source_steam
},
)
/** The installed movies as a list with covers; the one Steam plays is highlighted, and the list follows changes made in Steam. */
@Composable
private fun InstalledMoviesDialog(a: ModeSettingsActions, onDismiss: () -> Unit) {
val app = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var refresh by remember { mutableIntStateOf(0) }
val snapshot = rememberMovies(refresh, a.onBootMovieChanged)
var picked by remember { mutableStateOf<String?>(null) }
var removing by remember { mutableStateOf<BootMovieLibrary.Entry?>(null) }
var filter by rememberSaveable { mutableStateOf<String?>(null) }
val selected = picked ?: snapshot?.selected
LaunchedEffect(snapshot?.selected) { picked = null }
removing?.let { entry ->
RemoveMovieDialog(
entry,
onConfirm = {
removing = null
scope.launch {
withContext(Dispatchers.IO) { BootMovieLibrary.remove(app, entry.id) }
a.onBootMovieChanged()
refresh++
}
},
onDismiss = { removing = null },
)
}
val firstRow = remember { FocusRequester() }
val inputMode = LocalInputModeManager.current
LaunchedEffect(snapshot != null, filter) {
if (snapshot != null && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstRow }
}
AppDialog(shown, close, "boot-movies", wide = false, scrollable = false) {
val filters = listOf(
null to stringResource(R.string.store_all),
BootMovieLibrary.SOURCE_DROIDDECK to movieSourceLabel(BootMovieLibrary.SOURCE_DROIDDECK),
BootMovieLibrary.SOURCE_STEAM to movieSourceLabel(BootMovieLibrary.SOURCE_STEAM),
BootMovieLibrary.SOURCE_POINTSHOP to movieSourceLabel(BootMovieLibrary.SOURCE_POINTSHOP),
BootMovieLibrary.SOURCE_REPO to movieSourceLabel(BootMovieLibrary.SOURCE_REPO),
BootMovieLibrary.SOURCE_IMPORT to movieSourceLabel(BootMovieLibrary.SOURCE_IMPORT),
)
var filterOpen by remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
) {
Text(
stringResource(R.string.boot_movie_installed), fontSize = 15.sp, color = MaterialTheme.colorScheme.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
Box {
androidx.compose.runtime.CompositionLocalProvider(LocalChipMinWidth provides 100.dp) {
ValueChip(filters.first { it.first == filter }.second, filterOpen) { filterOpen = !filterOpen }
}
AnchoredMenu(filterOpen, onDismiss = { filterOpen = false }, compact = true) { firstItemFocus ->
filters.forEachIndexed { index, (source, label) ->
MenuItem(label, checked = filter == source, focusRequester = if (index == 0) firstItemFocus else null) {
filter = source
filterOpen = false
}
}
}
}
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = close)
}
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().weight(1f, fill = false)) {
itemsIndexed(snapshot?.entries.orEmpty().filter { filter == null || it.source == filter }, key = { _, entry -> entry.id }) { index, entry ->
ListRow(accent = entry.id == selected, tall = true, focus = if (index == 0) firstRow else null, onClick = { picked = entry.id; a.onBootMovie(entry.id) }) {
MovieCover(entry, Modifier.size(width = 96.dp, height = 54.dp))
Column(Modifier.weight(1f)) {
Text(entry.title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(movieSourceLabel(entry.source), fontSize = 12.sp, color = if (entry.id == selected) LocalPalette.current.signal else MaterialTheme.colorScheme.onSurfaceVariant)
}
if (entry.removable) SmallIconButton(Icons.Filled.Close, stringResource(R.string.boot_movie_remove), MaterialTheme.colorScheme.error) {
removing = entry
}
}
}
}
}
}
@Composable
private fun RemoveMovieDialog(entry: BootMovieLibrary.Entry, onConfirm: () -> Unit, onDismiss: () -> Unit) {
androidx.compose.material3.AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.boot_movie_remove_confirm, entry.title)) },
text = { Text(stringResource(R.string.boot_movie_remove_confirm_body)) },
confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm) { Text(stringResource(R.string.boot_movie_remove)) } },
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
)
}
@Composable
private fun ImportTab(s: ModeSettings, a: ModeSettingsActions) {
SettingsRow(
stringResource(R.string.boot_movie_custom),
stringResource(R.string.boot_movie_custom_hint, (BootMovie.MAX_BYTES shr 20).toInt(), BootMovie.MAX_CONVERT_SECONDS),
) {
SecondaryButton(
when {
s.bootMovieProgress >= 0 -> stringResource(R.string.boot_movie_converting, s.bootMovieProgress)
s.bootMovieImporting -> stringResource(R.string.common_working)
else -> stringResource(R.string.boot_movie_import)
},
enabled = !s.bootMovieImporting,
progress = s.bootMovieProgress.takeIf { it >= 0 }?.let { it / 100f },
onClick = a.onImportBootMovie,
)
}
}
@Composable
private fun SoundTab(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
val app = LocalContext.current.applicationContext
var volume by remember { mutableIntStateOf(SessionPrefs.bootMovieVolume(app)) }
var seconds by remember { mutableIntStateOf(SessionPrefs.bootMovieSeconds(app)) }
val duration by androidx.compose.runtime.produceState(0, s.bootMovie) {
value = withContext(Dispatchers.IO) { BootMovieLibrary.durationSeconds(BootMovie.currentFile(app)) }
}
ToggleRow(
host, "boot-movie-sound", stringResource(R.string.boot_movie_sound),
stringResource(R.string.common_applies_next_session), s.bootMovieSound, onChange = a.onBootMovieSound,
)
Box(Modifier.padding(horizontal = 6.dp)) {
ValueSlider(
volume, 0..100, 5, s.bootMovieSound, stringResource(R.string.boot_movie_volume), { "$it%" },
) { volume = it; SessionPrefs.setBootMovieVolume(app, it) }
}
Box(Modifier.padding(horizontal = 6.dp)) {
val shownSeconds = if (seconds in 1 until duration) seconds else duration
ValueSlider(
shownSeconds, 1..duration.coerceAtLeast(2), 1, duration > 1, stringResource(R.string.boot_movie_length),
{ value -> app.getString(R.string.boot_movie_seconds, value) },
) { next ->
val stored = if (next >= duration) 0 else next
seconds = stored
SessionPrefs.setBootMovieSeconds(app, stored)
}
}
Text(
stringResource(R.string.boot_movie_length_hint), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp).padding(bottom = 12.dp),
)
}
@Composable
private fun RepoTab(a: ModeSettingsActions) {
val progress = installProgress
val app = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
var sort by rememberSaveable { mutableStateOf(SteamDeckRepo.Sort.TRENDING) }
var device by rememberSaveable { mutableStateOf<String?>(null) }
var query by rememberSaveable { mutableStateOf("") }
var page by rememberSaveable { mutableIntStateOf(1) }
var retry by remember { mutableIntStateOf(0) }
var searching by remember { mutableStateOf(false) }
var jumping by remember { mutableStateOf(false) }
var previewing by remember { mutableStateOf<SteamDeckRepo.Post?>(null) }
var installed by remember { mutableStateOf(setOf<String>()) }
val chosen = rememberMovies(0, a.onBootMovieChanged)?.selected
val inUse by androidx.compose.runtime.produceState<String?>(null, chosen) {
value = withContext(Dispatchers.IO) {
chosen?.takeIf { it.startsWith(BootMovieLibrary.PREFIX) }?.let { BootMovieLibrary.repoId(app, it.removePrefix(BootMovieLibrary.PREFIX)) }
}
}
LaunchedEffect(progress.size) { installed = withContext(Dispatchers.IO) { BootMovieLibrary.installedRepoIds(app) } }
val result by androidx.compose.runtime.produceState<SteamDeckRepo.Page?>(null, sort, device, query, page, retry) {
value = null
value = withContext(Dispatchers.IO) { SteamDeckRepo.fetch(sort, device, query, page) }
}
val last by androidx.compose.runtime.produceState<Int?>(null, sort, device, query, retry) {
value = null
value = withContext(Dispatchers.IO) { SteamDeckRepo.lastPage(sort, device, query) }
}
LaunchedEffect(last) { last?.let { if (page > it) page = it } }
val installPost: (SteamDeckRepo.Post) -> Unit = { post ->
if (progress.isEmpty()) {
progress[post.id] = 0
installScope.launch {
val outcome = try {
withContext(Dispatchers.IO) { install(app, post) { progress[post.id] = it } }
} catch (e: kotlinx.coroutines.CancellationException) {
throw e
} catch (e: Exception) {
app.getString(R.string.boot_movie_repo_download_failed)
} finally {
progress.remove(post.id)
}
Toast.makeText(app, outcome ?: app.getString(R.string.boot_movie_repo_installed, post.title), Toast.LENGTH_LONG).show()
a.onBootMovieChanged()
}
}
}
val usePost: (SteamDeckRepo.Post) -> Unit = { post ->
scope.launch {
val name = withContext(Dispatchers.IO) { BootMovieLibrary.nameForRepo(app, post.id) }
if (name != null) a.onBootMovie(BootMovieLibrary.idOf(name))
}
}
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).padding(bottom = 12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
Box(Modifier.weight(1f)) {
ListRow(tall = true, onClick = { searching = true }) {
Icon(Icons.Filled.Search, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp))
Text(
query.ifEmpty { stringResource(R.string.boot_movie_repo_search) }, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (query.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground,
modifier = Modifier.weight(1f),
)
}
}
if (query.isNotEmpty()) SecondaryButton(stringResource(R.string.boot_movie_repo_clear), compact = true) { query = ""; page = 1 }
}
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
TabChip(stringResource(R.string.boot_movie_repo_all), device == null) { device = null; page = 1 }
TabChip(stringResource(R.string.boot_movie_repo_deck), device == "steam_deck") { device = "steam_deck"; page = 1 }
TabChip(stringResource(R.string.boot_movie_repo_machine), device == "steam_machine") { device = "steam_machine"; page = 1 }
}
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SteamDeckRepo.Sort.values().forEach { option ->
TabChip(
stringResource(
when (option) {
SteamDeckRepo.Sort.TRENDING -> R.string.boot_movie_repo_trending
SteamDeckRepo.Sort.DOWNLOADS -> R.string.boot_movie_repo_downloads
SteamDeckRepo.Sort.LIKES -> R.string.boot_movie_repo_likes
SteamDeckRepo.Sort.NEWEST -> R.string.boot_movie_repo_newest
},
),
sort == option,
) { sort = option; page = 1 }
}
}
when (val r = result) {
null -> Text(stringResource(R.string.common_working), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
is SteamDeckRepo.Page.Failed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Text(stringResource(R.string.boot_movie_repo_failed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f))
SecondaryButton(stringResource(R.string.boot_movie_repo_retry), compact = true) { retry++ }
}
is SteamDeckRepo.Page.Ok -> {
if (r.posts.isEmpty()) Text(stringResource(R.string.boot_movie_repo_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
r.posts.chunked(2).forEach { row ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
row.forEach { post ->
RepoCard(
post, installed = post.id in installed, inUse = post.id == inUse, percent = progress[post.id], busy = progress.isNotEmpty(),
modifier = Modifier.weight(1f), onPreview = { previewing = post }, onInstall = { installPost(post) }, onUse = { usePost(post) },
)
}
if (row.size == 1) Box(Modifier.weight(1f))
}
}
RepoPager(page, last, hasMore = r.posts.size >= SteamDeckRepo.PAGE_SIZE, onPage = { page = it }, onJump = { jumping = true })
}
}
}
if (searching) TextEntryDialog(
stringResource(R.string.boot_movie_repo_search), query, number = false, confirm = stringResource(R.string.stores_search_open),
onSubmit = { value -> if (value != query) { query = value; page = 1 } }, onDismiss = { searching = false },
)
if (jumping) TextEntryDialog(
stringResource(R.string.boot_movie_repo_go_to_page), page.toString(), number = true, confirm = stringResource(R.string.common_ok),
onSubmit = { value -> value.toIntOrNull()?.let { n -> page = n.coerceIn(1, maxOf(1, last ?: n)) } }, onDismiss = { jumping = false },
)
previewing?.let { post ->
PreviewDialog(
post, installed = post.id in installed, inUse = post.id == inUse, percent = progress[post.id], busy = progress.isNotEmpty(),
onInstall = { installPost(post) }, onUse = { usePost(post) }, onDismiss = { previewing = null },
)
}
}
/** Downloads [post] and puts it among the installed movies; returns a message when it failed, null when it worked. */
private fun install(app: android.content.Context, post: SteamDeckRepo.Post, onProgress: (Int) -> Unit): String? {
val folder = File(app.cacheDir, "boot-movie-download").apply { mkdirs() }
// Leftovers of a download that was cut short are cleared, and every download has a file of its own.
folder.listFiles()?.forEach { if (System.currentTimeMillis() - it.lastModified() > 60 * 60 * 1000L) it.delete() }
val file = File.createTempFile("movie-", ".webm", folder)
return try {
if (!SteamDeckRepo.download(post, file, onProgress)) return app.getString(R.string.boot_movie_repo_download_failed)
val cover = if (post.thumbnail.isNotEmpty()) SteamDeckRepo.bytes(post.thumbnail) else null
when (BootMovie.import(app, file, onProgress = onProgress, title = post.title, source = BootMovieLibrary.SOURCE_REPO, repoId = post.id, cover = cover, use = false)) {
is BootMovie.Import.Done -> null
BootMovie.Import.TooLong -> app.getString(R.string.boot_movie_too_long, BootMovie.MAX_CONVERT_SECONDS)
is BootMovie.Import.Unsupported -> app.getString(R.string.boot_movie_unsupported)
BootMovie.Import.Failed -> app.getString(R.string.boot_movie_import_failed)
}
} finally {
file.delete()
}
}
@Composable
private fun RepoCard(
post: SteamDeckRepo.Post, installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean, modifier: Modifier,
onPreview: () -> Unit, onInstall: () -> Unit, onUse: () -> Unit,
) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val shape = RoundedCornerShape(10.dp)
val thumbShape = RoundedCornerShape(7.dp)
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val previewLabel = stringResource(R.string.boot_movie_repo_preview)
Column(
verticalArrangement = Arrangement.spacedBy(5.dp),
modifier = modifier.clip(shape)
.background(if (inUse) pal.signal.copy(alpha = 0.14f) else colors.surface.copy(alpha = 0.6f))
.border(if (inUse) 2.dp else 1.dp, if (inUse) pal.signal else pal.line, shape).padding(6.dp),
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).clip(thumbShape).background(Color(0xFF0E1218))
.glideBorder(hot, thumbShape, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onPreview)
.controllerConfirm(onClick = onPreview)
.semantics { contentDescription = previewLabel },
) {
if (post.thumbnail.isNotEmpty()) AsyncImage(model = post.thumbnail, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
Box(Modifier.size(40.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.55f)), contentAlignment = Alignment.Center) {
Icon(Icons.Filled.PlayArrow, contentDescription = null, tint = Color.White, modifier = Modifier.size(26.dp))
}
}
Text(post.title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(repoInfo(post), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
RepoAction(installed, inUse, percent, busy, Modifier.fillMaxWidth(), onInstall, onUse)
}
}
@Composable
private fun repoInfo(post: SteamDeckRepo.Post): String =
listOf(post.author, "♥ ${post.likes}", "⇩ ${post.downloads}", if (post.seconds > 0) stringResource(R.string.boot_movie_seconds, post.seconds) else "")
.filter { it.isNotEmpty() }.joinToString(" · ")
private const val AFTER_OPEN = 3
private const val AFTER_INSTALL = 1
private const val AFTER_USE = 2
/** Install and Use are different buttons in turn, and the button is disabled while installing; it takes focus back for the controller. */
@Composable
private fun RepoAction(
installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean, modifier: Modifier, onInstall: () -> Unit, onUse: () -> Unit,
takeFocus: Boolean = false,
) {
val requester = remember { FocusRequester() }
val focused = remember { booleanArrayOf(false) }
var pending by remember { mutableIntStateOf(if (takeFocus) AFTER_OPEN else 0) }
val inputMode = LocalInputModeManager.current
LaunchedEffect(installed, inUse, busy, percent != null, pending) {
if (pending == 0) return@LaunchedEffect
if (inputMode.inputMode != InputMode.Keyboard) { pending = 0; return@LaunchedEffect }
focusWithinFrames({ focused[0] }) { requester }
when (pending) {
AFTER_OPEN -> pending = 0
AFTER_INSTALL -> if (installed && focused[0]) pending = 0
AFTER_USE -> if (inUse && focused[0]) pending = 0
else -> Unit
}
}
val m = modifier.focusRequester(requester).onFocusChanged { focused[0] = it.hasFocus || it.isFocused }
if (inUse) SecondaryButton(stringResource(R.string.boot_movie_in_use), compact = true, modifier = m, onClick = {})
else if (installed) SecondaryButton(stringResource(R.string.boot_movie_repo_use), compact = true, modifier = m, onClick = { pending = AFTER_USE; onUse() })
else SecondaryButton(
if (percent != null) stringResource(R.string.boot_movie_converting, percent) else stringResource(R.string.boot_movie_repo_install),
enabled = !busy, compact = true, modifier = m, onClick = { pending = AFTER_INSTALL; onInstall() },
)
}
/** A movie from SteamDeckRepo played straight from the site, so it can be checked before it is installed. */
@Composable
private fun PreviewDialog(
post: SteamDeckRepo.Post, installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean,
onInstall: () -> Unit, onUse: () -> Unit, onDismiss: () -> Unit,
) {
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val maxVideoHeight = (LocalConfiguration.current.screenHeightDp - 200).coerceAtLeast(120).dp
AppDialog(shown, close, "boot-movie-preview", wide = false, maxWidth = 620.dp) {
DialogTitleRow(post.title, close)
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
MoviePreview(post.video, Modifier.heightIn(max = maxVideoHeight).aspectRatio(16f / 9f))
}
Text(repoInfo(post), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
RepoAction(installed, inUse, percent, busy, Modifier.fillMaxWidth(), onInstall, onUse, takeFocus = true)
}
}
@Composable
private fun MoviePreview(url: String, modifier: Modifier = Modifier) {
val pal = LocalPalette.current
val shape = RoundedCornerShape(10.dp)
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
var state by remember(url) { mutableIntStateOf(0) }
var ratio by remember(url) { mutableFloatStateOf(16f / 9f) }
val player = remember(url) { arrayOfNulls<MediaPlayer>(1) }
DisposableEffect(url) {
onDispose {
runCatching { player[0]?.release() }
player[0] = null
}
}
val toggle = { runCatching { player[0]?.let { if (it.isPlaying) it.pause() else it.start() } }; Unit }
Box(
contentAlignment = Alignment.Center,
modifier = modifier.clip(shape).background(Color.Black)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle),
) {
AndroidView(
modifier = Modifier.aspectRatio(ratio),
factory = { viewContext ->
TextureView(viewContext).apply {
surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) {
val mp = MediaPlayer()
player[0] = mp
try {
mp.setDataSource(viewContext, Uri.parse(url), mapOf("User-Agent" to "DroidDeck"))
mp.setSurface(Surface(texture))
mp.isLooping = true
mp.setOnVideoSizeChangedListener { _, w, h -> if (w > 0 && h > 0) ratio = w.toFloat() / h }
mp.setOnPreparedListener { it.start(); state = 1 }
mp.setOnErrorListener { _, _, _ -> state = 2; true }
mp.prepareAsync()
} catch (e: Exception) {
state = 2
}
}
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) = Unit
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean {
runCatching { player[0]?.release() }
player[0] = null
return true
}
override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit
}
}
},
)
if (state == 0) Text(stringResource(R.string.common_working), fontSize = 13.sp, color = Color.White.copy(alpha = 0.8f))
if (state == 2) Text(stringResource(R.string.boot_movie_repo_preview_failed), fontSize = 13.sp, color = Color.White.copy(alpha = 0.8f), modifier = Modifier.padding(12.dp))
}
}
/** A dialog with one text box, for a search term or a page number; the Android keyboard comes up with it. */
@Composable
private fun TextEntryDialog(
title: String, initial: String, number: Boolean, confirm: String, onSubmit: (String) -> Unit, onDismiss: () -> Unit,
) {
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var text by remember { mutableStateOf(initial) }
val submit = { onSubmit(text.trim()); close() }
AppDialog(shown, close, "boot-movie-entry", wide = false, maxWidth = 460.dp) {
DialogTitleRow(title, close)
AdbTextField(
value = text, onValueChange = { text = it }, label = "", keyboardType = if (number) KeyboardType.Number else KeyboardType.Text,
imeAction = ImeAction.Done, placeholder = title, focusOnShow = true, onDone = { submit() },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close)
SecondaryButton(confirm, modifier = Modifier.weight(1f)) { submit() }
}
}
}
/** Page buttons around the current page, which opens a box to type another page into; first and last page show their numbers. */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun RepoPager(page: Int, last: Int?, hasMore: Boolean, onPage: (Int) -> Unit, onJump: () -> Unit) {
val reach = last ?: if (hasMore) Int.MAX_VALUE else page
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally),
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth(),
) {
SecondaryButton(stringResource(R.string.boot_movie_repo_previous), enabled = page > 1, compact = true) { onPage(page - 1) }
if (page - 3 > 1) SecondaryButton("1", compact = true) { onPage(1) }
for (n in maxOf(1, page - 3) until page) SecondaryButton("$n", compact = true) { onPage(n) }
TabChip("$page", true, Modifier.widthIn(min = 52.dp).heightIn(min = 44.dp), onJump)
for (n in page + 1..minOf(page + 3, reach)) SecondaryButton("$n", compact = true) { onPage(n) }
if (last != null && page + 3 < last) SecondaryButton("$last", compact = true) { onPage(last) }
SecondaryButton(stringResource(R.string.boot_movie_repo_next), enabled = page < reach, compact = true) { onPage(page + 1) }
}
}
@@ -0,0 +1,141 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
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.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.min
/** A small colour square; pressing it opens the colour picker. */
@Composable
internal fun ColorCube(color: Color, description: String, focus: FocusRequester? = null, onClick: () -> Unit) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(10.dp)
Box(
Modifier.then(if (focus != null) Modifier.focusRequester(focus) else Modifier).size(44.dp).clip(shape).background(color)
.border(1.dp, pal.line2, shape).glideBorder(hot, shape, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description },
)
}
/** Colour wheel (touch), hue / saturation / brightness sliders (controller and touch) and a hex box for one colour. */
@Composable
internal fun ColorPickerDialog(title: String, initial: Int, onDismiss: () -> Unit, onApply: (Int) -> Unit) {
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val start = remember { ThemeColors.toHsv(initial) }
var hue by remember { mutableStateOf(start.h) }
var sat by remember { mutableStateOf(start.s) }
var value by remember { mutableStateOf(start.v) }
var hexText by remember { mutableStateOf(ThemeColors.hex(initial)) }
val current = ThemeColors.fromHsv(hue, sat, value)
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { focusSoon { first } }
fun picked(h: Float = hue, s: Float = sat, v: Float = value) {
hue = h.coerceIn(0f, 360f); sat = s.coerceIn(0f, 1f); value = v.coerceIn(0f, 1f)
hexText = ThemeColors.hex(ThemeColors.fromHsv(hue, sat, value))
}
AppDialog(shown, close, "colorPicker", wide = false, maxWidth = 460.dp) {
DialogTitleRow(title, close)
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
ColorWheel(hue, sat, value) { h, s -> picked(h = h, s = s) }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Swatch(Color(initial))
Swatch(Color(current))
}
}
ValueSlider(hue.toInt(), 0..360, step = 5, enabled = true, label = stringResource(R.string.theme_color_hue), format = { "$it°" },
modifier = Modifier.focusRequester(first)) { picked(h = it.toFloat()) }
ValueSlider((sat * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_saturation), format = { "$it%" }) { picked(s = it / 100f) }
ValueSlider((value * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_brightness), format = { "$it%" }) { picked(v = it / 100f) }
AdbTextField(
value = hexText,
onValueChange = { text ->
hexText = text
ThemeColors.parseHex(text)?.let { argb -> ThemeColors.toHsv(argb).let { hsv -> hue = hsv.h; sat = hsv.s; value = hsv.v } }
},
label = "", keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done, placeholder = stringResource(R.string.theme_color_hex),
onDone = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() } },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close)
PrimaryButton(stringResource(R.string.common_ok), enabled = ThemeColors.parseHex(hexText) != null, modifier = Modifier.weight(1f)) {
ThemeColors.parseHex(hexText)?.let { onApply(it); close() }
}
}
}
}
@Composable
private fun Swatch(color: Color) {
val shape = RoundedCornerShape(10.dp)
Box(Modifier.size(48.dp).clip(shape).background(color).border(1.dp, LocalPalette.current.line2, shape))
}
/** Hue around the circle and saturation out from the middle, at full brightness; brightness has its own slider. */
@Composable
private fun ColorWheel(hue: Float, sat: Float, value: Float, onPick: (hue: Float, sat: Float) -> Unit) {
val rim = MaterialTheme.colorScheme.onBackground
val size = 168.dp
fun at(offset: Offset, side: Float) {
val center = side / 2f
val dx = offset.x - center
val dy = offset.y - center
val angle = Math.toDegrees(atan2(dy, dx).toDouble()).toFloat()
onPick((angle + 360f) % 360f, min(1f, hypot(dx, dy) / center))
}
Canvas(
Modifier.size(size)
.pointerInput(Unit) { detectTapGestures { at(it, this.size.width.toFloat()) } }
.pointerInput(Unit) { detectDragGestures { change, _ -> at(change.position, this.size.width.toFloat()); change.consume() } },
) {
val radius = this.size.minDimension / 2f
drawCircle(Brush.sweepGradient(List(7) { Color.hsv(it * 60f, 1f, 1f) }), radius)
drawCircle(Brush.radialGradient(listOf(Color.White, Color.Transparent), radius = radius), radius)
val theta = Math.toRadians(hue.toDouble())
val marker = Offset(radius + (kotlin.math.cos(theta) * sat * radius).toFloat(), radius + (kotlin.math.sin(theta) * sat * radius).toFloat())
drawCircle(Color.Black.copy(alpha = 0.55f), 9.dp.toPx(), marker)
drawCircle(rim, 7.dp.toPx(), marker)
drawCircle(Color.hsv(hue, sat, value), 5.dp.toPx(), marker)
}
}
@@ -30,6 +30,7 @@ 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.selection.toggleable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
@@ -73,6 +74,8 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -151,6 +154,7 @@ fun ComponentsPage(
onImport: () -> Unit,
onBack: () -> Unit,
games: List<Library.SteamGame> = emptyList(),
initialGameKey: String? = null,
generalFexPreset: String = "",
onGeneralFexPreset: (String) -> Unit = {},
requestInitialFocus: Boolean = true,
@@ -169,7 +173,7 @@ fun ComponentsPage(
val layer = if (comp in LAYERS) comp else GPU_TAB
BackHandler(onBack = onBack)
var scopeMenu by remember { mutableStateOf(false) }
var selectedGameKey by remember { mutableStateOf<String?>(null) }
var selectedGameKey by remember(initialGameKey) { mutableStateOf(initialGameKey) }
var fexMenu by remember { mutableStateOf(false) }
var gameProtonMenu by remember { mutableStateOf(false) }
var gameProtonId by remember { mutableStateOf<String?>(null) }
@@ -380,6 +384,7 @@ fun ComponentsPage(
var stackAt by remember { mutableStateOf(Offset.Zero) }
var pageAt by remember { mutableStateOf(Offset.Zero) }
val landed = remember { mutableStateMapOf<String, Int>() }
val nightlyPicked = remember { mutableStateMapOf<String, Boolean>() }
val rings = remember { mutableStateMapOf<String, Int>() }
fun land(l: String) { landed[l] = (landed[l] ?: 0) + 1; rings[l] = (rings[l] ?: 0) + 1 }
val arrivedSeen = remember { intArrayOf(Hops.arrived) }
@@ -503,7 +508,7 @@ fun ComponentsPage(
val availableTitle: @Composable (String) -> String = { l ->
when (l) {
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count { it.installed == null || it.update != null })
else -> stringResource(R.string.comp_nightlies_count, availableFor(l, catalog, snapshot).size)
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
}
}
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
@@ -580,12 +585,16 @@ fun ComponentsPage(
) { protonActions.onInstall(row.id) }
}
else -> {
val available = availableFor(l, catalog, snapshot)
val available = availableRows(l, catalog, snapshot)
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
for (d in available) GetLine(
d.file.removeSuffix(".wcp"), "${d.release} · " + stringResource(R.string.common_size_mb, d.size / 1048576.0),
progress = downloads[d.file], enabled = busy == null,
) { onDownload(d) }
for ((stable, nightly) in available) {
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
GetLine(
d.file.removeSuffix(".wcp"), "${d.release} · " + stringResource(R.string.common_size_mb, d.size / 1048576.0),
progress = downloads[d.file], enabled = busy == null,
channel = if (nightly != null) ({ ChannelToggle(d === nightly, enabled = busy == null) { nightlyPicked[stable.file] = d !== nightly } }) else null,
) { onDownload(d) }
}
}
}
}
@@ -921,6 +930,14 @@ private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapsh
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
}
// The rows to show: each stable row carries its paired nightly (if any), and a paired nightly has no row of its own.
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot)
val pairs = ComponentsManager.nightlyPairs(available)
val paired = pairs.values.toSet()
return available.filter { it !in paired }.map { it to pairs[it] }
}
@Composable
private fun LayerTitle(l: String): String = when (l) {
GPU_TAB -> stringResource(R.string.comp_gpu_drivers)
@@ -1306,7 +1323,7 @@ internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = fa
modifier = Modifier.size(44.dp).clip(RoundedCornerShape(12.dp))
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(hot, RoundedCornerShape(12.dp), pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick),
) {
if (busy) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
@@ -1325,7 +1342,7 @@ private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean =
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
.background(if (hot) pal.signal else colors.surfaceVariant)
.glideBorder(hot, RoundedCornerShape(10.dp), colors.onBackground, pal.line2, restWidth = 2.dp)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
@@ -1405,7 +1422,7 @@ private fun ChoiceLine(
modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE)
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(delHot, ROW_SHAPE, colors.error)
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete)
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete)
.controllerConfirm(onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
}
@@ -1416,7 +1433,8 @@ private fun ChoiceLine(
@Composable
private fun GetLine(
name: String, detail: String, progress: Int?, enabled: Boolean,
badge: String? = null, stage: String? = null, onCancel: (() -> Unit)? = null, action: String? = null, onGet: () -> Unit,
badge: String? = null, stage: String? = null, onCancel: (() -> Unit)? = null, action: String? = null,
channel: (@Composable () -> Unit)? = null, onGet: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -1431,12 +1449,43 @@ private fun GetLine(
if (progress != null) ProgressBit(progress)
else {
if (onCancel != null) FocusText(stringResource(R.string.proton_cancel_queued), pal.signal, onClick = onCancel)
channel?.invoke()
SmallButton(action ?: stringResource(R.string.comp_get), enabled = enabled, accent = true, onClick = onGet)
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
// Stable | Nightly in the same box as SmallButton: one focus stop, A (or a tap) flips it.
@Composable
private fun ChannelToggle(nightly: Boolean, enabled: Boolean, onFlip: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && enabled
val state = stringResource(if (nightly) R.string.comp_channel_nightly else R.string.comp_channel_stable)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp),
modifier = Modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
.background(colors.surfaceVariant)
.glideBorder(hot, RoundedCornerShape(10.dp), colors.onBackground, pal.line2, restWidth = 2.dp)
.hoverable(src).toggleable(value = nightly, interactionSource = src, indication = null, enabled = enabled, role = Role.Switch, onValueChange = { onFlip() })
.controllerConfirm(enabled = enabled, onClick = onFlip)
.semantics { stateDescription = state }
.padding(4.dp),
) {
for ((label, on) in listOf(R.string.comp_channel_stable to !nightly, R.string.comp_channel_nightly to nightly)) {
Text(
stringResource(label), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
color = if (!enabled) colors.onSurfaceVariant else if (on) (if (hot) pal.onSignal else pal.signal) else colors.onSurfaceVariant,
modifier = Modifier.clip(RoundedCornerShape(7.dp))
.background(if (on && enabled) (if (hot) pal.signal else pal.signal.copy(alpha = 0.16f)) else Color.Transparent)
.padding(horizontal = 10.dp, vertical = 6.dp),
)
}
}
}
@Composable
private fun DetailLine(detail: String, badge: String?) {
val colors = MaterialTheme.colorScheme
@@ -13,11 +13,12 @@ import androidx.compose.ui.graphics.drawscope.Stroke
@Composable
fun CursorOverlay(
position: Offset, visible: Boolean, scale: Float,
positionOf: () -> Offset, visible: Boolean, scale: Float,
image: ImageBitmap? = null, hotX: Int = 0, hotY: Int = 0, imageScale: Float = 1f,
) {
if (!visible) return
Canvas(modifier = Modifier.fillMaxSize()) {
val position = positionOf()
if (image != null) {
val w = (image.width * imageScale).toInt().coerceAtLeast(1)
val h = (image.height * imageScale).toInt().coerceAtLeast(1)
@@ -17,12 +17,15 @@ import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import com.droiddeck.launcher.input.DeckControls
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.min
@@ -49,13 +52,6 @@ class DeckControlsPanel(
select(if (pad != null) selectedWithPad else selected)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
if (pad != null && selectedWithPad != Tab.GAMEPAD && !GamepadGeometry.tall(w.toFloat(), h.toFloat())) {
post { if (selectedWithPad != Tab.GAMEPAD) select(Tab.GAMEPAD) }
}
}
override fun onDetachedFromWindow() {
DeckControls.releaseAll()
super.onDetachedFromWindow()
@@ -85,13 +81,17 @@ class DeckControlsPanel(
addView(view, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT))
}
}
val centre = FrameLayout(context).apply {
addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44), Gravity.CENTER))
val centre = HorizontalScrollView(context).apply {
isHorizontalScrollBarEnabled = false
overScrollMode = View.OVER_SCROLL_NEVER
addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44)))
}
addView(centre, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f))
addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true))
addView(space(dp(8)))
addView(roundButton("•••", context.getString(R.string.drawer_open_qam), onQam, wide = true))
if (SessionState.mode == SessionService.MODE_STEAM) {
addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true))
addView(space(dp(8)))
addView(roundButton("•••", context.getString(R.string.drawer_open_qam), onQam, wide = true))
}
}
private fun select(tab: Tab) {
@@ -102,6 +102,17 @@ class DeckControlsPanel(
view.background = if (on) filled(CORNER_PILL, ACCENT) else null
view.setTextColor(if (on) ON_ACCENT else TEXT_DIM)
}
tabViews[tab]?.let { selectedView ->
(selectedView.parent?.parent as? HorizontalScrollView)?.post {
val left = selectedView.left
val right = selectedView.right
val scroll = selectedView.parent?.parent as? HorizontalScrollView ?: return@post
when {
left < scroll.scrollX -> scroll.smoothScrollTo(left, 0)
right > scroll.scrollX + scroll.width -> scroll.smoothScrollTo(right - scroll.width, 0)
}
}
}
content.removeAllViews()
topBar.visibility = if (tab == Tab.GAMEPAD) View.GONE else View.VISIBLE
content.addView(
@@ -170,8 +181,10 @@ class DeckControlsPanel(
place(pill("RB") { st, d -> st.press(PadState.RB, d) }, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER)
place(pill("RT") { st, d -> st.rightTrigger = if (d) 1f else 0f }, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER)
place(pill("VIEW") { st, d -> st.press(PadState.SELECT, d) }, GamepadGeometry.Slot.VIEW)
place(centreTap("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu), GamepadGeometry.Slot.STEAM)
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
if (SessionState.mode == SessionService.MODE_STEAM) {
place(centreTap("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu), GamepadGeometry.Slot.STEAM)
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
}
place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU)
place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
GamepadGeometry.Slot.PANELS)
@@ -643,7 +656,7 @@ class DeckControlsPanel(
private const val CLICK_MS = 300L
private var selected = Tab.BOTH
private var selectedWithPad = Tab.GAMEPAD
private var selectedWithPad = Tab.BOTH
private const val CORNER = 20f
private const val CORNER_PILL = 22f
@@ -52,6 +52,7 @@ import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -142,8 +143,13 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
PrimaryButton(open, enabled = !s.busy, main = true, large = true, icon = Icons.Outlined.DesktopWindows, onClick = click)
},
beside = {
HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") }
HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true }
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") }
HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true }
}
if (s.desktopPresent) UninstallDesktop(enabled = !s.runtimeActionsBlocked, onUninstall = a.onRemoveDesktop)
}
},
rows = { tab ->
if (tab == SheetTab.FILES) DesktopFiles(s, a)
@@ -366,6 +372,7 @@ private fun DesktopFiles(s: FrontEndState, a: FrontEndActions) {
@Composable
private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) {
val canUninstall by rememberUpdatedState(enabled)
val colors = MaterialTheme.colorScheme
val label = stringResource(R.string.common_uninstall)
val title = stringResource(R.string.desktop_uninstall_title)
@@ -383,7 +390,7 @@ private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) {
Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() }
StepChoice(label, danger = true, enabled = open) { Steps.fold(); onUninstall() }
StepChoice(label, danger = true, enabled = open && canUninstall) { Steps.fold(); onUninstall() }
}
})
}
@@ -15,6 +15,7 @@ import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -105,7 +106,7 @@ fun DriverPage(
.glideBorder(refreshHot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.focusRequester(refreshFocus)
.hoverable(refreshSrc)
.clickable(interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh),
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh),
) {
if (checking) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
else Icon(Icons.Outlined.Refresh, contentDescription = stringResource(R.string.comp_check_drivers), tint = colors.onBackground, modifier = Modifier.size(20.dp))
@@ -185,7 +186,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f).then(modifier).focusRequester(mainFocus)
.then(if (row.removable) Modifier.focusProperties { right = delFocus } else Modifier)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect)
.hoverable(src).selectable(selected = selected, role = androidx.compose.ui.semantics.Role.RadioButton, interactionSource = src, indication = null, onClick = onSelect)
.padding(horizontal = 11.dp, vertical = 8.dp),
) {
Box(
@@ -218,7 +219,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
.glideBorder(delHot, RoundedCornerShape(10.dp), colors.error)
.focusRequester(delFocus)
.focusProperties { left = mainFocus }
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete),
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, row.name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
}
@@ -235,7 +236,7 @@ internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier
modifier = modifier.clip(shape)
.background(if (hot) color.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, shape, color)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
)
}
@@ -27,7 +27,7 @@ internal fun FrameGenMenu(
onPick(m); host.open = null
}
item(FrameGen.Mode.OFF, focus = firstItemFocus)
for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_WINFG, m))
for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_DDFG, m))
val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } +
FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) }
lsfg.forEachIndexed { i, m -> item(m, enabled = lossless.ready, detail = need.takeIf { i == 0 }) }
@@ -131,7 +131,7 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera
.background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
.alpha(if (t.dim && !hot) 0.55f else 1f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = t.onClick),
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = t.onClick),
) {
Box(modifier = Modifier.fillMaxWidth().shine(hot)) {
Art(t.art, t.iconRes, t.title, Modifier.fillMaxWidth(), wide, t.iconBitmap)
@@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.key
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Row
@@ -31,6 +32,7 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.ui.semantics.semantics
import androidx.compose.foundation.shape.CircleShape
@@ -111,7 +113,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
if (onAdd != null) Rise(0) { GamesHeader(gameCount, s.steamGamesX64, onAdd, Modifier.padding(bottom = 10.dp)) }
Rise(0) {
Row(verticalAlignment = Alignment.Bottom) {
GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp)) {
GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp), corner = { GameRemoveButton(current, s, a) }) {
GameHeroCopy(current, if (narrow) 28.sp else 38.sp)
GameActions(current, s, a, onEdit, launch)
}
@@ -133,7 +135,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
modifier = Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState())
.padding(horizontal = if (narrow) 14.dp else 20.dp, vertical = 16.dp),
) {
GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp)) {
GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp), corner = { GameRemoveButton(current, s, a) }) {
GameHeroCopy(current, if (narrow) 24.sp else 32.sp)
GameActions(current, s, a, onEdit, launch)
}
@@ -267,6 +269,21 @@ private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndA
}
}
/** A skipped sync is not a success: "0 files" used to show for a signed-out store or cloud saves turned off. */
internal fun cloudMessage(context: android.content.Context, r: com.droiddeck.launcher.stores.CloudSaves.Result): String = when (r.result) {
"ok" -> when {
r.conflicts > 0 -> context.getString(R.string.cloud_conflict_files, r.conflicts)
r.files == 0 -> context.getString(R.string.cloud_up_to_date)
else -> context.getString(R.string.cloud_done, r.files)
}
"skipped" -> context.getString(when (r.reason) {
"not-signed-in" -> R.string.cloud_signed_out
"no-cloud-saves" -> R.string.cloud_none
else -> R.string.cloud_not_synced
})
else -> context.getString(R.string.cloud_not_synced)
}
@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
@@ -289,7 +306,7 @@ private fun CloudRows(g: Library.SteamGame, open: Boolean, first: androidx.compo
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() }
com.droiddeck.launcher.stores.StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() }
}, "cloud-manual").start()
}
MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported, focusRequester = first,
@@ -301,7 +318,7 @@ private fun CloudRows(g: Library.SteamGame, open: Boolean, first: androidx.compo
com.droiddeck.launcher.stores.StoresState.post { enabled = written?.cloud ?: enabled }
}, "cloud-switch").start()
}
val ready = st != null && supported && busy == null
val ready = st != null && supported && enabled && busy == null
val pending = stringResource(R.string.cloud_pending)
val summary = when {
st == null || busy != null -> pending
@@ -453,6 +470,47 @@ private fun GamesDialogs(a: FrontEndActions, games: List<Library.SteamGame>) {
}
}
@Composable
private fun GameRemoveButton(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) {
val kind = com.droiddeck.launcher.frontend.GameRemoval.kind(g)
if (s.shortcutPicker || kind == com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER) return
if (g.gameFiles?.isDirectory != true) return
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
var asking by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) }
val shortcut = kind == com.droiddeck.launcher.frontend.GameRemoval.Kind.SHORTCUT
val label = stringResource(if (shortcut) R.string.edit_remove else R.string.common_uninstall)
val title = if (shortcut) stringResource(R.string.games_remove_title, g.name) else stringResource(R.string.stores_uninstall_title, g.name)
val body = when {
shortcut -> stringResource(R.string.games_remove_body)
g.library == Library.ADDED -> stringResource(R.string.stores_uninstall_body)
else -> stringResource(R.string.games_uninstall_body)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("game:remove").downToFirstTile().size(44.dp).clip(Shape12)
.background(if (hot) colors.error.copy(alpha = 0.22f) else Color.Black.copy(alpha = 0.34f))
.glideBorder(hot, Shape12, colors.error, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button) { asking = true }
.controllerConfirm { asking = true }
.semantics { contentDescription = label },
) {
androidx.compose.material3.Icon(
Icons.Outlined.Delete, contentDescription = null,
tint = if (hot) colors.error else Color.White, modifier = Modifier.size(18.dp),
)
}
if (asking) ConfirmDialog(
title = title,
text = body,
confirm = label,
onConfirm = { a.onGameRemoved(g) },
onDismiss = { asking = false },
)
}
@Composable
private fun EditGameButton(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -515,7 +573,7 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni
.clip(Shape12)
.background(if (selected) pal.signal.copy(alpha = 0.14f) else if (hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent)
.glideBorder(focused, Shape12, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onSelect)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onSelect)
.controllerConfirm(onClick = onLaunch)
.padding(horizontal = 10.dp, vertical = 6.dp),
) {
@@ -584,7 +642,7 @@ private fun libraryLabel(g: Library.SteamGame): String = when {
}
@Composable
private fun GameHero(g: Library.SteamGame, modifier: Modifier, content: @Composable ColumnScope.() -> Unit) {
private fun GameHero(g: Library.SteamGame, modifier: Modifier, corner: @Composable BoxScope.() -> Unit = {}, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
Box(modifier = modifier.clip(Shape16).background(artBrush(hueOf(g.name)))) {
val image = g.hero ?: g.art.takeIf { g.library != Library.EPIC_LAUNCHER }
@@ -607,5 +665,6 @@ private fun GameHero(g: Library.SteamGame, modifier: Modifier, content: @Composa
modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp),
content = content,
)
Box(Modifier.align(Alignment.TopEnd).padding(12.dp), content = corner)
}
}
@@ -22,6 +22,8 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
@@ -119,7 +121,7 @@ internal fun SideRail(
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.fillMaxWidth(),
modifier = Modifier.fillMaxWidth().selectableGroup(),
) {
val place: (String) -> Modifier = { key ->
Modifier.onGloballyPositioned {
@@ -192,7 +194,7 @@ private fun RailItem(
.background(fill)
.glideBorder(focused, Shape14, pal.signal)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.selectable(selected = current, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.then(if (iconOnly) Modifier.semantics { contentDescription = label } else Modifier),
) {
if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp))
@@ -132,7 +132,7 @@ class FrontEndState(
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val showPhantomGate: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
val launcherFullscreen: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
@@ -165,6 +165,7 @@ class FrontEndActions(
val onAddedGamesChanged: (folders: List<String>) -> Unit = {},
val onSteamGameArtChanged: (appId: Int) -> Unit = {},
val onAddedGameRemoved: (folder: String, appId: Long?, name: String) -> Unit = { _, _, _ -> },
val onGameRemoved: (Library.SteamGame) -> Unit = {},
val onAddedGamesArt: (Boolean) -> Unit = {},
val onSgdbKey: (String) -> Unit = {},
val onStopGameFileSync: () -> Unit = {},
@@ -188,6 +189,7 @@ class FrontEndActions(
val onImportLossless: () -> Unit,
val onProtons: () -> Unit,
val onComponents: (focusContent: Boolean) -> Unit,
val onGameComponents: (Library.SteamGame) -> Unit = { onComponents(true) },
val onComponentsTab: (String) -> Unit = {},
val onSaveImport: (Library.SteamGame) -> Unit = {},
val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> },
@@ -359,6 +359,7 @@ internal fun SetupPanel(
}
}
}
if (s.theme == Themes.GRADIENT) GradientColorRows()
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent ->
@@ -523,8 +524,9 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val back = stringResource(R.string.hop_from_games)
SettingCard(stringResource(R.string.setup_card_components), stringResource(R.string.setup_card_components_hint), "card:components", m.hopSource("card:components")) {
val at = Hops.sources["card:components"]
if (at == null) a.onComponents(true)
else Hops.go(HopOrigin("games", HOP_SURFACE_GAMES, null, "card:components", at, back, dest = "components", page = "components")) { a.onComponents(true) }
val open = { if (game == null) a.onComponents(true) else a.onGameComponents(game) }
if (at == null) open()
else Hops.go(HopOrigin("games", HOP_SURFACE_GAMES, null, "card:components", at, back, dest = "components", page = "components"), open)
}
}
add { m ->
@@ -789,3 +791,21 @@ private fun LanguageRow(host: MenuHost, chosen: String, onPick: (String) -> Unit
}
}
}
/** The two colours of the Gradient theme, each a small square that opens the colour picker. */
@Composable
private fun GradientColorRows() {
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
val (primary, secondary) = Themes.gradientColors
var picking by remember { androidx.compose.runtime.mutableIntStateOf(0) }
val primaryLabel = stringResource(R.string.theme_gradient_primary)
val secondaryLabel = stringResource(R.string.theme_gradient_secondary)
SettingsRow(primaryLabel, null) { ColorCube(androidx.compose.ui.graphics.Color(primary), primaryLabel) { picking = 1 } }
SettingsRow(secondaryLabel, null) { ColorCube(androidx.compose.ui.graphics.Color(secondary), secondaryLabel) { picking = 2 } }
if (picking != 0) ColorPickerDialog(
if (picking == 1) primaryLabel else secondaryLabel, if (picking == 1) primary else secondary,
onDismiss = { picking = 0 },
) { argb ->
if (picking == 1) Themes.setGradient(ctx, argb, secondary) else Themes.setGradient(ctx, primary, argb)
}
}
@@ -59,16 +59,22 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.rememberTextMeasurer
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 java.util.Locale
internal val Shape14 = RoundedCornerShape(14.dp)
@Composable
internal fun headingUppercase(text: String): String =
text.uppercase(LocalConfiguration.current.locales[0] ?: Locale.ROOT)
@Composable
internal fun Eyebrow(t: String) {
val pal = LocalPalette.current
@@ -76,7 +82,7 @@ internal fun Eyebrow(t: String) {
LaunchedEffect(Unit) { rule.animateTo(1f, Motion.tw(600, 120)) }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Box(modifier = Modifier.width(18.dp).height(1.5.dp).graphicsLayer { scaleX = rule.value; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0f, 0.5f) }.background(pal.signal))
Text(t.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = pal.signal)
Text(headingUppercase(t), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = pal.signal)
}
}
@@ -88,7 +94,7 @@ internal fun Eyebrow(t: String) {
internal fun SectionTitle(t: String, detail: String?) {
val colors = MaterialTheme.colorScheme
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 8.dp)) {
Text(t.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant)
Text(headingUppercase(t), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant)
if (detail != null) Text(detail, fontSize = 12.sp, color = colors.onBackground)
Box(modifier = Modifier.weight(1f).height(1.dp).background(LocalPalette.current.line))
}
@@ -179,10 +185,9 @@ internal fun PrimaryButton(
.graphicsLayer { alpha = if (LaunchOrigin.flooding === placed) 0f else 1f; scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
.clip(Shape12)
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
.shine(hot, 0.45f)
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12))
.glideBorder(hot, Shape12, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled) {
.then(if (hot) Modifier.border(2.dp, pal.signal, Shape12) else Modifier)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) {
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
onClick()
}
@@ -245,7 +250,7 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
contentAlignment = Alignment.Center,
modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).glideBorder(hot, Shape12, pal.signal, pal.line2)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = if (compact) 10.dp else 16.dp, vertical = if (compact) 7.dp else 11.dp),
) {
@@ -267,7 +272,7 @@ internal fun Cog(size: androidx.compose.ui.unit.Dp = 48.dp, onClick: () -> Unit)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("cog").downToFirstTile().size(size).onGloballyPositioned { placed[0] = it }.clip(if (size > 48.dp) Shape14 else Shape12).background(Color.White.copy(alpha = 0.03f)).glideBorder(hot, if (size > 48.dp) Shape14 else Shape12, pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current) {
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current) {
placed[0]?.takeIf { it.isAttached }?.let { PageOrigin.mark(Origin(it.boundsInRoot(), cornerPx)) }
spins++
onClick()
@@ -143,15 +143,15 @@ internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", on
}
}
otherId?.let { id ->
val valid = id.isNotEmpty() && GameEnvironment.validScope(id)
val open = { if (valid) { scope = id.toLong().toString(); otherId = null } }
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
AdbTextField(
id, { otherId = it.filter(Char::isDigit) }, stringResource(R.string.game_env_app_id), KeyboardType.Number, ImeAction.Done,
modifier = Modifier.weight(1f), compact = true,
onDone = { if (GameEnvironment.validScope(id)) { scope = id.toLong().toString(); otherId = null } },
onDone = open,
)
SecondaryButton(stringResource(R.string.game_env_open), enabled = id.isNotEmpty() && GameEnvironment.validScope(id)) {
scope = id.toLong().toString(); otherId = null
}
SecondaryButton(stringResource(R.string.game_env_open), enabled = valid, onClick = open)
}
}
if (error) Small(stringResource(R.string.game_env_error), error = true)
@@ -0,0 +1,128 @@
package com.droiddeck.launcher.ui
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import java.text.Collator
internal enum class GestureActionGroup(@StringRes val title: Int) {
MOUSE(R.string.gesture_group_mouse), APP(R.string.gesture_group_app),
NAVIGATION(R.string.gesture_group_navigation), LETTERS(R.string.gesture_group_letters),
NUMBERS(R.string.gesture_group_numbers), FUNCTION(R.string.gesture_group_function),
MODIFIERS(R.string.gesture_group_modifiers), NUMPAD(R.string.gesture_group_numpad),
SYMBOLS(R.string.gesture_group_symbols),
}
internal data class GestureAction(val id: String, val title: String, val group: GestureActionGroup)
internal fun gestureActionGroup(id: String): GestureActionGroup {
if (id == "show_keyboard") return GestureActionGroup.APP
if (id in setOf("left_click", "right_click", "middle_click", "left_click_drag", "right_click_drag",
"middle_mouse_pan", "inverted_middle_mouse_pan", "scroll_wheel")) return GestureActionGroup.MOUSE
val key = id.removePrefix("key_")
return when {
key.startsWith("KP_") -> GestureActionGroup.NUMPAD
key.length == 1 && key[0] in 'A'..'Z' -> GestureActionGroup.LETTERS
key.length == 1 && key[0].isDigit() -> GestureActionGroup.NUMBERS
key.matches(Regex("F(?:[1-9]|1[0-2])")) -> GestureActionGroup.FUNCTION
key.startsWith("CTRL_") || key.startsWith("SHIFT_") || key.startsWith("ALT_") || key.endsWith("_LOCK") -> GestureActionGroup.MODIFIERS
key in setOf("MINUS", "EQUAL", "BRACKET_LEFT", "BRACKET_RIGHT", "SEMICOLON", "APOSTROPHE",
"GRAVE", "TILDE", "BACKSLASH", "COMMA", "PERIOD", "SLASH") || id == "plus_minus" -> GestureActionGroup.SYMBOLS
else -> GestureActionGroup.NAVIGATION
}
}
internal fun filterGestureActions(actions: List<GestureAction>, query: String, group: GestureActionGroup?): List<GestureAction> {
val words = query.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }
val collator = Collator.getInstance()
return actions.filter { action ->
(group == null || action.group == group) && words.all { word ->
action.title.contains(word, ignoreCase = true) || action.id.removePrefix("key_").replace('_', ' ').contains(word, ignoreCase = true)
}
}.sortedWith(compareBy<GestureAction> { it.group.ordinal }.thenComparator { a, b ->
// Function keys follow their numeric sequence; names use the UI locale.
if (a.group == GestureActionGroup.FUNCTION) {
a.id.removePrefix("key_F").toInt().compareTo(b.id.removePrefix("key_F").toInt())
} else collator.compare(a.title, b.title)
}.thenBy { it.id })
}
@Composable
internal fun gestureActionTitle(action: String): String {
val named = when (action) {
"left_click" -> R.string.gesture_left_click
"right_click" -> R.string.gesture_right_click
"middle_click" -> R.string.gesture_middle_click
"show_keyboard" -> R.string.gesture_keyboard
"left_click_drag" -> R.string.gesture_left_drag
"right_click_drag" -> R.string.gesture_right_drag
"middle_mouse_pan" -> R.string.gesture_middle_pan
"inverted_middle_mouse_pan" -> R.string.gesture_middle_pan_inverted
"arrow_keys" -> R.string.gesture_arrows
"inverted_arrow_keys" -> R.string.gesture_arrows_inverted
"inverted_wasd" -> R.string.gesture_wasd_inverted
"scroll_wheel" -> R.string.gesture_scroll
else -> null
}
if (named != null) return stringResource(named)
return when (action) {
"wasd" -> "WASD"
"plus_minus" -> "+ / −"
"page_up_down" -> stringResource(R.string.gesture_key_page_up) + " / " + stringResource(R.string.gesture_key_page_down)
else -> gestureKeyTitle(action.removePrefix("key_"))
}
}
@Composable
private fun gestureKeyTitle(key: String): String {
if (key.startsWith("KP_")) return stringResource(R.string.gesture_key_numpad, gestureKeyTitle(key.removePrefix("KP_")))
val named = when (key) {
"ESC" -> R.string.gesture_key_escape
"BKSP" -> R.string.gesture_key_backspace
"ENTER" -> R.string.gesture_key_enter
"TAB" -> R.string.gesture_key_tab
"SPACE" -> R.string.gesture_key_space
"DEL" -> R.string.gesture_key_delete
"INSERT" -> R.string.gesture_key_insert
"HOME" -> R.string.gesture_key_home
"END" -> R.string.gesture_key_end
"PRIOR" -> R.string.gesture_key_page_up
"NEXT" -> R.string.gesture_key_page_down
"PRTSCN" -> R.string.gesture_key_print_screen
"UP" -> R.string.gesture_key_up
"DOWN" -> R.string.gesture_key_down
"LEFT" -> R.string.gesture_key_left_arrow
"RIGHT" -> R.string.gesture_key_right_arrow
"CAPS_LOCK" -> R.string.gesture_key_caps_lock
"NUM_LOCK" -> R.string.gesture_key_num_lock
"SCROLL_LOCK" -> R.string.gesture_key_scroll_lock
else -> null
}
if (named != null) return stringResource(named)
if (key.startsWith("CTRL_") || key.startsWith("SHIFT_") || key.startsWith("ALT_")) {
val name = stringResource(when (key.substringBefore('_')) {
"CTRL" -> R.string.pckb_key_ctrl
"SHIFT" -> R.string.gesture_key_shift
else -> R.string.pckb_key_alt
})
return stringResource(if (key.endsWith("_L")) R.string.gesture_key_left else R.string.gesture_key_right, name)
}
return when (key) {
"MINUS", "SUBTRACT" -> "−"
"EQUAL" -> "="
"ADD" -> "+"
"MULTIPLY" -> "×"
"DIVIDE", "SLASH" -> "/"
"BRACKET_LEFT" -> "["
"BRACKET_RIGHT" -> "]"
"SEMICOLON" -> ";"
"APOSTROPHE" -> "'"
"GRAVE" -> "`"
"TILDE" -> "~"
"BACKSLASH" -> "\\"
"COMMA" -> ","
"PERIOD" -> "."
else -> key.replace('_', ' ')
}
}
@@ -0,0 +1,35 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.TouchscreenGestures.Gesture
@Composable
fun GestureFeedback(gesture: Gesture?) {
Box(Modifier.fillMaxSize()) {
if (gesture != null) Text(stringResource(when (gesture) {
Gesture.TAP -> R.string.gesture_tap
Gesture.DRAG -> R.string.gesture_drag
Gesture.LONG_PRESS -> R.string.gesture_long_press
Gesture.DOUBLE_TAP -> R.string.gesture_double_tap
Gesture.TWO_FINGER_TAP -> R.string.gesture_two_tap
Gesture.TWO_FINGER_DRAG -> R.string.gesture_two_drag
Gesture.TWO_FINGER_HOLD -> R.string.gesture_two_hold
Gesture.PINCH -> R.string.gesture_pinch
Gesture.THREE_FINGER_TAP -> R.string.gesture_three_tap
Gesture.THREE_FINGER_DRAG -> R.string.gesture_three_drag
Gesture.THREE_FINGER_HOLD -> R.string.gesture_three_hold
}),
Modifier.align(Alignment.TopCenter).padding(top = 24.dp)
.background(MaterialTheme.colorScheme.surface).padding(horizontal = 16.dp, vertical = 8.dp),
color = MaterialTheme.colorScheme.onSurface)
}
}
@@ -79,6 +79,33 @@ internal object GlassesTab {
const val VR = "vr"
const val HARDWARE = "hardware"
const val TRACKING = "tracking"
const val CONTROLLERS = "controllers"
}
@Composable
internal fun VrControllerGroups(host: MenuHost, track: (String) -> Modifier = { Modifier }) {
val context = androidx.compose.ui.platform.LocalContext.current
androidx.compose.runtime.LaunchedEffect(Unit) { com.droiddeck.launcher.input.VrControllers.load(context) }
val c by com.droiddeck.launcher.input.VrControllers.settings.collectAsState()
val emulate = com.droiddeck.launcher.input.VrControllers.Emulate.entries
SettingsGroup(stringResource(R.string.vr_controllers_group)) {
ChoiceRow(host, "vr-emulate", stringResource(R.string.vr_controllers_emulate), stringResource(R.string.vr_controllers_emulate_hint),
emulate.map { it to stringResource(when (it) {
com.droiddeck.launcher.input.VrControllers.Emulate.OFF -> R.string.vr_controllers_off
com.droiddeck.launcher.input.VrControllers.Emulate.INDEX -> R.string.vr_controllers_index
com.droiddeck.launcher.input.VrControllers.Emulate.TOUCH -> R.string.vr_controllers_touch
com.droiddeck.launcher.input.VrControllers.Emulate.VIVE -> R.string.vr_controllers_vive
}) }, c.emulate, chipModifier = track("vr-emulate")) { com.droiddeck.launcher.input.VrControllers.setEmulate(context, it) }
if (c.emulate != com.droiddeck.launcher.input.VrControllers.Emulate.OFF) ChoiceRow(host, "vr-sticks",
stringResource(R.string.vr_controllers_sticks), stringResource(R.string.vr_controllers_sticks_hint),
listOf(false to stringResource(R.string.vr_controllers_sticks_game), true to stringResource(R.string.vr_controllers_sticks_hands)),
c.sticksMoveHands, chipModifier = track("vr-sticks")) { com.droiddeck.launcher.input.VrControllers.setSticksMoveHands(context, it) }
SettingsRow(stringResource(R.string.vr_controllers_buttons), stringResource(when (c.emulate) {
com.droiddeck.launcher.input.VrControllers.Emulate.OFF -> R.string.vr_controllers_buttons_off
com.droiddeck.launcher.input.VrControllers.Emulate.VIVE -> R.string.vr_controllers_buttons_vive
else -> R.string.vr_controllers_buttons_stick
}), hintLines = 6) {}
}
}
@Composable
@@ -122,7 +149,8 @@ internal fun GlassesGroups(
}
}
if (display) SettingsGroup(g.model) {
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(R.string.glasses_xreal_experimental)) {}
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(
if (g.supportsDisplayModeControl) R.string.glasses_xreal_experimental else R.string.glasses_pro2_experimental)) {}
val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(),
stringResource(if (g.sbs) R.string.glasses_mode_3d else R.string.glasses_mode_2d)) else null
when {
@@ -141,7 +169,7 @@ internal fun GlassesGroups(
ToggleRow(host, "glasses-game", stringResource(R.string.glasses_game_on), stringResource(R.string.glasses_game_on_hint),
s.gameOnGlasses, chipModifier = track("glasses-game")) { Glasses.setGameOnGlasses(it) }
}
if (display && g.canControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) {
if (display && g.canControl && g.supportsDisplayModeControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) {
SettingsGroup(stringResource(R.string.glasses_display_mode)) {
if (g.sbsSupport == GlassesState.SBS_FAILS && !g.sbs) {
ActionRow(stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_failed),
@@ -150,7 +178,7 @@ internal fun GlassesGroups(
g.sbs, chipModifier = track("glasses-3d")) { Glasses.set3d(it) }
}
}
if (display && g.canControl) {
if (display && g.canControl && g.supportsDisplayModeControl) {
val profiles = if (inSession) listOf(GlassesDisplayModes.profile(g.sbs, false))
else listOf(GlassesDisplayProfile.TWO_D, GlassesDisplayProfile.THREE_D)
for (profile in profiles) SettingsGroup(stringResource(if (profile == GlassesDisplayProfile.TWO_D)
@@ -187,9 +215,9 @@ internal fun GlassesGroups(
}
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr)) {
steamVr()
ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d), stringResource(R.string.glasses_auto3d_hint),
s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
if (g.canControl) {
if (g.supportsDisplayModeControl) ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d),
stringResource(R.string.glasses_auto3d_hint), s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
if (g.canControl && g.supportsDisplayModeControl) {
GlassesResolutionRow(host, g, s, GlassesDisplayProfile.VR, track)
if (steamVrRunning && tab != null) GlassesRefreshRow(host, g, s, track)
}
@@ -362,13 +390,3 @@ private fun GlassesRecenterAction(label: String, tag: String, tint: Int, opacity
}
}
@Composable
internal fun GlassesPlayingHint(model: String) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(GlassesIcon, null, tint = Color.White.copy(alpha = 0.35f), modifier = Modifier.size(56.dp))
Spacer(Modifier.height(10.dp))
Text(stringResource(R.string.glasses_playing, model), color = Color.White.copy(alpha = 0.45f), fontSize = 15.sp)
}
}
}
@@ -0,0 +1,85 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.displayCutout
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
/** Actions for the phone while the picture is on the glasses. Null hides the button. */
internal class GlassesPhoneActions(
val onRecenter: (() -> Unit)?,
val onRecenterJoyCons: (() -> Unit)?,
val onSteamVrMenu: (() -> Unit)?,
val onSwitchSticks: (() -> Unit)?,
val controllers: String?,
val onNextControllers: (() -> Unit)?,
val onKeyboard: () -> Unit,
val onSessionMenu: () -> Unit,
val onStopSteamVr: (() -> Unit)?,
val brightness: Int,
val brightnessMax: Int,
val onBrightness: ((Int) -> Unit)?,
)
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun GlassesPhonePanel(model: String, status: String?, a: GlassesPhoneActions) {
Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout).padding(16.dp), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.widthIn(max = 640.dp)) {
Icon(GlassesIcon, null, tint = Color.White.copy(alpha = 0.35f), modifier = Modifier.size(40.dp))
Spacer(Modifier.height(6.dp))
Text(stringResource(R.string.glasses_playing, model), color = Color.White.copy(alpha = 0.6f), fontSize = 15.sp)
if (status != null) Text(status, color = Color.White.copy(alpha = 0.4f), fontSize = 13.sp, textAlign = TextAlign.Center)
Spacer(Modifier.height(16.dp))
FlowRow(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.CenterHorizontally),
verticalArrangement = Arrangement.spacedBy(10.dp)) {
a.onRecenter?.let { PanelButton(stringResource(R.string.glasses_phone_recenter), "phone-recenter", it) }
a.onRecenterJoyCons?.let { PanelButton(stringResource(R.string.glasses_recenter_joycons_button), "phone-recenter-joycons", it) }
a.onSteamVrMenu?.let { PanelButton(stringResource(R.string.glasses_phone_steamvr_menu), "phone-steamvr-menu", it) }
a.onNextControllers?.let { next -> a.controllers?.let {
PanelButton(stringResource(R.string.glasses_phone_controllers, it), "phone-controllers", next) } }
a.onSwitchSticks?.let { PanelButton(stringResource(R.string.glasses_phone_switch_sticks), "phone-switch-sticks", it) }
PanelButton(stringResource(R.string.glasses_phone_keyboard), "phone-keyboard", a.onKeyboard)
PanelButton(stringResource(R.string.glasses_phone_session_menu), "phone-session-menu", a.onSessionMenu)
a.onStopSteamVr?.let { PanelButton(stringResource(R.string.glasses_phone_stop_steamvr), "phone-stop-steamvr", it) }
}
val setBrightness = a.onBrightness
if (setBrightness != null && a.brightnessMax > 0) {
Spacer(Modifier.height(14.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
PanelButton("−", "phone-brightness-down") { setBrightness((a.brightness - 1).coerceAtLeast(0)) }
Text(stringResource(R.string.glasses_phone_brightness, a.brightness.coerceAtLeast(0), a.brightnessMax),
color = Color.White.copy(alpha = 0.6f), fontSize = 14.sp)
PanelButton("+", "phone-brightness-up") { setBrightness((a.brightness + 1).coerceAtMost(a.brightnessMax)) }
}
}
}
}
}
@Composable
private fun PanelButton(label: String, tag: String, onClick: () -> Unit) =
SecondaryButton(label, compact = true, modifier = Modifier.testTag(tag), onClick = onClick)
@@ -1,9 +1,11 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.core.AddonPack
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.text.format.Formatter
import android.speech.tts.TextToSpeech
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
@@ -70,6 +72,7 @@ import com.droiddeck.launcher.handtracking.Advice
import com.droiddeck.launcher.handtracking.BodyPose
import com.droiddeck.launcher.handtracking.HandCamera
import com.droiddeck.launcher.handtracking.HandTracking
import com.droiddeck.launcher.handtracking.TrackingPack
import com.droiddeck.launcher.handtracking.Landmark
import com.droiddeck.launcher.handtracking.TrackingCameras
import kotlinx.coroutines.delay
@@ -186,11 +189,27 @@ internal fun HandCameraRows(host: MenuHost, track: (String) -> Modifier, inSessi
})
!s.permitted -> ActionRow(stringResource(R.string.hand_camera_access), stringResource(R.string.hand_camera_access_hint),
stringResource(R.string.hand_camera_allow_button), { ask.launch(Manifest.permission.CAMERA) })
!s.downloaded -> TrackingPackRow()
!inSession -> ActionRow(stringResource(R.string.hand_camera_placement), stringResource(R.string.hand_camera_placement_hint),
stringResource(R.string.hand_camera_check), { HandTracking.requestCheck() })
}
}
@Composable
private fun TrackingPackRow() {
val context = LocalContext.current
val pack by TrackingPack.state.collectAsState()
val size = Formatter.formatShortFileSize(context, TrackingPack.size)
when (val now = pack) {
is AddonPack.State.Downloading -> ActionRow(stringResource(R.string.tracking_pack_title),
stringResource(R.string.tracking_pack_hint, size), stringResource(R.string.tracking_pack_download), {}, progress = now.progress)
AddonPack.State.Failed -> ActionRow(stringResource(R.string.tracking_pack_title),
stringResource(R.string.tracking_pack_failed), stringResource(R.string.tracking_pack_retry), { TrackingPack.ensure(context) })
else -> ActionRow(stringResource(R.string.tracking_pack_title),
stringResource(R.string.tracking_pack_hint, size), stringResource(R.string.tracking_pack_download), { TrackingPack.ensure(context) })
}
}
@Composable
private fun PlacementCheck(settings: HandTracking.Settings, play: Boolean, onPlay: () -> Unit, onClose: () -> Unit) {
val context = LocalContext.current
@@ -18,6 +18,8 @@ import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
@@ -715,7 +717,7 @@ internal fun SheetChips(
horizontalArrangement = Arrangement.spacedBy(ChipGap),
modifier = (if (equal) Modifier.fillMaxWidth() else Modifier)
.focusProperties { enter = { chips.getOrNull(selected) ?: FocusRequester.Default } }
.focusGroup(),
.focusGroup().selectableGroup(),
) {
labels.forEachIndexed { i, label ->
val m = (if (equal) Modifier.weight(1f) else Modifier.widthIn(min = least))
@@ -743,7 +745,7 @@ private fun SheetChip(label: String, on: Boolean, modifier: Modifier, onClick: (
.background(if (under) Color.Transparent else colors.surfaceVariant.copy(alpha = 0.5f))
.shownBar(on, pal.signal)
.glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
@@ -3,6 +3,9 @@ package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
@@ -105,7 +108,7 @@ private fun LogoPreview(hero: File?, logo: File?, value: LogoPosition.Value) {
}
@Composable
private fun PinChip(label: String, selected: Boolean, onClick: () -> Unit) {
private fun PinChip(label: String, selected: Boolean, focus: FocusRequester?, onClick: () -> Unit) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val src = remember { MutableInteractionSource() }
@@ -113,7 +116,7 @@ private fun PinChip(label: String, selected: Boolean, onClick: () -> Unit) {
val shape = RoundedCornerShape(8.dp)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.clip(shape)
modifier = Modifier.then(if (focus != null) Modifier.focusRequester(focus) else Modifier).clip(shape)
.background(if (selected) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f))
.border(if (selected) 2.dp else 1.dp, if (selected) pal.signal else pal.line, shape)
.glideBorder(hot, shape, pal.signal)
@@ -140,6 +143,9 @@ internal fun LogoPositionDialog(
val shown = rememberShown(onBack)
val back = { shown.targetState = false }
var value by remember { mutableStateOf(start ?: LogoPosition.DEFAULT) }
val startPin = remember { value.pin }
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { focusSoon { first } }
var failed by remember { mutableStateOf(false) }
var busy by remember { mutableStateOf(false) }
val save: (LogoPosition.Value?) -> Unit = { next ->
@@ -172,7 +178,7 @@ internal fun LogoPositionDialog(
)
Text(stringResource(R.string.logo_pos_position), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp))
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (pin in LogoPosition.Pin.values()) PinChip(pin.label(), pin == value.pin) { value = value.copy(pin = pin) }
for (pin in LogoPosition.Pin.values()) PinChip(pin.label(), pin == value.pin, if (pin == startPin) first else null) { value = value.copy(pin = pin) }
}
ValueSlider(
value.widthPct, LogoPosition.MIN_PCT..LogoPosition.MAX_PCT, step = 1, enabled = true, label = stringResource(R.string.logo_pos_size),
@@ -66,6 +66,22 @@ fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () ->
)
}
@Composable
fun RuntimeActionsDialog(onRepair: () -> Unit, onRemove: () -> Unit, onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.runtime_actions_title)) },
text = { Text(stringResource(R.string.runtime_actions_text)) },
confirmButton = { TextButton(onClick = onRepair) { Text(stringResource(R.string.runtime_repair)) } },
dismissButton = {
Row {
TextButton(onClick = onRemove) { Text(stringResource(R.string.store_remove)) }
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
}
},
)
}
@Composable
fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: () -> Unit) {
var gameProfiles by remember { mutableStateOf(false) }
@@ -14,6 +14,7 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
@@ -81,6 +82,8 @@ class ModeSettings(
val picturePosition: String? = null,
val stretch16x9: Boolean? = null,
val steamClientArch: String? = null,
/** Steam only: a game launched from the front end returns there when it closes; null hides the row. */
val returnAfterGame: Boolean? = null,
val steamRepairQueued: Boolean = false,
val mangoapp: Boolean = true,
val steamController: String? = null,
@@ -98,6 +101,7 @@ class ModeSettings(
val wifiDiscoveryBlocked: Boolean = false,
val deckyInstalled: String? = null,
val deckyLatestRelease: DeckyManager.Release? = null,
val deckyBranch: Int = DeckyManager.BRANCH_STABLE,
val deckyChecking: Boolean = false,
val deckyStage: String? = null,
val deckyPercent: Int = -1,
@@ -133,17 +137,19 @@ class ModeSettingsActions(
val onSteamRepair: () -> Unit = {},
val onSteamClientArch: (String) -> Unit = {},
val onMangoapp: (Boolean) -> Unit = {},
val onReturnAfterGame: (Boolean) -> Unit = {},
val onSteamController: (String) -> Unit = {},
val onUnfoldedControls: (Boolean) -> Unit = {},
val onRunSteamAtStartup: (Boolean) -> Unit = {},
val onBootMovie: (String) -> Unit = {},
val onBootMovieSound: (Boolean) -> Unit = {},
val onImportBootMovie: () -> Unit = {},
val onRemoveBootMovie: () -> Unit = {},
val onBootMovieChanged: () -> Unit = {},
val onWifiDiscovery: (Boolean) -> Unit = {},
val onWifiDiscoverySettings: () -> Unit = {},
val onDeckyInstall: (DeckyManager.Release) -> Unit = {},
val onDeckyCheck: () -> Unit = {},
val onDeckyBranch: (Int) -> Unit = {},
val onDeckyEnabled: (Boolean) -> Unit = {},
val onDeckyUninstall: () -> Unit = {},
val onPickDeckyPluginZip: () -> Unit = {},
@@ -250,7 +256,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) {
ChoiceRow(
host, "touch", stringResource(R.string.mode_touch), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), s.touchMode,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), s.touchMode,
note = stringResource(R.string.mode_touch_note),
onPick = a.onTouch,
)
@@ -273,8 +279,10 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4),
SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360),
SessionPrefs.CONTROLLER_NONE to stringResource(R.string.second_mode_none),
), s.steamController,
note = stringResource(R.string.mode_controller_note),
note = if (s.steamController == SessionPrefs.CONTROLLER_NONE) stringResource(R.string.common_applies_next_session)
else stringResource(R.string.mode_controller_note),
onPick = a.onSteamController,
)
if (steam && s.unfoldedControls != null) ToggleRow(
@@ -423,6 +431,19 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
if (s.deckyInstalled != null) DeckyUninstall(enabled = s.deckyStage == null && !s.deckySessionRunning, onUninstall = a.onDeckyUninstall)
}
}
ChoiceRow(
host, "decky-channel", stringResource(R.string.decky_channel),
stringResource(R.string.decky_channel_hint),
listOf(
DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable),
DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease),
) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf(
DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing),
) else emptyList(),
s.deckyBranch,
enabled = s.deckyStage == null && !s.deckySessionRunning,
onPick = a.onDeckyBranch,
)
if (s.deckyInstalled != null) ToggleRow(
host, "decky-enabled", stringResource(R.string.mode_decky),
if (s.deckyEnabled) stringResource(R.string.mode_decky_on)
@@ -454,6 +475,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.mode_mangoapp_hint),
s.mangoapp, onChange = a.onMangoapp,
)
if (s.returnAfterGame != null) ToggleRow(
host, "returnaftergame", stringResource(R.string.mode_return_after_game),
stringResource(R.string.mode_return_after_game_hint),
s.returnAfterGame, onChange = a.onReturnAfterGame,
)
SettingsRow(
stringResource(R.string.mode_steam_repair),
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
@@ -467,41 +493,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
onPick = a.onSteamClientArch,
)
}
if (s.bootMovie != null) SettingsGroup(stringResource(R.string.boot_movie)) {
ChoiceRow(
host, "boot-movie", stringResource(R.string.boot_movie_video), stringResource(R.string.common_applies_next_session),
buildList {
add(BootMovie.DROIDDECK_30 to stringResource(R.string.boot_movie_droiddeck, 30))
add(BootMovie.DROIDDECK_60 to stringResource(R.string.boot_movie_droiddeck, 60))
s.bootMovieCustomName?.let { add(BootMovie.CUSTOM to it) }
}, s.bootMovie,
note = stringResource(R.string.boot_movie_note), onPick = a.onBootMovie,
)
ToggleRow(
host, "boot-movie-sound", stringResource(R.string.boot_movie_sound),
stringResource(R.string.common_applies_next_session), s.bootMovieSound, onChange = a.onBootMovieSound,
)
SettingsRow(
stringResource(R.string.boot_movie_custom),
stringResource(R.string.boot_movie_custom_hint, (BootMovie.MAX_BYTES shr 20).toInt(), BootMovie.MAX_CONVERT_SECONDS),
) {
Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {
SecondaryButton(
when {
s.bootMovieProgress >= 0 -> stringResource(R.string.boot_movie_converting, s.bootMovieProgress)
s.bootMovieImporting -> stringResource(R.string.common_working)
else -> stringResource(R.string.boot_movie_import)
},
enabled = !s.bootMovieImporting,
progress = s.bootMovieProgress.takeIf { it >= 0 }?.let { it / 100f },
onClick = a.onImportBootMovie,
)
if (s.bootMovieCustomName != null) SecondaryButton(
stringResource(R.string.boot_movie_remove), enabled = !s.bootMovieImporting, onClick = a.onRemoveBootMovie,
)
}
}
}
if (s.bootMovie != null) BootMovieGroup(s, a, host)
if (s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
val hint = when {
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
@@ -563,6 +555,35 @@ internal fun ProtonOptions(
GameEnvironmentRow()
}
@Composable
internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit) {
val context = androidx.compose.ui.platform.LocalContext.current
var left by remember { mutableIntStateOf(if (SessionPrefs.deckyZipWarningSeen(context)) 0 else DECKY_ZIP_WARNING_SECONDS) }
androidx.compose.runtime.LaunchedEffect(Unit) {
while (left > 0) {
kotlinx.coroutines.delay(1000L)
left--
}
SessionPrefs.setDeckyZipWarningSeen(context)
}
AlertDialog(
onDismissRequest = onCancel,
title = { Text(stringResource(R.string.decky_zip_warning_title)) },
text = { Text(stringResource(R.string.decky_zip_warning_text)) },
confirmButton = {
androidx.compose.material3.TextButton(onClick = onConfirm, enabled = left == 0) {
Text(
if (left > 0) androidx.compose.ui.res.pluralStringResource(R.plurals.decky_zip_warning_wait, left, left)
else stringResource(R.string.decky_zip_warning_continue),
)
}
},
dismissButton = { androidx.compose.material3.TextButton(onClick = onCancel) { Text(stringResource(R.string.common_cancel)) } },
)
}
private const val DECKY_ZIP_WARNING_SECONDS = 5
@Composable
private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -234,7 +234,7 @@ private fun HeaderButton(text: String, onClick: () -> Unit) {
modifier = Modifier.fillMaxHeight()
.background(Color.White.copy(alpha = 0.08f), RoundedCornerShape(7.dp))
.glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, Color.White.copy(alpha = 0.14f))
.clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.padding(horizontal = 12.dp),
) { Text(text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = Color.White) }
}
@@ -1,17 +1,21 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import android.app.Presentation
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.Display
import android.view.Gravity
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewConfiguration
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.FrameLayout
@@ -33,9 +37,9 @@ import com.termux.terminal.TerminalSessionClient
import com.termux.view.TerminalView
import com.termux.view.TerminalViewClient
internal class SecondScreenControls(
context: Context,
class SecondScreenPresentation(
private val sessionActivity: SessionActivity,
display: Display,
private val sendPointer: (x: Float, y: Float, width: Float, height: Float) -> Unit,
private val sendButton: (button: Int, pressed: Boolean) -> Unit,
private val sendWheel: (steps: Int) -> Unit,
@@ -43,8 +47,12 @@ internal class SecondScreenControls(
private val onQam: () -> Unit,
private val onClose: () -> Unit,
private val pad: PadBridge? = null,
) : LinearLayout(context) {
private val root get() = this
) : Presentation(sessionActivity, display) {
private val root = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.rgb(15, 18, 22))
isFocusableInTouchMode = true
}
private var currentMode = SecondScreenMode.NONE
private var keyboardHost: KeyboardHost? = null
private var terminalSession: TerminalSession? = null
@@ -52,22 +60,35 @@ internal class SecondScreenControls(
private var terminalPid = -1
private var ctrlActive = false
private var altActive = false
private var created = false
init {
orientation = VERTICAL
setBackgroundColor(Color.rgb(15, 18, 22))
isFocusableInTouchMode = true
setCancelable(false)
setCanceledOnTouchOutside(false)
setOnDismissListener { closeTerminal() }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
created = true
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
setContentView(root)
applyImmersiveMode()
renderMode()
}
fun showMode(mode: SecondScreenMode) {
if (currentMode == mode) return
if (currentMode == mode && isShowing) return
currentMode = mode
renderMode()
if (created) renderMode()
}
fun closeControls() {
closeTerminal()
keyboardHost?.hide()
keyboardHost = null
dismiss()
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
@@ -77,14 +98,24 @@ internal class SecondScreenControls(
return super.dispatchKeyEvent(event)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
applyImmersiveMode()
sessionActivity.refreshClipboard()
}
}
private fun renderMode() {
keyboardHost?.hide()
keyboardHost = null
closeTerminal()
root.removeAllViews()
if (currentMode == SecondScreenMode.NONE) return
val mode = if (currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) SecondScreenMode.NONE
else currentMode
if (mode == SecondScreenMode.NONE) return
when (currentMode) {
when (mode) {
SecondScreenMode.KEYBOARD_TRACKPAD -> renderKeyboardAndTrackpad()
SecondScreenMode.TERMINAL -> renderTerminal()
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam, pad), weightParams())
@@ -126,16 +157,18 @@ internal class SecondScreenControls(
}
}
controls.addView(keyboardButton)
controls.addView(Button(context).apply {
text = "STEAM"
contentDescription = context.getString(R.string.deck_open_steam_menu)
setOnClickListener { onSteamMenu() }
})
controls.addView(Button(context).apply {
text = "…"
contentDescription = context.getString(R.string.drawer_open_qam)
setOnClickListener { onQam() }
})
if (SessionState.mode == SessionService.MODE_STEAM) {
controls.addView(Button(context).apply {
text = "STEAM"
contentDescription = context.getString(R.string.deck_open_steam_menu)
setOnClickListener { onSteamMenu() }
})
controls.addView(Button(context).apply {
text = "…"
contentDescription = context.getString(R.string.drawer_open_qam)
setOnClickListener { onQam() }
})
}
panel.addView(controls, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
root.addView(panel, weightParams())
val host = KeyboardHost(context) { sessionActivity.dispatchKeyEvent(it) }
@@ -262,6 +295,16 @@ internal class SecondScreenControls(
private fun weightParams() = LinearLayout.LayoutParams(-1, 0, 1f)
private fun applyImmersiveMode() {
@Suppress("DEPRECATION")
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
}
private inner class TrackpadView(context: Context) : View(context) {
private val gestures = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(),
object : PointerGestures.Listener {
@@ -1,139 +0,0 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.view.Display
import android.view.View
import android.view.WindowManager
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.session.SessionState
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.AtomicLong
class SecondScreenWindow(
private val sessionActivity: SessionActivity,
val display: Display,
private val sendPointer: (Float, Float, Float, Float) -> Unit,
private val sendButton: (Int, Boolean) -> Unit,
private val sendWheel: (Int) -> Unit,
private val onSteamMenu: () -> Unit,
private val onQam: () -> Unit,
private val onClose: () -> Unit,
private val pad: PadBridge? = null,
) {
private val token = tokens.incrementAndGet()
private var activity = WeakReference<SecondScreenActivity>(null)
private var controls: SecondScreenControls? = null
private var mode = SecondScreenMode.NONE
private var launching = false
private var closed = false
val window get() = activity.get()?.window
val isShowing get() = !closed && (launching || activity.get()?.isFinishing == false)
fun show() {
if (isShowing || closed) return
owners[token] = WeakReference(this)
launching = true
try {
val intent = Intent(sessionActivity, SecondScreenActivity::class.java)
.putExtra(OWNER, token)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
sessionActivity.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display.displayId).toBundle())
} catch (error: Exception) {
launching = false
owners.remove(token)
throw error
}
}
fun showMode(mode: SecondScreenMode) {
this.mode = mode
controls?.showMode(mode)
}
fun closeControls() {
closed = true
launching = false
owners.remove(token)
controls?.closeControls()
controls = null
activity.get()?.finishAndRemoveTask()
activity.clear()
}
internal fun attach(host: SecondScreenActivity): View {
controls?.closeControls()
activity = WeakReference(host)
launching = false
return SecondScreenControls(host, sessionActivity, sendPointer, sendButton, sendWheel,
onSteamMenu, onQam, onClose, pad).also {
controls = it
it.showMode(mode)
}
}
internal fun detach(host: SecondScreenActivity) {
if (activity.get() !== host) return
controls?.closeControls()
controls = null
activity.clear()
if (host.isFinishing && !closed) onClose()
}
internal fun refreshClipboard() = sessionActivity.refreshClipboard()
companion object {
private const val OWNER = "secondScreenOwner"
private val tokens = AtomicLong()
private val owners = mutableMapOf<Long, WeakReference<SecondScreenWindow>>()
internal fun find(intent: Intent): SecondScreenWindow? =
owners[intent.getLongExtra(OWNER, 0)]?.get()?.takeUnless { it.closed }
}
}
class SecondScreenActivity : Activity() {
private var owner: SecondScreenWindow? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val host = SecondScreenWindow.find(intent)
if (host == null || !SessionState.running) {
finishAndRemoveTask()
return
}
owner = host
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
setContentView(host.attach(this))
applyImmersiveMode()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
applyImmersiveMode()
owner?.refreshClipboard()
}
}
@Deprecated("Back is handled by the session controls")
override fun onBackPressed() = Unit
override fun onDestroy() {
owner?.detach(this)
owner = null
super.onDestroy()
}
private fun applyImmersiveMode() {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
}
}
@@ -27,6 +27,7 @@ import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.icons.filled.Pause
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.Icon
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
@@ -68,6 +69,8 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
@@ -78,21 +81,93 @@ import androidx.compose.ui.text.style.TextOverflow
@Composable
fun HudText(text: String) {
fun HudText(text: String, graph: FloatArray = FloatArray(0), color: String = "mint", opacity: Int = 70) {
if (text.isEmpty() && graph.size < 2) return
val accent = hudInk(color)
val wash = (opacity.coerceIn(30, 100) / 100f)
val ink = accent.copy(alpha = (0.5f + wash * 0.5f).coerceIn(0.62f, 1f))
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) {
Text(
text,
fontFamily = FontFamily.Monospace,
fontSize = 12.sp,
color = Color.White,
Column(
horizontalAlignment = Alignment.End,
modifier = Modifier
.padding(12.dp)
.background(Color(0x8C000000))
.padding(horizontal = 8.dp, vertical = 3.dp),
)
.background(
Brush.verticalGradient(
listOf(accent.copy(alpha = wash * 0.28f), Color.Black.copy(alpha = wash * 0.72f)),
),
RoundedCornerShape(8.dp),
)
.padding(horizontal = 8.dp, vertical = 5.dp),
) {
if (text.isNotEmpty()) Text(
text,
fontFamily = FontFamily.Monospace,
fontSize = 12.sp,
color = ink,
textAlign = TextAlign.End,
)
if (graph.size >= 2) {
if (text.isNotEmpty()) Spacer(Modifier.height(4.dp))
HudGraph(graph, accent, wash)
}
}
}
}
@Composable
private fun HudGraph(samples: FloatArray, accent: Color, wash: Float) {
Canvas(Modifier.width(148.dp).height(44.dp)) {
val maxMs = (samples.maxOrNull() ?: 16.7f).coerceAtLeast(16.7f)
val step = size.width / (samples.size - 1)
fun yOf(ms: Float) = size.height * (1f - (ms / maxMs).coerceIn(0f, 1f))
val fillAlpha = wash * 0.5f
val fill = Path().apply {
moveTo(0f, size.height)
samples.forEachIndexed { i, ms -> lineTo(i * step, yOf(ms)) }
lineTo(size.width, size.height)
close()
}
drawPath(
fill,
Brush.verticalGradient(listOf(HUD_SLOW.copy(alpha = fillAlpha), accent.copy(alpha = fillAlpha * 0.45f))),
)
val guide = yOf(16.7f)
drawLine(Color.White.copy(alpha = 0.32f), Offset(0f, guide), Offset(size.width, guide), strokeWidth = 1f)
for (i in 0 until samples.lastIndex) {
val tone = ((samples[i] - 8f) / 25f).coerceIn(0f, 1f)
drawLine(
mix(accent, HUD_SLOW, tone).copy(alpha = 0.55f + wash * 0.4f),
Offset(i * step, yOf(samples[i])),
Offset((i + 1) * step, yOf(samples[i + 1])),
strokeWidth = 2.5f,
cap = StrokeCap.Round,
)
}
}
}
private fun hudInk(color: String): Color = Color(
when (color) {
"white" -> 0xFFF2F5F8
"sky" -> 0xFF66C0F4
"amber" -> 0xFFFFB74D
"violet" -> 0xFFD0A2FF
else -> 0xFF3DDC84
}.toInt(),
)
private fun mix(from: Color, to: Color, t: Float): Color {
val u = t.coerceIn(0f, 1f)
return Color(
red = from.red + (to.red - from.red) * u,
green = from.green + (to.green - from.green) * u,
blue = from.blue + (to.blue - from.blue) * u,
alpha = 1f,
)
}
private val HUD_SLOW = Color(0xFFFF5C6C.toInt())
private class LoadStage(@androidx.annotation.StringRes val label: Int, @androidx.annotation.StringRes val detail: Int)
private fun loadStages(steam: Boolean): List<LoadStage> = if (steam) listOf(
@@ -122,6 +197,7 @@ fun LoadingOverlay(
title: String = stringResource(R.string.load_starting_steam), steam: Boolean = true, onCancel: (() -> Unit)? = null,
endedDetail: String? = null,
onRetry: (() -> Unit)? = null,
onRepair: (() -> Unit)? = null,
onShareLogs: (() -> Unit)? = null,
onClose: (() -> Unit)? = null,
flood: Color? = null,
@@ -145,7 +221,7 @@ fun LoadingOverlay(
modifier = Modifier
.fillMaxSize()
.background(colors.background)
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {},
.blockTouches(),
) {
CapsuleWall(games, driftMs = 65_000, modifier = Modifier.alpha(0.3f))
Box(
@@ -187,7 +263,7 @@ fun LoadingOverlay(
textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 12.dp).widthIn(max = 520.dp),
)
if (ended) EndedActions(onRetry, onShareLogs, onClose)
if (ended) EndedActions(onRetry, onRepair, onShareLogs, onClose)
}
if (!ended && hint.isNotEmpty()) Text(
hint, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant.copy(alpha = 0.8f), textAlign = TextAlign.Center,
@@ -200,7 +276,7 @@ fun LoadingOverlay(
}
@Composable
private fun EndedActions(onRetry: (() -> Unit)?, onShareLogs: (() -> Unit)?, onClose: (() -> Unit)?) {
private fun EndedActions(onRetry: (() -> Unit)?, onRepair: (() -> Unit)?, onShareLogs: (() -> Unit)?, onClose: (() -> Unit)?) {
val first = remember { FocusRequester() }
LaunchedEffect(Unit) {
androidx.compose.runtime.withFrameNanos { }
@@ -209,7 +285,11 @@ private fun EndedActions(onRetry: (() -> Unit)?, onShareLogs: (() -> Unit)?, onC
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(top = 22.dp)) {
var firstUsed = false
fun claim(): Modifier = if (firstUsed) Modifier else { firstUsed = true; Modifier.focusRequester(first) }
if (onRetry != null) PrimaryButton(stringResource(R.string.store_try_again), modifier = claim(), onClick = onRetry)
if (onRepair != null) PrimaryButton(stringResource(R.string.runtime_repair), modifier = claim(), onClick = onRepair)
if (onRetry != null) {
if (onRepair != null) SecondaryButton(stringResource(R.string.store_try_again), modifier = claim(), onClick = onRetry)
else PrimaryButton(stringResource(R.string.store_try_again), modifier = claim(), onClick = onRetry)
}
if (onShareLogs != null) SecondaryButton(stringResource(R.string.drawer_share_logs), modifier = claim(),
progress = com.droiddeck.launcher.session.SessionLogShare.progress, onClick = onShareLogs)
if (onClose != null) SecondaryButton(stringResource(R.string.mode_back), modifier = claim(), onClick = onClose)
@@ -270,7 +350,6 @@ private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
fun SessionPausedOverlay(title: String = stringResource(R.string.load_steam_paused), onResume: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val interactionSource = remember { MutableInteractionSource() }
val resumeFocus = remember { FocusRequester() }
LaunchedEffect(Unit) {
androidx.compose.runtime.withFrameNanos { }
@@ -280,7 +359,7 @@ fun SessionPausedOverlay(title: String = stringResource(R.string.load_steam_paus
modifier = Modifier
.fillMaxSize()
.background(pal.background.copy(alpha = 0.94f))
.clickable(interactionSource = interactionSource, indication = null) {},
.blockTouches(),
contentAlignment = Alignment.Center,
) {
Column(
@@ -103,6 +103,7 @@ import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.ui.focus.focusProperties
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
@@ -110,6 +111,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -195,6 +197,11 @@ class DrawerActions(
val isHomeApp: Boolean,
val androidApps: List<HomeApp.LaunchableApp>,
val hudOn: Boolean,
val hudFps: Boolean = true,
val hudBattery: Boolean = true,
val hudGraph: Boolean = true,
val hudColor: String = SessionPrefs.HUD_COLOR_MINT,
val hudOpacity: Int = SessionPrefs.HUD_OPACITY_DEFAULT,
val frameGen: FrameGen.Mode,
val lossless: Lossless.State,
val oscMode: String,
@@ -222,6 +229,11 @@ class DrawerActions(
val secondScreenDisplays: List<SecondScreenDisplay>,
val selectedSecondScreenDisplay: Int,
val onHud: (Boolean) -> Unit,
val onHudFps: (Boolean) -> Unit = {},
val onHudBattery: (Boolean) -> Unit = {},
val onHudGraph: (Boolean) -> Unit = {},
val onHudColor: (String) -> Unit = {},
val onHudOpacity: (Int) -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onImportLossless: () -> Unit,
val onKeyboard: () -> Unit,
@@ -245,6 +257,7 @@ class DrawerActions(
val onLowLatencyController: (Boolean) -> Unit = {},
val onLowLatencyTouch: (Boolean) -> Unit = {},
val onTouch: (String) -> Unit,
val onGestureSettings: () -> Unit = {},
val onFexPreset: (String) -> Unit,
val onUpscaler: (Int) -> Unit = {},
val onUpscaleSharpness: (Int) -> Unit = {},
@@ -300,14 +313,14 @@ class DrawerActions(
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions) {
val pages = sessionDrawerPages(a.steam && a.secondScreenDisplays.isNotEmpty(), a.glassesPresent)
val pages = sessionDrawerPages(a.secondScreenDisplays.isNotEmpty(), a.glassesPresent)
val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER
LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) }
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val host = rememberMenuHost()
val (glasses, glassesSettings) = rememberGlasses()
val glassesPages = glassesTabs(glasses)
val glassesPages = glassesTabs(glasses) + (GlassesTab.CONTROLLERS to stringResource(R.string.vr_controllers_tab))
var selectedGlassesTab by rememberSaveable { mutableStateOf(GlassesTab.DISPLAY) }
val glassesTab = selectedGlassesTab.takeIf { key -> glassesPages.any { it.first == key } } ?: GlassesTab.DISPLAY
var androidAppsExpanded by rememberSaveable { mutableStateOf(false) }
@@ -372,10 +385,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
focus.request(first)
}
}
if (open || veil > 0.01f) Box(
modifier = Modifier.fillMaxSize()
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() },
)
if (open || veil > 0.01f) {
val closeLabel = stringResource(R.string.common_close)
Box(
modifier = Modifier.fillMaxSize()
.focusProperties { canFocus = false }
.semantics { contentDescription = closeLabel }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClickLabel = closeLabel) { host.open = null; a.onClose() },
)
}
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
val short = maxHeight < 440.dp
val sheetWidth = minOf(360.dp, maxWidth * 0.92f)
@@ -389,7 +407,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
modifier = Modifier
.fillMaxSize()
.background(pal.background.copy(alpha = 0.97f))
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
.blockTouches()
.focusGroup()
.controllerBack {
if (host.open != null) host.open = null else a.onClose()
@@ -461,6 +479,30 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SettingsGroup(stringResource(R.string.drawer_page_display)) {
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn,
chipModifier = focus.track(page, "hud"), onChange = a.onHud)
if (a.hudOn) {
ToggleRow(host, "hud-fps", stringResource(R.string.drawer_hud_fps), null, a.hudFps,
chipModifier = focus.track(page, "hud-fps"), onChange = a.onHudFps)
ToggleRow(host, "hud-battery", stringResource(R.string.drawer_hud_battery), null, a.hudBattery,
chipModifier = focus.track(page, "hud-battery"), onChange = a.onHudBattery)
ToggleRow(host, "hud-graph", stringResource(R.string.drawer_hud_graph), null, a.hudGraph,
chipModifier = focus.track(page, "hud-graph"), onChange = a.onHudGraph)
ChoiceRow(
host, "hud-color", stringResource(R.string.drawer_hud_color), null,
listOf(
SessionPrefs.HUD_COLOR_MINT to stringResource(R.string.drawer_hud_color_mint),
"white" to stringResource(R.string.drawer_hud_color_white),
"sky" to stringResource(R.string.drawer_hud_color_sky),
"amber" to stringResource(R.string.drawer_hud_color_amber),
"violet" to stringResource(R.string.drawer_hud_color_violet),
),
a.hudColor, chipModifier = focus.track(page, "hud-color"), onPick = a.onHudColor,
)
SliderRow(
stringResource(R.string.drawer_hud_opacity), null, a.hudOpacity,
SessionPrefs.HUD_OPACITY_RANGE, step = 10, format = { "$it%" },
modifier = focus.track(page, "hud-opacity"), onChange = a.onHudOpacity,
)
}
val fgOpen = host.open == "fg"
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) {
@@ -500,8 +542,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
type, chipModifier = focus.track(page, "pad-type"), onPick = a.onPadType)
}
ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
ActionRow(stringResource(R.string.gesture_settings), stringResource(R.string.gesture_settings_hint),
stringResource(R.string.ctrl_edit), a.onGestureSettings,
modifier = focus.track(page, "gesture-settings"))
ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null,
if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
@@ -553,7 +598,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SessionDrawerPage.SECOND_SCREEN -> {
SecondScreenGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.GLASSES -> {
SessionDrawerPage.GLASSES -> if (glassesTab == GlassesTab.CONTROLLERS) {
VrControllerGroups(host) { key -> focus.track(page, key) }
} else {
GlassesGroups(host, glasses, glassesSettings, { key -> focus.track(page, key) }, onRecenter = a.onGlassesRecenter,
tab = glassesTab, outputActive = a.glassesOutput, steamVrRunning = a.steamVr == SteamVr.Status.RUNNING,
steamVr = { SteamVrRow(a) })
@@ -707,7 +754,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.
modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.16f) else colors.surfaceVariant)
.glideBorder(hot, shape, pal.signal)
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, onClick = onClick)
.hoverable(source).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick).padding(horizontal = 16.dp, vertical = 10.dp),
) {
Icon(icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(22.dp))
@@ -744,7 +791,7 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
.clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f))
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(start = 12.dp, end = 14.dp),
) {
@@ -770,7 +817,7 @@ private fun SteamActionPill(
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(interactionSource)
.clickable(interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onConfirm ?: onClick),
) {
Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp))
@@ -789,7 +836,7 @@ private fun DrawerBumper(label: String, description: String, modifier: Modifier
contentAlignment = Alignment.Center,
modifier = modifier.size(44.dp).clip(ring)
.glideBorder(hot, ring, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = null, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description },
) {
@@ -810,7 +857,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
val motion = Motion.tw<Float>(340, easing = FastOutSlowInEasing)
androidx.compose.foundation.layout.BoxWithConstraints(
contentAlignment = Alignment.Center,
modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(),
modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds().selectableGroup(),
) {
val tab = if (compact) 36f else 44f
val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(24f, DRAWER_TAB_SPACING_DP)
@@ -843,7 +890,7 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
.semantics { contentDescription = pageDescription }
.testTag("drawer-tab-${item.name.lowercase()}")
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, interactionSource = source, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
) {
Icon(item.icon, contentDescription = null, tint = tint, modifier = Modifier.size(if (compact) 22.dp else 30.dp))
@@ -1375,6 +1422,7 @@ internal fun ComponentDownloadsDrawerGroup(
) {
val colors = MaterialTheme.colorScheme
val installed = packages.map { it.file }.toSet()
val nightlyPicked = remember { mutableStateMapOf<String, Boolean>() }
SettingsGroup(stringResource(R.string.drawer_component_downloads)) {
Text(stringResource(R.string.drawer_component_downloads_hint), fontSize = 12.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
@@ -1398,21 +1446,40 @@ internal fun ComponentDownloadsDrawerGroup(
}
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null },
title = ComponentsManager.LABEL.getValue(comp)) { firstItemFocus ->
val firstAvailable = items.firstOrNull { ComponentsManager.safeName(it.file) !in installed && it.file !in downloads }
items.forEach { item ->
// A nightly paired with a stable build rides on that row; Stable/Nightly tabs beside the row pick which one.
val pairs = ComponentsManager.nightlyPairs(items)
val rows = items.filter { it !in pairs.values }
fun shown(row: ComponentsManager.CatalogItem) = pairs[row]?.takeIf { nightlyPicked[row.file] == true } ?: row
val firstAvailable = rows.firstOrNull { shown(it).let { s -> ComponentsManager.safeName(s.file) !in installed && s.file !in downloads } }
rows.forEach { row ->
val item = shown(row)
val nightly = pairs[row]
val stored = ComponentsManager.safeName(item.file) in installed
val progress = downloads[item.file]
MenuItem(item.file.removeSuffix(".wcp"), checked = stored,
enabled = !stored && progress == null,
detail = when {
stored -> stringResource(R.string.wincomp_downloaded)
progress != null -> if (progress < 0) stringResource(R.string.wincomp_downloading, item.file.removeSuffix(".wcp")) else "$progress%"
else -> item.release + " · " + stringResource(R.string.common_size_mb, item.size / 1048576.0)
},
focusRequester = if (item == firstAvailable) firstItemFocus else null,
) {
onDownload(item)
host.open = null
val choose = @Composable { rowModifier: Modifier ->
MenuItem(item.file.removeSuffix(".wcp"), checked = stored,
enabled = !stored && progress == null,
detail = when {
stored -> stringResource(R.string.wincomp_downloaded)
progress != null -> if (progress < 0) stringResource(R.string.wincomp_downloading, item.file.removeSuffix(".wcp")) else "$progress%"
else -> item.release + " · " + stringResource(R.string.common_size_mb, item.size / 1048576.0)
},
focusRequester = if (row == firstAvailable) firstItemFocus else null,
modifier = rowModifier,
) {
onDownload(item)
host.open = null
}
}
if (nightly == null) choose(Modifier)
else Row(verticalAlignment = Alignment.CenterVertically) {
choose(Modifier.weight(1f))
TabStrip(
listOf(stringResource(R.string.comp_channel_stable), stringResource(R.string.comp_channel_nightly)),
selected = if (item === nightly) 1 else 0,
onSelect = { nightlyPicked[row.file] = it == 1 },
bumpers = false, compact = true, modifier = Modifier.padding(start = 6.dp, end = 4.dp),
)
}
}
}
@@ -1637,7 +1704,7 @@ private fun ConfirmChoice(label: String, danger: Boolean, enabled: Boolean, modi
.background(if (hot) accent.copy(alpha = if (danger) 0.18f else 0.14f) else Color.Transparent)
.glideBorder(hot, shape, accent)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 16.dp),
) {
@@ -34,7 +34,11 @@ import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
@@ -141,6 +145,11 @@ internal fun Modifier.controllerBack(onBack: () -> Unit): Modifier = onPreviewKe
}
}
internal fun Modifier.blockTouches(): Modifier = pointerInput(Unit) { detectTapGestures { } }
internal fun Modifier.tapOutside(onTap: () -> Unit): Modifier =
pointerInput(onTap) { detectTapGestures(onTap = { onTap() }) }
internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event ->
val keyEvent = event.nativeKeyEvent
val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1
@@ -157,6 +166,7 @@ internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modif
internal fun TabStrip(
tabs: List<String>, selected: Int, onSelect: (Int) -> Unit,
modifier: Modifier = Modifier, focusRequesters: List<FocusRequester>? = null,
bumpers: Boolean = true, compact: Boolean = false,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -164,12 +174,12 @@ internal fun TabStrip(
val scroll = rememberScrollState()
var tight by remember(tabs) { mutableStateOf(false) }
LaunchedEffect(scroll.maxValue) { if (scroll.maxValue in 1 until Int.MAX_VALUE) tight = true }
val tabPadding = if (tight) 10.dp else 16.dp
val tabPadding = if (compact) 10.dp else if (tight) 10.dp else 16.dp
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) {
BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) }
if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) }
Row(
modifier = Modifier.weight(1f, fill = false).clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape)
.horizontalScroll(scroll).padding(3.dp),
.horizontalScroll(scroll).selectableGroup().padding(3.dp),
) {
tabs.forEachIndexed { i, label ->
val on = i == selected
@@ -180,7 +190,7 @@ internal fun TabStrip(
val reveal = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() }
if (on) LaunchedEffect(Unit) { reveal.bringIntoView() }
Text(
label, fontSize = 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1,
label, fontSize = if (compact) 12.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1,
color = if (on) pal.onSignal else if (hot) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier
.bringIntoViewRequester(reveal)
@@ -189,13 +199,13 @@ internal fun TabStrip(
.clip(tabShape)
.background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(hot, tabShape, if (on) colors.onBackground else pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = tabPadding, vertical = 12.dp),
.padding(horizontal = tabPadding, vertical = if (compact) 6.dp else 12.dp),
)
}
}
BumperKey("RB", stringResource(R.string.widgets_next_tab)) { onSelect((selected + 1) % tabs.size) }
if (bumpers) BumperKey("RB", stringResource(R.string.widgets_next_tab)) { onSelect((selected + 1) % tabs.size) }
}
}
@@ -359,7 +369,7 @@ fun MenuItem(
.clip(RoundedCornerShape(8.dp))
.background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent)
.alpha(if (enabled) 1f else 0.4f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 10.dp, vertical = 9.dp),
) {
@@ -392,7 +402,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
.background(colors.surfaceVariant)
.glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, if (open) pal.signal else pal.line2)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
@@ -648,8 +658,8 @@ fun MultiRow(
}
@Composable
fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit, progress: Float? = null) {
SettingsRow(label, hint) { SecondaryButton(button, progress = progress, onClick = onClick) }
fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit, progress: Float? = null, modifier: Modifier = Modifier) {
SettingsRow(label, hint) { SecondaryButton(button, modifier = modifier, progress = progress, onClick = onClick) }
}
@Composable
@@ -783,7 +793,7 @@ fun <T> SegmentedTabs(options: List<Pair<T, String>>, selected: T?, modifier: Mo
.graphicsLayer { alpha = shown }
.clip(pillShape).background(pal.signal),
)
Row {
Row(Modifier.selectableGroup()) {
options.forEachIndexed { i, (value, label) ->
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
@@ -802,9 +812,8 @@ fun <T> SegmentedTabs(options: List<Pair<T, String>>, selected: T?, modifier: Mo
modifier = tabModifier(value).width(segment).fillMaxHeight()
.clip(pillShape)
.glideBorder(hot, pillShape, if (chosen) pal.onSignal else pal.signal)
.semantics { role = Role.Tab; this.selected = chosen }
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, onClick = pick)
.selectable(selected = chosen, role = Role.Tab, interactionSource = src, indication = LocalIndication.current, onClick = pick)
.controllerConfirm(onClick = pick),
) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = ink, maxLines = 1, softWrap = false)
@@ -29,13 +29,13 @@ import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.glasses.CalibrationDistance
import com.droiddeck.launcher.handtracking.TrackingPack
import com.droiddeck.launcher.glasses.Glasses
import com.droiddeck.launcher.glasses.SpatialCalibrationProgress
import com.droiddeck.launcher.glasses.SpatialTracking
import com.droiddeck.launcher.glasses.SpatialTrackingStatus
import com.droiddeck.launcher.glasses.StereoCalibrator
import kotlinx.coroutines.delay
import org.opencv.android.OpenCVLoader
import org.opencv.android.Utils
import org.opencv.core.Mat
import org.opencv.core.Size
@@ -95,7 +95,7 @@ class SpatialTrackingActivity : ComponentActivity() {
}
override fun onPause() { SpatialTracking.diagnostics(false);super.onPause() }
private fun printBoard() {
if(!OpenCVLoader.initLocal()) return
if(!TrackingPack.loadNative(this)) return
val c=StereoCalibrator(this);val mat=Mat()
c.board.generateImage(Size(1500.0,2100.0),mat,0,1)
val bitmap=Bitmap.createBitmap(1500,2100,Bitmap.Config.ARGB_8888)
@@ -115,13 +115,14 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
drop = drop.takeIf { headset },
overlay = { lifted ->
if (headset) DropSheet(
drop, glassesTabs(glasses), covered = lifted,
drop, glassesTabs(glasses) + (GlassesTab.CONTROLLERS to stringResource(R.string.vr_controllers_tab)), covered = lifted,
button = { enabled ->
PrimaryButton(stringResource(R.string.games_play_steamvr), enabled = !s.busy && glasses.usable, large = true, icon = Icons.Filled.PlayArrow, fill = true,
modifier = Modifier.fillMaxWidth().testTag("play-steamvr")) { if (enabled) { drop.open = false; a.onPlaySteamVr() } }
},
) { tab ->
GlassesGroups(rememberMenuHost(), glasses, glassesSettings,
if (tab == GlassesTab.CONTROLLERS) VrControllerGroups(rememberMenuHost())
else GlassesGroups(rememberMenuHost(), glasses, glassesSettings,
onRecenter = GlassesMenuMirror::recenter, inSession = false, tab = tab)
}
},
@@ -781,17 +781,18 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
}
@Composable
private fun ComponentsView(report: StorageReport, sessionRunning: Boolean, onBack: () -> Unit) {
internal fun ComponentsView(report: StorageReport, sessionRunning: Boolean, onBack: () -> Unit) {
val ctx = LocalContext.current
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val busy = sessionRunning || StorageState.cleaning
var confirm by remember { mutableStateOf<ComponentUsage?>(null) }
var confirmAll by remember { mutableStateOf(false) }
val unused = report.unusedComponents
SubHeader(stringResource(R.string.storage_components),
stringResource(R.string.storage_tools_detail, gb(report.components.sumOf { it.bytes }), gb(unused.sumOf { it.bytes })), onBack) {
if (unused.isNotEmpty()) PrimaryButton(stringResource(R.string.storage_remove_unused, gb(unused.sumOf { it.bytes })), compact = true, enabled = !busy) {
StorageState.clean(ctx, setOf(CleanItem.UNUSED_COMPONENTS)) { }
confirmAll = true
}
}
ActionStatus()
@@ -824,6 +825,19 @@ private fun ComponentsView(report: StorageReport, sessionRunning: Boolean, onBac
stringResource(if (c.packageFile != null) R.string.storage_component_confirm else R.string.storage_original_confirm, gb(c.bytes)),
stringResource(R.string.storage_remove), onConfirm = { StorageState.removeComponent(ctx, c) }, onDismiss = { confirm = null })
}
if (confirmAll) {
val total = gb(unused.sumOf { it.bytes })
val lines = unused.map { "• " + componentLabel(it) + " " + gb(it.bytes) }.joinToString("\n")
val warning = stringResource(
if (unused.any { it.packageFile != null }) R.string.storage_component_confirm else R.string.storage_original_confirm, total)
ConfirmDialog(
stringResource(R.string.storage_remove_unused, total),
lines + "\n\n" + warning,
stringResource(R.string.storage_remove),
onConfirm = { StorageState.clean(ctx, setOf(CleanItem.UNUSED_COMPONENTS)) { } },
onDismiss = { confirmAll = false },
)
}
}
@Composable
@@ -303,7 +303,7 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
val slide = remember { MutableTransitionState(false).apply { targetState = true } }
BoxWithConstraints(
Modifier.fillMaxSize().background(veil)
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onClose),
.tapOutside(onClose),
contentAlignment = Alignment.CenterEnd,
) {
val short = maxHeight < 440.dp
@@ -312,7 +312,7 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
(if (floating) Modifier.padding(12.dp).fillMaxHeight().width(minOf(420.dp, maxWidth * 0.92f)).clip(RoundedCornerShape(20.dp))
.background(pal.background).border(1.dp, pal.line2, RoundedCornerShape(20.dp))
else Modifier.fillMaxHeight().width(minOf(420.dp, maxWidth * 0.92f)).background(pal.background.copy(alpha = 0.97f)))
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
.blockTouches()
.controllerBack(onClose)
.then(if (kinds.isEmpty()) Modifier else Modifier.bumpers({ pick = (pick + kinds.size - 1) % kinds.size }, { pick = (pick + 1) % kinds.size }))
.padding(if (short) 12.dp else 16.dp),
@@ -370,7 +370,7 @@ internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier
modifier = modifier.fillMaxWidth().height(44.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.glideBorder(hot, shape, pal.signal, pal.line)
.clickable(interactionSource = interaction, indication = LocalIndication.current, onClick = onClick)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interaction, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp),
) {
@@ -29,6 +29,7 @@ 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))
Store.XBOX.id -> SourceColours(Color(0xFF17381B), Color(0xFFC6EDC2), Color(0xFF70C850))
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
@@ -41,6 +42,7 @@ internal fun sourceLabel(source: String): String = when (source) {
Store.GOG.id -> Store.GOG.label
Store.EPIC.id -> Store.EPIC.label
Store.AMAZON.id -> Store.AMAZON.label
Store.XBOX.id -> Store.XBOX.label
Store.ITCH.id -> Store.ITCH.label
else -> stringResource(R.string.source_added)
}
@@ -23,6 +23,8 @@ 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.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
@@ -49,7 +51,6 @@ 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.StoreAchievements
import com.droiddeck.launcher.stores.StoresState
@@ -66,7 +67,7 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
val narrow = LocalNarrowPane.current
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
val id = key.substringAfter(':')
val item = (StoresState.library[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
val item = StoresState.detailItem(store, id)
val installed = StoresState.installedGame(store, id)
val rawDownload = StoresState.download("${store.id}:$id")
val download = rawDownload?.takeIf { it.isActive }
@@ -84,18 +85,24 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
.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())
// The card it came from keeps its own bitmap under the hero until the wide art is decoded.
val heroArt = cardArtRequest(art, item?.tallImageUrl)
if (heroArt != null) AsyncImage(model = heroArt, 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)))
if (scores != null && !stacked) {
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0.45f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp))
}
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp)) {
val passName = item?.includedWith.orEmpty()
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
failedDownload != null && failedDownload.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + failedDownload.location
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
item?.subscription == true -> passName.ifBlank { "PC Game Pass" }
passName.isNotBlank() -> "Available with $passName"
item?.accessible == 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) } ?: ""
@@ -115,10 +122,22 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
Actions {
when {
installed != null -> {
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
val gone = StoresState.uninstalling["${store.id}:$id"]
PrimaryButton(stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && (store != Store.XBOX || !com.droiddeck.launcher.stores.xbox.XboxContent.busy(id)), main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) {
launchStoreGame(ctx, store, id, s, a)
}
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
if (store == Store.XBOX) {
SecondaryButton("Update / verify", enabled = download == null && !com.droiddeck.launcher.stores.xbox.XboxRuntime.isActive(id)) {
runCatching { com.droiddeck.launcher.stores.xbox.XboxBackend.update(ctx, installed) }
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: "Close this Xbox game before updating it." }
}
SecondaryButton("Manage content", enabled = download == null) {
com.droiddeck.launcher.stores.xbox.XboxContent.manage(ctx, installed)
}
}
if (gone != null) SecondaryButton(stringResource(R.string.stores_uninstalling), enabled = false, progress = gone) {}
else UninstallButton(title, installed, enabled = download == null, modifier = leadOn) {
else UninstallButton(title, installed, enabled = download == null && (store != Store.XBOX || !com.droiddeck.launcher.stores.xbox.XboxContent.busy(id))) {
StoresState.uninstall(ctx, installed) { StoresState.refresh(ctx); a.onLibraryChanged() }
}
}
@@ -138,14 +157,25 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
com.droiddeck.launcher.stores.download.DownloadQueue.clear(ctx, failedDownload.key)
}
}
item?.owned == true && StoresState.isUnfinished(item) -> {
item?.installable == true && StoresState.isUnfinished(item) -> {
InstallButton(stringResource(R.string.stores_resume_install), leadOn) { 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 -> InstallButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
leadOn,
) { StoresState.requestInstall(ctx, item) }
item?.installable == true -> {
InstallButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
leadOn,
) { StoresState.requestInstall(ctx, item) }
if (!item.accessible) {
SecondaryButton(
when {
item.isFree -> stringResource(R.string.stores_get_free)
item.hasPrice && item.finalPrice.isNotBlank() -> stringResource(R.string.stores_buy_price, item.finalPrice)
else -> stringResource(R.string.stores_view_on, store.shortLabel)
},
) { openStoreUrl(ctx, item) }
}
}
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { 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, modifier = leadOn) { openStoreUrl(ctx, item) }
}
@@ -156,7 +186,7 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
}
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
if (scores != null) Rise(2) {
val listed = StoresState.shelves[store]?.all.orEmpty().firstOrNull { it.id == id }
val listed = (StoresState.found[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
val developer = item?.developer?.ifBlank { null } ?: listed?.developer.orEmpty()
val publisher = item?.publisher?.ifBlank { null } ?: listed?.publisher.orEmpty()
val releaseDate = item?.releaseDate?.ifBlank { null } ?: listed?.releaseDate.orEmpty()
@@ -164,10 +194,10 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
}
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
val achievements = remember(store, id, item?.owned, installed) {
val achievements = remember(store, id, item?.accessible, installed) {
when {
StoreAchievements.forSource(store.id) == null -> null
item?.owned == true -> StoreAchievements.Game.of(item)
item?.accessible == true -> StoreAchievements.Game.of(item)
installed != null -> StoreAchievements.Game.of(installed.sidecar)
else -> null
}
@@ -25,6 +25,7 @@ import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.geometry.Size
@@ -83,6 +84,7 @@ 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.StoreLanguage
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
@@ -483,7 +485,7 @@ internal fun DownloadControls(s: FrontEndState, a: FrontEndActions) {
}
}
internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<FrontEndState>, a: FrontEndActions, accent: androidx.compose.ui.graphics.Color): StepAsk =
internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<FrontEndState>, a: FrontEndActions, accent: androidx.compose.ui.graphics.Color, onArrange: () -> Unit): StepAsk =
StepAsk(
anchor = at, side = StepSide.Left, accent = accent, items = 2, maxWidth = 440.dp,
handle = { androidx.compose.material3.Icon(androidx.compose.material.icons.Icons.Filled.Settings, null, tint = accent, modifier = Modifier.size(20.dp)) },
@@ -494,6 +496,13 @@ internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<Fron
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
val st = s.value
val context = androidx.compose.ui.platform.LocalContext.current
SettingsRow(stringResource(R.string.stores_tabs_arrange), null) {
RoundAction(Icons.Filled.SwapHoriz, stringResource(R.string.stores_tabs_arrange), size = 36.dp) {
StoresMotion.fold()
onArrange()
}
}
SettingsRow(stringResource(R.string.setup_stores_open_on), null, stacked = true) {
Box(Modifier.focusRequester(first).focusGroup()) { SegmentedTabs(
listOf(SessionPrefs.STORES_OPEN_LIBRARY to stringResource(R.string.stores_tab_library), SessionPrefs.STORES_OPEN_STORE to stringResource(R.string.stores_tab_store)),
@@ -503,9 +512,37 @@ internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<Fron
SettingsRow(stringResource(R.string.stores_show_mature), null) {
ToggleSwitch(st.storesShowMature, label = stringResource(R.string.stores_show_mature)) { a.onStoresShowMature(it) }
}
var langOpen by remember { mutableStateOf(false) }
val storedLanguage = SessionPrefs.storesInstallLanguage(context)
var language by remember(storedLanguage, StoreLanguage.preferredCode(context)) { mutableStateOf(storedLanguage) }
SettingsRow(stringResource(R.string.stores_install_language), stringResource(R.string.stores_install_language_hint), stacked = true) {
Box {
ValueChip(
if (language.isEmpty()) stringResource(R.string.stores_install_language_system)
else StoreLanguage.displayName(language),
langOpen,
) { langOpen = !langOpen }
AnchoredMenu(langOpen, { langOpen = false }, title = stringResource(R.string.stores_install_language)) { first ->
val options = listOf("") + StoreLanguage.KNOWN
options.forEachIndexed { i, code ->
MenuItem(
if (code.isEmpty()) stringResource(R.string.stores_install_language_system) else StoreLanguage.displayName(code),
checked = language == code,
focusRequester = if (i == 0) first else null,
) {
language = code
SessionPrefs.setStoresInstallLanguage(context, code)
langOpen = false
}
}
}
}
}
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { DownloadControls(st, a) }
val context = androidx.compose.ui.platform.LocalContext.current
var gogAchievements by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(com.droiddeck.launcher.stores.gog.GogComet.enabled(context)) }
androidx.compose.runtime.LaunchedEffect(Unit) {
if (gogAchievements) com.droiddeck.launcher.core.AddonPack.COMET.ensure(context)
}
SettingsRow(stringResource(R.string.gog_achievements), stringResource(R.string.gog_achievements_hint)) {
ToggleSwitch(gogAchievements, label = stringResource(R.string.gog_achievements)) {
gogAchievements = it
@@ -25,7 +25,10 @@ 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
@@ -42,8 +45,12 @@ 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.StoreLanguage
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.gog.GogDownloadManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable
internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
@@ -55,7 +62,19 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
val remembered = remember { SessionPrefs.storesInstallTarget(ctx) }
val defaultIndex = targets.indexOfFirst { it.root.absolutePath == remembered }.coerceAtLeast(0)
val focus = remember { List(targets.size) { FocusRequester() } }
val askLanguage = StoreLanguage.selectable(item.store)
val preferredLanguage = StoreLanguage.preferredCode(ctx)
var languages by remember { mutableStateOf(StoreLanguage.fallbackList(item.store)) }
var chosen by remember(preferredLanguage) { mutableStateOf(StoreLanguage.pick(languages, preferredLanguage)) }
var menuOpen by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { focus[defaultIndex] } }
LaunchedEffect(item.key) {
if (item.store != com.droiddeck.launcher.stores.Store.GOG) return@LaunchedEffect
val listed = withContext(Dispatchers.IO) { GogDownloadManager.listLanguages(ctx, item.id) }
if (listed.isEmpty()) return@LaunchedEffect
languages = listed
chosen = StoreLanguage.pick(listed, chosen)
}
AppDialog(shown, close, "installWhere", wide = false, maxWidth = if (targets.size > 2) 600.dp else 440.dp) {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
@@ -65,11 +84,27 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
)
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),
modifier = Modifier.clip(Shape12).clickable(role = Role.Button, onClick = close).controllerConfirm(onClick = close).padding(horizontal = 10.dp, vertical = 6.dp),
)
}
}
Rise(1) {
if (askLanguage) Rise(1) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
Text(stringResource(R.string.stores_install_language), fontSize = 13.sp, color = colors.onSurfaceVariant)
Box(Modifier.weight(1f)) {
ValueChip(StoreLanguage.displayName(chosen).ifEmpty { chosen }, menuOpen, modifier = Modifier.fillMaxWidth()) { menuOpen = !menuOpen }
AnchoredMenu(menuOpen, { menuOpen = false }, title = stringResource(R.string.stores_install_language), compact = true) { first ->
languages.forEachIndexed { i, code ->
MenuItem(StoreLanguage.displayName(code).ifEmpty { code }, checked = code == chosen, focusRequester = if (i == 0) first else null) {
chosen = code
menuOpen = false
}
}
}
}
}
}
Rise(if (askLanguage) 2 else 1) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
targets.forEachIndexed { i, t ->
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
@@ -89,7 +124,7 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
warning = isLow, modifier = Modifier.weight(1f),
) {
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
StoresState.install(ctx, item, t.root)
StoresState.install(ctx, item, t.root, if (askLanguage) chosen else null)
close()
}
}
@@ -10,6 +10,7 @@ import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.outlined.Folder
@@ -24,10 +25,12 @@ import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.zIndex
import androidx.compose.ui.layout.boundsInParent
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.positionInRoot
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.epic.EpicClient
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
@@ -37,6 +40,7 @@ import androidx.compose.ui.layout.onGloballyPositioned
import android.view.KeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.draw.drawWithContent
@@ -56,6 +60,8 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
@@ -65,6 +71,8 @@ import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import kotlin.math.roundToInt
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
@@ -90,6 +98,7 @@ import androidx.compose.material.icons.automirrored.filled.Login
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.ViewList
import androidx.compose.material.icons.filled.ViewModule
import com.droiddeck.launcher.stores.sortCatalogItems
import com.droiddeck.launcher.stores.retainCatalogOrder
import androidx.compose.foundation.layout.widthIn
@@ -115,6 +124,7 @@ 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.lerp
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@@ -136,7 +146,9 @@ 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.StoreTab
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.arrangeStoreTabs
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
@@ -154,26 +166,97 @@ internal fun tabsFor(store: Store?): List<String> = if (store == Store.AMAZON) T
internal fun tabFor(store: Store?, tab: String): String = if (tab in tabsFor(store)) tab else "library"
private data class PaneKey(val chip: String, val tab: String, val signedIn: Boolean)
private data class PaneKey(val chip: String, val tab: String, val signedIn: Boolean, val accountsLoaded: Boolean)
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class, androidx.compose.animation.ExperimentalAnimationApi::class)
@Composable
internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
val ctx = LocalContext.current
com.droiddeck.launcher.stores.xbox.XboxContent.plan?.let { content ->
androidx.compose.material3.AlertDialog(
onDismissRequest = { com.droiddeck.launcher.stores.xbox.XboxContent.dismiss() },
title = { Text("Xbox content") },
text = { Column {
if (content.error != null) Text(content.error)
else if (content.offers.isEmpty()) Text("No licensed PC content packages are available for this game.")
content.offers.forEach { offer ->
androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxContent.install(ctx, offer.item) }) {
Text(offer.item.title + if (offer.installed) " · Update / verify" else " · Install")
}
}
} },
confirmButton = { androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxContent.dismiss() }) { Text(stringResource(android.R.string.ok)) } },
)
}
com.droiddeck.launcher.stores.xbox.XboxBackend.packageChoice?.let { pending ->
androidx.compose.material3.AlertDialog(
onDismissRequest = { com.droiddeck.launcher.stores.xbox.XboxBackend.dismissPackages() },
title = { Text("Choose PC content") },
text = { Column { pending.choices.forEach { choice ->
androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxBackend.selectPackage(ctx, choice) }) {
Text(choice.getString("title") + " (" + choice.getString("kind") + ")")
}
} } },
confirmButton = {},
dismissButton = { androidx.compose.material3.TextButton(onClick = { com.droiddeck.launcher.stores.xbox.XboxBackend.dismissPackages() }) { Text(stringResource(android.R.string.cancel)) } },
)
}
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
val padH = if (narrow) 14.dp else 22.dp
var chip by rememberSaveable { mutableStateOf(Store.GOG.id) }
val tabs = remember {
androidx.compose.runtime.mutableStateListOf<StoreTab>().apply {
addAll(arrangeStoreTabs(SessionPrefs.storesTabOrder(ctx), SessionPrefs.storesTabHidden(ctx)))
}
}
var chip by rememberSaveable { mutableStateOf(tabs.firstOrNull { it.shown }?.store?.id ?: Store.GOG.id) }
var arranging by remember { mutableStateOf(false) }
val shownStores = tabs.filter { it.shown }.map { it.store }
fun commitTabs() {
SessionPrefs.setStoresTabOrder(ctx, tabs.map { it.store.id })
SessionPrefs.setStoresTabHidden(ctx, tabs.filterNot { it.shown }.map { it.store.id }.toSet())
}
fun shiftTab(store: Store, delta: Int) {
val from = tabs.indexOfFirst { it.store == store }
val to = from + delta
if (from < 0 || to !in tabs.indices) return
tabs.add(to, tabs.removeAt(from))
commitTabs()
}
fun moveTab(store: Store, to: Int) {
val from = tabs.indexOfFirst { it.store == store }
if (from < 0) return
val target = to.coerceIn(0, tabs.lastIndex)
if (target == from) return
tabs.add(target, tabs.removeAt(from))
commitTabs()
}
fun toggleTab(store: Store) {
val i = tabs.indexOfFirst { it.store == store }
if (i < 0) return
val show = !tabs[i].shown
if (!show && tabs.count { it.shown } <= 1) return
tabs[i] = tabs[i].copy(shown = show)
commitTabs()
}
LaunchedEffect(tabs.map { it.store to it.shown }, chip) {
val picked = Store.byId(chip) ?: return@LaunchedEffect
if (tabs.none { it.store == picked && it.shown }) chip = tabs.firstOrNull { it.shown }?.store?.id ?: chip
}
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) }
val liveState = androidx.compose.runtime.rememberUpdatedState(s)
LaunchedEffect(StoresState.openDownloads) { if (StoresState.openDownloads) { chip = DOWNLOADS; StoresState.openDownloads = false } }
val store = Store.byId(chip)
LaunchedEffect(tabs.toList()) {
if (chip != DOWNLOADS && Store.byId(chip) !in shownStores) chip = shownStores.firstOrNull()?.id ?: DOWNLOADS
}
val shownTab = tabFor(store, tab)
val pane = PaneKey(
chip, if (store == null) "" else shownTab,
store == null || (StoresState.isSignedIn(store) && StoresState.expired[store] != true),
store == null || StoresState.accountsLoaded,
)
val grids = remember { HashMap<PaneKey, LazyGridState>() }
val grid = grids.getOrPut(pane) { LazyGridState() }
@@ -215,7 +298,8 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
}
val pal = LocalPalette.current
fun cycleStore(step: Int) {
val ids = Store.entries.map { it.id }
val ids = tabs.filter { it.shown }.map { it.store.id }
if (ids.isEmpty()) return
val at = ids.indexOf(chip)
pickChip(ids[if (at < 0) (if (step > 0) 0 else ids.size - 1) else (at + step + ids.size) % ids.size])
}
@@ -223,6 +307,16 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
if (chip != st.id) pickChip(st.id) else move("first")
}
BackHandler(enabled = openGame != null) { closeGame() }
BackHandler(enabled = arranging) { arranging = false }
LaunchedEffect(arranging) {
val focus = ff ?: return@LaunchedEffect
if (!arranging || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
repeat(45) {
androidx.compose.runtime.withFrameNanos { }
val req = tabs.firstOrNull()?.let { focus.items["storechip:${it.store.id}"] } ?: return@repeat
if (runCatching { req.requestFocus() }.isSuccess) return@LaunchedEffect
}
}
val scroll = rememberScrollState()
val detailScroll = rememberScrollState()
LaunchedEffect(chip, tab) { scroll.scrollTo(0); grid.scrollToItem(0) }
@@ -298,14 +392,32 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
Column(
modifier = Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp)
.bumpers(
onPrevious = { if (openGame == null) cycleStore(-1) },
onNext = { if (openGame == null) cycleStore(1) },
onPrevious = {
val picked = Store.byId(focusedChip)
if (arranging) { if (picked != null) shiftTab(picked, -1) }
else if (openGame == null) cycleStore(-1)
},
onNext = {
val picked = Store.byId(focusedChip)
if (arranging) { if (picked != null) shiftTab(picked, 1) }
else if (openGame == null) cycleStore(1)
},
),
) {
Box(Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
StoreTheme(Store.byId(focusedChip ?: chip)) {
Rise(0) { StoreChips(chip, focusedChip, s.storeDownloadsActive, onStore = { st, _ -> openModes(st) }, onDownloads = { if (chip != DOWNLOADS) pickChip(DOWNLOADS) else move("first") },
onFocusChip = { focusedChip = it }, onSettings = { at -> if (at != null) StoresMotion.ask(storesSettingsStep(at, liveState, a, pal.signal)) }) }
Rise(0) {
StoreChips(
chip, focusedChip, s.storeDownloadsActive, tabs, arranging,
onStore = { st -> openModes(st) },
onDownloads = { if (chip != DOWNLOADS) pickChip(DOWNLOADS) else move("first") },
onFocusChip = { focusedChip = it },
onArrangeDone = { arranging = false },
onMoveTab = { st, to -> moveTab(st, to) },
onToggleTab = { toggleTab(it) },
onSettings = { at -> if (at != null) StoresMotion.ask(storesSettingsStep(at, liveState, a, pal.signal) { arranging = true }) },
)
}
}
}
val fade = with(androidx.compose.ui.platform.LocalDensity.current) { 14.dp.toPx() }
@@ -361,6 +473,9 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
when {
k.chip == DOWNLOADS -> Column(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { StoresDownloadsPane(s, a) }
st == null -> {}
!k.accountsLoaded -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
}
!k.signedIn -> Box(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { SignInCard(st, viewportH - 20.dp) }
else -> Storefront(st, k.tab, query, s, a, grids.getOrPut(k) { LazyGridState() }, onQuery = { query = it }, onOpen = { open(it) }, onTab = { switchTab(it) })
}
@@ -431,7 +546,10 @@ private fun InstallWhere(item: CatalogItem) {
val ctx = LocalContext.current
val pal = LocalPalette.current
val from = remember(item) { StoresMotion.recentInstall() }
if (from == null) { InstallWhereDialog(item) { StoresState.pendingInstall = null }; return }
if (from == null || StoreLanguage.selectable(item.store)) {
InstallWhereDialog(item) { StoresState.pendingInstall = null }
return
}
val title = stringResource(R.string.stores_install_title, item.title)
val internalLabel = stringResource(R.string.stores_target_internal)
val label = StoresMotion.installLabel
@@ -513,54 +631,149 @@ private fun SignInFloodLayer(hostAt: Offset) {
}
private class ChipDrag {
var store by mutableStateOf<Store?>(null)
var from by mutableIntStateOf(-1)
var target by mutableIntStateOf(-1)
var x by mutableFloatStateOf(0f)
}
@Composable
private fun StoreDot(store: Store, signedIn: Boolean) {
val c = sourceColours(store.id)
Box(
Modifier.size(12.dp)
.onGloballyPositioned { StoresMotion.dots[store] = it.boundsInRoot() }
.pulseRing(StoresMotion.pulses[store] ?: 0, c.dot)
.background(c.dot.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape),
)
}
@Composable
private fun RowScope.ArrangeStoreChip(
tab: StoreTab, index: Int, last: Int, gapPx: Float, drag: ChipDrag,
onFocusChip: (String?) -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit,
) {
val store = tab.store
val box = remember(store) { mutableFloatStateOf(0f) }
val pitch = box.floatValue + gapPx
val held = drag.store == store
val lift by animateFloatAsState(if (held) 1f else 0f, Motion.sp(0.7f, Spring.StiffnessMediumLow), label = "chipLift")
val shift by animateFloatAsState(
when {
drag.store == null || held -> 0f
drag.from < index && drag.target >= index -> -pitch
drag.from > index && drag.target <= index -> pitch
else -> 0f
},
Motion.sp(0.6f, Spring.StiffnessMediumLow), label = "chipShift",
)
val pill = remember { RoundedCornerShape(99.dp) }
val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true
fun reset() {
drag.store = null
drag.from = -1
drag.target = -1
drag.x = 0f
}
fun commit() {
val from = drag.from
val to = drag.target
reset()
if (from >= 0 && to >= 0 && to != from) onMoveTab(store, to)
}
StoreChip(
label = store.shortLabel, on = false, under = false, key = store.id, mark = sourceColours(store.id).dot, lift = lift,
modifier = Modifier.weight(1f)
.zIndex(if (held) 2f else 0f)
.onSizeChanged { box.floatValue = it.width.toFloat() }
.graphicsLayer {
translationX = if (held) drag.x else shift
shadowElevation = 14.dp.toPx() * lift
shape = pill
clip = false
}
.pointerInput(store, index) {
detectDragGestures(
onDragStart = {
drag.store = store
drag.from = index
drag.target = index
drag.x = 0f
},
onDragEnd = { commit() },
onDragCancel = { reset() },
) { change, amount ->
change.consume()
val step = box.floatValue + gapPx
if (step <= 0f) return@detectDragGestures
drag.x = (drag.x + amount.x).coerceIn(-drag.from * step, (last - drag.from) * step)
drag.target = (drag.from + (drag.x / step).roundToInt()).coerceIn(0, last)
}
}
.alpha(if (tab.shown) 1f else 0.32f),
lead = { StoreDot(store, signedIn) },
onFocused = onFocusChip,
) { onToggleTab(store) }
}
@Composable
private fun StoreChips(
selected: String, focused: String?, active: Int, onStore: (Store, Rect?) -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit,
onFocusChip: (String?) -> Unit,
selected: String, focused: String?, active: Int, tabs: List<StoreTab>, arranging: Boolean,
onStore: (Store) -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit,
onArrangeDone: () -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit,
) {
val pal = LocalPalette.current
val keys = Store.entries.map { it.id } + DOWNLOADS
val keys = tabs.filter { it.shown }.map { it.store.id } + DOWNLOADS
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, Rect>() }
val rootBounds = remember { HashMap<String, Rect>() }
val highlighted = focused ?: selected
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode
val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard
val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard && !arranging
val tint = androidx.compose.animation.animateColorAsState(
Store.byId(highlighted)?.let { sourceColours(it.id).dot } ?: pal.signal, Motion.tw(160), label = "chipTint",
)
val gap = 8.dp
val gapPx = with(androidx.compose.ui.platform.LocalDensity.current) { gap.toPx() }
val drag = remember { ChipDrag() }
Box(Modifier.fillMaxWidth()) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
for (store in Store.entries) {
val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true
StoreChip(
label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot,
modifier = Modifier.weight(1f).onGloballyPositioned { bounds[store.id] = it.boundsInParent(); rootBounds[store.id] = it.boundsInRoot() },
lead = {
val c = sourceColours(store.id)
Box(
Modifier.size(12.dp)
.onGloballyPositioned { StoresMotion.dots[store] = it.boundsInRoot() }
.pulseRing(StoresMotion.pulses[store] ?: 0, c.dot),
) { Box(Modifier.matchParentSize().clip(CircleShape).background(c.dot).alpha(if (signedIn) 1f else 0.35f)) }
},
description = store.label + if (signedIn) "" else " " + stringResource(R.string.stores_chip_signed_out),
onFocused = onFocusChip,
) { onStore(store, rootBounds[store.id]) }
Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
for (tab in tabs) {
val store = tab.store
if (arranging) {
val index = tabs.indexOfFirst { it.store == store }
key(store) { ArrangeStoreChip(tab, index, tabs.lastIndex, gapPx, drag, onFocusChip, onMoveTab, onToggleTab) }
} else if (tab.shown) {
val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true
key(store) {
StoreChip(
label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot,
modifier = Modifier.weight(1f).onGloballyPositioned { bounds[store.id] = it.boundsInParent(); rootBounds[store.id] = it.boundsInRoot() },
lead = { StoreDot(store, signedIn) },
description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out),
onFocused = onFocusChip,
) { onStore(store) }
}
}
}
StoreChip(
label = null, on = selected == DOWNLOADS, under = fillShown && highlighted == DOWNLOADS, key = DOWNLOADS, mark = pal.signal,
modifier = Modifier.onGloballyPositioned {
bounds[DOWNLOADS] = it.boundsInParent()
StoresMotion.downloadsChip = it.boundsInRoot()
},
lead = { Icon(Icons.Outlined.Download, null, modifier = Modifier.size(18.dp)) },
trail = if (active > 0) { { CountPill(active) } } else null,
description = stringResource(R.string.stores_tab_downloads),
onFocused = onFocusChip,
) { onDownloads() }
var cogAt by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) {
IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) }
if (arranging) {
IconChip(Icons.Filled.Check, stringResource(R.string.stores_tabs_arrange_done)) { onArrangeDone() }
} else {
StoreChip(
label = null, on = selected == DOWNLOADS, under = fillShown && highlighted == DOWNLOADS, key = DOWNLOADS, mark = pal.signal,
modifier = Modifier.onGloballyPositioned {
bounds[DOWNLOADS] = it.boundsInParent()
StoresMotion.downloadsChip = it.boundsInRoot()
},
lead = { Icon(Icons.Outlined.Download, null, modifier = Modifier.size(18.dp)) },
trail = if (active > 0) { { CountPill(active) } } else null,
description = stringResource(R.string.stores_tab_downloads),
onFocused = onFocusChip,
) { onDownloads() }
var cogAt by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) {
IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) }
}
}
}
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
@@ -570,7 +783,7 @@ private fun StoreChips(
@Composable
private fun StoreChip(
label: String?, on: Boolean, under: Boolean, key: String, mark: Color, modifier: Modifier, lead: @Composable () -> Unit,
trail: (@Composable () -> Unit)? = null, description: String? = null,
trail: (@Composable () -> Unit)? = null, description: String? = null, lift: Float = 0f,
onFocused: (String?) -> Unit = {}, onClick: () -> Unit,
) {
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
@@ -595,10 +808,10 @@ private fun StoreChip(
if (f.isFocused && inputMode.inputMode == androidx.compose.ui.input.InputMode.Keyboard) onFocused(key)
else if (!f.isFocused) onFocused(null)
}
.heightIn(min = 44.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape)
.background(if (under) Color.Transparent else colors.surface)
.heightIn(min = 44.dp).graphicsLayer { scaleX = scale * (1f + 0.08f * lift); scaleY = scale * (1f + 0.08f * lift) }.clip(shape)
.background(if (under) Color.Transparent else lerp(colors.surface, pal.signal, 0.18f * lift))
.shownBar(on, mark)
.glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line)
.glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else lerp(pal.line, pal.signal, lift))
.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)
@@ -736,7 +949,7 @@ private fun Storefront(
val q = query.trim().lowercase()
val foundKeys = remember(found) { found.map { it.key }.toSet() }
fun matches(i: CatalogItem) = q.isEmpty() || i.title.lowercase().contains(q) || i.key in foundKeys
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.owned
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.accessible
fun shelf(l: List<CatalogItem>?) = l?.filter(::shown)
val everything = remember(library, shelves, found) { (found + library + (shelves?.all ?: emptyList())).distinctBy { it.id } }
LaunchedEffect(store, q) { StoresState.search(ctx, store, q) }
@@ -787,7 +1000,7 @@ private fun Storefront(
CompletableFuture.allOf(*requests.map { it.second }.toTypedArray()).await()
requests.forEach { (item, future) ->
val bytes = future.getNow(null) ?: return@forEach
if (item.owned && item.sizeBytes <= 0) com.droiddeck.launcher.stores.StoreSizes.known[item.key] = bytes
if (item.accessible && item.sizeBytes <= 0) com.droiddeck.launcher.stores.StoreSizes.known[item.key] = bytes
}
resolvedSizeSortKey = candidateKeys
}
@@ -800,9 +1013,14 @@ private fun Storefront(
val density = androidx.compose.ui.platform.LocalDensity.current
val focus = LocalFrontFocus.current
val scope = rememberCoroutineScope()
val headerItems = 1 + (if (sizeSortPending) 1 else 0) +
(if (StoresState.status[store] != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0)
// A bar only where the tab has nothing else on it: shelves, the shelf of owned games, or a grid still loading.
val gridEmpty = if (showGrid) visible.isEmpty() else (shelves == null || shelves.isEmpty) && library.isEmpty()
val barLine = StoresState.status[store]?.takeIf { gridEmpty && syncCount(it) != null }
val headerItems = 1 + (if (sizeSortPending) 1 else 0) + (if (barLine != null) 1 else 0) +
(if (StoresState.problems[store] != null) 1 else 0)
val listMode = s.storesView == "list" && tab == "library"
val capsules = s.storesView == "capsules" && tab == "library"
val tileWidth = if (capsules) CapsuleWidth else CardWidth
val card: @Composable (CatalogItem) -> Unit = { item ->
val first = if (showGrid) item.key == visible.firstOrNull()?.key else !firstPlaced
firstPlaced = true
@@ -834,12 +1052,12 @@ private fun Storefront(
}
}
if (listMode) GameListRow(item, store, installedKeys, onOpen, first, navigation)
else GameCard(item, store, s, a, installedKeys, onOpen, first, navigation)
else GameCard(item, store, s, a, installedKeys, onOpen, first, navigation, capsule = capsules)
}
LazyVerticalGrid(
columns = if (listMode) GridCells.Fixed(1) else GridCells.Adaptive(CardWidth), state = grid, modifier = Modifier.fillMaxSize().focusGroup().onSizeChanged {
columns = if (listMode) GridCells.Fixed(1) else GridCells.Adaptive(tileWidth), state = grid, modifier = Modifier.fillMaxSize().focusGroup().onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
val minimum = with(density) { (if (listMode) CardWidth * 2 else CardWidth).roundToPx() }
val minimum = with(density) { (if (listMode) CardWidth * 2 else tileWidth).roundToPx() }
columns = ((it.width + gap) / (minimum + gap)).toInt().coerceAtLeast(1)
},
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
@@ -882,7 +1100,7 @@ private fun Storefront(
Text(stringResource(R.string.store_section_loading), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
StoresState.status[store]?.let { line -> item(key = "sync", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { SyncBar(line) } } }
barLine?.let { line -> item(key = "sync", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { SyncBar(line) } } }
StoresState.problems[store]?.let { line -> item(key = "problem", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { Box(Modifier.padding(bottom = 8.dp)) { Note(line) } } } }
when (tab) {
"library" -> if (!loaded) Unit
@@ -924,7 +1142,7 @@ private suspend fun <T> CompletableFuture<T>.await(): T =
@Composable
private fun SectionLabel(title: String) {
Text(
title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
headingUppercase(title), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.fillMaxWidth().padding(top = 6.dp, start = 2.dp),
)
}
@@ -934,7 +1152,7 @@ private fun HeaderTabs(labels: List<String>, selected: Int, onSelect: (Int) -> U
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(8.dp)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.selectableGroup()) {
labels.forEachIndexed { i, label ->
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
@@ -943,7 +1161,7 @@ private fun HeaderTabs(labels: List<String>, selected: Int, onSelect: (Int) -> U
label, fontSize = 15.sp, fontWeight = FontWeight.Bold, maxLines = 1,
color = if (i == selected || hot) colors.onBackground else colors.onSurfaceVariant.copy(alpha = 0.7f),
modifier = Modifier.clip(shape).glideBorder(hot, shape, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick)
.hoverable(src).selectable(selected = i == selected, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 4.dp, vertical = 6.dp),
)
@@ -959,6 +1177,7 @@ internal fun ModeHeader(
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var searching by remember { mutableStateOf(query.isNotEmpty()) }
var focusOnOpen by remember { mutableStateOf(false) }
val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "searchOpen")
Column(Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp).padding(vertical = 4.dp)) {
@@ -973,11 +1192,11 @@ internal fun ModeHeader(
Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) {
AdbTextField(
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = placeholder, compact = true, focusOnShow = true,
onFocusChange = { focused -> if (!focused && query.isEmpty()) searching = false },
placeholder = placeholder, compact = true, focusOnShow = focusOnOpen,
onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } },
)
}
} else SearchIcon(stringResource(R.string.stores_search_open)) { searching = true }
} else SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true }
}
trailing()
}
@@ -990,6 +1209,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
Store.GOG -> Color(0xFFC25BC8) to Color(0xFF9A3FA1)
Store.EPIC -> Color(0xFFE6E6E6) to Color(0xFFBDBDBD)
Store.AMAZON -> Color(0xFFFF9900) to Color(0xFFE07800)
Store.XBOX -> Color(0xFF70C850) to Color(0xFF107C10)
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
null -> return base
}
@@ -1094,12 +1314,13 @@ private fun SortButton(s: FrontEndState, a: FrontEndActions) {
@Composable
private fun ViewButton(s: FrontEndState, a: FrontEndActions) {
val list = s.storesView == "list"
val views = SessionPrefs.STORES_VIEWS
val next = views[(views.indexOf(s.storesView) + 1) % views.size]
HeaderIconButton(
if (list) stringResource(R.string.stores_view_cards) else stringResource(R.string.stores_view_list),
if (list) Icons.Filled.GridView else Icons.Filled.ViewList,
stringResource(when (next) { "capsules" -> R.string.stores_view_capsules; "list" -> R.string.stores_view_list; else -> R.string.stores_view_cards }),
when (next) { "capsules" -> Icons.Filled.ViewModule; "list" -> Icons.Filled.ViewList; else -> Icons.Filled.GridView },
"view",
) { a.onStoresView(if (list) "cards" else "list") }
) { a.onStoresView(next) }
}
@Composable
@@ -1144,7 +1365,7 @@ private fun GameListRow(
modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp).then(navigation).paneItem("card:${item.key}")
.then(if (first) Modifier.firstTile() else Modifier)
.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)
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open)
.padding(horizontal = 10.dp, vertical = 8.dp),
) {
CardArt(item, Modifier.width(96.dp).height(54.dp).clip(RoundedCornerShape(8.dp)))
@@ -1226,9 +1447,13 @@ private fun LazyGridScope.storeGrid(games: List<CatalogItem>, empty: String, car
}
private val CardWidth = 112.dp
private val CapsuleWidth = 92.dp
@Composable
private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: FrontEndActions, installedKeys: Set<String>, onOpen: (String) -> Unit, first: Boolean = false, navigation: Modifier = Modifier) {
private fun GameCard(
item: CatalogItem, store: Store, s: FrontEndState, a: FrontEndActions, installedKeys: Set<String>, onOpen: (String) -> Unit,
first: Boolean = false, navigation: Modifier = Modifier, capsule: Boolean = false,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -1241,7 +1466,8 @@ private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: Front
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
val corner = with(androidx.compose.ui.platform.LocalDensity.current) { 10.dp.toPx() }
val open = {
placed[0]?.takeIf { it.isAttached }?.let { StoresMotion.markCard(CardMark(item.key, it.boundsInRoot(), corner, item.imageUrl ?: item.tallImageUrl)) }
val art = if (capsule) item.tallImageUrl ?: item.imageUrl else item.imageUrl ?: item.tallImageUrl
placed[0]?.takeIf { it.isAttached }?.let { StoresMotion.markCard(CardMark(item.key, it.boundsInRoot(), corner, art)) }
onOpen(item.key)
}
val screen = with(androidx.compose.ui.platform.LocalDensity.current) { androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp.toPx() }
@@ -1250,47 +1476,76 @@ private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: Front
modifier = Modifier.fillMaxWidth()
.onGloballyPositioned { c ->
placed[0] = c
if (item.owned && item.sizeBytes <= 0) {
if (item.accessible && 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)
}
}
.then(navigation).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),
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open).controllerConfirm(onClick = open),
) {
CardFace(item, download, hot) { CardMarker(item, installed, download) }
CardFace(item, download, hot, capsule) { CardMarker(item, installed, download, compact = capsule) }
}
}
private fun syncCount(line: String): Pair<Int, Int>? {
val match = Regex("(\\d+)\\s*/\\s*(\\d+)").find(line) ?: return null
val done = match.groupValues[1].toIntOrNull() ?: return null
val total = match.groupValues[2].toIntOrNull()?.takeIf { it > 0 } ?: return null
return done to total
}
@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 }
val count = syncCount(line) ?: return
val done = count.first
val total = count.second
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)
Box(Modifier.weight(1f)) { androidx.compose.material3.LinearProgressIndicator(progress = { (done.toFloat() / total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth().height(3.dp)) }
Text("$done/$total", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
}
}
private val CardStrip = 26.dp
@Composable
internal fun cardArtRequest(url: String?, cover: String?): coil.request.ImageRequest? {
val ctx = LocalContext.current
val under = cover?.takeIf { it != url }
return remember(url, under) {
url?.let { coil.request.ImageRequest.Builder(ctx).data(it).apply { if (under != null) placeholderMemoryCacheKey(under) }.build() }
}
}
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun CardFace(item: CatalogItem, download: com.droiddeck.launcher.stores.download.DownloadEntry?, hot: Boolean, marker: @Composable () -> Unit) {
val url = item.imageUrl ?: item.tallImageUrl
private fun CardFace(
item: CatalogItem, download: com.droiddeck.launcher.stores.download.DownloadEntry?, hot: Boolean, capsule: Boolean = false,
marker: @Composable () -> Unit,
) {
val url = if (capsule) item.tallImageUrl ?: item.imageUrl else item.imageUrl ?: item.tallImageUrl
val art = cardArtRequest(url, item.tallImageUrl)
val blurs = android.os.Build.VERSION.SDK_INT >= 31
var landscape by remember(url) { mutableStateOf(false) }
BoxWithConstraints(Modifier.fillMaxWidth()) {
val total = maxWidth * 9f / 16f + CardStrip
val total = if (capsule) maxWidth * 7f / 5f + CardStrip else 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())
if (art != null && capsule && landscape) {
// Stores without portrait covers (itch) would lose most of the art to a portrait crop.
AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize().blur(24.dp))
Spacer(Modifier.matchParentSize().background(Color.Black.copy(alpha = if (blurs) 0.35f else 0.7f)))
AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.matchParentSize().padding(bottom = CardStrip))
} else if (art != null) AsyncImage(
model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize(),
onSuccess = { r ->
val drawn = r.result.drawable
if (capsule && drawn.intrinsicWidth > 0 && drawn.intrinsicHeight > 0) landscape = drawn.intrinsicWidth > drawn.intrinsicHeight * 0.95f
},
)
Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(CardStrip).clipToBounds()) {
if (url != null) AsyncImage(
model = url, contentDescription = null, contentScale = ContentScale.Crop,
if (art != null) AsyncImage(
model = art, 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)))
@@ -1315,7 +1570,7 @@ private fun CardFace(item: CatalogItem, download: com.droiddeck.launcher.stores.
}
@Composable
private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droiddeck.launcher.stores.download.DownloadEntry?) {
private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droiddeck.launcher.stores.download.DownloadEntry?, compact: Boolean = false) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val small = 10.sp
@@ -1323,13 +1578,14 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
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) }
if (game != null && !compact) androidx.compose.runtime.LaunchedEffect(item.key) { com.droiddeck.launcher.stores.StoreSizes.requestDisk(ctx, item.key, game) }
if (!compact) 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)
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.accessible && StoresState.isUnfinished(item) -> Text(stringResource(R.string.stores_resume), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
item.accessible && compact -> Unit
item.accessible -> 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)
@@ -1342,9 +1598,10 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
@Composable
internal fun CardArt(item: CatalogItem, modifier: Modifier) {
val url = item.imageUrl ?: item.tallImageUrl
val art = cardArtRequest(url, item.tallImageUrl)
val colors = MaterialTheme.colorScheme
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())
if (art != null) AsyncImage(model = art, 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))))
}
@@ -1405,9 +1662,16 @@ internal fun openUrl(ctx: android.content.Context, url: String) {
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()
if (game != null) {
com.droiddeck.launcher.stores.StoreLaunch.prepare(ctx, store, id) { a.onSteamGame(game) }
return
}
com.droiddeck.launcher.stores.StoreLaunch.prepare(ctx, store, id) { a.onSteamGame(game) }
val app = ctx.applicationContext
Thread({
val installed = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull()
StoresState.post {
if (installed == null) android.widget.Toast.makeText(ctx, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
else com.droiddeck.launcher.stores.StoreLaunch.prepare(ctx, store, id) { a.onSteamGame(installed) }
}
}, "store-play").start()
}
@@ -6,6 +6,10 @@ import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import android.content.Context
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
@@ -29,6 +33,30 @@ object Themes {
const val PAPER = "paper"
const val ICON_BLUE = "blue"
const val ELECTRIC = "electric"
const val GRADIENT = "gradient"
const val DEFAULT_PRIMARY = 0xFF8B5CF6.toInt()
const val DEFAULT_SECONDARY = 0xFF22D3EE.toInt()
/** The two colours of the custom Gradient theme: primary, then secondary. Changing them restyles the app at once. */
var gradientColors by mutableStateOf(DEFAULT_PRIMARY to DEFAULT_SECONDARY)
private set
fun loadGradient(context: Context) {
gradientColors = SessionPrefs.gradientColors(context)
}
fun setGradient(context: Context, primary: Int, secondary: Int) {
SessionPrefs.setGradientColors(context, primary, secondary)
gradientColors = primary to secondary
}
/** The theme the person chose, with the custom colours read first; for code that is not in a composition. */
fun current(context: Context): Palette {
val id = SessionPrefs.theme(context)
if (id == GRADIENT) loadGradient(context)
return byId(id)
}
val all: List<Palette> = listOf(
Palette(
@@ -56,12 +84,16 @@ object Themes {
ELECTRIC, R.string.theme_electric, R.string.theme_electric_detail,
background = Color(0xFF070A10), surface = Color(0xFF0F1522), surfaceVariant = Color(0xFF16203A), line = Color(0xFF1E2A47), line2 = Color(0xFF2A3A5E),
onBackground = Color(0xFFEEF3FF), onSurfaceVariant = Color(0xFF8B9AB8),
primary = Color(0xFF2E86FF), primary2 = Color(0xFF136CE0), onPrimary = Color(0xFFFFFFFF), signal = Color(0xFF2E86FF),
primary = Color(0xFF2E86FF), primary2 = Color(0xFF2684FF), onPrimary = Color(0xFF03111F), signal = Color(0xFF2E86FF),
good = Color(0xFF4CD37F),
),
ThemeColors.palette(DEFAULT_PRIMARY, DEFAULT_SECONDARY, R.string.theme_gradient, R.string.theme_gradient_detail),
)
fun byId(id: String): Palette = all.firstOrNull { it.id == id } ?: all[0]
fun byId(id: String): Palette {
if (id == GRADIENT) return ThemeColors.palette(gradientColors.first, gradientColors.second, R.string.theme_gradient, R.string.theme_gradient_detail)
return all.firstOrNull { it.id == id } ?: all[0]
}
}
val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.GRAPHITE) }
@@ -0,0 +1,157 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/** Colour maths for the custom gradient theme: hue, saturation and brightness in, a readable palette out. */
internal object ThemeColors {
/** Hue 0..360, saturation and brightness 0..1. */
class Hsv(val h: Float, val s: Float, val v: Float)
fun toHsv(argb: Int): Hsv {
val r = (argb shr 16 and 0xFF) / 255f
val g = (argb shr 8 and 0xFF) / 255f
val b = (argb and 0xFF) / 255f
val top = max(r, max(g, b))
val delta = top - min(r, min(g, b))
val hue = when {
delta == 0f -> 0f
top == r -> 60f * (((g - b) / delta) % 6f)
top == g -> 60f * ((b - r) / delta + 2f)
else -> 60f * ((r - g) / delta + 4f)
}
return Hsv(if (hue < 0f) hue + 360f else hue, if (top == 0f) 0f else delta / top, top)
}
fun fromHsv(h: Float, s: Float, v: Float): Int =
Color.hsv(h.mod(360f), s.coerceIn(0f, 1f), v.coerceIn(0f, 1f)).toArgb()
fun hex(argb: Int): String = "#%06X".format(argb and 0xFFFFFF)
/** `#RRGGBB`, `RRGGBB` or `#RGB`; null for anything else. */
fun parseHex(text: String): Int? {
val digits = text.trim().removePrefix("#")
if (!digits.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }) return null
val full = when (digits.length) {
3 -> digits.map { "$it$it" }.joinToString("")
6 -> digits
else -> return null
}
return 0xFF000000.toInt() or full.toInt(16)
}
private const val MIN_LUMINANCE = 0.10f
/** The colour, made brighter (then paler, for a deep blue that brightness alone cannot lift) when it is too dark to show on the dark background. */
fun readable(argb: Int): Int {
if (Color(argb).luminance() >= MIN_LUMINANCE) return argb or 0xFF000000.toInt()
val hsv = toHsv(argb)
var v = hsv.v
var s = hsv.s
var out = argb
while (v < 1f && Color(out).luminance() < MIN_LUMINANCE) {
v = min(1f, v + 0.04f)
out = fromHsv(hsv.h, s, v)
}
while (s > 0f && Color(out).luminance() < MIN_LUMINANCE) {
s = max(0f, s - 0.04f)
out = fromHsv(hsv.h, s, v)
}
return out
}
/** A dark neutral tinted with the primary's hue; plain greys stay grey. */
fun tint(primary: Int, saturation: Float, brightness: Float): Color {
val hsv = toHsv(primary)
val strength = (hsv.s / 0.35f).coerceIn(0f, 1f)
return Color(fromHsv(hsv.h, saturation * strength, brightness))
}
private val DARK_INK = Color(0xFF03111F)
private fun contrast(a: Color, b: Color): Float {
val x = a.luminance()
val y = b.luminance()
return (max(x, y) + 0.05f) / (min(x, y) + 0.05f)
}
/** Dark or white text, whichever reads better on the worse of the two gradient colours. */
internal fun inkFor(first: Int, second: Int): Color {
fun worst(ink: Color) = min(contrast(ink, Color(first)), contrast(ink, Color(second)))
return if (worst(DARK_INK) >= worst(Color.White)) DARK_INK else Color.White
}
private const val MIN_CONTRAST = 4.5f
/** The colour nudged just enough, lighter for dark text and darker for white text, to give [ink] a readable contrast on it. */
private fun fitTo(ink: Color, argb: Int): Int {
fun short(color: Int) = contrast(ink, Color(color)) < MIN_CONTRAST
if (!short(argb)) return argb
val hsv = toHsv(argb)
var v = hsv.v
var s = hsv.s
var out = argb
if (ink == DARK_INK) {
while (v < 1f && short(out)) { v = min(1f, v + 0.04f); out = fromHsv(hsv.h, s, v) }
while (s > 0f && short(out)) { s = max(0f, s - 0.04f); out = fromHsv(hsv.h, s, v) }
} else {
while (v > 0f && short(out)) { v = max(0f, v - 0.04f); out = fromHsv(hsv.h, s, v) }
}
return out
}
private fun gradientColor(first: Int, second: Int, fraction: Float): Int {
fun channel(shift: Int): Int {
val a = first shr shift and 0xFF
val b = second shr shift and 0xFF
return (a + (b - a) * fraction).roundToInt().coerceIn(0, 255)
}
return (0xFF shl 24) or (channel(16) shl 16) or (channel(8) shl 8) or channel(0)
}
private fun gradientFits(ink: Color, first: Int, second: Int): Boolean =
(0..32).all { step ->
val color = gradientColor(first, second, step / 32f)
contrast(ink, Color(color)) >= MIN_CONTRAST + 0.02f
}
private fun moveTowardContrast(ink: Color, argb: Int): Int {
val hsv = toHsv(argb)
return if (ink == DARK_INK) {
when {
hsv.v < 1f -> fromHsv(hsv.h, hsv.s, min(1f, hsv.v + 0.04f))
hsv.s > 0f -> fromHsv(hsv.h, max(0f, hsv.s - 0.04f), hsv.v)
else -> argb
}
} else {
fromHsv(hsv.h, hsv.s, max(0f, hsv.v - 0.04f))
}
}
fun palette(primary: Int, secondary: Int, label: Int, detail: Int): Palette {
val seen = readable(primary)
val seenSecond = readable(secondary)
val ink = inkFor(seen, seenSecond)
var first = fitTo(ink, seen)
var second = fitTo(ink, seenSecond)
while (!gradientFits(ink, first, second)) {
val nextFirst = moveTowardContrast(ink, first)
val nextSecond = moveTowardContrast(ink, second)
if (nextFirst == first && nextSecond == second) break
first = nextFirst
second = nextSecond
}
return Palette(
Themes.GRADIENT, label, detail,
background = tint(first, 0.50f, 0.045f), surface = tint(first, 0.45f, 0.075f), surfaceVariant = tint(first, 0.42f, 0.115f),
line = tint(first, 0.40f, 0.16f), line2 = tint(first, 0.36f, 0.22f),
onBackground = tint(first, 0.05f, 0.97f), onSurfaceVariant = tint(first, 0.16f, 0.68f),
primary = Color(first), primary2 = Color(second), onPrimary = ink, signal = Color(first),
good = Color(0xFF4CD37F),
)
}
}
@@ -0,0 +1,330 @@
package com.droiddeck.launcher.ui
import androidx.annotation.StringRes
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Keyboard
import androidx.compose.material.icons.filled.Mouse
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.TouchApp
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.GestureKeys
import com.droiddeck.launcher.input.GesturePrefs
import com.droiddeck.launcher.input.TouchGestureConfig
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_LEFT_CLICK
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_RIGHT_CLICK
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_MIDDLE_CLICK
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_SHOW_KEYBOARD
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_KEY_TILDE
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.PAN_ACTIONS
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ZOOM_ACTIONS
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_HOLD
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_CLICK
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_DRAG_MOVEMENT_DIRECT
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_DRAG_MOVEMENT_RELATIVE
@Composable
fun TouchGestureDialog(game: String?, onDismiss: () -> Unit, onSaved: () -> Unit) {
val context = LocalContext.current
// Keep an open editor attached to the game it was opened for.
val targetGame = remember { game }
val initialDefaults = remember { GesturePrefs.read(context) }
val initialGame = remember { targetGame?.takeIf { GesturePrefs.hasOverride(context, it) }?.let { GesturePrefs.read(context, it) } }
var defaults by remember { mutableStateOf(initialDefaults) }
var gameDraft by remember { mutableStateOf(initialGame) }
var forGame by rememberSaveable { mutableStateOf(targetGame != null) }
val config = if (forGame) gameDraft ?: defaults else defaults
val change: (TouchGestureConfig) -> Unit = { if (forGame) gameDraft = it else defaults = it }
var tab by rememberSaveable { mutableIntStateOf(0) }
val tabs = listOf(R.string.gesture_tab_one, R.string.gesture_tab_two, R.string.gesture_tab_three, R.string.gesture_tab_options)
val mouse = listOf(ACTION_LEFT_CLICK, ACTION_RIGHT_CLICK, ACTION_MIDDLE_CLICK)
val actions = mouse + ACTION_SHOW_KEYBOARD + GestureKeys.codes.keys.map { "key_$it" } + ACTION_KEY_TILDE
val p = LocalPalette.current
GestureDialogFrame(onDismiss,
footer = {
Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.gesture_cancel)) }
Spacer(Modifier.width(12.dp))
Button(onClick = {
if (defaults != initialDefaults) GesturePrefs.save(context, null, defaults)
if (targetGame != null && gameDraft != initialGame) {
gameDraft?.let { GesturePrefs.save(context, targetGame, it) } ?: GesturePrefs.clear(context, targetGame)
}
onSaved()
}, modifier = Modifier.testTag("gesture-save")) { Text(stringResource(R.string.gesture_save_changes)) }
}
}) {
ScrollableTabRow(tab, edgePadding = 12.dp, containerColor = p.surface, divider = { HorizontalDivider(color = p.line) }) {
tabs.forEachIndexed { index, title ->
Tab(tab == index, onClick = { tab = index }, text = { Text(stringResource(title)) }, selectedContentColor = p.onBackground,
unselectedContentColor = p.onSurfaceVariant, modifier = Modifier.testTag("gesture-tab-$index"))
}
}
key(tab) {
Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
GestureFilterChip(!forGame, onClick = { forGame = false }, label = { Text(stringResource(R.string.gesture_defaults)) }, modifier = Modifier.testTag("gesture-scope-default"))
if (targetGame != null) GestureFilterChip(forGame, onClick = { forGame = true }, label = { Text(stringResource(R.string.gesture_game)) }, modifier = Modifier.testTag("gesture-scope-game"))
}
if (forGame && gameDraft != null) TextButton(onClick = { gameDraft = null }, modifier = Modifier.testTag("gesture-inherit")) { Text(stringResource(R.string.gesture_use_defaults)) }
}
when (tab) {
0 -> {
GestureSection(R.string.gesture_tab_one)
GestureCard(R.string.gesture_tap, config.tapEnabled, { change(config.copy(tapEnabled = it)) }) {
GestureActionField("tap", R.string.gesture_tap, config.tapAction, actions) { change(config.copy(tapAction = it)) }
}
GestureCard(R.string.gesture_drag, config.dragEnabled, { change(config.copy(dragEnabled = it)) }) {
GestureActionField("drag", R.string.gesture_drag, config.dragAction, PAN_ACTIONS) { change(config.copy(dragAction = it)) }
}
GestureCard(R.string.gesture_long_press, config.longPressEnabled, { change(config.copy(longPressEnabled = it)) }) {
GestureActionField("long-press", R.string.gesture_long_press, config.longPressAction, actions) { change(config.copy(longPressAction = it)) }
GestureHoldOptions(config.longPressAction, config.longPressMouseBehavior, config.longPressDelay, { change(config.copy(longPressMouseBehavior = it)) }, { change(config.copy(longPressDelay = it)) })
}
GestureCard(R.string.gesture_double_tap, config.doubleTapEnabled, { change(config.copy(doubleTapEnabled = it)) }) {
GestureDelay(stringResource(R.string.gesture_double_delay), config.doubleTapDelay) { change(config.copy(doubleTapDelay = it)) }
}
}
1 -> {
GestureSection(R.string.gesture_tab_two)
GestureCard(R.string.gesture_two_tap, config.twoFingerTapEnabled, { change(config.copy(twoFingerTapEnabled = it)) }) {
GestureActionField("two-tap", R.string.gesture_two_tap, config.twoFingerTapAction, actions) { change(config.copy(twoFingerTapAction = it)) }
}
GestureCard(R.string.gesture_two_drag, config.twoFingerDragEnabled, { change(config.copy(twoFingerDragEnabled = it)) }) {
GestureActionField("two-drag", R.string.gesture_two_drag, config.twoFingerDragAction, PAN_ACTIONS) { change(config.copy(twoFingerDragAction = it)) }
}
GestureCard(R.string.gesture_two_hold, config.twoFingerHoldEnabled, { change(config.copy(twoFingerHoldEnabled = it)) }) {
GestureActionField("two-hold", R.string.gesture_two_hold, config.twoFingerHoldAction, actions) { change(config.copy(twoFingerHoldAction = it)) }
GestureHoldOptions(config.twoFingerHoldAction, config.twoFingerHoldMouseBehavior, config.twoFingerHoldDelay, { change(config.copy(twoFingerHoldMouseBehavior = it)) }, { change(config.copy(twoFingerHoldDelay = it)) })
}
GestureCard(R.string.gesture_pinch, config.pinchEnabled, { change(config.copy(pinchEnabled = it)) }) {
GestureActionField("pinch", R.string.gesture_pinch, config.pinchAction, ZOOM_ACTIONS) { change(config.copy(pinchAction = it)) }
}
}
2 -> {
GestureSection(R.string.gesture_tab_three)
GestureCard(R.string.gesture_three_tap, config.threeFingerTapEnabled, { change(config.copy(threeFingerTapEnabled = it)) }) {
GestureActionField("three-tap", R.string.gesture_three_tap, config.threeFingerTapAction, actions) { change(config.copy(threeFingerTapAction = it)) }
}
GestureCard(R.string.gesture_three_drag, config.threeFingerDragEnabled, { change(config.copy(threeFingerDragEnabled = it)) }) {
GestureActionField("three-drag", R.string.gesture_three_drag, config.threeFingerDragAction, PAN_ACTIONS) { change(config.copy(threeFingerDragAction = it)) }
}
GestureCard(R.string.gesture_three_hold, config.threeFingerHoldEnabled, { change(config.copy(threeFingerHoldEnabled = it)) }) {
GestureActionField("three-hold", R.string.gesture_three_hold, config.threeFingerHoldAction, actions) { change(config.copy(threeFingerHoldAction = it)) }
GestureHoldOptions(config.threeFingerHoldAction, config.threeFingerHoldMouseBehavior, config.threeFingerHoldDelay, { change(config.copy(threeFingerHoldMouseBehavior = it)) }, { change(config.copy(threeFingerHoldDelay = it)) })
}
}
3 -> {
GestureSection(R.string.gesture_tab_options)
GestureSettingsCard(R.string.gesture_movement) {
GestureChoiceChips(config.mouseDragMovementMode, listOf(MOUSE_DRAG_MOVEMENT_DIRECT to stringResource(R.string.gesture_direct), MOUSE_DRAG_MOVEMENT_RELATIVE to stringResource(R.string.gesture_relative))) { change(config.copy(mouseDragMovementMode = it)) }
}
GestureSettingsCard(R.string.gesture_recognition) {
Text(stringResource(R.string.gesture_threshold, config.gestureThreshold), style = MaterialTheme.typography.bodyMedium)
Slider(config.gestureThreshold.toFloat(), { change(config.copy(gestureThreshold = it.toInt())) }, valueRange = 10f..100f, steps = 17)
}
GestureSettingsCard(R.string.gesture_feedback) {
GestureToggle(R.string.gesture_debug, config.showGestureDebugOverlay) { change(config.copy(showGestureDebugOverlay = it)) }
}
OutlinedButton(onClick = { change(TouchGestureConfig()) }, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.gesture_reset)) }
}
}
}
}
}
}
@Composable
private fun GestureDialogFrame(onDismiss: () -> Unit,
footer: @Composable () -> Unit = {}, content: @Composable ColumnScope.() -> Unit) {
val p = LocalPalette.current
// The app window does not opt into RTL, so these dialogs follow their resource locale explicitly.
val direction = if (LocalConfiguration.current.layoutDirection == android.view.View.LAYOUT_DIRECTION_RTL) LayoutDirection.Rtl else LayoutDirection.Ltr
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
CompositionLocalProvider(LocalLayoutDirection provides direction) {
Box(Modifier.fillMaxSize().systemBarsPadding().imePadding().padding(12.dp), contentAlignment = Alignment.Center) {
Surface(Modifier.widthIn(max = 1040.dp).fillMaxWidth().fillMaxHeight(), shape = RoundedCornerShape(22.dp), color = p.background,
contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2)) {
Column {
Row(Modifier.fillMaxWidth().padding(end = 4.dp), horizontalArrangement = Arrangement.End) {
IconButton(onClick = onDismiss, modifier = Modifier.size(40.dp)) { Icon(Icons.Default.Close, stringResource(R.string.gesture_close)) }
}
content()
HorizontalDivider(color = p.line)
footer()
}
}
}
}
}
}
@Composable
private fun GestureSection(@StringRes title: Int) {
Text(stringResource(title), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
}
@Composable
private fun GestureCard(@StringRes title: Int, checked: Boolean, onToggle: (Boolean) -> Unit,
content: @Composable ColumnScope.() -> Unit) {
val p = LocalPalette.current
Surface(Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), color = p.surface,
border = BorderStroke(1.dp, if (checked) p.line2 else p.line)) {
Column {
Row(Modifier.fillMaxWidth().toggleable(checked, role = Role.Switch, onValueChange = onToggle)
.padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f).padding(end = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(stringResource(title), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
}
Switch(checked, onCheckedChange = null)
}
if (checked) Column(Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), content = content)
}
}
}
@Composable
private fun GestureActionField(id: String, @StringRes gesture: Int, selected: String, choices: List<String>, onChoose: (String) -> Unit) {
var open by remember { mutableStateOf(false) }
val p = LocalPalette.current
Surface(onClick = { open = true }, modifier = Modifier.fillMaxWidth().testTag("gesture-choice-$id"), shape = RoundedCornerShape(10.dp),
color = p.surfaceVariant, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2)) {
Row(Modifier.padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(stringResource(R.string.gesture_action_label), color = p.onSurfaceVariant, style = MaterialTheme.typography.labelSmall)
Text(gestureActionTitle(selected), style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium)
}
Icon(Icons.AutoMirrored.Filled.ArrowForward, null, modifier = Modifier.size(19.dp), tint = p.onSurfaceVariant)
}
}
if (open) GestureActionPicker(choices, selected, onDismiss = { open = false }) { open = false; onChoose(it) }
}
@Composable
internal fun GestureActionPicker(choices: List<String>, selected: String, onDismiss: () -> Unit, onChoose: (String) -> Unit) {
var query by rememberSaveable { mutableStateOf("") }
var category by remember { mutableStateOf<GestureActionGroup?>(null) }
val catalog = choices.distinct().map { GestureAction(it, gestureActionTitle(it), gestureActionGroup(it)) }
val groups = GestureActionGroup.entries.filter { group -> catalog.any { it.group == group } }
val shown = filterGestureActions(catalog, query, category)
val p = LocalPalette.current
GestureDialogFrame(onDismiss) {
OutlinedTextField(query, onValueChange = { query = it }, modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).testTag("gesture-action-search"),
singleLine = true, shape = RoundedCornerShape(12.dp), placeholder = { Text(stringResource(R.string.gesture_search_actions)) },
leadingIcon = { Icon(Icons.Default.Search, null) }, trailingIcon = {
if (query.isNotEmpty()) IconButton(onClick = { query = "" }) { Icon(Icons.Default.Close, stringResource(R.string.gesture_clear_search)) }
})
Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
GestureFilterChip(category == null, onClick = { category = null }, label = { Text(stringResource(R.string.gesture_all_actions)) })
if (groups.size > 1) groups.forEach { group ->
GestureFilterChip(category == group, onClick = { category = group }, label = { Text(stringResource(group.title)) }, modifier = Modifier.testTag("gesture-category-${group.name}"))
}
}
if (shown.isEmpty()) Box(Modifier.weight(1f).fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.gesture_no_actions), color = p.onSurfaceVariant)
} else LazyColumn(Modifier.weight(1f).fillMaxWidth().testTag("gesture-action-list"), contentPadding = PaddingValues(start = 20.dp, end = 20.dp, bottom = 16.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)) {
groups.forEach { group ->
val entries = shown.filter { it.group == group }
if (entries.isNotEmpty()) {
item(key = group.name) { Text(stringResource(group.title), style = MaterialTheme.typography.labelLarge, color = p.onSurfaceVariant, modifier = Modifier.padding(top = 12.dp, bottom = 5.dp)) }
items(entries, key = { it.id }) { action ->
val isSelected = action.id == selected
Surface(shape = RoundedCornerShape(12.dp), color = if (isSelected) p.primary.copy(alpha = 0.12f) else p.surface,
border = BorderStroke(1.dp, if (isSelected) p.primary else p.line)) {
Row(Modifier.fillMaxWidth().selectable(isSelected, role = Role.RadioButton, onClick = { onChoose(action.id) })
.testTag("gesture-action-${action.id}").padding(horizontal = 14.dp, vertical = 9.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(when (group) { GestureActionGroup.MOUSE -> Icons.Default.Mouse; GestureActionGroup.APP -> Icons.Default.TouchApp; else -> Icons.Default.Keyboard },
null, tint = if (isSelected) p.primary else p.onSurfaceVariant, modifier = Modifier.size(22.dp))
Text(action.title, Modifier.weight(1f).padding(horizontal = 14.dp), style = MaterialTheme.typography.bodyLarge)
RadioButton(isSelected, onClick = null)
}
}
}
}
}
}
}
}
@Composable
private fun GestureHoldOptions(action: String, behavior: String, delay: Int, onBehavior: (String) -> Unit, onDelay: (Int) -> Unit) {
if (TouchGestureConfig.isMouseButtonAction(action)) {
Text(stringResource(R.string.gesture_mouse_behavior), style = MaterialTheme.typography.labelMedium, color = LocalPalette.current.onSurfaceVariant)
GestureChoiceChips(behavior, listOf(MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_button), MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_click_once)), onBehavior)
}
GestureDelay(stringResource(R.string.gesture_hold_delay), delay, onDelay)
}
@Composable
private fun GestureFilterChip(selected: Boolean, onClick: () -> Unit, label: @Composable () -> Unit, modifier: Modifier = Modifier) {
val p = LocalPalette.current
FilterChip(selected, onClick, label, modifier = modifier, colors = FilterChipDefaults.filterChipColors(
containerColor = p.surface, labelColor = p.onSurfaceVariant,
selectedContainerColor = p.primary.copy(alpha = 0.16f), selectedLabelColor = p.onBackground))
}
@Composable
private fun GestureChoiceChips(selected: String, options: List<Pair<String, String>>, choose: (String) -> Unit) {
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
options.forEach { (id, label) -> GestureFilterChip(selected == id, onClick = { choose(id) }, label = { Text(label) }) }
}
}
@Composable
private fun GestureSettingsCard(@StringRes title: Int, content: @Composable ColumnScope.() -> Unit) {
val p = LocalPalette.current
Surface(shape = RoundedCornerShape(16.dp), color = p.surface, border = BorderStroke(1.dp, p.line)) {
Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(stringResource(title), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
content()
}
}
}
@Composable
private fun GestureToggle(@StringRes title: Int, checked: Boolean, change: (Boolean) -> Unit) {
Row(Modifier.fillMaxWidth().toggleable(checked, role = Role.Switch, onValueChange = change).padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(title), Modifier.weight(1f).padding(end = 12.dp), style = MaterialTheme.typography.bodyMedium)
Switch(checked, null)
}
}
@Composable
private fun GestureDelay(label: String, value: Int, change: (Int) -> Unit) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(label, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)
Text(stringResource(R.string.gesture_ms, value), Modifier.background(LocalPalette.current.surfaceVariant, RoundedCornerShape(6.dp)).padding(horizontal = 10.dp, vertical = 5.dp), style = MaterialTheme.typography.labelLarge)
}
Slider(value.toFloat().coerceIn(100f, 1000f), { change((it / 50).toInt() * 50) }, valueRange = 100f..1000f, steps = 17)
}
@@ -16,7 +16,7 @@ import com.droiddeck.launcher.session.SessionPrefs
internal class TrackingRecoveryView(context: Context) : View(context) {
private var recovery: TrackingRecovery? = null
private var stereo = false
private var palette = Themes.byId(SessionPrefs.theme(context))
private var palette = Themes.current(context)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var blocks = emptyList<StaticLayout>()
@@ -26,7 +26,7 @@ internal class TrackingRecoveryView(context: Context) : View(context) {
importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES
}
fun update(state: TrackingRecovery?, stereo: Boolean, palette: Palette = Themes.byId(SessionPrefs.theme(context))) {
fun update(state: TrackingRecovery?, stereo: Boolean, palette: Palette = Themes.current(context)) {
if (recovery == state && this.stereo == stereo && this.palette == palette) return
recovery = state
this.stereo = stereo