Merge main into feat/viture-xr

This commit is contained in:
maxjivi05 committed 2026-10-13 23:35:29 -04:00
commit 697c75337f
903 files changed
+70115 -47401

No files matched your search

@@ -111,10 +111,8 @@ private enum class AddSource(val label: Int, val hint: Int) {
private val ICON_TYPES = listOf("png", "jpg", "jpeg", "webp")
private val FieldShape = RoundedCornerShape(8.dp)
/** What an icon choice shows: a picked file, or a suggestion's link. */
private fun iconModel(ref: String): Any = if (ref.startsWith("https://")) ref else File(ref)
/** The Desktop page's Add: a script, an AppImage, a GitHub release or a Flatpak, with a name and icon. */
@Composable
internal fun AddAppDialog(runtimeReady: Boolean, onDismiss: () -> Unit, onAdd: (UserApps.Request, String) -> Unit) {
val ctx = LocalContext.current
@@ -159,7 +157,6 @@ internal fun AddAppDialog(runtimeReady: Boolean, onDismiss: () -> Unit, onAdd: (
val busy = UserAppsState.working
val tabFocus = remember { AddSource.entries.map { FocusRequester() } }
val inputMode = LocalInputModeManager.current.inputMode
// Once, as it opens: typing a name switches the input mode too, and must keep its field.
LaunchedEffect(Unit) {
if (inputMode == InputMode.Keyboard) {
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
@@ -240,10 +237,6 @@ internal fun AddAppDialog(runtimeReady: Boolean, onDismiss: () -> Unit, onAdd: (
}
}
/**
* An added app's name and icon, changed on its page. [icon]: null keeps the current one, "" goes
* back to the default, else a picked file or a suggestion.
*/
@Composable
internal fun EditAppDialog(app: UserApps.App, onDismiss: () -> Unit, onSave: (String, String?, String?) -> Unit) {
val ctx = LocalContext.current
@@ -299,7 +292,6 @@ internal fun EditAppDialog(app: UserApps.App, onDismiss: () -> Unit, onSave: (St
}
}
/** Open from the first frame; [onDismiss] once the closing animation has run. */
@Composable
internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolean> {
val shown = remember { MutableTransitionState(false).apply { targetState = true } }
@@ -307,25 +299,17 @@ internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolea
return shown
}
/**
* The card both dialogs sit in, sized to fit a landscape handheld without scrolling: it scales in
* like the app's menus, rises above the keyboard, and closes on a tap outside or B.
*/
@Composable
internal fun AppDialog(
shown: MutableTransitionState<Boolean>, close: () -> Unit, label: String, wide: Boolean,
modifier: Modifier = Modifier, maxWidth: Dp? = null,
/** [width] fixed, else as wide as its content when [fitContent], else as wide as it may be. */
width: Dp? = null, fitContent: Boolean = false,
/** What B / Back does, when not [close] (a picker goes up a folder first). */
back: (() -> Unit)? = null,
content: @Composable ColumnScope.() -> Unit,
) {
val pal = LocalPalette.current
// The page's ring stays out of sight behind it.
VeilRing()
Dialog(onDismissRequest = back ?: close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
// The page's focus memory stays the page's: nothing in here is a place to come back to.
CompositionLocalProvider(LocalFrontFocus provides null) {
Box(
contentAlignment = Alignment.Center,
@@ -368,7 +352,6 @@ internal fun AppDialog(
}
}
/** The eyebrow and title, with [trailing] (the tabs) beside them when there is room, else under them. */
@Composable
internal fun DialogHeader(eyebrow: String, title: String, trailing: (@Composable () -> Unit)? = null) {
val heading = @Composable {
@@ -391,7 +374,6 @@ internal fun DialogHeader(eyebrow: String, title: String, trailing: (@Composable
}
}
/** Side by side and of one height on a wide card, stacked on a narrow one. */
@Composable
private fun Columns(first: @Composable ColumnScope.() -> Unit, second: @Composable ColumnScope.() -> Unit) {
Rise(1) {
@@ -407,7 +389,6 @@ private fun Columns(first: @Composable ColumnScope.() -> Unit, second: @Composab
}
}
/** A titled inset of the card; it fills the height its column is given. */
@Composable
private fun Panel(title: String, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -421,7 +402,6 @@ private fun Panel(title: String, content: @Composable ColumnScope.() -> Unit) {
}
}
/** Why the main button is off (or nothing), then Cancel and the main button, at the card's foot. */
@Composable
internal fun DialogFooter(note: String?, confirm: String, enabled: Boolean, onCancel: () -> Unit, onConfirm: () -> Unit) {
val lineColor = LocalPalette.current.line
@@ -446,7 +426,6 @@ private fun hideKeyboard(view: View) {
?.hideSoftInputFromWindow(view.windowToken, 0)
}
/** The app's text field, with what is wrong with its value under it. */
@Composable
private fun CheckedField(value: String, onChange: (String) -> Unit, label: String, placeholder: String, problem: String?) {
val view = LocalView.current
@@ -468,7 +447,6 @@ private fun NameField(name: String, onName: (String) -> Unit, placeholder: Strin
)
}
/** The app as the Desktop page will show it: its icon, its name ([name] null: not known yet) and kind. */
@Composable
private fun AppPreview(icon: Any?, glyph: ImageVector, name: String?, kind: String) {
val colors = MaterialTheme.colorScheme
@@ -493,7 +471,6 @@ private fun AppPreview(icon: Any?, glyph: ImageVector, name: String?, kind: Stri
}
}
/** The icon's picker and [clear] (a label and what it does). */
@Composable
private fun IconActions(onChoose: () -> Unit, clear: Pair<Int, () -> Unit>?) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -504,7 +481,6 @@ private fun IconActions(onChoose: () -> Unit, clear: Pair<Int, () -> Unit>?) {
}
}
/** Icons found in [repo], looked up off the main thread once the name has settled; [selected] is ringed. */
@Composable
private fun IconSuggestions(repo: String, selected: String?, onPick: (String) -> Unit) {
val found by produceState<List<String>?>(null, repo) {
@@ -537,7 +513,6 @@ private fun SuggestedIcon(url: String, selected: Boolean, onClick: () -> Unit) {
.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))
// The chosen one is ticked; the ring stays with focus.
if (selected) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.align(Alignment.TopEnd).padding(2.dp).size(14.dp).clip(androidx.compose.foundation.shape.CircleShape).background(pal.signal),
@@ -545,7 +520,6 @@ private fun SuggestedIcon(url: String, selected: Boolean, onClick: () -> Unit) {
}
}
/** The chosen file, or none yet, laid out like the app's text fields, with the button that picks it. */
@Composable
private fun FileRow(path: String?, onChoose: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -567,7 +541,6 @@ private fun FileRow(path: String?, onChoose: () -> Unit) {
}
}
/** Whether the script's folder will be linked or copied in, worked out off the main thread. */
@Composable
private fun FolderNote(scriptPath: String) {
var plan by remember(scriptPath) { mutableStateOf<UserApps.ScriptPlan?>(null) }
@@ -62,7 +62,6 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
/** Each art slot's thumbnail, in its true shape: width, height, corner. */
private fun AddedGameArt.Slot.shape(): Triple<Dp, Dp, Dp> = when (this) {
AddedGameArt.Slot.COVER -> Triple(28.dp, 41.dp, 5.dp)
AddedGameArt.Slot.BACKGROUND -> Triple(60.dp, 34.dp, 5.dp)
@@ -92,7 +91,6 @@ private fun artSourceLabel(source: String): String = stringResource(
},
)
/** A thumbnail of [model] (a file or URL) in [slot]'s shape, scaled by [scale]. */
@Composable
private fun SlotThumb(slot: AddedGameArt.Slot, model: Any?, scale: Float = 1f, selected: Boolean = false) {
val pal = LocalPalette.current
@@ -110,7 +108,6 @@ private fun SlotThumb(slot: AddedGameArt.Slot, model: Any?, scale: Float = 1f, s
}
}
/** A row of the editor: a label column, then the value. */
@Composable
private fun FieldRow(label: String, focus: FocusRequester? = null, onClick: () -> Unit, value: @Composable () -> Unit) {
ListRow(focus = focus, onClick = onClick) {
@@ -119,20 +116,13 @@ private fun FieldRow(label: String, focus: FocusRequester? = null, onClick: () -
}
}
/** Where the editor opens: its game's folder, straight on Target, and whether it came from the added-games summary. */
internal class EditRequest(val folder: String, val openTarget: Boolean, val fromSummary: Boolean, val preview: EditPreview)
/**
* What the editor shows on its first frame, from what the page already has (the game's row, or
* the summary's); the rest (the ranked exes, where each piece of art came from) follows.
* [exeName] / [startIn] null = not known yet.
*/
internal class EditPreview(
val name: String, val exeName: String?, val startIn: String?, val launchOptions: String,
val art: Map<AddedGameArt.Slot, File?>,
) {
companion object {
/** From the Games tab's row for [game] and the few preferences the edits keep. */
fun of(context: android.content.Context, game: com.droiddeck.launcher.frontend.Library.SteamGame, folder: String): EditPreview {
val exe = SessionPrefs.addedGameExe(context, folder).ifEmpty {
com.droiddeck.launcher.frontend.AddedExes.list(context).firstOrNull { it.folder == folder && it.picked }?.exe.orEmpty()
@@ -144,28 +134,20 @@ internal class EditPreview(
)
}
/** From a summary row's game and its cover. */
fun of(game: AddedGames.Game, cover: File?) = EditPreview(
game.name, game.exe.name, game.guestDir.substringAfterLast('/'), game.launchOptions, mapOf(AddedGameArt.Slot.COVER to cover),
)
}
}
/** A small spinner where a value is still being read. */
@Composable
private fun Loading() {
androidx.compose.material3.CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp)
}
/**
* An added game's editor, Steam's non-Steam Properties in the app: Name, Target (the ranked exes,
* "?" where nothing clearly won, Other exe…), Start in, Launch options, the four pieces of art, and
* Remove (two presses; the files stay). Every change goes through the game's own Steam shortcut.
*/
@Composable
internal fun AddedGameEditor(
request: EditRequest, onBack: () -> Unit, onClose: () -> Unit, onChanged: () -> Unit,
/** Remove pressed twice: the game's folder, its shortcut appid when known, its name. */
onRemove: (folder: String, appId: Long?, name: String) -> Unit,
) {
val ctx = LocalContext.current
@@ -260,7 +242,6 @@ internal fun AddedGameEditor(
RemoveRow(armed) {
if (!armed) armed = true else {
armed = false
// At once: the page drops the game and the rest runs off this dialog's life.
onRemove(folder, game?.appId, game?.name ?: preview.name)
if (request.fromSummary) onBack()
close()
@@ -304,7 +285,6 @@ internal fun AddedGameEditor(
}
}
/** Start in as a path on the device: the override mapped back under the game's folder, else the exe's folder. */
private fun hostPath(context: android.content.Context, game: AddedGames.Game): String {
val folderGuest = AddedGames.guestPath(context, game.folder) ?: return game.exe.parentFile?.path.orEmpty()
return when {
@@ -322,7 +302,6 @@ private fun ValueText(text: String, muted: Boolean = false) {
)
}
/** "Remove" in red; pressed once it asks, a second press within four seconds removes. */
@Composable
private fun RemoveRow(armed: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -344,7 +323,6 @@ private fun RemoveRow(armed: Boolean, onClick: () -> Unit) {
}
}
/** One line of text in a compact dialog: [title] and a red X, the field, OK. */
@Composable
internal fun TextEntryDialog(title: String, initial: String, onDismiss: () -> Unit, onSave: (String) -> Unit) {
val shown = rememberShown(onDismiss)
@@ -365,11 +343,6 @@ internal fun TextEntryDialog(title: String, initial: String, onDismiss: () -> Un
}
}
/**
* The art chooser for one [slot]: back, the slot's name and a red X; the images grouped by where
* they come from (the game's folder, Steam, SteamGridDB, fetched as it opens), the current one
* outlined, a tap applies it; "Pick image…" and "Reset to automatic".
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun ArtChooserDialog(
@@ -456,12 +429,6 @@ private fun ArtOption(slot: AddedGameArt.Slot, option: AddedGameArt.Option, sele
}
}
/**
* After "Add all games in this folder": how many were added and how many were there already, then
* one row per added game (cover, name, exe, "?" where unsure); a row opens that game's editor.
* [games] are the added games as the add left them, shown at once; the rows then follow edits and
* removals, and the covers arrive.
*/
@Composable
internal fun AddedGamesSummaryDialog(
games: List<AddedGames.Game>, already: Int, checking: String? = null,
@@ -478,8 +445,6 @@ internal fun AddedGamesSummaryDialog(
var gone by remember { mutableStateOf(emptySet<String>()) }
var armed by remember { mutableStateOf<String?>(null) }
LaunchedEffect(armed) { if (armed != null) { kotlinx.coroutines.delay(4_000); armed = null } }
// Rows show as the games arrive; each is refreshed once (current name and exe, a removed one
// dropped) and gets its cover, without redoing the ones already done when more arrive.
var resolved by remember { mutableStateOf(emptyMap<String, Pair<AddedGames.Game, File?>?>()) }
LaunchedEffect(games) {
for (old in games) {
@@ -534,7 +499,6 @@ internal fun AddedGamesSummaryDialog(
}
}
/** A summary row's red X: the first press arms it (filled), a second within 4 s removes the game. */
@Composable
private fun RemoveX(armed: Boolean, description: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -10,7 +10,6 @@ internal fun scaledAppDensity(base: Density, percent: Int): Density {
return if (scale == 1f) base else Density(base.density * scale, base.fontScale)
}
/** Responsive layouts and popup height limits must see the same dp space as the scaled UI. */
internal fun scaledAppConfiguration(base: Configuration, percent: Int): Configuration {
val scale = AppUiPrefs.normalizeScale(percent) / 100f
if (scale == 1f) return base
@@ -97,28 +97,21 @@ import kotlinx.coroutines.withContext
import java.text.DateFormat
import java.util.Date
/** The Components page's layer for the GPU drivers, under every Proton's. */
const val GPU_TAB = "gpu"
/** The Components page's layer for the Proton itself, the one the indented layers belong to. */
const val PROTON_TAB = "proton"
/** The stack's layers, top to bottom: LB / RB and the d-pad walk them in this order. */
internal val LAYERS = listOf(PROTON_TAB, "dxvk", "vkd3d", "fex", GPU_TAB)
/** The layer [by] steps from [current] (LB -1, RB +1), wrapping round the stack. */
internal fun layerStep(current: String, by: Int): String {
val i = LAYERS.indexOf(current).coerceAtLeast(0)
return LAYERS[((i + by) % LAYERS.size + LAYERS.size) % LAYERS.size]
}
/** One installed row: a Proton's original bundle (one per Proton build) or a stored package. */
private class InstalledItem(
val name: String, val detail: String, val tag: String,
val selected: Boolean, val removable: Boolean,
/** Stored package file, or null for an original. */
val file: String?,
/** The Proton build an original belongs to. */
val protonVersion: String?,
)
@@ -134,14 +127,6 @@ private val QUEUED = Color(0xFFFFB86B)
private val ROW_SHAPE = RoundedCornerShape(10.dp)
private val LAYER_SHAPE = RoundedCornerShape(12.dp)
/**
* Everything a game runs on, as one stack: the Proton, its DXVK, VKD3D-Proton and FEX indented
* under it because they belong to it, then the GPU drivers that every Proton shares. One selection
* glides along the stack (LB / RB, or the d-pad in it); beside it a detail frame that never moves -
* what is in use, what is installed and what is available, and what else can be done - only its
* rows trade places. A swap is asked for by stepping out of its row, and the row flies home to its
* layer. On a narrow page the stack is the page, and a layer's detail floods out of its card.
*/
@Composable
fun ComponentsPage(
snapshot: Snapshot?,
@@ -167,13 +152,10 @@ fun ComponentsPage(
generalFexPreset: String = "",
onGeneralFexPreset: (String) -> Unit = {},
requestInitialFocus: Boolean = true,
/** The GPU drivers layer ([GPU_TAB]): what it shows and does. */
gpu: GpuDriversState = GpuDriversState(),
gpuActions: GpuDriversActions = GpuDriversActions(),
/** The Proton layer ([PROTON_TAB]): the Protons DroidDeck can install, and installing them. */
protons: ProtonsState = ProtonsState(),
protonActions: ProtonsActions = ProtonsActions(),
/** The Proton layer's options for every Proton (sync, FEX preset, SSBS, environment). */
protonOptions: @Composable () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
@@ -391,12 +373,10 @@ fun ComponentsPage(
val views = snapshot?.protons ?: emptyList()
val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull()
// Where things sit, root px: each layer card, each row (for a swap's dot), the page itself.
val cardsAt = remember { mutableStateMapOf<String, Rect>() }
val rowsAt = remember { HashMap<String, Rect>() }
var stackAt by remember { mutableStateOf(Offset.Zero) }
var pageAt by remember { mutableStateOf(Offset.Zero) }
// A layer card pops and rings as a swap's dot lands on it, and rings as a hop arrives on it.
val landed = remember { mutableStateMapOf<String, Int>() }
val rings = remember { mutableStateMapOf<String, Int>() }
fun land(l: String) { landed[l] = (landed[l] ?: 0) + 1; rings[l] = (rings[l] ?: 0) + 1 }
@@ -404,24 +384,20 @@ fun ComponentsPage(
LaunchedEffect(Hops.arrived) {
if (Hops.arrived == arrivedSeen[0]) return@LaunchedEffect
arrivedSeen[0] = Hops.arrived
// Once the page has flooded in from the rail.
delay(Motion.ms(700).toLong())
rings[layer] = (rings[layer] ?: 0) + 1
}
/** The row at [key] squashes into a dot and flies home to [to]'s card, which pops on landing. */
fun flyHome(key: String, to: String) {
val from = rowsAt[key] ?: return land(to)
Flights.fly(Flight(from, to = { cardsAt[to]?.center }, onLand = { land(to) }))
}
// A confirm stepping out of the row that asked: right of a left-column row, left of a right one.
fun ask(key: String, right: Boolean, title: String, note: String, verb: String, danger: Boolean, face: String = "", then: () -> Unit) {
val at = rowsAt[key] ?: return then()
val cancel = ctx.getString(R.string.common_cancel)
Steps.ask(StepAsk(
anchor = at, side = if (right) StepSide.Left else StepSide.Right,
accent = if (danger) colors.error else pal.signal, pillCorner = 10.dp, items = 3, maxWidth = 340.dp,
// The row's own name rides on top, as the pull's handle.
handle = {
Box(Modifier.fillMaxSize().padding(start = 46.dp, end = 14.dp), contentAlignment = Alignment.CenterStart) {
Text(face, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = if (danger) colors.error else pal.signal, maxLines = 2, overflow = TextOverflow.Ellipsis)
@@ -437,7 +413,6 @@ fun ComponentsPage(
})
}
// The runtime and display drivers on their own pages, flooding out of the link that opens them.
var driverPage by remember { mutableStateOf<String?>(null) }
var driverShown by remember { mutableStateOf<String?>(null) }
var driverLeaving by remember { mutableStateOf(false) }
@@ -450,7 +425,6 @@ fun ComponentsPage(
driverShown = null; driverLeaving = false; driverFrom = null
}
}
// Narrow: a layer's detail floods out of its card, and B draws it back in.
var narrowOpen by rememberSaveable { mutableStateOf<String?>(null) }
var narrowShown by remember { mutableStateOf<String?>(null) }
var narrowLeaving by remember { mutableStateOf(false) }
@@ -466,21 +440,17 @@ fun ComponentsPage(
BackHandler(enabled = driverPage != null || narrowOpen != null) {
if (driverPage != null) driverPage = null else narrowOpen = null
}
// Leaving the page: nothing stays stepped out of a row that is no longer on screen.
androidx.compose.runtime.DisposableEffect(Unit) { onDispose { Steps.drop() } }
val checked = if (catalogAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(catalogAt * 1000)) else stringResource(R.string.comp_never)
val firstRow = remember { FocusRequester() }
val layerFocus = remember { LAYERS.associateWith { FocusRequester() } }
// Arrived (from the rail, a hop, a game's card): a pad starts on the chosen layer.
LaunchedEffect(requestInitialFocus) {
if (!requestInitialFocus || selectedGame != null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
delay(Motion.ms(200).toLong())
focusSoon { layerFocus.getValue(layer) }
}
var travel by remember { mutableIntStateOf(1) }
// LB / RB (taken by the activity before the page sees them): a pad anywhere on the page goes to
// the new layer's card, so one on a row - which leaves with its layer - is never left with nothing.
var pageFocused by remember { mutableStateOf(false) }
val seenLayer = remember { arrayOf(layer) }
LaunchedEffect(layer) {
@@ -494,7 +464,6 @@ fun ComponentsPage(
if (l != layer) { travel = if (LAYERS.indexOf(l) > LAYERS.indexOf(layer)) 1 else -1; onComp(l) }
}
// ---- one layer's detail, a slot at a time ------------------------------------------------------
val compState = { l: String -> view?.components?.get(l) }
val bar: @Composable (String) -> Unit = { l ->
when (l) {
@@ -531,7 +500,6 @@ fun ComponentsPage(
}
}
// Installed and Available, as (title, rows) for a layer; [right] says which column it is in.
var showAllPairs by rememberSaveable { mutableStateOf(false) }
val installedTitle: @Composable (String) -> String = { l ->
when (l) {
@@ -643,8 +611,6 @@ fun ComponentsPage(
}
}
PROTON_TAB -> {
// Not installed, and installed with a newer release out: an update goes in beside the
// build it replaces, which stays until it is removed (games are mapped to it by name).
val rows = protons.rows.filter { it.installed == null || it.update != null }
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_new))
for (row in rows) GetLine(
@@ -731,17 +697,13 @@ fun ComponentsPage(
}
}
// ---- the frame ------------------------------------------------------------------------------
val detail: @Composable (String, Boolean) -> Unit = { l, narrowPage ->
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) {
// Two columns while each gets room for a row's name and its Get; one under the other below that.
val single = narrowPage || maxWidth < 600.dp
Column(Modifier.fillMaxSize()) {
// The in-use bar keeps its place; only its words change.
AnimatedContent(l, transitionSpec = { fadeIn(Motion.tw(240)) togetherWith fadeOut(Motion.tw(160)) }, label = "inUse") { k -> bar(k) }
val detailScroll = androidx.compose.runtime.key(l) { rememberScrollState() }
Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(detailScroll).padding(top = 12.dp, bottom = 16.dp)) {
// Shared performance settings stay visible before the downloadable catalog.
if (l == PROTON_TAB) {
if (!protons.runtimeReady) EmptyLine(stringResource(R.string.content_needs_runtime))
if (protons.sessionRunning) EmptyLine(stringResource(R.string.proton_stop_first))
@@ -801,7 +763,6 @@ fun ComponentsPage(
onNext = { pick(layerStep(layer, 1)) },
) else Modifier),
) {
// ---- header: the title, the device, when the lists were checked and the one refresh ----
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
Text(stringResource(R.string.comp_title), fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
if (!narrow) DeviceChip(gpu)
@@ -894,7 +855,6 @@ fun ComponentsPage(
)
} else {
Row(Modifier.weight(1f).fillMaxWidth()) {
// ---- the stack ----
Box(
(if (narrow) Modifier.fillMaxWidth() else Modifier.width(250.dp)).fillMaxHeight()
.onGloballyPositioned { stackAt = it.positionInRoot() },
@@ -911,7 +871,6 @@ fun ComponentsPage(
else runCatching { firstRow.requestFocus() }
},
)
// Over the cards: under them, their rest fill hid it as it crossed them.
ChipGlide(LAYERS.indexOf(layer), local, tint, GlideAxis.Vertical, corner = 12.dp)
}
if (!narrow) {
@@ -921,7 +880,6 @@ fun ComponentsPage(
}
}
}
// Narrow: the layer's detail over the stack, out of its card.
narrowShown?.let { l ->
val from = cardsAt[l]?.let { Origin(it.translate(-pageAt), 12f * density.density) }
val body: @Composable () -> Unit = {
@@ -936,7 +894,6 @@ fun ComponentsPage(
}
if (from == null) body() else PageFlood(from, narrowLeaving) { body() }
}
// The runtime or display driver on its own page.
driverShown?.let { d ->
val body: @Composable () -> Unit = {
Box(Modifier.fillMaxSize().background(colors.background).pointerInput(Unit) { detectTapGestures { } }) {
@@ -967,7 +924,6 @@ fun ComponentsPage(
onDismissRequest = { confirm = null },
title = { Text(confirmTitle) },
text = { Text(body, fontSize = 14.sp) },
// Opens on Cancel, so a stray A press on a controller never swaps or deletes anything.
confirmButton = {
val del = confirmVerb == R.string.common_delete || confirmVerb == R.string.comp_game_reset
FocusText(stringResource(confirmVerb), if (del) colors.error else pal.signal) { confirm = null; action() }
@@ -1008,7 +964,6 @@ fun ComponentsPage(
}
}
/** The Installed rows of one component layer for the Proton the page shows. */
@Composable
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?): List<InstalledItem> {
view ?: return emptyList()
@@ -1027,7 +982,6 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
}
}
/** The Nightlies of one component layer that are not stored yet. */
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> {
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
@@ -1040,14 +994,8 @@ private fun LayerTitle(l: String): String = when (l) {
else -> ComponentsManager.LABEL[l] ?: l
}
/** Records where a row sits, for the confirm that steps out of it and the dot that flies from it. */
private fun Modifier.trackRow(key: String, into: HashMap<String, Rect>): Modifier = onGloballyPositioned { into[key] = it.boundsInRoot() }
/**
* The stack: a heading over the Proton and the three layers that belong to it (indented, on a
* line), then a heading over the GPU drivers that every Proton shares. Each card is a layer's name
* and what it is set to; a dot marks a layer swapped away from its original.
*/
@Composable
private fun Stack(
layer: String, view: ComponentsManager.ProtonView?, gpu: GpuDriversState,
@@ -1096,7 +1044,6 @@ private fun StackHeading(text: String) {
)
}
/** One layer: 40dp to see, 44 to touch; its name, what it is set to, and a dot when it is swapped. */
@Composable
private fun LayerCard(
title: String, value: String, swapped: Boolean, selected: Boolean, landed: Int, ring: Int,
@@ -1106,7 +1053,6 @@ private fun LayerCard(
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
// The stack's glide draws the picked card's look by touch only; with a pad, its rest look and the bar.
val under = selected && androidx.compose.ui.platform.LocalInputModeManager.current.inputMode != androidx.compose.ui.input.InputMode.Keyboard
Box(Modifier.fillMaxWidth().heightIn(min = 44.dp), contentAlignment = Alignment.Center) {
Row(
@@ -1125,7 +1071,6 @@ private fun LayerCard(
if (swapped) Box(Modifier.size(7.dp).clip(CircleShape).background(pal.signal))
Text(title, fontSize = 13.5.sp, fontWeight = FontWeight.Bold, color = if (selected || hot) colors.onBackground else colors.onSurfaceVariant, maxLines = 1)
Spacer(Modifier.weight(1f))
// The value ticks over as a swap lands.
AnimatedContent(
value,
transitionSpec = { (slideInVertically(Motion.tw(260)) { it / 2 } + fadeIn(Motion.tw(260))) togetherWith (slideOutVertically(Motion.tw(160)) { -it / 2 } + fadeOut(Motion.tw(160))) },
@@ -1135,7 +1080,6 @@ private fun LayerCard(
}
}
/** What is in use for the layer: a dot (green, or amber while a change waits), a sentence, and a note or Cancel. */
@Composable
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null) {
val colors = MaterialTheme.colorScheme
@@ -1152,7 +1096,6 @@ private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel:
}
}
/** A titled column of rows. */
@Composable
private fun RowGroup(title: String, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -1437,10 +1380,6 @@ internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = fa
}
}
/**
* A small button. Resting: grey outline (blue text when [accent]). Focused or hovered: a solid blue
* fill with an outline in the text colour - unmistakable in a column of identical buttons.
*/
@Composable
private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -1485,10 +1424,6 @@ private fun Tag(text: String) {
)
}
/**
* One installed choice: a radio for the one in use, its name and detail, and a trash at the right
* of the ones that can go. [progress] shows a download for it in place of the tag.
*/
@Composable
private fun ChoiceLine(
name: String, detail: String, selected: Boolean, removable: Boolean,
@@ -1525,10 +1460,8 @@ private fun ChoiceLine(
}
DetailLine(detail, badge)
}
// The radio says which is in use; a download in flight shows where a tag would.
if (progress != null) ProgressBit(progress)
}
// The trash column is always there (empty when the row can't be deleted) so rows line up.
if (!removable) Spacer(Modifier.padding(end = 6.dp).size(44.dp))
else {
val delSrc = remember { MutableInteractionSource() }
@@ -1546,7 +1479,6 @@ private fun ChoiceLine(
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
/** One thing not installed yet: its name and detail, and Get - its download shown in the row once started. */
@Composable
private fun GetLine(
name: String, detail: String, progress: Int?, enabled: Boolean,
@@ -1571,7 +1503,6 @@ private fun GetLine(
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
/** A row's second line, led by [badge] (Recommended) in green when there is one. */
@Composable
private fun DetailLine(detail: String, badge: String?) {
val colors = MaterialTheme.colorScheme
@@ -1599,10 +1530,6 @@ private fun ProgressBit(progress: Int) {
}
}
/**
* The GPU and how far it is supported, as a chip: a green dot and "<GPU> · tested", amber when it
* is not. A steps the device's full details out of it, with the copy for a bug report.
*/
@Composable
private fun DeviceChip(s: GpuDriversState) {
val colors = MaterialTheme.colorScheme
@@ -1643,7 +1570,6 @@ private fun DeviceChip(s: GpuDriversState) {
) { face() }
}
/** What the Proton layer installs: the Protons DroidDeck can download, and one being installed. */
class ProtonsState(
val rows: List<ProtonRow> = emptyList(),
val busyId: String? = null,
@@ -1656,16 +1582,10 @@ class ProtonsState(
class ProtonsActions(
val onInstall: (String) -> Unit = {},
val onCancel: (String) -> Unit = {},
/** The source's id and the installed folder to delete. */
val onRemove: (String, String) -> Unit = { _, _ -> },
/** Deletes every build of the source but the newest. */
val onRemoveOlder: (String) -> Unit = {},
)
/**
* A Proton DroidDeck can install: the folder its newest build is installed as (null when it is
* not), every installed build oldest first, and a newer release's tag when one is out.
*/
class ProtonRow(
val id: String, val name: String, val installed: String?, val queued: Boolean,
val installedAll: List<String> = listOfNotNull(installed), val update: String? = null,
@@ -11,11 +11,6 @@ import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
/**
* The session's pointer. [image]: the program's own cursor (wl_pointer.set_cursor - labwc's resize
* arrows, a text field's I-beam), in session pixels, drawn [imageScale] times larger with its hotspot
* ([hotX], [hotY]) on [position]; null = the program has not set one, and the built-in arrow is drawn.
*/
@Composable
fun CursorOverlay(
position: Offset, visible: Boolean, scale: Float,
@@ -27,16 +27,6 @@ import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.min
/**
* The Steam Deck controller's back grips and trackpads, on the second screen.
*
* Four tabs: the grips as a 2x2 grid (left grips on the left, upper above lower, as they sit on a
* Deck); either trackpad on its own with a bar to click it; and both trackpads with the grips in a
* row beneath. Given the [pad] (the unfolded screen's panel), a fifth: a whole gamepad, each side
* an analog stick or a trackpad as the player picks. A trackpad clicks from its bar or from a second finger while the first is down.
* Drawn for OLED: true black, with outlines rather than filled surfaces, and the Steam blue only
* where something is being touched.
*/
@SuppressLint("ViewConstructor")
class DeckControlsPanel(
context: Context,
@@ -61,8 +51,6 @@ class DeckControlsPanel(
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
// Held flat the gamepad has no Panels button, so another tab would have no way back:
// turning the phone from upright onto its side returns to the gamepad.
if (pad != null && selectedWithPad != Tab.GAMEPAD && !GamepadGeometry.tall(w.toFloat(), h.toFloat())) {
post { if (selectedWithPad != Tab.GAMEPAD) select(Tab.GAMEPAD) }
}
@@ -115,7 +103,6 @@ class DeckControlsPanel(
view.setTextColor(if (on) ON_ACCENT else TEXT_DIM)
}
content.removeAllViews()
// The gamepad needs every row of the panel; held upright its Panels button brings the tabs back.
topBar.visibility = if (tab == Tab.GAMEPAD) View.GONE else View.VISIBLE
content.addView(
when (tab) {
@@ -159,7 +146,6 @@ class DeckControlsPanel(
addView(TrackpadView(context, right = true), LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { leftMargin = dp(6) })
}
addView(pads, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { bottomMargin = dp(12) })
// Mirrored, as hands hold them: the upper grips outside, the lower ones in the middle.
val grips = LinearLayout(context).apply {
orientation = HORIZONTAL
val row = listOf("L4" to DeckControls.L4, "L5" to DeckControls.L5, "R5" to DeckControls.R5, "R4" to DeckControls.R4)
@@ -173,15 +159,6 @@ class DeckControlsPanel(
addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84)))
}
/**
* A whole pad, placed for two thumbs rather than in columns (see [GamepadGeometry]): on each side
* a surface where the thumb rests - most of play is on the sticks or trackpads - and a short
* slide inward along its arc, the d-pad on the left and the face buttons on the right; the bumpers and triggers above, at the top of the arc; View, Steam, QAM and Menu in the
* middle, which a thumb only reaches on purpose. Each surface is an analog stick or a Steam
* trackpad, switched from its corner and remembered (SessionPrefs.gamepadSurface). Its tab bar
* is hidden; held upright, a Panels button brings the other tabs back, and held flat there is no
* room for one.
*/
private fun gamepad(pad: PadBridge): View = GamepadLayout(context).apply {
fun pill(label: String, write: (PadState, Boolean) -> Unit) = PadButton(context, pad, label, write)
place(surfaceSlot(pad, right = false), GamepadGeometry.Slot.LEFT_MAIN)
@@ -215,13 +192,11 @@ class DeckControlsPanel(
}
}
/** One side's stick or trackpad, with a chip in its outer corner that swaps the two. */
private fun surfaceSlot(pad: PadBridge, right: Boolean): View = FrameLayout(context).apply {
val slot = this
fun show() {
slot.removeAllViews()
val stick = SessionPrefs.gamepadSurface(context, right) == SessionPrefs.SURFACE_STICK
// No caption: the switch in its corner says which it is.
slot.addView(if (stick) StickView(context, pad, right) else TrackpadView(context, right, captioned = false),
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
val chip = TextView(context).apply {
@@ -239,7 +214,6 @@ class DeckControlsPanel(
show()
}
}
// In the corner away from the thumb, so play does not swap it by accident.
slot.addView(chip, FrameLayout.LayoutParams(dp(30), dp(30),
(if (right) Gravity.START else Gravity.END) or Gravity.TOP).apply { setMargins(dp(6), dp(6), dp(6), dp(6)) })
}
@@ -280,7 +254,6 @@ class DeckControlsPanel(
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
/** A surface drawn the same way everywhere on the panel; pressed, it lights up in the accent. */
private abstract class Surface(context: Context) : View(context) {
protected val density = resources.displayMetrics.density
protected val rect = RectF()
@@ -307,7 +280,6 @@ class DeckControlsPanel(
}
}
/** A held button: down while a finger is on it. */
private open class HoldButton(
context: Context,
private val label: String,
@@ -353,10 +325,6 @@ class DeckControlsPanel(
private class ClickBar(context: Context, right: Boolean) :
HoldButton(context, context.getString(R.string.deck_click), if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad), { DeckControls.setClick(right, it) })
/**
* One trackpad: where the first finger is, as the Deck reports it (-1..1, y up), and a click
* while a second finger is down.
*/
private class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true) : Surface(context) {
private var touching = false
private var clicked = false
@@ -396,7 +364,6 @@ class DeckControlsPanel(
}
MotionEvent.ACTION_POINTER_DOWN -> click(true)
MotionEvent.ACTION_POINTER_UP -> {
// The finger that lifted may be the first; the pad follows whichever stays.
val stays = if (event.actionIndex == 0) 1 else 0
touch(event.getX(stays), event.getY(stays))
click(event.pointerCount - 1 > 1)
@@ -428,7 +395,6 @@ class DeckControlsPanel(
}
}
/** A pad button held while a finger is on it, written into the shared pad as the on-screen pad does. */
private class PadButton(
context: Context,
private val pad: PadBridge,
@@ -441,11 +407,6 @@ class DeckControlsPanel(
}
}
/**
* An analog stick that centres where the thumb lands, so it is never missed: the knob follows
* the finger from there out to the ring. Tapping it again and holding (within [CLICK_MS]) is
* the stick's click - L3 or R3 - for as long as the thumb stays down.
*/
private class StickView(context: Context, private val pad: PadBridge, private val right: Boolean) : Surface(context) {
private var touching = false
private var clicking = false
@@ -475,7 +436,6 @@ class DeckControlsPanel(
val r = reach().coerceAtLeast(1f)
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
// Centred where the thumb lands, but kept far enough in for the ring to fit.
originX = event.x.coerceIn(r, (width - r).coerceAtLeast(r))
originY = event.y.coerceIn(r, (height - r).coerceAtLeast(r))
touching = true
@@ -525,10 +485,9 @@ class DeckControlsPanel(
}
}
/** The d-pad: the direction is the finger's angle from the centre, diagonals included. */
private class DirectionPad(context: Context, private val pad: PadBridge) : View(context) {
private val density = resources.displayMetrics.density
private var held = 0 // bits: 1 up, 2 right, 4 down, 8 left
private var held = 0
private val arm = Paint(Paint.ANTI_ALIAS_FLAG)
private val rect = RectF()
@@ -558,7 +517,6 @@ class DeckControlsPanel(
val dx = event.getX(0) - width / 2f
val dy = event.getY(0) - height / 2f
if (hypot(dx, dy) < min(width, height) * 0.08f) 0 else {
// Eight sectors of 45 degrees, starting with right and going clockwise.
val sector = ((Math.toDegrees(atan2(dy.toDouble(), dx.toDouble())) + 360 + 22.5) % 360 / 45).toInt()
intArrayOf(2, 2 or 4, 4, 4 or 8, 8, 8 or 1, 1, 1 or 2)[sector]
}
@@ -585,7 +543,6 @@ class DeckControlsPanel(
}
}
/** A, B, X and Y in a diamond, as on a Deck; several fingers can hold several at once. */
private class FaceButtons(context: Context, private val pad: PadBridge) : View(context) {
private val buttons = listOf(PadState.Y to "Y", PadState.B to "B", PadState.A to "A", PadState.X to "X")
private var held = emptySet<Int>()
@@ -595,7 +552,6 @@ class DeckControlsPanel(
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
}
/** Top, right, bottom, left - the centre of each, and the radius of all. */
private fun layout(): Pair<List<Pair<Float, Float>>, Float> {
val cx = width / 2f
val cy = height / 2f
@@ -626,7 +582,6 @@ class DeckControlsPanel(
if (event.actionMasked == MotionEvent.ACTION_POINTER_UP && p == event.actionIndex) continue
val x = event.getX(p)
val y = event.getY(p)
// The nearest button within reach, so a thumb between two still lands on one.
val nearest = centres.indices.minByOrNull { hypot(centres[it].first - x, centres[it].second - y) } ?: continue
if (hypot(centres[nearest].first - x, centres[nearest].second - y) <= radius * 1.6f) now.add(buttons[nearest].first)
}
@@ -649,7 +604,6 @@ class DeckControlsPanel(
}
}
/** Lays its controls out where [GamepadGeometry] puts them for the panel's size. */
private class GamepadLayout(context: Context) : ViewGroup(context) {
private val slots = LinkedHashMap<View, GamepadGeometry.Slot>()
@@ -686,12 +640,9 @@ class DeckControlsPanel(
}
companion object {
/** A second press on a stick this soon after the last is its click (L3, R3). */
private const val CLICK_MS = 300L
/** The tab last shown, kept for the session so reopening the panel lands where it was. */
private var selected = Tab.BOTH
/** The same for the unfolded screen's panel, which opens on the gamepad. */
private var selectedWithPad = Tab.GAMEPAD
private const val CORNER = 20f
@@ -93,12 +93,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
// The Desktop tab in the Steam tab's shape: a tilted wall of little windows behind the word and
// one big Open desktop, with Play's lip and lifted sheet under it (Display, Controls, Session and
// Files). Under the hero the page scrolls to two shelves - the apps that run in the desktop, and
// what can be added - and the hero folds into a slim header as it goes.
/** The desktop's own chips: its session settings, then Files. */
private val DESKTOP_TABS = modeSheetTabs(steam = false) + SheetTab.FILES
@Composable
@@ -108,7 +103,6 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
val narrow = LocalNarrowPane.current
val colors = MaterialTheme.colorScheme
LaunchedEffect(Unit) { UserAppsState.refresh(ctx) }
// Flathub's installed apps sit with the others on the dock.
LaunchedEffect(s.ready) { com.droiddeck.launcher.store.StoreState.refresh(ctx) }
val installed = s.emulators.filter { it.installed }
val apps = UserAppsState.items
@@ -116,14 +110,11 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
val mode = SessionService.MODE_DESKTOP
val tabs = DESKTOP_TABS.map { it to sheetTabLabel(it) }
val open = if (s.desktopInstalled) stringResource(R.string.content_open_desktop) else stringResource(R.string.content_install_open_desktop)
// Opened from a card: the page floods out of it, its picture on the tile.
fun openFrom(at: Rect?, art: Any?, page: String) {
at?.let { PageOrigin.mark(Origin(it, 16f * density.density, art = art)) }
onSelect(page)
}
// The Steam tab's shape, the whole pane: the dock of apps along the top of the wall, the word
// and Open desktop at the foot, and nothing under the settings sheet but the hero itself.
LiftHero(
key = "desktop", tabs = tabs,
onOpen = a.onDesktopSettings, onPrimary = a.onDesktop,
@@ -134,15 +125,12 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
},
scrim = { lifted ->
WallFade()
// Over the fades, so the cards read at full strength; gone as the sheet lifts, so
// nothing but the wall is behind it.
Box(Modifier.graphicsLayer { val v = lifted(); alpha = 1f - v; translationY = -12.dp.toPx() * v }) {
DesktopDock(s, a, installed, apps, openFrom = ::openFrom)
}
},
words = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
// The word at the wordmark's size.
Text(
stringResource(R.string.rail_desktop), fontSize = if (narrow) 30.sp else 42.sp, lineHeight = if (narrow) 34.sp else 46.sp,
fontWeight = FontWeight.Black, color = colors.onBackground,
@@ -151,13 +139,10 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
}
},
button = { click ->
// Enabled without a runtime or the desktop: the session's loading screen installs them first.
PrimaryButton(open, enabled = !s.busy, main = true, large = true, icon = Icons.Outlined.DesktopWindows, onClick = click)
},
beside = {
// Flathub, whose apps run in the desktop: its storefront floods out of this button.
HeroIconButton(Icons.Outlined.Storefront, stringResource(R.string.flathub_name), FlathubTeal, "desktop:flathub") { at -> openFrom(at, null, "store") }
// Add your own app or game.
HeroIconButton(Icons.Filled.Add, stringResource(R.string.user_apps_add), null, "desktop:add") { if (!s.busy) adding = true }
},
rows = { tab ->
@@ -168,11 +153,6 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
if (adding && !s.busy) AddAppDialog(s.ready, onDismiss = { adding = false }) { request, label -> UserAppsState.add(ctx, request, label) }
}
/**
* The dock along the top of the Desktop hero: what runs in the desktop (emulators installed, apps
* added, Flathub's installed apps), then the emulators that can be added - one
* row of cards that scrolls sideways, over the wall. It sinks back with the wall as the sheet lifts.
*/
@Composable
private fun DesktopDock(
s: FrontEndState, a: FrontEndActions, installed: List<Library.Emulator>, apps: List<UserApps.App>,
@@ -184,14 +164,12 @@ private fun DesktopDock(
val available = s.emulators.filter { !it.installed }
val flatpaks = com.droiddeck.launcher.store.StoreState.installed
val keys = installed.map { "emu:${it.id}" } + apps.map { "user:${it.key}" } + flatpaks.map { "flatpak:${it.id}" }
// Where the last of your apps sits, for a new emulator's dot to land after it.
var lastAt by remember { mutableStateOf<Rect?>(null) }
var dockAt by remember { mutableStateOf<Rect?>(null) }
val seen = remember { mutableSetOf<String>() }
val mounted = remember { booleanArrayOf(false) }
LaunchedEffect(Unit) { mounted[0] = true }
val scroll = rememberScrollState()
// Nothing yet (the emulators' catalog still on its way): no heading over an empty row.
if (keys.isEmpty() && available.isEmpty() && UserAppsState.working == null && UserAppsState.lastError == null) return
Column(Modifier.fillMaxWidth().padding(top = if (narrow) 14.dp else 22.dp)) {
Text(
@@ -205,7 +183,6 @@ private fun DesktopDock(
) {
keys.forEachIndexed { i, k ->
key(k) {
// A card that arrives after the dock is up (an emulator just installed) opens in.
val state = remember { MutableTransitionState(!mounted[0] || k in seen) }.apply { targetState = true }
LaunchedEffect(Unit) { seen += k }
AnimatedVisibility(state, enter = expandHorizontally(Motion.sp(0.75f)) + fadeIn(Motion.tw(300, 80))) {
@@ -224,7 +201,6 @@ private fun DesktopDock(
k, flatpak.name, flatpak.summary ?: stringResource(R.string.flathub_name),
art = flatpak.icon ?: com.droiddeck.launcher.store.FlathubApi.iconUrl(flatpak.id), first = i == 0,
) { at ->
// Its page on Flathub: open, update or remove it there.
com.droiddeck.launcher.store.StoreState.openRequest = flatpak.id
openFrom(at, flatpak.icon, "store")
} else if (app != null) DesktopCard(k, app.name, stringResource(app.kind.label()), art = app.icon, fallback = if (app.kind == UserApps.Kind.SCRIPT) Icons.Outlined.Terminal else Icons.Outlined.Apps, first = i == 0) { at ->
@@ -234,7 +210,6 @@ private fun DesktopDock(
}
}
}
// Between yours and what can be added: a thin rule.
if (keys.isNotEmpty()) Box(Modifier.padding(horizontal = 4.dp).width(1.dp).height(120.dp).background(pal.line2))
available.forEach { e ->
key(e.id) {
@@ -247,8 +222,6 @@ private fun DesktopDock(
art = e.iconRes, badge = if (busyHere) null else stringResource(R.string.comp_get),
progress = if (busyHere) s.packagePercent else null, first = keys.isEmpty() && e == available.first(),
) { at ->
// Get installs it there and then, and a dot flies to where its card will be;
// when it cannot (no runtime, a session running), its page says why.
if (canGet && pkg != null && at != null) {
a.onInstallPackage(pkg.id)
val end = lastAt
@@ -268,10 +241,6 @@ private fun DesktopDock(
}
}
/**
* A square button the big one's height beside it on the hero: an icon in [tint] (the palette's
* signal when null). [onClick] gets its bounds, for a page to flood out of.
*/
@Composable
private fun HeroIconButton(icon: androidx.compose.ui.graphics.vector.ImageVector, description: String, tint: Color?, id: String, onClick: (Rect?) -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -295,10 +264,6 @@ private fun HeroIconButton(icon: androidx.compose.ui.graphics.vector.ImageVector
) { Icon(icon, null, tint = accent, modifier = Modifier.size(26.dp)) }
}
/**
* The hero's wall: little windows tilted and drifting as Steam's capsules do, each a window with a
* bar along its foot and an emulator's or app's icon inside; blank windows when there are none.
*/
@Composable
private fun DesktopWall(icons: List<Any>) {
val pal = LocalPalette.current
@@ -308,11 +273,6 @@ private fun DesktopWall(icons: List<Any>) {
}
}
/**
* One thing that runs in the desktop: its icon over a blurred, darkened copy of itself, a status on
* the art (Get, or how far an install is), and under it its name on up to two lines and what it
* is. [onClick] gets the art's bounds, for a page to flood out of or a dot to fly from.
*/
@Composable
private fun DesktopCard(
key: String, name: String, detail: String, art: Any?,
@@ -384,10 +344,6 @@ private fun DesktopCard(
}
}
/**
* The desktop sheet's Files chip: the file manager and the ROMs folder (both from Setup's old
* tools), how much the desktop takes, and Uninstall - its only home - which asks in red first.
*/
@Composable
private fun DesktopFiles(s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
@@ -408,7 +364,6 @@ private fun DesktopFiles(s: FrontEndState, a: FrontEndActions) {
}
}
/** Uninstall the desktop: are you sure steps out of it in red, Keep first and focused. */
@Composable
private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -435,7 +390,6 @@ private fun UninstallDesktop(enabled: Boolean, onUninstall: () -> Unit) {
}
}
/** The add or remove under way, or why the last one failed. */
@Composable
private fun UserAppsProgressLine() {
val colors = MaterialTheme.colorScheme
@@ -55,13 +55,6 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* One driver list as a full page - the Runtime driver or the Display driver - opened from the
* session's settings page. Installed drivers are picked by tapping the row and each carries a trash
* can (the "Auto"/"Runtime default" row is a setting, not a driver, so it has none); what the last
* check of the release repos found is offered below; the refresh button beside the title is the
* only thing that goes online.
*/
@Composable
fun DriverPage(
title: String,
@@ -85,16 +78,13 @@ fun DriverPage(
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var confirm by remember { mutableStateOf<DriverRow?>(null) }
// Back (the controller's B too) closes this page only, back to the session's settings.
BackHandler(onBack = onBack)
// D-pad: up from the first driver lands on refresh; the page opens with the driver in use focused.
val refreshFocus = remember { FocusRequester() }
val selectedFocus = remember { FocusRequester() }
val inputMode = LocalInputModeManager.current
var pageFocused by remember { mutableStateOf(false) }
LaunchedEffect(inputMode.inputMode) {
if (inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
// The chooser holds controller focus until its closing animation finishes.
snapshotFlow { Steps.step }.first { it == null }
focusWithinFrames({ pageFocused }) { selectedFocus }
}
@@ -162,7 +152,6 @@ fun DriverPage(
fontSize = 13.sp,
)
},
// Opens on Cancel, so a stray A press on a controller never deletes anything.
confirmButton = { FocusText(stringResource(R.string.common_delete), colors.error) { confirm = null; onDelete(row.id) } },
dismissButton = {
val cancelFocus = remember { FocusRequester() }
@@ -180,10 +169,6 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val shape = RoundedCornerShape(10.dp)
// Two focus targets side by side - the driver itself, and its trash can - so a controller's
// d-pad right reaches the trash can and left comes back. (Inside one clickable row the trash
// can was a child of the focused area and "right" had nowhere to go.) The row's outline still
// follows the driver part, so it looks the same.
val mainFocus = remember { FocusRequester() }
val delFocus = remember { FocusRequester() }
Row(
@@ -236,7 +221,6 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
/** A text button that shows where controller focus is: an outline in its own colour. */
@Composable
internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier, onClick: () -> Unit) {
val src = remember { MutableInteractionSource() }
@@ -45,14 +45,6 @@ import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
/**
* The Steam tab with nothing installed. The blank wall drifts as the full one does, and the
* DroidDeck mark wanders over it, bouncing off the page's edges and off [avoid] (the words and
* buttons) like an idle DVD logo, carrying a clearing in the wall with it. On arrival its outline
* traces in, the D fills, and the ball pops toward the viewer, flips twice and slams back into its
* socket; the ring the slam sends out fills each blank capsule it reaches. Poking the ball plays
* the pop again, without the mark stopping. [fade] is drawn over the wall and under the mark.
*/
@Composable
internal fun EmptyLibrary(avoid: Rect?, fade: @Composable () -> Unit) {
val clock = rememberMarkClock(avoid)
@@ -63,23 +55,16 @@ internal fun EmptyLibrary(avoid: Rect?, fade: @Composable () -> Unit) {
}
}
// The trace and fill, in ms from arrival.
private const val TRACE_MS = 1250f
private const val FILL_FROM = 450f
// The ball's timeline: its fade-in, pop, flip and slam, the ripple and the capsules it lights.
private const val POP_FROM = 900f
private const val IMPACT = 2200f
private const val RIPPLE_MS = 1250f
private const val HIT_MS = 900f
private const val END = 3600f
// Where a poke restarts the ball's timeline: just before the wind-up.
private const val POKE = 880f
private const val DRIFT_MS = 75_000f
/**
* Time into the mark's arrival, into the ball's timeline (a poke restarts only that), into the
* wall's drift, and where the mark is on the page and where its last slam landed.
*/
private class MarkClock {
var intro by mutableFloatStateOf(0f)
var ball by mutableFloatStateOf(0f)
@@ -107,7 +92,6 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
if (clock.page == Size.Zero) { withFrameMillis { }; continue }
val f = MarkFrame(clock.page, Offset.Zero)
if (clock.at == Offset.Unspecified) clock.at = Offset(clock.page.width * 0.64f, clock.page.height * 0.42f)
// Animations off in the system settings: the finished mark, still, on a still wall.
if (Motion.scale == 0f) {
clock.intro = END
clock.ball = END
@@ -123,7 +107,6 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
val before = clock.ball
clock.ball += dt
// Drift, bouncing off the page edges and off whatever it should keep clear of.
var x = clock.at.x + vx * dt / 1000f
var y = clock.at.y + vy * dt / 1000f
val hw = f.halfWidth
@@ -152,10 +135,6 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
return clock
}
/**
* The mark on a page of [size], centred on [centre]: about a third of the page tall. [k] scales
* the timeline's distances, which were drawn on a 460px mark.
*/
private class MarkFrame(size: Size, val centre: Offset) {
val height = min(size.height * 0.3f, size.width * 0.28f * LogoShape.HEIGHT / LogoShape.WIDTH)
val s = height / LogoShape.HEIGHT
@@ -180,11 +159,9 @@ private val HitEase = CubicBezierEasing(0.2f, 0.7f, 0.3f, 1f)
private fun clamp01(v: Float) = v.coerceIn(0f, 1f)
private fun mix(a: Float, b: Float, t: Float) = a + (b - a) * t
/** One stretch of a keyframed value: [from] to [to] while [p] runs from [a] to [b]. */
private fun span(p: Float, a: Float, b: Float, from: Float, to: Float, ease: Easing) =
mix(from, to, ease.transform(clamp01((p - a) / (b - a))))
/** When the ripple's edge reaches [progress] of its way out, as a share of the ripple's time. */
private val rippleTime: FloatArray = FloatArray(257) { RippleEase.transform(it / 256f) }
private fun rippleReaches(progress: Float): Float {
var lo = 0
@@ -196,14 +173,12 @@ private fun rippleReaches(progress: Float): Float {
return lo / 256f
}
/** How lit a capsule the ripple reached [since] ms ago is: up fast, then fading back. */
private fun hitAmount(since: Float): Float {
if (since < 0f || since > HIT_MS) return 0f
val p = since / HIT_MS
return if (p < 0.14f) HitEase.transform(p / 0.14f) else 1f - HitEase.transform((p - 0.14f) / 0.86f)
}
/** The blank wall: the same tilted, drifting columns as [CapsuleWall], each capsule lit as the ripple passes. */
@Composable
private fun EmptyWall(clock: MarkClock) {
val pal = LocalPalette.current
@@ -239,7 +214,6 @@ private fun EmptyWall(clock: MarkClock) {
val dy = if (c % 2 == 0) -shift else shift - run
for (i in 0 until perRun * 2) {
val y = top + i * (capH + gap) + dy
// The capsule's centre on the page, out of the wall's tilt.
val lx = x + capW / 2 - pivot.x
val ly = y + capH / 2 - pivot.y
val sx = pivot.x + lx * cs + ly * sn
@@ -266,7 +240,6 @@ private fun EmptyWall(clock: MarkClock) {
}
}
}
// The clearing the mark carries with it.
drawRect(
Brush.radialGradient(
0f to bg, 255f / 420f to bg, 330f / 420f to bg.copy(alpha = 0.7f), 1f to Color.Transparent,
@@ -276,7 +249,6 @@ private fun EmptyWall(clock: MarkClock) {
}
}
/** The mark, its ball's pop and flip, and the ring the slam sends out. */
@Composable
private fun Mark(clock: MarkClock) {
val pal = LocalPalette.current
@@ -303,7 +275,6 @@ private fun Mark(clock: MarkClock) {
val t = clock.ball
val intro = clock.intro
// The ripple, from where the slam landed, under the mark.
if (clock.slam != Offset.Unspecified && t in IMPACT..IMPACT + RIPPLE_MS) {
val p = (t - IMPACT) / RIPPLE_MS
val alpha = if (p < 0.7f) mix(0.9f, 0.35f, p / 0.7f) else mix(0.35f, 0f, (p - 0.7f) / 0.3f)
@@ -323,7 +294,6 @@ private fun Mark(clock: MarkClock) {
} else 0f
translate(0f, shake) {
// The D, as flat raised slabs with a solid edge underneath.
val fill = Out.transform(clamp01((intro - FILL_FROM) / 450f))
if (fill > 0f) {
val lift = 8f * k * (1f - fill)
@@ -338,7 +308,6 @@ private fun Mark(clock: MarkClock) {
drawPath(right, ink.copy(alpha = fill))
}
// The trace around both halves on arrival, the GameCube nod.
if (intro < TRACE_MS) {
val drawn = TraceEase.transform(clamp01(intro / 775f))
val alpha = if (intro < 775f) 1f else 1f - (intro - 775f) / 475f
@@ -352,7 +321,6 @@ private fun Mark(clock: MarkClock) {
}
}
// The ball.
val shown = Out.transform(clamp01((intro - 650f) / 300f))
if (shown > 0f) {
val p = (t - POP_FROM) / (IMPACT - POP_FROM)
@@ -366,7 +334,6 @@ private fun Mark(clock: MarkClock) {
val q = clamp01((pop - 1f) / 0.6f)
val bob = if (t > END) -4f * k * (0.5f - 0.5f * cos(2f * PI.toFloat() * (t - END) / 5200f)) else 0f
// Its shadow stays on the slabs, spreading and softening as the ball rises.
val blur = mix(10f, 28f, q) * k
val sr = f.ball * 0.93f * mix(1f, 1.4f, q)
val dark = Color.Black.copy(alpha = mix(0.6f, 0.25f, q) * shown)
@@ -396,7 +363,6 @@ private fun Mark(clock: MarkClock) {
}
}
// The flash where it lands.
if (t in IMPACT..IMPACT + 420f) {
val p = Out.transform((t - IMPACT) / 420f)
drawCircle(pal.signal.copy(alpha = 1f - p), (f.ball + 6f * k) * mix(1f, 1.4f, p), f.centre, style = Stroke(max(4f * k, 2.dp.toPx())))
@@ -405,10 +371,6 @@ private fun Mark(clock: MarkClock) {
}
}
/**
* The ball as a coin of [thick]ness turned [deg] about its vertical axis: flat faces in the logo's
* blue, and between them a solid rim that shows as it turns edge-on.
*/
private fun DrawScope.coin(c: Offset, r: Float, thick: Float, deg: Float, face: Color, rim: Color) {
val a = Math.toRadians(deg.toDouble())
val cs = cos(a).toFloat()
@@ -62,13 +62,11 @@ import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.stores.formatBytes
import java.io.File
/** What a picker lists besides folders. */
internal enum class PickKind(val extensions: Set<String>) {
EXE(setOf("exe")),
IMAGE(setOf("png", "jpg", "jpeg", "webp", "ico")),
}
/** A place a file can be picked from: internal storage or a card, at its root. */
internal class PickVolume(val root: File, val label: String, val removable: Boolean) {
val free: Long get() = runCatching { StatFs(root.path).availableBytes }.getOrDefault(0L)
}
@@ -79,15 +77,10 @@ internal fun pickVolumes(context: Context): List<PickVolume> =
File(o.path.substringBefore("/Android/")).takeIf { it.isDirectory }?.let { PickVolume(it, o.name, removable = true) }
}.distinctBy { it.root.absolutePath }
/** A folder in a listing; [readable] false = shown greyed, not opened. */
internal class PickFolder(val dir: File, val readable: Boolean)
internal class PickListing(val folders: List<PickFolder>, val files: List<File>)
/**
* Every folder of [dir] (dot-folders left out, the unreadable ones marked), then the files [kind]
* takes; each A-Z.
*/
internal fun pickListing(dir: File, kind: PickKind): PickListing {
val all = dir.listFiles()?.filter { !it.name.startsWith(".") }.orEmpty().sortedBy { it.name.lowercase() }
return PickListing(
@@ -96,13 +89,6 @@ internal fun pickListing(dir: File, kind: PickKind): PickListing {
)
}
/**
* The compact in-app file picker: [title] and a red X on one line; the storage rows (internal
* storage, each card, free space); inside one, its root first, a breadcrumb, "..", every folder
* and the [kind] files, scrolling in the dialog. Its width is what the first step needed and stays;
* long names are cut short. B / Back goes up a folder, and closes from the storage rows. [start]
* opens in a folder. [onAddAll] adds a row on top of a folder with subfolders.
*/
@Composable
internal fun ExePickerDialog(
title: String, kind: PickKind = PickKind.EXE, start: File? = null,
@@ -165,7 +151,6 @@ internal fun ExePickerDialog(
}
}
/** A compact dialog's title line: [leading] (a back arrow), the title, a small red X. */
@Composable
internal fun DialogTitleRow(title: String, onClose: () -> Unit, leading: (@Composable () -> Unit)? = null) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
@@ -175,7 +160,6 @@ internal fun DialogTitleRow(title: String, onClose: () -> Unit, leading: (@Compo
}
}
/** A 32 dp icon button for a dialog's title line. */
@Composable
internal fun SmallIconButton(icon: ImageVector, description: String, tint: androidx.compose.ui.graphics.Color, onClick: () -> Unit) {
val src = remember { MutableInteractionSource() }
@@ -193,7 +177,6 @@ internal fun SmallIconButton(icon: ImageVector, description: String, tint: andro
}
}
/** One row of a compact dialog's list, the Install dialog's style: [content] laid out in a row. */
@Composable
internal fun ListRow(
enabled: Boolean = true, accent: Boolean = false, tall: Boolean = false, focus: FocusRequester? = null,
@@ -217,7 +200,6 @@ internal fun ListRow(
) { content(hot) }
}
/** A list row with an icon, a name (cut short when long) and a detail on the right. */
@Composable
internal fun PickerRow(
icon: ImageVector?, name: String, detail: String?, tall: Boolean = false, file: Boolean = false, accent: Boolean = false,
@@ -16,12 +16,6 @@ import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
/**
* One line of text in a slot of fixed width - a rail label, a key cap - set as large as
* [maxSize] when it fits and smaller, down to [minSize], when it does not. Labels are as long as
* their language makes them ("Components" is "コンポーネント", "Componentes", "구성 요소"), so a
* fixed size cuts some of them off; below [minSize] the end is ellipsized rather than clipped.
*/
@Composable
fun FitText(
text: String,
@@ -48,27 +48,19 @@ import kotlin.math.abs
import kotlin.math.hypot
import kotlinx.coroutines.coroutineScope
// One focus ring for a whole screen that slides from control to control. When focus moves, the
// edge on the side it is heading springs ahead and the trailing edge catches up a beat later, so
// the ring stretches like a drop and snaps into the new control's shape.
/** A control that can show the ring: where it is and what its ring looks like there. */
internal class GlideSource {
var coords: LayoutCoordinates? = null
var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape)
var color by mutableStateOf(Color.Transparent)
var width by mutableStateOf(2.dp)
/** Focuses the control again: a step-out hands focus back to the control it came out of. */
val requester = androidx.compose.ui.focus.FocusRequester()
}
internal class FocusGlide(val view: View) {
var host: LayoutCoordinates? = null
/** Controls that are hot, the latest last: focus and a hovering pointer can each hold one. */
val hot = mutableStateListOf<GlideSource>()
/** Bumped when the current control moves (a scroll, a relayout). */
var moves by mutableIntStateOf(0)
/** Off while a page floods in or out (PageFlood); back on, it appears on whatever has focus. */
var hidden by mutableStateOf(false)
val current: GlideSource? get() = hot.lastOrNull()
@@ -77,7 +69,6 @@ internal class FocusGlide(val view: View) {
fun release(s: GlideSource) { hot.remove(s) }
fun moved(s: GlideSource) { if (hot.lastOrNull() === s) moves++ }
/** [s]'s bounds in the host, cut to what is on screen; null when it is not laid out or is scrolled away. */
fun boundsOf(s: GlideSource): Rect? {
val h = host ?: return null
val c = s.coords ?: return null
@@ -89,12 +80,10 @@ internal class FocusGlide(val view: View) {
internal val LocalFocusGlide = staticCompositionLocalOf<FocusGlide?> { null }
/** Floods on screen (a launch, a stop, the return from one): every ring keeps out of the way of them. */
internal object RingVeil {
var count by mutableIntStateOf(0)
}
/** Keeps the focus ring off while this is in the composition. */
@Composable
internal fun VeilRing() {
DisposableEffect(Unit) {
@@ -110,11 +99,6 @@ private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: De
is Outline.Generic -> minOf(size.width, size.height) / 2f
}
/**
* A control's outline: [restColor] at [restWidth] always, and [hotColor] at [hotWidth] while [hot].
* Under a [FocusGlideHost] the hot outline is the host's one sliding ring; elsewhere (a dialog, a
* popup, a screen with no host) it is drawn here, as a plain border.
*/
@Composable
internal fun Modifier.glideBorder(
hot: Boolean,
@@ -140,54 +124,34 @@ internal fun Modifier.glideBorder(
return base.focusRequester(src.requester).onGloballyPositioned { src.coords = it; glide.moved(src) }
}
/** Leading edge on a focus move: quick and a little loose. */
/** A spring an edge chases its target on: damping ratio and stiffness, as Compose's. */
private class Edge(val damping: Float, val stiffness: Float)
private fun lead() = Edge(0.62f, 700f)
/** Trailing edge: slower, settles without a bounce to speak of. */
private fun trail() = Edge(0.78f, 360f)
/** Following a control that moves under the ring (a scroll): tight, no wobble. */
private fun follow() = Edge(1f, 2400f)
/** How long after a focus move the ring keeps its stretchy springs and keeps checking where it is. */
private const val SETTLE_MS = 450L
/** How long the control must stand still before the ring stops checking where it is. */
private const val STILL_MS = 120L
/** The longest the ring keeps checking after a move, for a control that never stands still. */
private const val TRACK_MAX_MS = 2_000L
/** How strongly the ring tints what it holds. */
private const val RING_FILL = 0.14f
/** Moves closer together than this are a held direction: the ring runs along as one, no stretch. */
private const val REPEAT_MS = 180L
/** A move further than this goes as a droplet: pinched to a drop, carried across, opened onto the control. */
private val FAR = 360.dp
/**
* Hosts the sliding focus ring for everything inside it. The ring is drawn over [content], in the
* host's space, so put the host inside anything that moves as a whole (a sheet that slides in).
*/
@Composable
internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
val view = LocalView.current
val density = LocalDensity.current
val dir = LocalLayoutDirection.current
val glide = remember(view) { FocusGlide(view) }
val edges = remember { List(4) { Animatable(0f) } } // left, top, right, bottom
val edges = remember { List(4) { Animatable(0f) } }
val corner = remember { Animatable(0f) }
/** How solid the ring is: 1 while it travels as a drop, 0 (an outline) on a control. */
val solid = remember { Animatable(0f) }
val alpha = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
// An edge each, the corner, a droplet carrying all of them, its solid fill, and the chase.
val jobs = remember { arrayOfNulls<Job>(8) }
// The chase: each edge on a spring of its own toward where focus is now. A new target only
// moves where it is heading - restarting an animation on every focus move started it from
// its first frame (which does not move), so a held direction over a busy page (each rail item
// swaps the page) left the ring standing while focus ran on ahead.
val target = remember { FloatArray(4) }
val vel = remember { FloatArray(4) }
val springs = remember { Array(4) { follow() } }
@@ -206,15 +170,12 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
var delays = LongArray(4)
var lastMove = 0L
fun go(i: Int, v: Float, spec: Edge, wait: Long) {
// A drop cut short by another move turns back into an outline on the way.
if (jobs[5]?.isActive == true || solid.targetValue > 0f) {
jobs[5]?.cancel()
jobs[6]?.cancel()
jobs[6] = scope.launch { solid.animateTo(0f, Motion.tw(120)) }
}
val chasing = jobs[7]?.isActive == true
// An edge some other animation was moving (the appear, a drop's opening) is taken over
// at the speed it was going.
jobs[i]?.let { if (it.isActive) { it.cancel(); vel[i] = edges[i].velocity } }
if (!chasing) for (j in 0..3) if (jobs[j]?.isActive != true) vel[j] = edges[j].velocity
target[i] = v
@@ -225,7 +186,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
var last = withFrameNanos { it }
while (true) {
val frame = withFrameNanos { it }
// Real time, however long the frame took, in small steps so a stiff spring holds.
val dt = ((frame - last) / 1e9f).coerceAtMost(0.1f) / Motion.scale.coerceAtLeast(0.01f)
last = frame
val now = System.nanoTime()
@@ -251,7 +211,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
}
}
}
/** Pinch into a solid dot where it is, carry it over, and open it into [b] as it arrives. */
fun droplet(s: GlideSource, b: Rect) {
jobs.forEach { it?.cancel() }
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
@@ -260,19 +219,15 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
val r = with(density) { 6.dp.toPx() }
fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r)
val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f)
// Pinch into a solid drop where it is.
coroutineScope {
launch { solid.animateTo(1f, Motion.tw(80)) }
launch { corner.animateTo(r, Motion.tw(90)) }
dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } }
}
// Across as a dot, every edge together, on a timed ease, steering each frame for
// where the control is now: one still rising into place is met where it ends up.
val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density
val travel = (180 + distance * 0.12f).toInt().coerceIn(220, 380)
val p = Animatable(0f)
val flight = launch { p.animateTo(1f, Motion.tw(travel, easing = FastOutSlowInEasing)) }
// Takes the control's shape as it arrives, not after: no resting as a dot.
while (flight.isActive && p.value < 0.78f) {
val to = (glide.boundsOf(s) ?: b).center
dot(Offset(here.x + (to.x - here.x) * p.value, here.y + (to.y - here.y) * p.value)).forEachIndexed { i, v -> edges[i].snapTo(v) }
@@ -316,8 +271,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
return@collectLatest
}
if (src == null) {
// Focus passing between two controls can let go of one a moment before the next
// takes it: wait a beat, so that reads as a move and not a fade out and back in.
delay(60)
jobs.forEach { it?.cancel() }
solid.snapTo(0f)
@@ -342,7 +295,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
shown = src
first = false
if (!wasShowing) {
// Appearing: a hair bigger, pulled in onto the control as it fades up.
val out = with(density) { 3.dp.toPx() }
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
jobs.forEach { it?.cancel() }
@@ -352,7 +304,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
cornerTo(src, b, snap = true)
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
} else {
// Moving: the edges on the side it is heading lead.
val dx = b.center.x - (edges[0].value + edges[2].value) / 2f
val dy = b.center.y - (edges[1].value + edges[3].value) / 2f
val horizontal = abs(dx) >= abs(dy)
@@ -365,7 +316,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
dropped = !held && hypot(dx, dy) > with(density) { FAR.toPx() }
if (dropped) droplet(src, b)
else {
// A held direction runs along as one piece; a single press stretches.
dirSpecs = if (held) List(4) { Edge(0.9f, 900f) }
else List(4) { i -> when (i) { leadIdx -> lead(); trailIdx -> trail(); else -> Edge(0.7f, 520f) } }
delays = LongArray(4) { i -> if (i == trailIdx && !held) 30L else 0L }
@@ -376,15 +326,11 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
if (!dropped) listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> go(i, v, dirSpecs[i], delays[i]) }
last = b
} else if (b != last && jobs[5]?.isActive != true) {
// It moved under the ring: keep the stretch while the move is fresh, else follow.
val fresh = (System.nanoTime() - movedAt) / 1_000_000 < SETTLE_MS
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> go(i, v, if (fresh) dirSpecs[i] else follow(), 0L) }
if (last == null) scope.launch { alpha.animateTo(1f, Motion.tw(120)) }
last = b
}
// Layer animations (a tile growing, a row sliding, a page rising in) move it without
// a relayout, so look again each frame until it has stood still a moment: a fixed
// window let the ring park mid-rise and jump over when something next laid out.
val now = System.nanoTime()
val settled = (now - start) / 1_000_000 > SETTLE_MS && (now - stillSince) / 1_000_000 > STILL_MS
if (settled || (now - start) / 1_000_000 > TRACK_MAX_MS) break
@@ -411,8 +357,6 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
cornerRadius = CornerRadius(corner.value), alpha = a * f,
)
if (f < 0.99f) {
// The ring's own infill: the only fill a pad sees, so it is always exactly what
// the ring holds and moves with it (a row's own sliding fill trailed it).
drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * RING_FILL,
@@ -8,11 +8,6 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
/**
* The frame generation picker, anchored to whatever opened it (host key "fg"). One copy for Setup,
* a game's launch settings and the session drawer, so they say the same thing. Importing a
* Lossless.dll is offered once the account is known to own Lossless Scaling.
*/
@Composable
internal fun FrameGenMenu(
host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State,
@@ -59,13 +59,10 @@ import java.io.File
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
// Cover art: posters, the art grid and its tiles.
/** Where each art tile sits, root px, by its key: a page opened from one floods out of it. */
internal object TileBounds {
val at = HashMap<String, androidx.compose.ui.geometry.Rect>()
/** The page about to open came from tile [key] (its art or icon for the flood), if it is on screen. */
fun mark(key: String, art: Any?, corner: Float) {
at[key]?.let { PageOrigin.mark(Origin(it, corner, art = art)) }
}
@@ -97,12 +94,8 @@ internal fun Poster(art: File?, name: String, modifier: Modifier) {
@Composable
internal fun ArtGrid(tiles: List<Tile>, wide: Boolean = false) {
val square = tiles.isNotEmpty() && tiles.all { it.art == null && (it.iconRes != null || it.iconBitmap != null) }
// Big enough to recognise a game by its art and read its name under it; icon tiles are squares.
val minSize = if (square) 76.dp else if (wide) 120.dp else 96.dp
val gap = 12.dp
// Laid out whole, not lazily: the pad's focus search only finds tiles that exist, and a lazy
// grid composes only the rows on screen, so a press towards the next row bounced back among
// the visible tiles. A few hundred tiles lay out fine; the page's scroll follows the focused one.
BoxWithConstraints(modifier = Modifier.fillMaxWidth()) {
val avail = maxWidth - 8.dp
val cols = ((avail + gap) / (minSize + gap)).toInt().coerceAtLeast(1)
@@ -152,10 +145,6 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera
}
}
/**
* Art for a portrait (2:3) tile. Box art fills it; wide art - a PS3 disc's ICON0, a game's header -
* is shown whole over a blurred, darkened copy of itself instead of losing its sides to the crop.
*/
@Composable
private fun CoverImage(art: File, modifier: Modifier) {
var wideArt by remember(art) { mutableStateOf(false) }
@@ -99,7 +99,6 @@ import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.store.UserAppsState
import java.io.File
// The front end's right-hand pane and the page it shows: backdrop, desktop card and emulators.
@OptIn(androidx.compose.animation.ExperimentalAnimationApi::class)
@Composable
@@ -119,35 +118,25 @@ internal fun Pane(
}
Backdrop(backdropArt)
val pal = LocalPalette.current
// Pages keep drawing while they leave, so one can fold away instead of blinking out.
val pages = remember { HashMap<String, @Composable () -> Unit>() }
// Pages opened from a control (the cog), with where that control sat, in this pane's coordinates.
val origins = remember { HashMap<String, Origin>() }
val paneAt = remember { arrayOf(Offset.Zero) }
val livePage by rememberUpdatedState(s.pageKey)
// Picking another game changes the detail beside the list, not the whole page.
val railContent = if (selected.startsWith("app:")) "games" else selected
val target = if (page != null && s.pageKey != null) s.pageKey else railContent
// The game the Games page shows. It must outlive the selection: while the page animates out,
// drawing it with what is selected now (another rail item) turned it into a copy of that page.
val gameShown = remember { arrayOf("games") }
if (selected == "games" || selected.startsWith("app:")) gameShown[0] = selected
// What the pane showed before this change: the content a page opened over belongs to it.
val before = remember { arrayOf(target) }
if (page != null && s.pageKey != null) {
pages[s.pageKey] = page
if (s.pageKey !in origins) PageOrigin.take()?.let { o ->
// A hop's page came out of its own rail item, and is that item's content.
origins[s.pageKey] = inPane(o.translate(-paneAt[0])).let { if (it.owner == null) it.ownedBy(railContent) else it }
}
} else if (target != before[0] && target !in origins) {
// A section's own page opened from a control in it (an emulator's card, a ROM's) floods
// out of that control and belongs to what was showing; a hop's comes out of its rail item.
PageOrigin.take()?.let { o -> origins[target] = inPane(o.translate(-paneAt[0])).let { if (it.owner == null) it.ownedBy(before[0]) else it } }
}
before[0] = target
val targetNow by rememberUpdatedState(target)
// A page leaving through a hop's link is not coming back to its control.
val leave = if (Hops.linking) PageLeave.Link else PageLeave.Ordinary
LaunchedEffect(target) { Hops.linking = false }
AnimatedContent(
@@ -155,16 +144,13 @@ internal fun Pane(
modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() },
transitionSpec = {
when {
// Into a page from its control: the control floods the pane (PageFlood) as it sinks back.
targetState in origins -> (fadeIn(Motion.tw(120)))
.togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f))
.apply { targetContentZIndex = 1f }
// Back out of it: the flood draws back into the control as the pane comes forward again.
initialState in origins && pageExit(origins[initialState]?.owner, targetState, leave) == PageExit.Drain ->
(fadeIn(Motion.tw(300, 100)) + scaleIn(Motion.tw(460, 40), initialScale = 0.95f))
.togetherWith(ExitTransition.None)
.apply { targetContentZIndex = -1f }
// Away to something else: the control is not coming back, so the page sinks with the pane.
initialState in origins -> (fadeIn(Motion.tw(300, 80)) + slideInVertically(Motion.tw(420, 80)) { it / 24 })
.togetherWith(fadeOut(Motion.tw(170)) + scaleOut(Motion.tw(170), targetScale = 0.95f))
.apply { targetContentZIndex = 1f }
@@ -177,8 +163,6 @@ internal fun Pane(
) { key ->
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb) }
// A hop leaving this content: it sinks back as the dot leaves it (and comes forward
// again, freshly drawn, when the hop is undone).
val hopSink by androidx.compose.animation.core.animateFloatAsState(
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
)
@@ -190,16 +174,13 @@ internal fun Pane(
val from = origins[key]
if (from == null) shown()
else {
// The control's own picture (a card's art, an emulator's icon) on the tile as it grows.
val art = when (val m = from.art) {
null -> null
is Int -> androidx.compose.ui.res.painterResource(m)
else -> coil.compose.rememberAsyncImagePainter(m)
}
val leaving = transition.targetState == EnterExitState.PostExit
// Settled as the page starts to leave, from what is coming in, not from where it came in.
val drains = remember(leaving) { !leaving || pageExit(from.owner, target, leave) == PageExit.Drain }
// Keeps a leaving page on screen while its flood draws back into the control.
transition.animateFloat(
transitionSpec = { if (targetState == EnterExitState.PostExit && drains) Motion.tw(PAGE_RETURN_MS) else snap() },
label = "pageReturn",
@@ -212,11 +193,6 @@ internal fun Pane(
}
}
/**
* An origin left of the pane (a rail item a hop flew to) starts half inside it, at the item's
* height: the page swells out of the pane's edge beside the item. Wholly outside, its tile was a
* bar that raced across from the far edge.
*/
internal fun inPane(o: Origin): Origin =
if (o.bounds.right > 0f) o else o.translate(Offset(-o.bounds.right + o.bounds.width / 2f, 0f))
@@ -225,8 +201,6 @@ private fun Backdrop(art: File?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Crossfade(targetState = art, animationSpec = Motion.tw(700), label = "backdrop") { a ->
// A game's own art, blurred, where it has some; otherwise the plain ground with one quiet
// glow of the theme's signal colour - a colour per title hash read as noise.
if (a != null && Build.VERSION.SDK_INT >= 31) {
Box(modifier = Modifier.fillMaxSize().alpha(0.26f).blur(70.dp)) {
AsyncImage(model = a, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.5f; scaleY = 1.5f })
@@ -257,7 +231,6 @@ private fun Content(
val density = androidx.compose.ui.platform.LocalDensity.current.density
val padH = if (narrow) 16.dp else 22.dp
val padV = if (narrow) 12.dp else 18.dp
// Setup scrolls inside itself, under its tabs.
if (selected == "setup") {
Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) {
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
@@ -268,33 +241,26 @@ private fun Content(
UpdatesPage(s, a, modifier.padding(horizontal = padH, vertical = padV))
return
}
// Steam is a full-bleed wall of the library with Play over it.
if (selected == "steam") {
SteamHome(s, a, modifier)
return
}
// The Store scrolls and navigates inside itself (its tabs and an app's page).
if (selected == "store") {
StorePage(s, a, modifier)
return
}
// Stores (GOG, Epic, Amazon) takes the whole pane: chips, shelves and a game's page inside it.
if (selected == "stores") {
StoresPage(s, a, modifier)
return
}
// The Games tab lays out its own list and detail.
if (selected == "games" || selected.startsWith("app:")) {
GamesPage(s, a, selected, onSelect, modifier)
return
}
// Desktop is the Steam tab's shape: a hero with its lifted sheet, and shelves under it.
if (selected == "desktop") {
DesktopPage(s, a, modifier, onSelect)
return
}
// Every other page scrolls as one - header, hero and grid - so a short screen reaches the grid
// instead of showing a sliver of it under a fixed hero. A focused tile scrolls itself into view.
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
when {
selected == "android-apps" && s.isHomeApp -> {
@@ -322,7 +288,6 @@ private fun Content(
if (e == null) Note(stringResource(R.string.content_not_installed)) else {
val pkgId = Library.packageId(e.id)
val pkg = pkgId?.let { id -> s.packages?.firstOrNull { it.id == id } }
// Out of its card on Desktop, with the card's icon; B draws it back in.
Rise(1) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp),
@@ -367,8 +332,6 @@ private fun Content(
}
else Rise(5, Modifier.fillMaxWidth()) {
Column {
// RetroArch's games come from many systems: chips filter them, one
// selection gliding between them.
val systems = remember(e.games) { e.games.map { romSystem(it) }.distinct() }
var system by rememberSaveable(e.id) { mutableStateOf<String?>(null) }
if (systems.size > 1) Box(Modifier.padding(top = 10.dp)) {
@@ -467,7 +430,6 @@ internal fun UserApps.Kind.label() = when (this) {
UserApps.Kind.FLATPAK -> R.string.user_apps_kind_flatpak
}
/** An added app's icon: its own, or the kind's when it has none. */
@Composable
private fun UserAppIcon(app: UserApps.App, size: Int) {
if (app.icon != null) AppIcon(app.icon, app.name, size)
@@ -482,7 +444,6 @@ private fun UserAppIcon(app: UserApps.App, size: Int) {
}
}
/** The add or remove under way, or why the last one failed. */
@Composable
private fun UserAppsProgress() {
val colors = MaterialTheme.colorScheme
@@ -501,7 +462,6 @@ private fun UserAppsProgress() {
}
}
/** An added app's page: open it, change its name and icon, update one added from GitHub, or remove it (asked first). */
@Composable
private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions, onSelect: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -556,7 +516,6 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
}
}
/** Remove, which asks first: are you sure steps out of it in red, Keep first and focused. */
@Composable
private fun RemoveAppButton(app: UserApps.App, enabled: Boolean, onRemove: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -581,7 +540,6 @@ private fun RemoveAppButton(app: UserApps.App, enabled: Boolean, onRemove: () ->
}
}
/** Looks up a newer release of an app added from GitHub, then installs it. */
@Composable
private fun UpdateButton(app: UserApps.App, s: FrontEndState) {
val ctx = LocalContext.current
@@ -604,13 +562,8 @@ private fun UpdateButton(app: UserApps.App, s: FrontEndState) {
}
}
/**
* One emulator: its icon, system and games. One not yet installed says so in words and keeps full
* contrast - dimming it read as disabled rather than one press from installing.
*/
@Composable
private fun systemLabel(e: Library.Emulator): String =
if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { it.uppercase() }
/** The system a ROM belongs to: the folder it sits in under the ROMs folder. */
private fun romSystem(rom: Library.Rom): String = rom.hostPath.parentFile?.name.orEmpty()
@@ -61,12 +61,7 @@ import coil.compose.AsyncImage
import com.droiddeck.launcher.frontend.Library
import kotlinx.coroutines.launch
// The Games page: the list, the hero for the selected game and its labels.
/**
* The Games tab: installed Steam games down the left, most recently played first, and the one
* picked beside them - its banner, Launch and the launch settings. One game skips the list.
*/
@Composable
internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) {
val games = remember(s.steamGames) { s.steamGames.sortedByDescending { it.lastPlayed } }
@@ -155,11 +150,9 @@ private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActio
}
g.protonPrefix?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton(stringResource(R.string.games_prefix), compact = true) { a.onBrowseFiles(dir) }
// Only games added to the library; Steam titles keep their saves with Steam Cloud.
if (g.library == Library.ADDED) ManageSaves(g, dir, a)
}
if (!s.shortcutPicker) GameShortcutMenu(g, a)
// A game added in DroidDeck (Custom): its editor, Steam's Properties for a non-Steam game.
if (!s.shortcutPicker && g.library == Library.ADDED && g.source == Library.ADDED && g.gameFiles != null) EditGameButton { onEdit(g) }
BusyChip(s)
}
@@ -184,10 +177,6 @@ private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
}
}
/**
* Manage saves: import a GameHub or Winlator save zip into this game's prefix, export its saves as
* either, or open the save folder found for it. The saves are looked for when the menu opens.
*/
@Composable
private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndActions) {
var open by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) }
@@ -211,7 +200,6 @@ private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndA
}
}
Box {
// A GOG or Epic game's saves are its cloud saves: the one place for them, named so.
val cloudGame = com.droiddeck.launcher.stores.Store.byId(g.source).let { it == com.droiddeck.launcher.stores.Store.GOG || it == com.droiddeck.launcher.stores.Store.EPIC }
val label = stringResource(if (cloudGame) R.string.store_cloud_saves else R.string.games_manage_saves)
SecondaryButton(label, compact = true) { open = !open }
@@ -235,12 +223,6 @@ private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndA
}
}
/**
* A GOG or Epic game's cloud saves: the Cloud saves switch, Upload and Download - three rows from
* the first frame, so nothing moves under the pad while the cloud is checked. Until the check is
* back the two actions are disabled and read "…"; then only their subtitles change: the last sync,
* "No cloud saves", or a conflict, when Upload and Download become Keep local and Keep cloud.
*/
@Composable
private fun CloudRows(g: Library.SteamGame, open: Boolean, first: androidx.compose.ui.focus.FocusRequester) {
val store = com.droiddeck.launcher.stores.Store.byId(g.source)?.takeIf { it != com.droiddeck.launcher.stores.Store.AMAZON } ?: return
@@ -253,7 +235,6 @@ private fun CloudRows(g: Library.SteamGame, open: Boolean, first: androidx.compo
runCatching { com.droiddeck.launcher.stores.CloudSaves.status(context, store, id) }.getOrNull()
}
}
// The game's own switch (sidecar "cloud"), known locally: right from the first frame.
val folder = g.gameFiles
var enabled by remember(g.gameId, open) { androidx.compose.runtime.mutableStateOf(folder?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it)?.cloud } ?: true) }
val st = status
@@ -285,17 +266,14 @@ private fun CloudRows(g: Library.SteamGame, open: Boolean, first: androidx.compo
st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString())
else -> stringResource(R.string.cloud_never)
}
// A conflict turns the two actions into its two answers; the rows stay where they are.
MenuItem(stringResource(if (conflict) R.string.cloud_keep_local else R.string.cloud_upload), checked = false, enabled = ready, detail = summary) { sync(up = true, force = conflict) }
MenuItem(stringResource(if (conflict) R.string.cloud_keep_cloud else R.string.cloud_download), checked = false, enabled = ready, detail = if (st == null || busy != null) pending else null) { sync(up = false, force = conflict) }
}
/** When it was last played (or where it is, if never) over its name, then room for Launch. */
@Composable
private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SourceChip(g.source)
// A Custom game's chip already says what its eyebrow would; the line then stays empty.
val eyebrow = lastPlayedText(g.lastPlayed) ?: libraryLabel(g)
if (eyebrow.isNotEmpty()) Text(
eyebrow.uppercase(),
@@ -316,14 +294,11 @@ private fun GameList(
onSelect: (Library.SteamGame) -> Unit, onLaunch: (Library.SteamGame) -> Unit, onAdd: (() -> Unit)?, modifier: Modifier,
) {
val colors = MaterialTheme.colorScheme
// Laid out whole, as the art grid is: the pad's focus search only finds rows that exist.
Column(
verticalArrangement = Arrangement.spacedBy(2.dp),
modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp),
) {
GamesHeader(games.size, onAdd, Modifier.padding(start = 6.dp, bottom = 10.dp))
// A game that arrives while the list is up (Steam installed it in the session that just
// ended, or it was added) eases in; the ones there when the page opened are simply there.
val seen = remember { HashSet<Int>() }
var settled by remember { androidx.compose.runtime.mutableStateOf(false) }
for (g in games) key(g.appId) {
@@ -338,7 +313,6 @@ private fun GameList(
}
}
/** "Games N", and the + that adds a game from its .exe beside it ([onAdd] null: no +). */
@Composable
private fun GamesHeader(count: Int, onAdd: (() -> Unit)?, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
@@ -349,17 +323,11 @@ private fun GamesHeader(count: Int, onAdd: (() -> Unit)?, modifier: Modifier) {
}
}
/**
* The Games tab's dialogs, one at a time: the + picker, the summary after "Add all games in this
* folder", and a game's editor (from the page's ✎ or a summary row, with back to the summary).
*/
internal object GamesDialogState {
var adding by androidx.compose.runtime.mutableStateOf(false)
var summary by androidx.compose.runtime.mutableStateOf<Pair<List<com.droiddeck.launcher.frontend.AddedGames.Game>, Int>?>(null)
var editing by androidx.compose.runtime.mutableStateOf<EditRequest?>(null)
/** The subfolder "Add all games in this folder" is looking at; null when it is done. */
var checking by androidx.compose.runtime.mutableStateOf<String?>(null)
/** The summary an editor opened from it goes back to. */
var behindEditor: Pair<List<com.droiddeck.launcher.frontend.AddedGames.Game>, Int>? = null
}
@@ -409,7 +377,6 @@ private fun GamesDialogs(a: FrontEndActions) {
}
}
/** The ✎ on a Custom game's page: icon only. */
@Composable
private fun EditGameButton(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -430,7 +397,6 @@ private fun EditGameButton(onClick: () -> Unit) {
}
}
/** A round + that opens the .exe picker. */
@Composable
private fun AddGameButton(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -452,7 +418,6 @@ private fun AddGameButton(onClick: () -> Unit) {
}
}
/** Fades and slides a row in once when [arriving]; nothing for one already there (or with animations off). */
@Composable
internal fun Modifier.arriveIn(arriving: Boolean): Modifier {
val t = remember { androidx.compose.animation.core.Animatable(if (arriving) 0f else 1f) }
@@ -460,7 +425,6 @@ internal fun Modifier.arriveIn(arriving: Boolean): Modifier {
return graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 12.dp.toPx() }
}
/** One game in the list. Moving onto it with the pad shows it; A launches it, a tap only shows it. */
@Composable
private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Unit, onLaunch: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -484,7 +448,6 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni
}
Column(modifier = Modifier.weight(1f)) {
Text(g.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
// Where it came from beside when it was played: a store's games sit among Steam's own.
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SourceChip(g.source, small = true)
Text(
@@ -496,7 +459,6 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni
}
}
/** A page's title, with room at its right for controls or status. */
@Composable
internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit = {}) {
Row(
@@ -511,13 +473,11 @@ internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit
}
}
/** Why a launch button is greyed out: the runtime is being worked on. Nothing when it is not. */
@Composable
internal fun BusyChip(s: FrontEndState) {
if (s.busy) ActionChip(if (s.percent >= 0) stringResource(R.string.games_runtime_busy_percent, s.percent) else s.stage, ok = false)
}
/** Whether Steam can start, said where Play is rather than only in Setup. */
@Composable
internal fun RuntimeChip(s: FrontEndState) = when {
s.busy -> Chip(if (s.percent >= 0) stringResource(R.string.setup_runtime_progress, s.stage, s.percent) else s.stage, ok = false)
@@ -527,12 +487,10 @@ internal fun RuntimeChip(s: FrontEndState) = when {
else -> Chip(stringResource(R.string.games_runtime_ready), ok = true)
}
/** "Last played 3 days ago" from Steam's unix seconds; null for a game never played. */
@Composable
private fun lastPlayedText(lastPlayed: Long): String? =
playedSpan(lastPlayed)?.let { stringResource(R.string.games_last_played, it.replaceFirstChar { c -> c.lowercase() }) }
/** "3 days ago" from Steam's unix seconds; null for a game never played. */
private fun playedSpan(lastPlayed: Long): String? {
if (lastPlayed <= 0L) return null
return android.text.format.DateUtils.getRelativeTimeSpanString(
@@ -540,10 +498,6 @@ private fun playedSpan(lastPlayed: Long): String? {
).toString()
}
/**
* Where a never-played game lives, beside its source chip: Steam's library, the Games storage for
* a store install (the chip names the store), "Custom game" for a folder the user added.
*/
@Composable
private fun libraryLabel(g: Library.SteamGame): String = when {
g.library != Library.ADDED -> if (g.library == "internal") stringResource(R.string.games_internal) else g.library
@@ -551,11 +505,6 @@ private fun libraryLabel(g: Library.SteamGame): String = when {
else -> ""
}
/**
* A game's wide banner: Steam's hero art where the client cached one, else its capsule blurred to
* fill the width. The copy sits bottom-left over a scrim of the ground colour so it always reads;
* the art takes the banner's size, so a banner given a minimum height grows to fit its copy.
*/
@Composable
private fun GameHero(g: Library.SteamGame, modifier: Modifier, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -82,14 +82,9 @@ import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import com.droiddeck.launcher.core.PhantomProcessLimit
// The front end's side rail: the page list and the resume entry under it.
internal val AttentionAmber = Color(0xFFFFB547)
/**
* The launcher's sections, always on screen down the left edge: the app is landscape-only, so the
* width a hamburger menu would save is better spent keeping every section one press away.
*/
@Composable
internal fun SideRail(
s: FrontEndState, selected: String,
@@ -97,7 +92,6 @@ internal fun SideRail(
) {
val colors = MaterialTheme.colorScheme
val compact = LocalConfiguration.current.screenHeightDp < 420
// Under 600dp wide (4:3 and square screens) the labels would cost a fifth of the width.
val iconOnly = isNarrowScreen()
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
@@ -105,11 +99,9 @@ internal fun SideRail(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
) {
// Every section on screen at once: items shrink (to 44dp, still a touch target) before the rail scrolls.
val count = 6 + (if (s.gameStoresEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0)
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
// A hop in flight moves the selection ahead of the page it is bringing.
val shown = Hops.railPreview ?: selected
val keys = buildList {
add("steam"); add("games")
@@ -119,13 +111,10 @@ internal fun SideRail(
if (s.isHomeApp) add("android-apps")
add("setup"); add("updates")
}
// Where each item sits in the column, for the selection that glides between them.
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
var railAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onGloballyPositioned { railAt = it.boundsInRoot().topLeft }) {
// One selection for the whole rail, under the items: it glides from item to item as the
// chips' does, its leading edge first, and a jump of more than one item goes as a drop.
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-railAt), tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
@@ -133,22 +122,16 @@ internal fun SideRail(
modifier = Modifier.fillMaxWidth(),
) {
val place: (String) -> Modifier = { key ->
// In root px: an item that comes and goes sits in its own wrapper, not the column.
Modifier.onGloballyPositioned {
bounds[key] = it.boundsInRoot()
Hops.railBounds[key] = it.boundsInRoot()
}
}
RailItem(stringResource(R.string.rail_steam), Icons.Outlined.SportsEsports, "steam", shown == "steam", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
// Always there, so the items below it never move; an empty library says how to fill it.
RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", shown == "games", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("games") }) { onSelect("games") }
// The game stores, right under Games: what they install lands there. Its badge counts
// the downloads in flight, so a download started here is never out of sight.
// A section switched on in Setup comes in as the rail's own entrance; off, it folds away.
if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", shown == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, place = place, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", shown == "desktop", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", shown == "components", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("components") }) { onSelect("components") }
// Home mode's extra section goes last, so it shifts nothing above it.
if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", shown == "android-apps", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
RailItem(stringResource(R.string.rail_setup), Icons.Outlined.Tune, "setup", shown == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, place = place, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", shown == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, place = place, onFocus = { onFocusSelect("updates") }) { onSelect("updates") }
@@ -169,9 +152,7 @@ internal fun SideRail(
private fun RailItem(
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp,
badge: Boolean = false,
/** A number on the item (downloads in flight); 0 shows nothing. */
count: Int = 0,
/** Reports where the item sits, for the rail's gliding selection and a hop's dot. */
place: (String) -> Modifier = { Modifier },
onFocus: () -> Unit = {}, onClick: () -> Unit,
) {
@@ -193,7 +174,6 @@ private fun RailItem(
if (current) pal.signal else if (focused || hovered) colors.onBackground else colors.onSurfaceVariant,
Motion.tw(220), label = "railFg",
)
// The selected look is the rail's glide under the item, so the item draws only hover here.
val fill by animateColorAsState(
if (current) Color.Transparent else if (focused || hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent,
Motion.tw(220), label = "railFill",
@@ -205,7 +185,6 @@ private fun RailItem(
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.railFor(key)) else Modifier)
.testTag("rail-$key")
.then(place(key))
// Pops as a hop's dot lands on it.
.landingPop(Hops.railLanded[key] ?: 0)
.graphicsLayer { scaleX = scale; scaleY = scale }
.size(width = if (iconOnly) 52.dp else 80.dp, height = height)
@@ -228,14 +207,12 @@ private fun RailItem(
if (count > 0) Text(
if (count > 9) "9+" else count.toString(),
fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.onSignal, maxLines = 1,
// Pops with the Downloads chip's count as an install's dot lands there.
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 4.dp else 6.dp, end = if (iconOnly) 5.dp else 12.dp)
.landingPop().clip(RoundedCornerShape(8.dp)).background(pal.signal).padding(horizontal = 5.dp, vertical = 1.dp),
)
}
}
/** The running session, one press from anywhere in the launcher. */
@Composable
private fun ResumeRailItem(name: String, compact: Boolean, iconOnly: Boolean, onResume: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -246,7 +223,6 @@ private fun ResumeRailItem(name: String, compact: Boolean, iconOnly: Boolean, on
val resumeDescription = stringResource(R.string.rail_resume_named, name)
val pulse = rememberInfiniteTransition(label = "pulse")
val ringScale by pulse.animateFloat(0.4f, 1.6f, infiniteRepeatable(tween(1600, easing = Motion.Ease), RepeatMode.Restart), label = "ring")
// Animations off: the live dot alone, no pulsing ring.
val still = Motion.scale == 0f
Column(
horizontalAlignment = Alignment.CenterHorizontally,
@@ -266,7 +242,6 @@ private fun ResumeRailItem(name: String, compact: Boolean, iconOnly: Boolean, on
if (!still) Box(modifier = Modifier.size(14.dp).graphicsLayer { scaleX = ringScale; scaleY = ringScale; alpha = (1.6f - ringScale) / 1.2f }.border(1.5.dp, pal.good, CircleShape))
Box(modifier = Modifier.size(7.dp).clip(CircleShape).background(pal.good))
}
// Icons only: the live dot alone says something is running; its description says what.
if (!iconOnly) {
Text(stringResource(R.string.resume_session), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, softWrap = false)
Text(name, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
@@ -97,7 +97,6 @@ class FrontEndState(
val frameGenLabel: String,
val romsDir: String?,
val logsEnabled: Boolean,
/** Setup's Debugging tools toggle (AgentAccess): off unless the user turns it on. */
val agentCommands: Boolean = false,
val steamGames: List<Library.SteamGame>,
val emulators: List<Library.Emulator>,
@@ -109,7 +108,6 @@ class FrontEndState(
val gameSyncFolder: String? = null,
val pageKey: String? = null,
val theme: String = Themes.GRAPHITE,
/** The language picked in Setup, or AppLanguage.SYSTEM to follow the system. */
val language: String = "",
val appScale: Int = com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE,
val isHomeApp: Boolean = false,
@@ -135,19 +133,13 @@ class FrontEndState(
val launcherFullscreen: Boolean = true,
val animationsEnabled: Boolean = true,
val gameStoresEnabled: Boolean = true,
/** Setup › Stores: the download engine's speed tier (stores/download/StoreDownloadTier ids). */
val gameStoresSpeedTier: String = "fast",
/** Setup › Stores: the tab a signed-in store opens on (SessionPrefs.STORES_OPEN_LIBRARY / STORE). */
val storesOpenTab: String = SessionPrefs.STORES_OPEN_LIBRARY,
/** A page to open once: "stores:downloads", or a selection such as "app:<id>" (a notification's tap). */
val navigate: String? = null,
/** Setup: art for added games is fetched; the user has a SteamGridDB key of their own. */
val addedGamesArt: Boolean = true,
val sgdbUserKey: Boolean = false,
val storesShowMature: Boolean = false,
/** Downloads queued, running or paused across the three stores; the rail item's badge. */
val storeDownloadsActive: Int = 0,
/** The Updates page: DroidDeck's own builds and the channel followed. */
val updates: UpdatesState = UpdatesState(),
)
@@ -159,30 +151,21 @@ class FrontEndActions(
val onGameShortcut: (Library.SteamGame) -> Unit = {},
val onExportGameFile: (Library.SteamGame) -> Unit = {},
val onSyncGameFiles: () -> Unit = {},
/** The Games tab's +: the .exe picked in its dialog, to add as a game. */
val onAddGameExe: (path: String) -> Unit = {},
/** These added games (by folder) were added or edited: the Games tab updates just them. */
val onAddedGamesChanged: (folders: List<String>) -> Unit = {},
/** An added game removed in its editor: off the Games tab at once, out of Steam after. */
val onAddedGameRemoved: (folder: String, appId: Long?, name: String) -> Unit = { _, _, _ -> },
/** Setup's Artwork switch and the user's SteamGridDB API key ("" removes it). */
val onAddedGamesArt: (Boolean) -> Unit = {},
val onSgdbKey: (String) -> Unit = {},
val onStopGameFileSync: () -> Unit = {},
val onCopyGameLink: (Library.SteamGame) -> Unit = {},
val onDesktop: () -> Unit,
val onEmulator: (Library.Emulator) -> Unit,
/** A Flatpak app by id and name, from the Store. */
val onFlatpakApp: (String, String) -> Unit = { _, _ -> },
/** An app added on the Desktop page. */
val onUserApp: (com.droiddeck.launcher.runtime.UserApps.App) -> Unit = {},
val onRom: (Library.Rom) -> Unit,
val onResume: () -> Unit,
/** Reads Steam's session settings for its lifted sheet (under Play). */
val onSteamSettings: () -> Unit,
/** Reads the desktop's session settings for its lifted sheet (under Open desktop). */
val onDesktopSettings: () -> Unit,
/** A lifted sheet's rows for one tab of [mode]'s settings, as last read. */
val modeSheet: @Composable (mode: String, tab: String, extras: SheetExtras) -> Unit = { _, _, _ -> },
val onRemoveDesktop: () -> Unit = {},
val onInstallPackage: (String) -> Unit,
@@ -191,11 +174,8 @@ class FrontEndActions(
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onImportLossless: () -> Unit,
val onProtons: () -> Unit,
/** The Components page: FEX / DXVK / VKD3D-Proton per Proton. */
val onComponents: (focusContent: Boolean) -> Unit,
/** The Components page on one layer ([GPU_TAB], a component id): a hop's destination. */
val onComponentsTab: (String) -> Unit = {},
/** A game page's Manage saves: import a save zip into this game, or export its saves in a layout. */
val onSaveImport: (Library.SteamGame) -> Unit = {},
val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> },
val onPerformance: () -> Unit,
@@ -206,6 +186,7 @@ class FrontEndActions(
val onAgentCommands: () -> Unit = {},
val onShareLogs: () -> Unit = {},
val onClearLogs: () -> Unit = {},
val onResetSettings: () -> Unit = {},
val onOffline: () -> Unit,
val onPageBack: () -> Unit = {},
val onTheme: (String) -> Unit = {},
@@ -219,7 +200,6 @@ class FrontEndActions(
val onStoresOpenTab: (String) -> Unit = {},
val onNavigated: () -> Unit = {},
val onStoresShowMature: (Boolean) -> Unit = {},
/** The Games list rebuilt now: a store install or removal changed what is on disk. */
val onLibraryChanged: () -> Unit = {},
val onHomeApp: () -> Unit = {},
val onHomeScreen: (Boolean) -> Unit = {},
@@ -242,15 +222,12 @@ class FrontEndActions(
internal object Motion {
var scale by mutableStateOf(1f)
private set
/** App animations can be disabled independently; Android's "Remove animations" always wins. */
fun refresh(context: android.content.Context) {
scale = if (SessionPrefs.animationsEnabled(context))
Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
else 0f
}
val Ease = CubicBezierEasing(0.2f, 0.8f, 0.2f, 1f)
/** A wall-clock wait (a coroutine delay) scaled as the animations around it are. Compose already
* scales its own animation clock by the same setting, so animation specs take unscaled times. */
fun ms(base: Int) = (base * scale).roundToInt()
fun <T> tw(base: Int, delay: Int = 0, easing: Easing = Ease): FiniteAnimationSpec<T> = if (scale == 0f) snap() else tween(base, delay, easing)
fun <T> sp(damping: Float = 0.7f, stiffness: Float = Spring.StiffnessMediumLow): FiniteAnimationSpec<T> =
@@ -305,26 +282,15 @@ internal fun Modifier.shine(trigger: Boolean, strength: Float = 0.22f): Modifier
}
}
/**
* Controller focus on the front end: each rail item's requester and the page's main button (Play,
* Open desktop, Open <emulator>, Launch...). The pane leaves, to the left, for the selected rail
* item - whatever tile or button it leaves from - and remembers that control, so coming back in
* lands on it again; a page not yet visited enters on its main button.
*/
internal class FrontFocus {
val rail = HashMap<String, FocusRequester>()
val primary = FocusRequester()
var primaryAttached by mutableStateOf(0)
var focusedRail by mutableStateOf<String?>(null)
fun railFor(key: String): FocusRequester = rail.getOrPut(key) { FocusRequester() }
// The pane's controls by id (a tile's key, a button's label), how many of each are on screen,
// and the last one focused.
val items = HashMap<String, FocusRequester>()
val attached = HashMap<String, Int>()
// State, so the controller hints follow it: A launches from a game row but selects elsewhere.
var last by mutableStateOf<String?>(null)
// The first tile of the page's grid: Down from the page's buttons goes to it, not to whichever
// tile happens to sit under the button.
val firstTile = FocusRequester()
var firstTileAttached = 0
fun paneEntry(): FocusRequester {
@@ -339,16 +305,13 @@ internal class FrontFocus {
companion object { const val PRIMARY = "\u0000primary" }
}
/** Down from this button goes to the first tile of the page's grid, when there is one. */
@Composable
internal fun Modifier.downToFirstTile(): Modifier {
// Sheet rows walk their settings; Desktop's dock stays composed behind the sheet.
if (LocalSheetBeat.current != null) return this
val ff = LocalFrontFocus.current ?: return this
return this.focusProperties { down = if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
}
/** Marks the first tile of the page's grid. */
@Composable
internal fun Modifier.firstTile(): Modifier {
val ff = LocalFrontFocus.current ?: return this
@@ -359,7 +322,6 @@ internal fun Modifier.firstTile(): Modifier {
return this.focusRequester(ff.firstTile)
}
/** Lets the pane come back to this control: it is remembered when focused. */
@Composable
internal fun Modifier.paneItem(id: String): Modifier {
val ff = LocalFrontFocus.current ?: return this
@@ -373,14 +335,8 @@ internal fun Modifier.paneItem(id: String): Modifier {
internal val LocalFrontFocus = staticCompositionLocalOf<FrontFocus?> { null }
/** The pane's exit animation (170ms) and a frame's margin: a new page is in after this. */
private const val PAGE_EXIT_MS = 200
/**
* Asks [target] for focus once a frame until [done] (or a focus request lands), for at most half a
* second: a control can take focus only once it is laid out, and that is a frame or two, not a
* fixed number of milliseconds.
*/
internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusRequester) {
repeat(30) {
androidx.compose.runtime.withFrameNanos { }
@@ -389,11 +345,6 @@ internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusR
}
}
/**
* Asks [target] for focus on the next frames until a request lands (a control can take focus only
* once it is laid out), for at most half a second; then leaves focus alone, so a press right after
* is never pulled back.
*/
internal suspend fun focusSoon(target: () -> FocusRequester) {
repeat(30) {
androidx.compose.runtime.withFrameNanos { }
@@ -442,20 +393,15 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
}
}
// A page reached by a hop goes back the way it came; any other page just closes.
val pageBack = { if (!Hops.back(a.onPageBack)) a.onPageBack() }
BackHandler(enabled = !processSettingsPageVisible && s.pageKey != null && page != null) { pageBack() }
// Left any other way, the hop's page has no way back to keep.
LaunchedEffect(s.pageKey, selected) { Hops.forget(s.pageKey ?: selected) }
// A section reached by a hop (Desktop's Flathub card to the Store) goes back the way it came.
BackHandler(enabled = !processSettingsPageVisible && s.pageKey == null && Hops.origin?.page == selected) {
val rail = Hops.origin?.rail ?: return@BackHandler
Hops.back { selected = rail }
}
val density = androidx.compose.ui.platform.LocalDensity.current.density
remember(density) { Hops.density = density; true }
// Back (and B) from a ROM, an emulator, an added app or Flathub steps out one level instead
// of leaving the app: a ROM -> its emulator, the others -> Desktop.
BackHandler(
enabled = !processSettingsPageVisible && (s.pageKey == null || page == null) &&
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"),
@@ -463,32 +409,24 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop"
}
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
// The last game uninstalled leaves the Games tab on its empty state.
LaunchedEffect(s.steamGames.isEmpty()) {
if (s.steamGames.isEmpty() && selected.startsWith("app:")) selected = "games"
}
remember { Motion.refresh(ctx); true }
val railSelection = when {
// A hop's page belongs to the rail item it flew to.
Hops.origin != null && s.pageKey == Hops.origin?.page -> Hops.origin!!.dest
// Performance opens from Play's sheet, and is Steam's.
s.pageKey == "performance" -> "steam"
s.pageKey == "controller-mapping" -> "setup"
selected.startsWith("app:") -> "games"
// Flathub is a page of Desktop's, as an emulator's is.
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop"
else -> s.pageKey ?: selected
}
// Bumped each time a rail item is picked, so a controller moves on into the new page.
var railPicks by remember { mutableStateOf(0) }
val showRailPage: (String, Boolean) -> Unit = { key, focusContent ->
// Components is a full page like Protons or Performance, opened over the current rail
// selection rather than replacing it.
if (key == "components") a.onComponents(focusContent)
else {
if (s.pageKey != null) a.onPageBack()
// Another section: no way back to keep, and no sheet to put back.
Hops.origin = null
Hops.restore = null
Hops.sinking = null
@@ -511,19 +449,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
.windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
.onFocusChanged { anyFocused = it.hasFocus },
) {
// Start controllers on the current page's main action, else on the rail.
LaunchedEffect(processSettingsPageVisible) {
if (processSettingsPageVisible) return@LaunchedEffect
snapshotFlow { window.isWindowFocused }.first { it }
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
}
// A tile or button that opens a page goes away with the page it was on, and focus with it;
// the pad then had nothing to move from (a press landed back on the rail's first item). So
// once the new page is in, a controller lands on its main button.
// Backing out of a page: it stays on screen while it leaves (and holds focus there), so hand
// focus back now to the control it was opened from. Not when the page closed because
// another rail item was picked: focus is on the rail then, and stays there.
var openPage by remember { mutableStateOf<String?>(null) }
LaunchedEffect(s.pageKey) {
val closed = openPage != null && s.pageKey == null
@@ -534,7 +465,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
LaunchedEffect(selected, s.pageKey, processSettingsPageVisible) {
if (processSettingsPageVisible) return@LaunchedEffect
// Past the old page's exit (170ms), then the first frame the new page takes focus.
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
if (s.pageKey == "performance") {
@@ -547,12 +477,10 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
if (anyFocused) return@LaunchedEffect
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
}
// A rail item picked with a controller moves on into its page, once the page is in.
LaunchedEffect(railPicks) {
if (railPicks == 0 || processSettingsPageVisible) return@LaunchedEffect
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
// Waits for the new page's main button rather than a fixed guess at how long it takes.
withTimeoutOrNull(1_000) { snapshotFlow { frontFocus.primaryAttached > 0 }.first { it } } ?: return@LaunchedEffect
focusWithinFrames({ frontFocus.focusedRail == null && anyFocused }) { frontFocus.paneEntry() }
}
@@ -562,9 +490,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val railFocus = Modifier
.focusProperties { enter = { frontFocus.railFor(railSelection) } }
.focusGroup()
// Back from a hop onto a surface that is not a sheet (a game's Components card, Desktop's
// Flathub card): focus
// goes back to the control that asked, once the page has gone.
LaunchedEffect(Hops.restore) {
val r = Hops.restore ?: return@LaunchedEffect
if (r.surface == HOP_SURFACE_SHEET) return@LaunchedEffect
@@ -594,9 +519,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
}
// Dots on their way somewhere: a hop to another section and back, a swap flying home.
FlightsLayer(screenAt)
// A confirm stepping out of the control that asked for it.
StepsLayer(screenAt)
appToChooseDisplay?.let { app ->
@@ -661,11 +584,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
}
val hasBackTarget = (s.pageKey != null && page != null) ||
// A section reached by a hop goes back to where it came from, not to the rail.
(s.pageKey == null && Hops.origin?.page == selected) ||
((s.pageKey == null || page == null) &&
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"))
// At the top of a section, Back goes to the rail - the launcher itself is never backed out of.
BackHandler(enabled = !processSettingsPageVisible && !hasBackTarget) {
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
runCatching { frontFocus.railFor(railSelection).requestFocus() }
@@ -81,11 +81,9 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.R
// The Setup page: runtime and device checks, tools, frame generation and launch settings.
private enum class CheckState { OK, WARN, BUSY }
/** One requirement in Setup's system check: a status mark, what it is, and at most one action. */
@Composable
private fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
val colors = MaterialTheme.colorScheme
@@ -159,7 +157,6 @@ internal fun SetupPanel(
}
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
// Tested hardware passes; an Adreno below it (a 610, say) warns rather than claiming support.
val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() }
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED
val gpuName = remember { DeviceSupport.gpuName(ctx) }
@@ -168,15 +165,12 @@ internal fun SetupPanel(
var showLimitDetails by rememberSaveable { mutableStateOf(false) }
var editSgdbKey by remember { mutableStateOf(false) }
if (editSgdbKey) SgdbKeyDialog(s.sgdbUserKey, onSave = { a.onSgdbKey(it); editSgdbKey = false }, onDismiss = { editSgdbKey = false })
// Four tabs by scope, a chip row with one gliding selection; LB and RB turn them from
// anywhere on the page. Build and credits are on the Updates page.
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_diagnostics))
var tab by rememberSaveable { mutableStateOf(0) }
val chipFocus = remember { List(4) { FocusRequester() } }
var tabTurned by remember { mutableStateOf(false) }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
val inputModeManager = LocalInputModeManager.current
// The control a controller was on went with the old tab: it lands on the new tab's chip.
LaunchedEffect(tab) {
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
androidx.compose.runtime.withFrameNanos { }
@@ -260,8 +254,6 @@ internal fun SetupPanel(
}
}
AnimatedVisibility(showLimitDetails, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
// One sentence and at most three buttons. The computer route and its
// raw command live on the full page Wireless debugging opens.
Column(modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, top = 4.dp, bottom = 10.dp)) {
Text(
if (limitBlocks) PhantomProcessLimit.gateInstructions(ctx, s.phantomProcessStatus)
@@ -298,7 +290,6 @@ internal fun SetupPanel(
)
}
val all = listOf(gpuCheck, runtimeCheck, limitCheck, accountCheck)
// Everything passes: one line says so, and Details opens the checks in place.
ReadinessCard(
passing, checks.size,
listOfNotNull(
@@ -312,7 +303,6 @@ internal fun SetupPanel(
val shownChecks = all.filterIndexed { i, _ -> checks[i] }
shownChecks.forEachIndexed { i, check -> check(i < shownChecks.lastIndex) }
}
// Each check that warns is its own card, its Fix it as it always was.
if (passing < checks.size) {
SectionTitle(stringResource(R.string.setup_needs_you), null)
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
@@ -392,7 +382,6 @@ internal fun SetupPanel(
)
}
}
// Two columns on a wide page: how it looks; this device and the library's art.
if (wide) Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top) {
Column(Modifier.weight(1f)) { look() }
Column(Modifier.weight(1f)) { device(); art() }
@@ -405,6 +394,8 @@ internal fun SetupPanel(
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint),
stringResource(R.string.setup_reset_settings_button), a.onResetSettings)
}
}
}
@@ -413,10 +404,6 @@ internal fun SetupPanel(
}
}
/**
* The checks as one card while they all pass: a ring with how many pass, "Ready to play" and one
* line of what that means, and a Details chip that opens the checks themselves in place ([checks]).
*/
@Composable
private fun ReadinessCard(passing: Int, total: Int, line: String, open: Boolean, onDetails: () -> Unit, checks: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -458,26 +445,18 @@ private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
FrameGenMenu(host, s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless)
}
/**
* What shapes a launch, beside the game rather than three screens away in Setup. They are the
* app-wide settings - each card opens the same page or menu Setup does.
*/
@Composable
internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame? = null) {
// Three across, two on a narrow page; each row's cards share one height.
val columns = if (LocalNarrowPane.current) 2 else 3
val controller = a.controller
val context = androidx.compose.ui.platform.LocalContext.current
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
// The game's prefix is compatdata/<id>, as droiddeck-game-env reads it: a Steam title's appid, an
// added game's shortcut appid (unsigned). Recommended scans the game's own folder either way.
val wincompKey = game?.takeIf { it.library == com.droiddeck.launcher.frontend.Library.ADDED || it.appId > 0 }?.profileKey
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
val cards = buildList<@Composable (Modifier) -> Unit> {
add { m ->
val back = stringResource(R.string.hop_from_games)
// Components is its own section: the card hops there, and B on it comes back here.
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)
@@ -493,9 +472,6 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
// An Epic game's own launch choices, kept in its sidecar so a launch from the Steam client
// honours them too (droiddeck-store-launch reads the same file).
// Store launch choices; cloud saves have their own view.
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC || it == com.droiddeck.launcher.stores.Store.GOG }
if (cardStore != null && game?.gameFiles != null) add { m ->
Box(m) {
@@ -526,10 +502,8 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
/** Epic's account page behind its sign-in: signing in there presents any step the account still owes. */
private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
/** The Epic card: the sign-in and offline switches, read from and written to the game's sidecar, and Resolve Epic sign-in. */
@Composable
private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) {
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
@@ -548,8 +522,6 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
if (epic && options.offline) add(stringResource(R.string.epic_card_offline))
else if (epic && options.eos) add(stringResource(R.string.epic_card_eos))
}.ifEmpty { listOf(stringResource(R.string.epic_card_none)) }.joinToString(" · ")
// Each switch goes straight to the sidecar on disk - both launch paths read it there - and the
// card shows what was read back, so a write that did not take is never shown as done.
fun set(change: (com.droiddeck.launcher.stores.EpicOptions) -> com.droiddeck.launcher.stores.EpicOptions) {
Thread({
val written = runCatching { com.droiddeck.launcher.stores.StoreGameSidecar.updateEpic(folder, change) }
@@ -578,8 +550,6 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
MenuItem(stringResource(R.string.epic_offline), checked = options.offline) { set { it.copy(offline = !it.offline) } }
}
if (epic) {
// Epic asks some accounts to accept something once (privacy policy, EULA) before a game may
// sign in - EOS's "corrective action". Signing in on Epic's site shows it.
MenuItem(stringResource(R.string.epic_resolve), checked = false) {
host.open = null
runCatching {
@@ -614,10 +584,6 @@ private fun SettingCard(label: String, value: String, id: String, modifier: Modi
}
}
/**
* The app's language: "System default" (what Android uses, named in brackets) or one of the
* languages the app ships, each in its own script. Steam is set to the same language when it starts.
*/
@Composable
private fun LanguageRow(host: MenuHost, chosen: String, onPick: (String) -> Unit) {
val context = androidx.compose.ui.platform.LocalContext.current
@@ -66,7 +66,6 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
// Small building blocks shared by the front end's pages: text styles, chips and buttons.
internal val Shape14 = RoundedCornerShape(14.dp)
@@ -97,7 +96,6 @@ internal fun SectionTitle(t: String, detail: String?) {
@Composable internal fun Note(t: String) = Text(t, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.fillMaxWidth().clip(Shape12).background(MaterialTheme.colorScheme.surface).border(1.dp, LocalPalette.current.line2, Shape12).padding(12.dp))
/** A page's buttons: they wrap onto a second line rather than run off a narrow page. */
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun Actions(content: @Composable () -> Unit) = FlowRow(
@@ -105,13 +103,11 @@ internal fun Actions(content: @Composable () -> Unit) = FlowRow(
verticalArrangement = Arrangement.spacedBy(10.dp),
) { content() }
/** A status chip in a row of buttons, centred on their height. */
@Composable
internal fun ActionChip(t: String, ok: Boolean) = Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok) }
internal val Shape16 = RoundedCornerShape(16.dp)
/** One level up, as Back and B do: a real button, big enough to hit ([compact]: for the tightest layouts). */
@Composable
internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -154,7 +150,6 @@ internal fun PrimaryButton(
main: Boolean = false,
compact: Boolean = false,
modifier: Modifier = Modifier,
/** The Steam tab's own Play: bigger than any other button on a page. */
large: Boolean = false,
icon: ImageVector? = null,
fill: Boolean = false,
@@ -162,7 +157,6 @@ internal fun PrimaryButton(
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
// The page's main button is where the pane is entered from the rail.
val frontFocus = if (main) LocalFrontFocus.current else null
if (frontFocus != null) DisposableEffect(Unit) {
frontFocus.primaryAttached++
@@ -174,24 +168,19 @@ internal fun PrimaryButton(
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "btnScale")
val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift")
// Where it sits, so a session it starts can grow out of it (LaunchFlood).
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = if (fill) Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally) else Arrangement.spacedBy(8.dp),
modifier = modifier.then(track)
.onGloballyPositioned { placed[0] = it }
// 48dp to touch on a handheld; compact rows keep 44.
.heightIn(min = if (compact) 44.dp else 48.dp)
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.primary).onFocusChanged { if (it.isFocused) frontFocus.last = FrontFocus.PRIMARY } else Modifier)
.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)
// Off, its fill can match the surface it sits on: the outline keeps it a button.
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12))
// The grow and shine alone barely show on the light fill: outline it when a
// controller is on it, as the other controls are.
.glideBorder(hot, Shape12, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled) {
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
@@ -229,11 +218,6 @@ private fun FittedLabel(text: String, style: TextStyle, modifier: Modifier = Mod
}
}
/**
* [label] while idle; while [progress] is set, a spinner and how far along it is in its place.
* The label stays laid out underneath, invisible, so the button keeps its width. The spinner
* turns until there is a first figure to show.
*/
@Composable
internal fun ProgressLabel(label: @Composable (Modifier) -> Unit, progress: Float?, fontSize: androidx.compose.ui.unit.TextUnit = 15.sp) {
val pal = LocalPalette.current
@@ -275,7 +259,6 @@ internal fun Cog(size: androidx.compose.ui.unit.Dp = 48.dp, onClick: () -> Unit)
val colors = MaterialTheme.colorScheme
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
// A press spins it on a half turn as the page it opens blooms out of it (PageOrigin).
var spins by remember { mutableIntStateOf(0) }
val rot by animateFloatAsState((if (hot) 90f else 0f) + spins * 180f, Motion.sp(0.55f), label = "cog")
val pal = LocalPalette.current
@@ -48,8 +48,6 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
// Environment variables for Proton games: one shared profile and one per game, in the app's own
// dialog, with each variable's actions in a menu off its value as everywhere else.
@Composable
fun GameEnvironmentRow(
@@ -58,8 +56,6 @@ fun GameEnvironmentRow(
initialScope: String = "",
) {
var open by remember { mutableStateOf(false) }
// Opened with a pad, the editor starts with focus in it; the dialog is a window of its own and
// would otherwise give the pad nothing to move from.
var byPad by remember { mutableStateOf(false) }
val inputMode = LocalInputModeManager.current
SettingsRow(stringResource(R.string.game_env_title), if (showHint) stringResource(R.string.game_env_hint) else null) {
@@ -71,7 +67,6 @@ fun GameEnvironmentRow(
if (open) GameEnvironmentEditor(byPad, initialScope) { open = false }
}
/** With a pad driving, focus [target] once the dialog is laid out, and keep the dialog in pad mode. */
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
internal fun PadFocus(byPad: Boolean, target: FocusRequester) {
@@ -128,7 +123,6 @@ internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", on
PadFocus(byPad, firstFocus)
DialogHeader(stringResource(R.string.game_env_eyebrow), stringResource(R.string.game_env_title))
Small(stringResource(R.string.game_env_applies))
// Which profile: everything shared, or one game's.
Panel {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
@@ -173,7 +167,6 @@ internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", on
name, value, inherited = !own.containsKey(name), open = menu == "var:$name", enabled = !busy,
onToggle = { menu = if (menu == "var:$name") null else "var:$name" }, onDismiss = { if (menu == "var:$name") menu = null },
onEdit = { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = EnvironmentVariableEdit(scope, profileName, name, value ?: "") },
// A value set here or inherited can be switched off for this profile; one set here can go back to inheriting.
onUnset = if (value != null) ({ menu = null; save(current.withEntries(scope, own + (name to null))) }) else null,
onRestore = if (own.containsKey(name)) ({ menu = null; save(current.withEntries(scope, own - name)) }) else null,
shared = scope.isEmpty(),
@@ -182,9 +175,7 @@ internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", on
}
}
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
// Footer: add a variable, reset the profile, done.
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(top = 4.dp)) {
// Only once the settings are in: a button drawn disabled first comes up without its box.
if (current != null) Box {
SecondaryButton(stringResource(R.string.game_env_add), enabled = !busy) { menu = if (menu == "add") null else "add" }
AnchoredMenu(menu == "add", onDismiss = { if (menu == "add") menu = null }, title = stringResource(R.string.game_env_add)) { first ->
@@ -216,12 +207,10 @@ internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", on
private data class EnvironmentVariableEdit(val scope: String, val profileName: String, val name: String, val value: String)
/** The panel the profile and the variables sit in, as a settings group does. */
@Composable
private fun Panel(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) =
Column(Modifier.fillMaxWidth().clip(Shape14).background(MaterialTheme.colorScheme.surface).border(1.dp, LocalPalette.current.line, Shape14), content = content)
/** One variable: its name, what it is set to (and whether that comes from the shared profile), and a menu of what to do with it. */
@Composable
private fun VariableRow(
name: String, value: String?, inherited: Boolean, open: Boolean, enabled: Boolean, shared: Boolean,
@@ -299,7 +288,6 @@ private fun VariableValueEditor(name: String, value: String, onChange: (String)
var open by remember(name) { mutableStateOf(false) }
var custom by remember(name) { mutableStateOf(option == null || value !in option.choices && option.type != GameEnvironmentOptions.Type.MULTIPLE) }
when {
// On/off variables pick from their two values like any other choice: one way to set a value.
option != null && option.choices.isNotEmpty() -> {
SettingsRow(stringResource(R.string.game_env_value), null, highlighted = open) {
Box {
@@ -2,32 +2,14 @@ package com.droiddeck.launcher.ui
import kotlin.math.min
/**
* Where the unfolded screen's gamepad puts each control, for a panel of a given size: plain
* numbers, so the layout is tested without a device (GamepadGeometryTest).
*
* Each thumb pivots at its bottom corner; its main control (a stick or trackpad) sits where it
* rests, diagonally in from the corner, and the right side mirrors the left.
*
* A wide strip (a foldable held flat as a tablet): the second control - the d-pad, the face
* buttons - a slide inward along the arc, the shoulders above, and View, Steam, QAM and Menu
* between the arcs. The reach R is the strip's height, or a third of its width.
*
* A tall panel (held upright): the second control a slide up the arc instead, the shoulders above
* that, View, Steam, QAM and Menu between the two sticks, and Panels - the Deck controls' other
* tabs - between the shoulders. Each side's column S is half the width, or as much as the height
* holds. A wide strip has no room for Panels and leaves it out.
*/
object GamepadGeometry {
enum class Slot {
LEFT_MAIN, LEFT_SECOND, RIGHT_MAIN, RIGHT_SECOND,
LEFT_OUTER_SHOULDER, LEFT_INNER_SHOULDER, RIGHT_INNER_SHOULDER, RIGHT_OUTER_SHOULDER,
VIEW, STEAM, QAM, MENU,
/** The Deck controls' other tabs: on a tall panel only. */
PANELS,
}
/** A control's box: its centre and size, in pixels. */
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
val left get() = cx - width / 2f
val top get() = cy - height / 2f
@@ -38,19 +20,15 @@ object GamepadGeometry {
left < other.right && other.left < right && top < other.bottom && other.top < bottom
}
/** The middle buttons, in a row in this order; two by two as on a Deck, View and Menu above Steam and QAM. */
private val middle = listOf(Slot.VIEW, Slot.STEAM, Slot.QAM, Slot.MENU)
private val twoByTwo = mapOf(Slot.VIEW to 0, Slot.MENU to 1, Slot.STEAM to 2, Slot.QAM to 3)
/** A panel this shape is laid out as a tall panel (held upright), which has room for Panels;
* anything flatter is a wide strip. */
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
fun layout(w: Float, h: Float, density: Float): Map<Slot, Box> {
if (w <= 0f || h <= 0f) return emptyMap()
val pad = 8 * density
val buttonH = 40 * density
// A row needs its buttons comfortable; two by two will take them a little narrower.
val rowButton = 64 * density
val gridButton = 48 * density
val gutter = 8 * density
@@ -75,14 +53,12 @@ object GamepadGeometry {
val mainTop = h - reach * 0.40f - main / 2f
val shoulderW = reach * 0.36f
val shoulderH = (reach * 0.16f).coerceAtLeast(buttonH)
// Above the main controls, never over them, and inside the panel.
val shoulderY = min(h - reach * 0.94f + shoulderH / 2f, mainTop - gutter - shoulderH / 2f)
.coerceAtLeast(pad + shoulderH / 2f)
pair(Slot.LEFT_MAIN, Slot.RIGHT_MAIN, reach * 0.40f, h - reach * 0.40f, main, main)
pair(Slot.LEFT_SECOND, Slot.RIGHT_SECOND, reach * 1.03f, h - reach * 0.30f, second, second)
pair(Slot.LEFT_OUTER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER, reach * 0.22f, shoulderY, shoulderW, shoulderH)
pair(Slot.LEFT_INNER_SHOULDER, Slot.RIGHT_INNER_SHOULDER, reach * 0.62f, shoulderY, shoulderW, shoulderH)
// Between the arcs: in a row if they fit, else two by two, else one above another.
val gap = w - 2 * reach * 1.32f
val columns = when {
gap >= middle.size * rowButton -> middle.size
@@ -102,12 +78,10 @@ object GamepadGeometry {
pair(Slot.LEFT_SECOND, Slot.RIGHT_SECOND, side * 0.74f, secondCy, second, second)
pair(Slot.LEFT_OUTER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER, side * 0.20f, shoulderY, shoulderW, shoulderH)
pair(Slot.LEFT_INNER_SHOULDER, Slot.RIGHT_INNER_SHOULDER, side * 0.57f, shoulderY, shoulderW, shoulderH)
// Between the two sticks at the bottom: two by two, or one above another.
val gap = w - 2 * (side * 0.40f + main / 2f)
val columns = if (gap >= 2 * gridButton) 2 else 1
val rows = (middle.size + columns - 1) / columns
middleGrid(columns, gap - 2 * gutter, h - pad - rows * buttonH - (rows - 1) * 10 * density)
// Between the inner shoulders, where it fits.
val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter)
if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
}
@@ -62,14 +62,12 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
/** One matched driver pair in the list (DriverPairs), and what this device makes of it. */
class PairRow(
val key: String,
val name: String,
val version: String,
val detail: String,
val recommended: Boolean,
/** Built for this GPU's family; the others only show when asked. */
val suits: Boolean,
val complete: Boolean,
val installed: Boolean,
@@ -85,13 +83,11 @@ class GpuDriversState(
val unsupported: Boolean = false,
val auto: Boolean = true,
val pairs: List<PairRow> = emptyList(),
/** The pair key being installed, and how far along (-1 = unknown). */
val busy: String? = null,
val percent: Int = -1,
val autoStatus: String = "",
val releaseStatus: String = "",
val checking: Boolean = false,
// Advanced: each driver on its own.
val linuxRows: List<DriverRow> = emptyList(),
val linuxSelected: String = "",
val androidRows: List<DriverRow> = emptyList(),
@@ -99,10 +95,8 @@ class GpuDriversState(
val linuxDownloads: List<DownloadRow> = emptyList(),
val androidDownloads: List<DownloadRow> = emptyList(),
val canRestoreBundled: Boolean = false,
/** The Android + Linux bundle both drivers are set to ("DD-Turnip 0.1.0"), or null. */
val activeBundle: String? = null,
) {
/** The pair both drivers are set to, if they make one. */
val activePair: PairRow? get() = pairs.firstOrNull { it.active }
}
@@ -117,16 +111,10 @@ class GpuDriversActions(
val onDownloadDriver: (String) -> Unit = {},
val onImportLinux: () -> Unit = {},
val onImportAndroid: () -> Unit = {},
/** The tab's own import: a bundle, or a single driver of either kind. */
val onImportZip: () -> Unit = {},
val onRestoreBundled: () -> Unit = {},
)
/**
* Everything about the chip - SoC, GPU, CPU, memory, system, the phone's own Vulkan driver, the
* drivers in use - gathered once, off the main thread, with a button that copies it for a bug
* report. Stepped out of the Components page's device chip; [first] is where a pad starts.
*/
@Composable
internal fun DeviceDetails(first: FocusRequester) {
val colors = MaterialTheme.colorScheme
@@ -159,7 +147,6 @@ internal fun DeviceDetails(first: FocusRequester) {
}
}
/** One part of the device details: its title, then label/value rows. Focusable, so the d-pad walks the list. */
@Composable
private fun DeviceInfoSection(section: DeviceInfo.Section) {
val colors = MaterialTheme.colorScheme
@@ -29,17 +29,6 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
// A link from a control in one section to a page in another (the Play sheet's Graphics drivers,
// a game's Components card): the control squashes into a dot that flies to the destination's rail
// item, the rail's selection glides there as it passes the top of its arc, and the page floods
// out of the rail item once it lands. B on that page flies the dot back and puts the source
// surface back as it was, focus on the control that asked.
/**
* Where a hop came from: the rail item that was showing ([rail]), the surface on it (a sheet, the
* Games page) and its tab, the control's key and its root bounds, and the words for the way back.
* [page] is the page key the hop opened, so leaving it any other way forgets the way back.
*/
internal class HopOrigin(
val rail: String,
val surface: String,
@@ -51,46 +40,29 @@ internal class HopOrigin(
val page: String,
)
/** The surfaces a hop can start from and come back to. */
internal const val HOP_SURFACE_GAMES = "games"
internal const val HOP_SURFACE_DESKTOP = "desktop"
internal const val HOP_SURFACE_SHEET = "sheet"
internal object Hops {
/** The hop the page on screen was reached by, while B can still undo it. */
var origin by mutableStateOf<HopOrigin?>(null)
/** The pane content a hop is leaving (a rail key): it sinks back as the dot leaves it. */
var sinking by mutableStateOf<String?>(null)
/** Set while a hop's dot is flying: the rail item its selection has already glided to. */
var railPreview by mutableStateOf<String?>(null)
/**
* Set as a page leaves through a hop (either way), so the pane sinks it rather than draining
* it; the pane clears it once the change has started.
*/
var linking by mutableStateOf(false)
/** A surface to put back as it was (a sheet re-lifted on its tab), once, and the control to focus. */
var restore by mutableStateOf<HopOrigin?>(null)
/** Per rail item, bumped when a dot lands on it: the item pops. */
val railLanded = mutableStateMapOf<String, Int>()
/** Bumped when a hop's page has flooded in: its target (a layer card) sends out one ring. */
var arrived by mutableIntStateOf(0)
/** Where each rail item sits, root px. */
val railBounds = HashMap<String, Rect>()
/** Where each control that can start a hop sits, root px. */
val sources = HashMap<String, Rect>()
/**
* Hops from the control at [origin].bounds to [origin].dest: [go] opens the page there once the dot lands.
* With animations off there is no dot and no flood, only the page.
*/
fun go(origin: HopOrigin, go: () -> Unit) {
val railAt = railBounds[origin.dest]
val finish: () -> Unit = {
@@ -103,7 +75,6 @@ internal object Hops {
arrived++
}
if (railAt == null || Motion.scale == 0f) { finish(); return }
// The surface the control is on sinks as its dot leaves, and stays down as it goes.
sinking = origin.rail
Flights.fly(Flight(
origin.bounds, to = { railAt.center },
@@ -112,10 +83,6 @@ internal object Hops {
))
}
/**
* B on a page reached by a hop: the page sinks, the source surface comes back as it was, and
* the dot flies home from the rail item to the control. False when there is no hop to undo.
*/
fun back(close: () -> Unit): Boolean {
val o = origin ?: return false
origin = null
@@ -133,26 +100,18 @@ internal object Hops {
return true
}
/** The page the hop opened has gone some other way: there is no way back to keep. */
fun forget(pageKey: String?) {
val o = origin ?: return
if (pageKey != o.page) { origin = null; sinking = null }
}
/** Screen density, for the rail item's corner; set by the front end. */
var density = 1f
}
/** Shows a rail section directly (no page closing, nothing forgotten): what a hop's way back calls. */
internal val LocalShowSection = androidx.compose.runtime.staticCompositionLocalOf<(String) -> Unit> { {} }
/** Remembers where this control sits, so a hop from it can fly from it and back to it. */
internal fun Modifier.hopSource(key: String): Modifier = onGloballyPositioned { Hops.sources[key] = it.boundsInRoot() }
/**
* "B · back to <source>" at the right of a page's header while it was reached by a hop; a tap is B.
* Nothing when it was not.
*/
@Composable
internal fun HopBackChip(onBack: () -> Unit) {
val o = Hops.origin ?: return
@@ -44,25 +44,15 @@ import java.lang.ref.WeakReference
import kotlin.math.PI
import kotlin.math.sin
// Starting a session from a blue button: the button grows until the page is its blue, and the
// loading screen opens on that blue and gathers it into the ball of the throbber.
// Stopping one from the drawer runs it the other way: Stop grows until the page is blue, and the
// front end opens on that blue and draws it back down into the button the session came from.
// Any other way out (backing out of the loading screen, closing the ended screen, the session
// ending) spreads the blue back out of the throbber's ball instead (FloodSpread).
/** Carries the flood's colour to the session, which opens on it. */
const val EXTRA_FLOOD = "com.droiddeck.launcher.FLOOD"
/** Where the last pressed blue button sat, so a session started by it can grow out of it. */
internal object LaunchOrigin {
private var bounds: Rect? = null
private var button: Any? = null
private var at = 0L
/** The last button a session was started from, for a stop to return into. */
private var last: WeakReference<Any>? = null
/** The button a flood is growing out of: it steps aside so only the flood shows. */
var flooding by mutableStateOf<Any?>(null)
fun mark(r: Rect, key: Any) {
@@ -72,10 +62,6 @@ internal object LaunchOrigin {
at = SystemClock.uptimeMillis()
}
/**
* Where the button the running session was started from sits now, if it is still on screen;
* it hides for the return, as for the flood.
*/
fun takeReturn(): Rect? {
val key = last?.get() as? Array<*> ?: return null
val c = key.getOrNull(0) as? LayoutCoordinates ?: return null
@@ -84,7 +70,6 @@ internal object LaunchOrigin {
return c.boundsInRoot()
}
/** The button behind a launch starting now, if one was pressed just before; it hides for the flood. */
fun take(): Rect? {
val b = bounds?.takeIf { SystemClock.uptimeMillis() - at < 1_500 }
if (b != null) flooding = button
@@ -94,7 +79,6 @@ internal object LaunchOrigin {
}
}
/** A session stopped behind a flood: the blue the front end opens on, for a few seconds. */
internal object QuitFlood {
private var color: Int? = null
private var at = 0L
@@ -111,7 +95,6 @@ internal object QuitFlood {
}
}
/** The page a flood grows over, sinking back a touch as it is covered; [progress] is the flood's. */
@Composable
internal fun FloodBehind(progress: () -> Float, content: @Composable () -> Unit) {
Box(Modifier.fillMaxSize().graphicsLayer { val k = sinkScale(progress()); scaleX = k; scaleY = k }) { content() }
@@ -121,19 +104,10 @@ private fun sinkScale(progress: Float) = 1f - 0.04f * progress
private val Gather = CubicBezierEasing(0.6f, 0f, 0.15f, 1f)
/**
* The pressed button, [from] in root px, stretching out to cover the page. Each edge rides its own
* loose spring: the ones with furthest to go set off first and quickest, the ones near the page's
* edge lag and then snap after them, so it pulls like something elastic rather than zooming. It
* goes blobby in flight, its gradient settles into the flat blue of the ball, and [onProgress]
* (0 to 1) lets the page behind sink a little. Calls [onCovered] once nothing but blue shows.
* Swallows touches while it runs.
*/
@Composable
internal fun LaunchFlood(
from: Rect,
onProgress: (Float) -> Unit,
/** The button's own colours, where it is not the page's blue one (a red Stop). */
fromColors: Pair<Color, Color>? = null,
cornerAtRest: Dp = 12.dp,
onCovered: () -> Unit,
@@ -142,10 +116,6 @@ internal fun LaunchFlood(
val pal = LocalPalette.current
val start = fromColors ?: (colors.primary to pal.primary2)
VeilRing()
// Left, top, right, bottom: 0 on the button, 1 on the page's edge. Springs overshoot past the
// edge, off the page, so the wobble is felt in the pull. An underdamped spring then swings back
// short of the edge (about 3% at this damping), so once an edge has reached the page's it holds
// there, or the page would show through in a sliver while the next screen opens.
val edges = remember { List(4) { Animatable(0f) } }
val reached = remember { BooleanArray(4) }
fun edge(i: Int) = edges[i].value.let { if (reached[i]) maxOf(it, 1f) else it }
@@ -174,7 +144,6 @@ internal fun LaunchFlood(
}
}
}
// Covered once every edge has reached the page's.
snapshotFlow { (0 until 4).all { edge(it) >= 1f } }.first { it }
covered()
runs.forEach { it.join() }
@@ -185,15 +154,9 @@ internal fun LaunchFlood(
}
}
/**
* The flood from a button at [from] with its edges [v] of the way to the page's (left, top, right,
* bottom): the button sinking with the page behind, blobby in flight, its colours [start] giving
* way to the flat [signal] in the first half.
*/
private fun DrawScope.drawFlood(from: Rect, v: List<Float>, start: Pair<Color, Color>, signal: Color, cornerAtRest: Float) {
val (l, t, r, b) = v
val mean = v.sumOf { it.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
// The button sinks with the page behind (FloodBehind), so the flood leaves from where it is now.
val k = sinkScale(mean)
val cx = size.width / 2f
val cy = size.height / 2f
@@ -203,10 +166,8 @@ private fun DrawScope.drawFlood(from: Rect, v: List<Float>, start: Pair<Color, C
val bottom = lerp(cy + (from.bottom - cy) * k, size.height, b)
val w = (right - left).coerceAtLeast(0f)
val h = (bottom - top).coerceAtLeast(0f)
// A button's corners at rest, a blob in flight, square once it fills the page.
val blob = sin(PI * mean).toFloat().coerceAtLeast(0f)
val corner = lerp(cornerAtRest * (1f - mean), minOf(w, h) * 0.42f, blob)
// The button's gradient gives way to the ball's flat blue in the first half.
val mix = (mean * 2f).coerceAtMost(1f)
val brush = Brush.linearGradient(
listOf(lerp(start.first, signal, mix), lerp(start.second, signal, mix)),
@@ -215,12 +176,6 @@ private fun DrawScope.drawFlood(from: Rect, v: List<Float>, start: Pair<Color, C
drawRoundRect(brush, topLeft = Offset(left, top), size = Size(w, h), cornerRadius = CornerRadius(corner))
}
/**
* The front end's first frames after a stop: the page in [flood] after a beat, drawn back down
* into the button at [to] (root px, measured before the page sank) on critically damped springs,
* the far edges first, so it sets down on the button without a bounce. [onProgress] (1 to 0) lets
* the page behind rise back. No button to return to: the blue fades. Calls [onLanded] at the end.
*/
@Composable
internal fun FloodReturn(flood: Color, to: Rect?, onProgress: (Float) -> Unit, onLanded: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -234,7 +189,6 @@ internal fun FloodReturn(flood: Color, to: Rect?, onProgress: (Float) -> Unit, o
LaunchedEffect(page != Size.Zero) {
if (page == Size.Zero) return@LaunchedEffect
progress(1f)
// A beat of plain blue first, so the change of screen does not read as a cut.
delay(Motion.ms(220).toLong())
if (to == null || Motion.scale == 0f) {
fade.animateTo(0f, Motion.tw(240, easing = FastOutSlowInEasing))
@@ -262,10 +216,6 @@ internal fun FloodReturn(flood: Color, to: Rect?, onProgress: (Float) -> Unit, o
}
}
/**
* The session's first frames: the page in [flood], drawing in to a circle over [ball] (centre and
* radius in root px, once the throbber is laid out) that lands the size of it. Calls [onLanded] then.
*/
@Composable
internal fun FloodGather(flood: Color, ball: Pair<Offset, Float>?, onLanded: () -> Unit) {
val gather = remember { Animatable(0f) }
@@ -275,7 +225,6 @@ internal fun FloodGather(flood: Color, ball: Pair<Offset, Float>?, onLanded: ()
LaunchedEffect(ball != null) {
if (ball == null || started) return@LaunchedEffect
started = true
// A beat of plain blue first, so the change of screen does not read as a cut.
delay(Motion.ms(90).toLong())
gather.animateTo(1f, Motion.tw(640, easing = Gather))
landed()
@@ -292,18 +241,12 @@ internal fun FloodGather(flood: Color, ball: Pair<Offset, Float>?, onLanded: ()
}
}
/** Where the loading screen's throbber ball sits now (centre and radius, root px), for a flood leaving from it. */
internal object ThrobberSpot {
var ball: Pair<Offset, Float>? = null
}
private val Spread = CubicBezierEasing(0.7f, 0f, 0.4f, 1f)
/**
* Leaving a session: [flood] spreading out of [ball] (centre and radius in root px; the middle of
* the screen when there is none) until it covers the screen, the way FloodGather drew it in. Calls
* [onCovered] then, for the front end to open on the same blue. Swallows touches while it runs.
*/
@Composable
internal fun FloodSpread(flood: Color, ball: Pair<Offset, Float>?, onCovered: () -> Unit) {
VeilRing()
@@ -5,16 +5,11 @@ import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
// Sizes that decide how the launcher reflows on 4:3 and square screens (480x360 or 480x480 dp) as
// well as on the 16:9 ones it was first laid out for.
/** A page narrower than this reflows: settings rows stack, grids drop columns, posters go. */
val NarrowPaneWidth = 520.dp
/** Whether the page being drawn is narrow - the pane beside the rail on a 4:3 or square screen. */
val LocalNarrowPane = compositionLocalOf { false }
/** Too narrow a screen for a labelled rail: the rail shows icons only. */
@Composable
internal fun isNarrowScreen(): Boolean = LocalConfiguration.current.screenWidthDp < 600
@@ -115,14 +115,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
// Play's settings, lifted out from under Play instead of opened on a page of their own. At rest a
// lip tucks out under Play and says what it will do. Down (or a pull up, or a tap on the lip)
// stretches the lip, the wall sinks back, and a sheet rises from the pane's foot with Play riding
// its top edge as the handle - StepOut's move, with the pane for a box. B, Up from the chips or a
// tap above folds it away; A on Play launches straight from it, the sheet folding into the pill
// before the launch flood. Open desktop does the same with the desktop's settings.
/** The sheets' tabs (their chips), by id. */
internal object SheetTab {
const val DISPLAY = "display"
const val CONTROLS = "controls"
@@ -133,30 +126,21 @@ internal object SheetTab {
const val FILES = "files"
}
/**
* Where the open sheet's top edge sits in a pane [paneH] tall (px), for a button [buttonH] tall
* riding it: 60dp down a 360dp pane, the same share of any other, and never so high that the
* button's top comes closer than [minAbove] to the pane's. [ride] is how far below the edge the
* button's centre sits.
*/
internal fun sheetTop(paneH: Float, buttonH: Float, minAbove: Float, ride: Float): Float =
maxOf(paneH * 60f / 360f, minAbove + buttonH / 2f - ride)
/** A finger's hold on the sheet: where it started (0 rest, 1 open), where it is, whether it has it. */
private class SheetDrag {
var from = 0f
var progress = 0f
var engaged = false
}
/** One piece of the sheet's rows fades and rises in on its own beat (a settings group asks for its index). */
internal class SheetBeat(private val pieces: List<Animatable<Float, AnimationVector1D>>) {
private var next = 1
fun take(): Int = next++
fun value(i: Int): Float = pieces[i.coerceIn(0, pieces.lastIndex)].value
}
/** The sheet whose rows are being laid out, so each settings group can take its beat. */
internal val LocalSheetBeat = staticCompositionLocalOf<SheetBeat?> { null }
internal val LocalSheetChipWidth = compositionLocalOf { Dp.Unspecified }
@@ -168,7 +152,6 @@ private val ChipGap = 6.dp
internal fun sheetChipWidth(row: Dp, count: Int): Dp =
if (count > 0 && row / count >= 96.dp) (row - ChipGap * (count - 1)) / count else 0.dp
/** A settings group's piece of the sheet's entrance; nothing outside a sheet. */
@Composable
internal fun Modifier.sheetPiece(): Modifier {
val beat = LocalSheetBeat.current ?: return this
@@ -186,13 +169,6 @@ private val ChipsTop = 14.dp
private val RowsTop = 54.dp
private const val PIECES = 12
/**
* A hero with one big button and the sheet that lifts out from under it. [key] names the sheet
* (a hop comes back to it, the lip remembers what it said); [tabs] are its chips (id to label) and
* [rows] what each holds. [background] sinks and [words] fade as it opens. [button] draws the
* button itself with the click it should make; [onPrimary] is what that click does once the
* sheet is out of the way. [onOpen] reads the settings the rows show.
*/
@OptIn(ExperimentalComposeUiApi::class, androidx.compose.animation.ExperimentalAnimationApi::class)
@Composable
internal fun LiftHero(
@@ -201,26 +177,13 @@ internal fun LiftHero(
onOpen: () -> Unit,
onPrimary: () -> Unit,
background: @Composable () -> Unit,
/**
* Drawn over [background] at the pane's own size: the wall's fades, which must not sink with
* it. Given how far the sheet is up (0 to 1), for anything there that should give way to it.
*/
scrim: @Composable (lifted: () -> Float) -> Unit = {},
words: @Composable () -> Unit,
/**
* Buttons beside the big one (Desktop's Flathub and +). They stay where they are and fade as
* the sheet lifts: only the big button rides it.
*/
beside: @Composable () -> Unit = {},
button: @Composable (onClick: () -> Unit) -> Unit,
rows: @Composable (tab: String) -> Unit,
modifier: Modifier = Modifier,
/**
* Down on the button lifts the sheet (Play). False: Down goes to the lip, which A lifts, and Down
* from the lip goes on past it to what is under the hero (Desktop's shelves).
*/
downOpens: Boolean = true,
/** Told when the sheet starts to lift (true) and once it has gone (false). */
onOpenChange: (Boolean) -> Unit = {},
start: Dp = 44.dp,
bottom: Dp = 44.dp,
@@ -233,7 +196,6 @@ internal fun LiftHero(
val pal = LocalPalette.current
val ff = LocalFrontFocus.current
val narrow = LocalNarrowPane.current
// Held as states too, so the sheet's focus rule reads what they are now, not at the last composition.
val openState = remember { mutableStateOf(false) }
var open by openState
var shown by remember { mutableStateOf(false) }
@@ -241,11 +203,8 @@ internal fun LiftHero(
var launching by launchingState
var tab by remember { mutableStateOf(0) }
var travel by remember { mutableStateOf(1) }
// The control to focus once a sheet put back by a hop's B has lifted, instead of the first chip.
var focusOnLift by remember { mutableStateOf<String?>(null) }
// Set as the sheet closes and Play lands: the lip may come back before the sheet has quite gone.
var lipBack by remember { mutableStateOf(false) }
// Set as a finger's drag lets go: the sheet is already where it is going.
var dragSettled by remember { mutableStateOf(false) }
val scope = androidx.compose.runtime.rememberCoroutineScope()
var dragJob by remember { mutableStateOf<Job?>(null) }
@@ -264,18 +223,15 @@ internal fun LiftHero(
val playSrc = remember { MutableInteractionSource() }
val playHovered by playSrc.collectIsHoveredAsState()
var playFocused by remember { mutableStateOf(false) }
// Set as a pad leaves the sheet to the left for Play, which folds it once Play has focus.
val leftForPlay = remember { booleanArrayOf(false) }
var heroAt by remember { mutableStateOf(Offset.Zero) }
var rest by remember { mutableStateOf<Rect?>(null) }
fun focusPlay() { if (ff != null && inputMode.inputMode == InputMode.Keyboard) runCatching { ff.primary.requestFocus() } }
fun close() {
if (!open) return
// Focus leaves the rows before they go; the sheet lets it go once it is closing.
open = false
focusPlay()
}
// Back from a hop the sheet started (or a page it opened): put it back as it was.
LaunchedEffect(Unit) {
val r = Hops.restore ?: return@LaunchedEffect
if (r.surface != HOP_SURFACE_SHEET || r.rail != key) return@LaunchedEffect
@@ -284,7 +240,6 @@ internal fun LiftHero(
focusOnLift = r.control
open = true
}
// Launched: the session covers the screen, and the sheet is put away under it.
val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
val obs = androidx.lifecycle.LifecycleEventObserver { _, e ->
@@ -298,7 +253,6 @@ internal fun LiftHero(
LaunchedEffect(open, launching) {
if (!dragSettled) { dragJob?.cancel(); dragJob = null }
if (dragSettled) {
// A finger brought it here and has already animated it: only what opening needs.
dragSettled = false
if (open) {
if (inputMode.inputMode == InputMode.Keyboard) { withFrameNanos { }; runCatching { chipFocus[tab].requestFocus() } }
@@ -311,10 +265,8 @@ internal fun LiftHero(
onOpen()
fold.snapTo(0f); foldTop.snapTo(0f)
coroutineScope {
// Pull: the lip stretches down as the wall sinks back and dims.
launch { pull.animateTo(24f, Motion.sp(0.7f, 380f)) }
launch { sink.animateTo(1f, Motion.tw(260)) }
// Lift: the sheet rises with Play riding its top edge; the lip lets go.
launch {
delay(Motion.ms(120).toLong())
launch { lipGone.animateTo(1f, Motion.tw(140)) }
@@ -323,7 +275,6 @@ internal fun LiftHero(
launch { ride.animateTo(1f, Motion.sp(0.7f, 380f)) }
launch { hot.snapTo(1f); delay(Motion.ms(100).toLong()); hot.animateTo(0f, Motion.tw(200)) }
}
// Each piece on its beat from the Lift, as the reel has it: 260ms + 55ms a piece after it starts.
pieces.forEachIndexed { i, p -> launch { delay(Motion.ms(120 + 260 + i * 55).toLong()); p.animateTo(1f, Motion.tw(220)) } }
if (inputMode.inputMode == InputMode.Keyboard) launch {
val control = focusOnLift
@@ -335,7 +286,6 @@ internal fun LiftHero(
}
}
} else if (launching) {
// Play from the sheet: the rows go, the sheet folds into the pill, then the launch.
coroutineScope {
pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } }
launch { delay(Motion.ms(60).toLong()); fold.animateTo(1f, Motion.sp(1f, 420f)) }
@@ -343,8 +293,6 @@ internal fun LiftHero(
}
shown = false
onPrimary()
// The session covers the screen and the sheet is put away under it (ON_STOP). If
// nothing started, put it away anyway.
delay(3_000)
launching = false
} else if (shown) {
@@ -353,7 +301,6 @@ internal fun LiftHero(
launch { delay(Motion.ms(60).toLong()); lift.animateTo(0f, Motion.sp(1f, 380f)) }
launch { delay(Motion.ms(100).toLong()); ride.animateTo(0f, Motion.sp(0.55f, 300f)) }
launch { sink.animateTo(0f, Motion.tw(300)) }
// The lip tucks back under Play as it lands, not once every spring has settled.
launch { delay(Motion.ms(420).toLong()); lipGone.snapTo(0f); lipBack = true }
}
shown = false
@@ -361,20 +308,16 @@ internal fun LiftHero(
lipGone.snapTo(0f)
hot.snapTo(1f)
} else {
// Snapped shut under a session: everything back at rest, no animation.
listOf(pull, sink, lift, ride, lipGone, fold, foldTop).forEach { it.snapTo(0f) }
pieces.forEach { it.snapTo(0f) }
hot.snapTo(1f)
}
}
BackHandler(enabled = open && !launching) { close() }
// The ring keeps out of the lift and the fold, and comes back on whatever has focus once
// they are done: Play rides the sheet on a layer, and the ring hung where Play had been.
if (ride.isRunning || (shown && !open)) VeilRing()
val openNow = open || shown
LaunchedEffect(openNow) { onOpenChange(openNow) }
// The lip: there while Play has a pad or a pointer on it, or always with touch alone.
val touchOnly = inputMode.inputMode == InputMode.Touch
val lipFocus = remember { FocusRequester() }
val settingsLabel = stringResource(R.string.drawer_page_settings)
@@ -382,7 +325,6 @@ internal fun LiftHero(
val lipWanted = !open && (!shown || lipBack) && (playFocused || playHovered || touchOnly || lipFocused) && drop?.let { it.open || it.shown } != true
LaunchedEffect(lipWanted) {
if (lipWanted) {
// Back from the sheet it comes straight away; otherwise a beat after Play has focus.
if (!lipBack) delay(Motion.ms(160).toLong())
lipShow.animateTo(1f, Motion.tw(220))
} else {
@@ -391,10 +333,8 @@ internal fun LiftHero(
}
}
// How far the sheet travels, for a finger's drag to follow: set once the hero is measured.
val travelPx = remember { floatArrayOf(1f) }
val drag = remember { SheetDrag() }
/** The sheet [p] of the way up (0 at rest, 1 open) under a finger. */
fun follow(p: Float) {
drag.progress = p
scope.launch {
@@ -403,7 +343,6 @@ internal fun LiftHero(
pieces.forEach { it.snapTo(p.coerceIn(0f, 1f)) }
}
}
/** A finger takes the sheet where it is: up from rest, or down from open. */
fun beginDrag() {
dragJob?.cancel(); dragJob = null
dragSettled = false
@@ -416,10 +355,6 @@ internal fun LiftHero(
onOpenNow.value()
}
}
/**
* The finger lets go with [v] px/s (up negative): a flick goes the way it was flicked; a slow
* drag stays once it is a third of the way from where it started.
*/
fun settleDrag(v: Float) {
drag.engaged = false
val flick = with(density) { 600.dp.toPx() }
@@ -443,8 +378,6 @@ internal fun LiftHero(
}
if (open != opens) open = opens else dragSettled = false
}
// Pulled down past the top of the rows, the sheet itself comes down with the finger; up again
// before letting go, it goes back up before the rows scroll.
val rowsPull = remember {
object : androidx.compose.ui.input.nestedscroll.NestedScrollConnection {
override fun onPreScroll(available: Offset, source: androidx.compose.ui.input.nestedscroll.NestedScrollSource): Offset {
@@ -468,9 +401,6 @@ internal fun LiftHero(
}
BoxWithConstraints(
modifier.fillMaxSize().onGloballyPositioned { heroAt = it.boundsInRoot().topLeft }
// A swipe anywhere on the hero moves the sheet under the finger - up from rest, down
// when open - and lets go open or shut by how far it went and how fast. A swipe that
// starts the wrong way (down at rest) is left alone, for the page under it.
.pointerInput(drop) {
val tracker = androidx.compose.ui.input.pointer.util.VelocityTracker()
var decided = false
@@ -489,7 +419,6 @@ internal fun LiftHero(
if (launching) return@detectVerticalDragGestures
if (!decided) {
decided = true
// Up at rest opens; down when open closes. Anything else is not for the sheet.
when {
drop != null && (drop.open || drop.shown) -> if (drop.open && amount < 0f) drop.beginDrag()
open || shown || amount < 0f -> if (if (open) amount > 0f else amount < 0f) beginDrag()
@@ -515,24 +444,18 @@ internal fun LiftHero(
val restRect = rest?.translate(-heroAt)
val buttonH = restRect?.height ?: with(density) { 56.dp.toPx() }
val openTop = sheetTop(h, buttonH, with(density) { 16.dp.toPx() }, with(density) { 3.dp.toPx() })
// Play's raised place: its centre 3dp under the sheet's edge, same left inset.
val raise = restRect?.let { (openTop + with(density) { 3.dp.toPx() } - buttonH / 2f) - it.top } ?: 0f
travelPx[0] = (h - openTop).coerceAtLeast(1f)
val pill = restRect?.translate(0f, raise)
// What the sheet holds: the chips to the right of Play, the rows under them.
val chipsX = with(density) {
if (narrow || pill == null) 16.dp.toPx() else pill.right + 20.dp.toPx() - inset
}
val chipWidth = with(density) { sheetChipWidth((w - 2 * inset - chipsX - 64.dp.toPx()).coerceAtLeast(0f).toDp(), tabs.size) }
// The wall behind sinks back about the pane's centre.
val foot = h
val wallSink = { maxOf(sink.value, drop?.sink?.value ?: 0f) }
Box(Modifier.fillMaxSize().clipToBounds().graphicsLayer { val k = 1f - 0.05f * wallSink(); scaleX = k; scaleY = k }) { background() }
// The fades stay put: scaled with the wall they stopped short of the pane's edges and left
// a bright band of unfaded wall down the side and along the top.
scrim { sink.value }
// The dim; a tap on it (above the sheet) folds the sheet away.
if (shown || open) Box(
Modifier.fillMaxSize()
.graphicsLayer { alpha = sink.value }.background(Color.Black.copy(alpha = 0.42f))
@@ -540,7 +463,6 @@ internal fun LiftHero(
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, enabled = open && !launching) { close() },
)
// The sheet: inset at the sides, rounded at the top, no bottom edge - the pane's foot is its foot.
if (shown) {
val top = lerp(foot, openTop, lift.value)
val sheetLeft = inset
@@ -565,7 +487,6 @@ internal fun LiftHero(
val rimColor = pal.signal.copy(alpha = lerp(0.55f, 0.9f, hot.value))
if (ft > 0f) drawPath(path, rimColor, style = Stroke(rim))
else {
// Sides and top only: the sheet runs on under the pane's foot.
rimPath.reset()
rimPath.moveTo(l, b)
rimPath.lineTo(l, t + c)
@@ -577,35 +498,27 @@ internal fun LiftHero(
}
}
val chipsY = with(density) { if (narrow && pill != null) (pill.bottom - openTop) + 10.dp.toPx() else ChipsTop.toPx() }
// The rows start under the chips, which are 44dp to touch: from 54dp they ran under the
// chips' feet and, scrolled, covered them.
val rowsY = with(density) { maxOf(RowsTop.toPx(), chipsY + 52.dp.toPx()) }
val sheetW = sheetRight - sheetLeft
Box(
Modifier
.offset { IntOffset(sheetLeft.roundToInt(), top.roundToInt()) }
.size(with(density) { sheetW.toDp() }, with(density) { (foot - openTop).coerceAtLeast(0f).toDp() })
// Touches on the sheet stay on it; none reach the dim behind.
.pointerInput(Unit) { detectTapGestures { } }
.controllerBack { close() }
.bumpers(
// LB / RB: focus goes to the new tab's chip, so a pad on a row (which goes with
// its tab) is never left with nothing.
onPrevious = { if (tab > 0) { travel = -1; tab--; runCatching { chipFocus[tab].requestFocus() } } },
onNext = { if (tab < tabs.lastIndex) { travel = 1; tab++; runCatching { chipFocus[tab].requestFocus() } } },
)
// A pad stays in the sheet until it folds; Left from it reaches Play, the handle, and folds it.
.focusProperties { exit = { dir -> if (!openState.value || launchingState.value) FocusRequester.Default else if (dir == FocusDirection.Left && ff != null) { leftForPlay[0] = true; ff.primary } else FocusRequester.Cancel } }
.focusGroup(),
) {
Box(
Modifier
.offset { IntOffset(chipsX.roundToInt(), chipsY.roundToInt()) }
// Over the rows, whatever they scroll under them.
.zIndex(1f)
.width(with(density) { (sheetW - chipsX - 64.dp.toPx()).coerceAtLeast(0f).toDp() })
.graphicsLayer { val v = pieces[0].value; alpha = v; translationY = (1f - v) * 6.dp.toPx() }
// Up from the chips folds the sheet (a finger drags it down, see the hero's drag).
.onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode == KeyEvent.KEYCODE_DPAD_UP) { if (k.action == KeyEvent.ACTION_DOWN) close(); true } else false
@@ -635,8 +548,6 @@ internal fun LiftHero(
CompositionLocalProvider(LocalSheetBeat provides remember { SheetBeat(pieces) }) {
Column(
Modifier.fillMaxSize()
// Focus never lands in rows on their way out. Same group always, only
// its rule changes (canFocus here made the scroll's own group a stop).
.focusProperties { enter = { if (leavingNow.value) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup()
.verticalScroll(rememberScrollState())
@@ -660,7 +571,6 @@ internal fun LiftHero(
}
}
// The words and the button, where they always were; the button rides the sheet's edge.
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) {
Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() }
Spacer(Modifier.height(18.dp))
@@ -670,7 +580,6 @@ internal fun LiftHero(
.onGloballyPositioned { rest = it.boundsInRoot() }
.graphicsLayer { translationY = raise * ride.value; alpha = 1f - (drop?.sink?.value ?: 0f) }
.onFocusChanged {
// Left out of the sheet (from the chips or a row) folds it, as Up from the chips does.
if (it.hasFocus && leftForPlay[0]) { leftForPlay[0] = false; if (openState.value && !launchingState.value) close() }
playFocused = it.hasFocus
}
@@ -693,7 +602,6 @@ internal fun LiftHero(
if (open || shown) { launching = true; open = false } else onPrimary()
}
}
// Gone with the words while the sheet is up; nothing a pad or a finger can reach then.
val besideShown = !(open || shown)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
@@ -703,9 +611,7 @@ internal fun LiftHero(
}
}
// The lip, under Play: stretched by the pull, gone as the sheet lifts.
val r0 = restRect
// A lip a pad can reach stays composed (unseen at rest) so Down always has it to land on.
if (r0 != null && (lipShow.value > 0.01f || pull.value > 0.5f || (!downOpens && !open && !shown))) {
var handleW by remember { mutableStateOf(0f) }
val lipH = 32.dp + pull.value.dp
@@ -715,7 +621,6 @@ internal fun LiftHero(
.offset { IntOffset((r0.center.x - handleW / 2f).roundToInt(), (r0.bottom + raise * ride.value + (lipShow.value - 1f) * 8.dp.toPx()).roundToInt()) }
.onSizeChanged { handleW = it.width.toFloat() }
.graphicsLayer { alpha = lipShow.value * (1f - lipGone.value) * (1f - (drop?.sink?.value ?: 0f)) }
// 44dp to touch, with a 32dp visible handle.
.heightIn(min = 44.dp).testTag("sheet-open")
.semantics { contentDescription = settingsLabel }
.then(
@@ -733,10 +638,6 @@ internal fun LiftHero(
}
}
/**
* The sheet's handle, tucked under Play: "Settings" and a chevron that bobs up every so often,
* saying there is a drawer to pull up. Still with animations off.
*/
@Composable
internal fun Handle(height: Dp, above: Boolean = false) {
val colors = MaterialTheme.colorScheme
@@ -744,7 +645,6 @@ internal fun Handle(height: Dp, above: Boolean = false) {
val shape = if (above) RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) else RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)
val still = Motion.scale == 0f
val bob = androidx.compose.animation.core.rememberInfiniteTransition(label = "handle")
// A quick lift and settle, then a rest: a nudge, not a pulse.
val lift by bob.animateFloat(
0f, 0f,
androidx.compose.animation.core.infiniteRepeatable(
@@ -772,7 +672,6 @@ internal fun Handle(height: Dp, above: Boolean = false) {
}
}
/** A 1dp outline down the sides and along the foot, none along the top (the lip tucks under Play). */
private fun Modifier.drawBorderSidesAndFoot(color: Color, corner: Dp, flip: Boolean = false): Modifier =
this.drawWithContent {
drawContent()
@@ -789,12 +688,6 @@ private fun Modifier.drawBorderSidesAndFoot(color: Color, corner: Dp, flip: Bool
if (flip) scale(1f, -1f) { drawPath(p, color, style = Stroke(sw)) } else drawPath(p, color, style = Stroke(sw))
}
/**
* The sheet's chips: equal capsules with one selection gliding under them (the stores' chip row),
* LB and RB a chip at a time, a tap or A on a far one a hop as a drop. A pad picks a chip by
* moving onto it, and comes into the row on the picked one. [first] takes focus as the sheet
* opens. Too narrow for equal chips, the row scrolls.
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun SheetChips(
@@ -808,10 +701,8 @@ internal fun SheetChips(
val pal = LocalPalette.current
val bounds = remember { mutableStateMapOf<Int, Rect>() }
val tint = rememberUpdatedState(pal.signal)
// Each chip its own requester: one moved from chip to chip under a focused chip lost the ring.
val chips = focus ?: remember(labels.size) { List(labels.size) { FocusRequester() } }
var within by remember { mutableStateOf(false) }
// LB / RB with a pad on the chips: focus goes with the selection.
LaunchedEffect(selected) { if (within) runCatching { chips[selected].requestFocus() } }
BoxWithConstraints(
Modifier.fillMaxWidth().onFocusChanged { within = it.hasFocus },
@@ -820,11 +711,9 @@ internal fun SheetChips(
val equal = !width.isSpecified && maxWidth / labels.size.coerceAtLeast(1) >= 96.dp
val least = if (width.isSpecified) maxOf(width, 64.dp) else 64.dp
val scroll = rememberScrollState()
// Room inside the scroll for the focus ring, which the scroll's clip would otherwise cut.
Box(if (equal) Modifier.fillMaxWidth() else Modifier.edgeFade(scroll).horizontalScroll(scroll).padding(3.dp)) {
Row(
horizontalArrangement = Arrangement.spacedBy(ChipGap),
// Up from the rows lands on the picked chip, not whichever sits above: landing picks.
modifier = (if (equal) Modifier.fillMaxWidth() else Modifier)
.focusProperties { enter = { chips.getOrNull(selected) ?: FocusRequester.Default } }
.focusGroup(),
@@ -836,7 +725,6 @@ internal fun SheetChips(
SheetChip(label, i == selected, m.onFocusChanged { if (it.isFocused && i != selected) onPick(i) }) { onPick(i) }
}
}
// Over the chips: under them, their rest fill hid it as it crossed them.
ChipGlide(selected, bounds[selected], tint)
}
}
@@ -849,8 +737,6 @@ private fun SheetChip(label: String, on: Boolean, modifier: Modifier, onClick: (
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(99.dp)
// The row's glide draws the picked chip's look by touch only; with a pad it draws its own rest
// look, and the bar says which is picked.
val under = on && LocalInputModeManager.current.inputMode != InputMode.Keyboard
Box(
contentAlignment = Alignment.Center,
@@ -866,10 +752,6 @@ private fun SheetChip(label: String, on: Boolean, modifier: Modifier, onClick: (
}
}
/**
* A read-only line that is a link: [title], [value] under it, and "[link] ↗" at the right in the
* signal blue - not a picker, so no value box. A (or a tap) follows it. [id] is its focus key.
*/
@Composable
internal fun LinkRow(title: String, value: String, link: String, id: String, arrow: String = "↗", onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -2,17 +2,29 @@ package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.input.SecondScreenDisplay
@@ -53,3 +65,31 @@ fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () ->
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
)
}
@Composable
fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: () -> Unit) {
var gameProfiles by remember { mutableStateOf(false) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.setup_reset_settings_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(R.string.setup_reset_settings_body))
Row(
Modifier.fillMaxWidth().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it },
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(checked = gameProfiles, onCheckedChange = null)
Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.setup_reset_settings_profiles), style = MaterialTheme.typography.bodyMedium)
}
}
},
confirmButton = {
TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }) {
Text(stringResource(R.string.setup_reset_settings_button), color = MaterialTheme.colorScheme.error)
}
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
)
}
@@ -30,18 +30,15 @@ import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
/** [tag] is shown beside the name: [BUNDLED], [DOWNLOADED], [IMPORTED], or "" for Auto / Runtime default. */
class DriverRow(val id: String, val name: String, val detail: String, val removable: Boolean, val tag: String = "") {
companion object {
const val BUNDLED = "BUNDLED"
const val DOWNLOADED = "DOWNLOADED"
const val IMPORTED = "IMPORTED"
/** One half of an Android + Linux bundle: picked and deleted together with the other. */
const val BUNDLE = "ANDROID + LINUX"
}
}
/** A [DriverRow.tag] as shown, in the app's language. */
@Composable
internal fun driverTagLabel(tag: String): String = when (tag) {
DriverRow.BUNDLED -> stringResource(R.string.driver_tag_bundled)
@@ -51,7 +48,6 @@ internal fun driverTagLabel(tag: String): String = when (tag) {
else -> tag
}
/** A release driver (Banners-Turnip, WinNative) that is not installed yet; [key] is its asset name. */
class DownloadRow(val key: String, val label: String, val detail: String, val progress: Int? = null)
class ModeSettings(
@@ -60,57 +56,43 @@ class ModeSettings(
val panelSize: Pair<Int, Int> = 1280 to 720,
val hdr: Boolean,
val hdrReason: String?,
/** The GPU drivers in use, as the row that opens them on the Components page says it. */
/** The drivers line; null shows Auto. */
val gpuDrivers: String? = null,
/** Frames per second the session is capped at; 0 = none. */
val fpsLimit: Int = 0,
val upscaler: Int = 0,
val upscaleSharpness: Int = 75,
val touchMode: String,
val suspendPolicy: String,
val steamDownloadsInBackground: Boolean = false,
val zramCompression: Boolean? = null,
val zramSupported: Boolean? = null,
val pipSupported: Boolean = false,
val pipAutoEnter: Boolean = false,
/** Steam only. */
val oscMode: String?,
/** Steam only: whether single and double Back actions are swapped. */
val backActionsInverted: Boolean = false,
val directAudio: Boolean?,
val mic: Boolean?,
val gameStorage: String? = null,
val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(),
/** Steam only: record allocation and sampled storage timings in the next session's Share logs. */
val storageDiagnostics: Boolean = false,
val fexPreset: String? = null,
/** Steam only: Force SSBS for Proton games (SessionPrefs.forceSsbs). */
val forceSsbs: Boolean = false,
/** Steam only: SessionPrefs.SYNC_* chosen for Proton games; null outside Steam. */
val syncBackend: String? = null,
val stretch16x9: Boolean? = null,
val steamRepairQueued: Boolean = false,
/** Steam: the QAM's performance overlay (mangoapp) is started. */
val mangoapp: Boolean = true,
/** Steam only: what the pad is to the client (SessionPrefs.CONTROLLER_*); null outside Steam. */
val steamController: String? = null,
/** Unfolded controls (Steam only; null hides the row). */
val unfoldedControls: Boolean? = null,
/** Steam only: start a Steam session when DroidDeck opens. */
val runSteamAtStartup: Boolean = false,
/** Null outside Steam; the saved choice is separate from Android's access and device switch. */
val wifiDiscovery: Boolean? = null,
val wifiDiscoveryPermission: Boolean = false,
val wifiDiscoveryLocation: Boolean = false,
val wifiDiscoveryAsked: Boolean = false,
val wifiDiscoveryBlocked: Boolean = false,
/** Latest Banners-Turnip release: what each driver menu offers to download, and the refresh line. */
/** Steam only: Decky Loader is managed from the Steam session settings. */
val deckyInstalled: String? = null,
val deckyLatestRelease: DeckyManager.Release? = null,
val deckyChecking: Boolean = false,
val deckyStage: String? = null,
val deckyPercent: Int = -1,
/** The stage is the Decky plugin's binary download. */
val deckyDownloadingBinary: Boolean = false,
val deckyEnabled: Boolean = false,
val deckySessionRunning: Boolean = false,
@@ -119,7 +101,6 @@ class ModeSettings(
class ModeSettingsActions(
val onResolution: (String) -> Unit,
val onHdr: (Boolean) -> Unit,
/** Opens the GPU drivers on the Components page: they are shared by every session. */
val onGpuDrivers: () -> Unit = {},
val onFpsLimit: (Int) -> Unit = {},
val onUpscaler: (Int) -> Unit = {},
@@ -127,6 +108,7 @@ class ModeSettingsActions(
val onTouch: (String) -> Unit,
val onSuspendPolicy: (String) -> Unit,
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
val onZramCompression: (Boolean) -> Unit = {},
val onPipAutoEnter: (Boolean) -> Unit = {},
val onOsc: (String) -> Unit,
val onBackActionsInverted: (Boolean) -> Unit = {},
@@ -154,15 +136,10 @@ class ModeSettingsActions(
val onDismiss: () -> Unit,
)
/**
* The chips of a mode's lifted sheet, in order: Steam's six; the desktop's Display, Controls and
* Session (its Files chip is the Desktop page's own).
*/
internal fun modeSheetTabs(steam: Boolean): List<String> =
if (steam) listOf(SheetTab.STEAM, SheetTab.DISPLAY, SheetTab.CONTROLS, SheetTab.AUDIO, SheetTab.SESSION, SheetTab.LIBRARY)
else listOf(SheetTab.DISPLAY, SheetTab.CONTROLS, SheetTab.SESSION)
/** A sheet tab's chip label. */
@Composable
internal fun sheetTabLabel(tab: String): String = when (tab) {
SheetTab.DISPLAY -> stringResource(R.string.drawer_page_display)
@@ -174,19 +151,13 @@ internal fun sheetTabLabel(tab: String): String = when (tab) {
else -> stringResource(R.string.setup_tool_files)
}
/**
* Rows the front end adds to a sheet's tabs: frame generation (Display), Performance (Session) and
* the Graphics drivers link to Components (Display, given the drivers' summary).
*/
class SheetExtras(
val frameGen: @Composable () -> Unit = {},
val performance: @Composable () -> Unit = {},
val drivers: @Composable (summary: String?) -> Unit = {},
/** The Steam tab's account rows (offline mode), from the front end's own state. */
val account: @Composable (host: MenuHost) -> Unit = {},
)
/** One tab of a mode's lifted sheet: the rows the settings page had, grouped by what they are for. */
@Composable
fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) {
val steam = s.mode == SessionService.MODE_STEAM
@@ -303,6 +274,12 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.mode_background_downloads_hint),
s.steamDownloadsInBackground, onChange = a.onSteamDownloadsInBackground,
)
if (s.zramCompression != null) ToggleRow(
host, "zram", stringResource(R.string.mode_zram),
stringResource(if (s.zramSupported == false) R.string.mode_zram_unsupported else R.string.mode_zram_hint),
s.zramCompression && s.zramSupported != false, enabled = s.zramSupported == true,
onChange = a.onZramCompression,
)
}
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
@@ -320,7 +297,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
if (tab == SheetTab.LIBRARY && steam) {
if (s.gameStorage != null) SettingsGroup(stringResource(R.string.mode_storage)) {
val custom = s.gameStorage.isNotEmpty() && s.gameStorage != "off" && s.storageOptions.none { it.path == s.gameStorage }
// Each choice: its path, its menu line, the chip's shorter line, and the label it is saved with.
class StorageChoice(val path: String, val label: String, val chip: String, val saved: String)
val internal = stringResource(R.string.mode_storage_internal)
val options = buildList {
@@ -467,10 +443,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
)
}
/**
* The options that apply to every Proton - how Wine syncs, FEX's preset, Force SSBS and the games'
* environment - for the Components page's Proton layer.
*/
@Composable
internal fun ProtonOptions(
syncBackend: String, fexPreset: String, forceSsbs: Boolean,
@@ -497,10 +469,6 @@ internal fun ProtonOptions(
GameEnvironmentRow()
}
/**
* Uninstall for Decky Loader: are you sure steps out of it in red, Cancel first, so a stray A
* costs nothing.
*/
@Composable
private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -527,8 +495,6 @@ private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) {
}
}
/** Width × height for the session, with the common handheld shapes one tap away. */
/** Entry for the user's SteamGridDB API key; the saved key is never shown back. */
@Composable
internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss: () -> Unit) {
var key by remember { mutableStateOf("") }
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.ui
/** Package metadata shown on an emulator's own detail page. */
class PackageRow(
val id: String,
val kind: String,
@@ -42,38 +42,20 @@ import kotlinx.coroutines.launch
import kotlin.math.PI
import kotlin.math.sin
// A page opened from a control (the cog beside Play) grows out of it as a session grows out of
// Play (LaunchFlood): the control stretches out over the pane on loose springs, the far edges
// first, and the page rises into it once it is covered. Back draws it down into the control again.
/**
* Where a page opened from: the control's bounds and corner radius, in px, and the rail item that
* was showing it ([owner]), so the page only draws back into it when that content returns. [art]
* is the control's picture for the tile (a drawable id, or an image Coil loads), if it has one.
*/
internal class Origin(val bounds: Rect, val corner: Float, val owner: String? = null, val art: Any? = null) {
fun translate(by: Offset) = Origin(bounds.translate(by), corner, owner, art)
fun ownedBy(key: String) = Origin(bounds, corner, key, art)
}
/** How a page that opened from a control leaves. */
internal enum class PageExit {
/** Back into the control it came from, which is on screen again. */
Drain,
/** Out through a link into another section, which takes the page there itself. */
Hop,
/** Away with the pane, as any page goes: the control it came from is not coming back. */
Sink,
}
/** Why a page is leaving: an ordinary change of page, or a link into another section. */
internal enum class PageLeave { Ordinary, Link }
/**
* The exit for a page opened from a control on [owner]'s content, leaving for [incoming]. It only
* draws back into the control when the content that control belongs to is what comes back; a page
* left for another rail item or another page drained into a control that was no longer there.
*/
internal fun pageExit(owner: String?, incoming: String, leave: PageLeave): PageExit = when {
owner != null && incoming == owner -> PageExit.Drain
leave == PageLeave.Link -> PageExit.Hop
@@ -84,57 +66,37 @@ internal object PageOrigin {
private var origin: Origin? = null
private var at = 0L
/** The control a page is about to open from, in root coordinates. */
fun mark(o: Origin) {
origin = o
at = SystemClock.uptimeMillis()
}
/** The control just pressed, once: stale after a second, so a page opened another way never floods. */
fun take(): Origin? = origin.takeIf { SystemClock.uptimeMillis() - at < 1_000 }.also { origin = null }
}
/** How long a leaving page is kept for its flood to draw back into the control. */
internal const val PAGE_RETURN_MS = 900
/**
* [content], a page that opened from the control at [from] (in this element's coordinates): the
* control's tile stretching over it until covered, then the page rising in as the tile fades.
* Once [leaving], the reverse: the tile comes back over the page and draws down into the control.
* A page that [sinks] instead goes with the pane and draws no tile at all.
* The focus ring stays out of it until it is done.
*/
@Composable
internal fun PageFlood(
from: Origin,
leaving: Boolean,
/** What the tile shows instead of the control's fill: a game card's art, cropped to the tile as it grows. */
art: Painter? = null,
sinks: Boolean = false,
/**
* Where on the page the control's tile lands (root px), when the page has its own picture of
* the control - a game page's hero art: the tile grows onto it instead of over the whole pane,
* corner to corner ([ontoCorner] there), and the page comes in around it. Back leaves from it.
* Null, or off screen: the pane, as any page.
*/
onto: (() -> Rect?)? = null,
ontoCorner: androidx.compose.ui.unit.Dp = 0.dp,
content: @Composable () -> Unit,
) {
val pal = LocalPalette.current
val glide = LocalFocusGlide.current
// Left, top, right, bottom: 0 on the control, 1 on the pane's edge.
val edges = remember { List(4) { Animatable(0f) } }
val shown = remember { Animatable(0f) }
val tile = remember { Animatable(1f) }
var size by remember { mutableStateOf(Size.Zero) }
var at by remember { mutableStateOf(Offset.Zero) }
// Where this flood lands (in its own space), read as it opens and again as it leaves.
var target by remember { mutableStateOf<Rect?>(null) }
val density = androidx.compose.ui.platform.LocalDensity.current
LaunchedEffect(size != Size.Zero, leaving, sinks) {
if (sinks) {
// Whatever the flood in was doing, the page is shown whole and leaves with the pane.
tile.snapTo(0f)
shown.snapTo(1f)
glide?.hidden = false
@@ -142,15 +104,12 @@ internal fun PageFlood(
}
if (size == Size.Zero) return@LaunchedEffect
glide?.hidden = true
// The page lays out under the tile at once, so its picture is there within a frame or two.
target = onto?.let { get ->
kotlinx.coroutines.withTimeoutOrNull(300) { snapshotFlow { get() }.first { it != null } }
}?.translate(-at)?.takeIf { it.height > 1f && it.overlaps(Rect(Offset.Zero, size)) }
if (target != null) {
coroutineScope {
if (!leaving) {
// Onto the page's picture, every edge together on one firm spring: no blob, and
// nowhere to go past it.
val runs = edges.map { launch { it.animateTo(1f, Motion.sp(0.85f, 320f)) } }
snapshotFlow { edges.all { it.value >= 0.9f } }.first { it }
launch { shown.animateTo(1f, Motion.tw(240)) }
@@ -202,7 +161,6 @@ internal fun PageFlood(
Modifier.fillMaxSize().clipToBounds().onSizeChanged { size = Size(it.width.toFloat(), it.height.toFloat()) }
.onGloballyPositioned { at = it.positionInRoot() },
) {
// Landing on the page's picture, the page must not rise: its picture would move off the tile.
val rise = if (onto != null) 0f else 1f
Box(Modifier.fillMaxSize().graphicsLayer { alpha = shown.value; translationY = (1f - shown.value) * 14.dp.toPx() * rise }) { content() }
val onCorner = with(density) { ontoCorner.toPx() }
@@ -212,13 +170,8 @@ internal fun PageFlood(
}
}
/**
* The control's tile with its edges [v] of the way to the pane's (left, top, right, bottom):
* sinking with the page behind, blobby in flight, square once it fills the pane.
*/
private fun DrawScope.drawTile(
from: Origin, v: List<Float>, fill: Color, line: Color, alpha: Float, art: Painter? = null,
/** Lands on this instead of the pane (a page's picture of the control), corner [toCorner]. */
to: Rect? = null, toCorner: Float = 0f,
) {
val (l, t, r, b) = v
@@ -229,7 +182,6 @@ private fun DrawScope.drawTile(
left = lerp(f.left, to.left, l); top = lerp(f.top, to.top, t)
right = lerp(f.right, to.right, r); bottom = lerp(f.bottom, to.bottom, b)
} else {
// The control sinks with the page behind it (scaled to 0.95 about the pane's centre).
val k = 1f - 0.05f * mean
val cx = size.width / 2f
val cy = size.height / 2f
@@ -240,14 +192,11 @@ private fun DrawScope.drawTile(
}
val w = (right - left).coerceAtLeast(0f)
val h = (bottom - top).coerceAtLeast(0f)
// Onto a picture it keeps a card's shape, corner to corner; over the pane it blobs in flight.
val corner = if (to != null) lerp(from.corner, toCorner, mean).coerceAtMost(minOf(w, h) / 2f)
else lerp(from.corner * (1f - mean), minOf(w, h) * 0.42f, sin(PI * mean).toFloat().coerceAtLeast(0f))
drawRoundRect(fill, Offset(left, top), Size(w, h), CornerRadius(corner), alpha = alpha)
val pic = art?.intrinsicSize?.takeIf { it.isSpecified && it.width > 0f && it.height > 0f }
if (art != null && pic != null && w > 0f && h > 0f) {
// The art covers the tile at every size (a centre crop), so a portrait card opens into the
// wide pane without stretching.
val k = maxOf(w / pic.width, h / pic.height)
val dw = pic.width * k
val dh = pic.height * k
@@ -255,7 +204,6 @@ private fun DrawScope.drawTile(
translate(left + (w - dw) / 2f, top + (h - dh) / 2f) { with(art) { draw(Size(dw, dh), alpha = alpha) } }
}
}
// The control's outline, kept while it is still the size of one.
val edge = (1f - mean * 3f).coerceIn(0f, 1f)
if (edge > 0f) drawRoundRect(line, Offset(left, top), Size(w, h), CornerRadius(corner), alpha = alpha * edge, style = Stroke(1.dp.toPx()))
}
@@ -54,16 +54,6 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* A PC keyboard on screen: every key is a physical key (a Linux evdev code) pressed and released
* on the session's wl_keyboard, as a USB keyboard would - Esc, the function row, Ctrl, Alt, Super,
* the arrows and the editing block included, none of which the Android keyboard can send.
*
* A key goes down when a finger lands on it and up when it lifts, so holding one repeats it the way
* the program's own key repeat does. Ctrl, Shift, Alt and Super are sticky: one tap holds the
* modifier for the next key, a second tap locks it, a third lets it go. A controller moves over the
* keys with the d-pad and presses with A.
*/
private data class PcKey(val label: String, val code: Int, val weight: Float = 1f, val shifted: String? = null, @StringRes val labelRes: Int = 0)
private fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted)
@@ -110,7 +100,6 @@ private const val MOD_LOCKED = 2
@Composable
fun PcKeyboard(
/** evdev code, pressed. */
sendKey: (Int, Boolean) -> Unit,
onAndroidKeyboard: () -> Unit,
onClose: () -> Unit,
@@ -142,21 +131,17 @@ fun PcKeyboard(
if (key.code == 58) capsOn = !capsOn
releaseOnceModifiers()
}
// Nothing is left held when the keyboard goes away.
androidx.compose.runtime.DisposableEffect(Unit) {
onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) }
}
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
// Slightly under half the screen, header included, so the program stays in view above it:
// six rows share what is left of 47% after the header, the gaps and the padding.
val rowHeight = ((maxHeight * 0.47f - 24.dp - 3.dp * 6 - 10.dp) / 6).coerceIn(24.dp, 44.dp)
Box(
Modifier.fillMaxWidth()
.background(Color(0xE6101418), RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
.border(1.dp, pal.line2, RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
// Touches on the keyboard stop here; the program underneath never sees them.
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); waitForUpOrCancellation()?.consume() } }
.padding(horizontal = 8.dp, vertical = 5.dp),
) {
@@ -221,7 +206,6 @@ private fun RowScope.KeyCap(
down = false; onUp()
}
}
// A controller: A (or the d-pad's centre) is the finger.
.onPreviewKeyEvent { e ->
val kc = e.key.nativeKeyCode
if (kc != KeyEvent.KEYCODE_BUTTON_A && kc != KeyEvent.KEYCODE_DPAD_CENTER && kc != KeyEvent.KEYCODE_ENTER) return@onPreviewKeyEvent false
@@ -10,7 +10,6 @@ import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionDisplay
/** Pre-session resolution choice, applied when the session starts. */
@Composable
fun ResolutionRow(
host: MenuHost, choice: String, panel: Pair<Int, Int>, onPick: (String) -> Unit,
@@ -36,7 +36,6 @@ import com.termux.terminal.TerminalSessionClient
import com.termux.view.TerminalView
import com.termux.view.TerminalViewClient
/** Touch controls drawn on a second Android display while the compositor remains on the main one. */
class SecondScreenPresentation(
private val sessionActivity: SessionActivity,
display: Display,
@@ -83,7 +82,6 @@ class SecondScreenPresentation(
if (created) renderMode()
}
/** Releases the auxiliary Linux shell before the window is dismissed. */
fun closeControls() {
closeTerminal()
keyboardHost?.hide()
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.ui
/** Stable page identities keep focus and scroll positions when a secondary display comes and goes. */
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("touch"),
GLASSES("glasses-game"),
@@ -76,7 +76,6 @@ import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.text.style.TextOverflow
// The session's loading screen, its paused screen and the HUD text style.
@Composable
fun HudText(text: String) {
@@ -94,7 +93,6 @@ fun HudText(text: String) {
}
}
/** One line of the loading screen's checklist; [detail] is what it says while it is the one running. */
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(
@@ -108,11 +106,6 @@ private fun loadStages(steam: Boolean): List<LoadStage> = if (steam) listOf(
LoadStage(R.string.load_opening, R.string.load_opening_detail),
)
/**
* The checklist stage a loading line's [topic] belongs to, -1 when it says nothing about the stage.
* The lines are the session script's "== STEP" milestones and the installer's own progress; they
* arrive in order, and the screen never steps back.
*/
private fun stageOf(topic: LoadingState.Topic, steam: Boolean): Int = when (topic) {
LoadingState.Topic.RUNTIME -> 0
LoadingState.Topic.SESSION -> 1
@@ -125,15 +118,12 @@ private fun stageOf(topic: LoadingState.Topic, steam: Boolean): Int = when (topi
@Composable
fun LoadingOverlay(
step: String, percent: Int, elapsed: String, hint: String, ended: Boolean,
/** What [step] is about, and whether it is a download or install line worth showing as it is (see [LoadingState]). */
topic: LoadingState.Topic, readable: Boolean,
title: String = stringResource(R.string.load_starting_steam), steam: Boolean = true, onCancel: (() -> Unit)? = null,
/** An ended session's exit status and log path, shown small under the advice. */
endedDetail: String? = null,
onRetry: (() -> Unit)? = null,
onShareLogs: (() -> Unit)? = null,
onClose: (() -> Unit)? = null,
/** The blue the page opens on when a button flooded to it, gathered into the throbber's ball. */
flood: Color? = null,
onFlooded: () -> Unit = {},
) {
@@ -148,7 +138,6 @@ fun LoadingOverlay(
val active = reached.coerceAtMost(stages.lastIndex)
val detail = if (percent >= 0 || readable) step.replaceFirstChar { it.uppercase() } else stringResource(stages[active].detail)
val context = LocalContext.current
// The Steam tab's wall behind it, dimmed and slowed: starting Steam reads as the same place settling in.
val games by produceState(emptyList<Library.SteamGame>()) {
value = withContext(Dispatchers.IO) { runCatching { Library.steamGames(context).sortedByDescending { it.lastPlayed } }.getOrDefault(emptyList()) }
}
@@ -176,7 +165,6 @@ fun LoadingOverlay(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.align(Alignment.Center).verticalScroll(rememberScrollState()).padding(horizontal = 32.dp, vertical = 24.dp),
) {
// Held on the plain D while the flood gathers, and started fresh when it lands.
key(flood == null) {
LogoThrobber(
Modifier.width(if (ended) 88.dp else 110.dp).onGloballyPositioned { ball = throbberBall(it.boundsInRoot()).also { b -> ThrobberSpot.ball = b } },
@@ -211,7 +199,6 @@ fun LoadingOverlay(
}
}
/** What to do about an ended session: nothing leaves on a timer, and the pad starts on Try again. */
@Composable
private fun EndedActions(onRetry: (() -> Unit)?, onShareLogs: (() -> Unit)?, onClose: (() -> Unit)?) {
val first = remember { FocusRequester() }
@@ -229,7 +216,6 @@ private fun EndedActions(onRetry: (() -> Unit)?, onShareLogs: (() -> Unit)?, onC
}
}
/** One segment per stage: done ones filled, the current one filling (or running, with no percent). */
@Composable
private fun LoadSegments(count: Int, active: Int, percent: Int, modifier: Modifier = Modifier) {
val pal = LocalPalette.current
@@ -257,7 +243,6 @@ private fun LoadSegments(count: Int, active: Int, percent: Int, modifier: Modifi
}
}
/** Cancel as the pad's B, in the corner; a tap works too. */
@Composable
private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
@@ -281,7 +266,6 @@ private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
}
}
/** A session paused in the background, ready to pick up where it left off. */
@Composable
fun SessionPausedOverlay(title: String = stringResource(R.string.load_steam_paused), onResume: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -182,16 +182,13 @@ private class DrawerFocus {
} else if (focused == key) focused = null
}
/** Where focus was last on [page], if anywhere. */
fun target(page: SessionDrawerPage) = last[page]
fun request(key: String) = runCatching { requester(key).requestFocus() }
fun forget(page: SessionDrawerPage) { last.remove(page) }
}
/** Everything the drawer shows and does. */
class DrawerActions(
val steam: Boolean,
/** The drawer's heading: the emulator for a program from the rail, else Steam or Desktop. */
val title: String? = null,
val isHomeApp: Boolean,
val androidApps: List<HomeApp.LaunchableApp>,
@@ -203,7 +200,6 @@ class DrawerActions(
val suspendPolicy: String,
val steamDownloadsInBackground: Boolean = false,
val backActionsInverted: Boolean,
/** What the pad is to Steam (SessionPrefs.CONTROLLER_*), switched live; null hides the row. */
val padType: String? = null,
val onPadType: (String) -> Unit = {},
val touchMode: String,
@@ -211,17 +207,12 @@ class DrawerActions(
val fexPreset: String,
val upscaler: Int = 0,
val upscaleSharpness: Int = 75,
/** The compositor's post chain (gpu/ScreenEffects), changed live. */
val effects: ScreenEffects = ScreenEffects.OFF,
/** Cardboard mode (gpu/Cardboard): side-by-side eyes for a phone VR viewer, changed live. */
val cardboard: Cardboard = Cardboard.OFF,
/** Whether the device has a rotation sensor (head tracking possible). */
val cardboardSensor: Boolean = false,
/** SteamVR in the guest for Cardboard mode (gpu/SteamVr); null while unknown. */
val steamVr: SteamVr.Status? = null,
val glassesPresent: Boolean = false,
val glassesOutput: Boolean = false,
/** Texture filtering for DirectX 9-11 games (core/TextureFiltering); lands on their next launch. */
val textureAnisotropy: Int? = 0,
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
val secondScreenMode: SecondScreenMode,
@@ -230,18 +221,13 @@ class DrawerActions(
val onHud: (Boolean) -> Unit,
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onImportLossless: () -> Unit,
/** The Android keyboard (text, turned into key presses). */
val onKeyboard: () -> Unit,
/** The on-screen PC keyboard: real keys, Esc, F1-F12, Ctrl, Alt... */
val onHardwareKeyboard: () -> Unit,
val onSteamMenu: (() -> Unit)?,
val onQam: (() -> Unit)?,
/** Null hides the achievements row. */
val onAchievements: (() -> Unit)? = null,
/** (unlocked, total), or null when unknown. */
val achievementsProgress: Pair<Int, Int>? = null,
val onOsc: (String) -> Unit,
/** Edits the Steam touch layout of the game in front, when Steam's controls are up. */
val onEditSteamTouch: (() -> Unit)? = null,
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val onRumble: (Boolean) -> Unit = {},
@@ -259,7 +245,6 @@ class DrawerActions(
val onCardboard: (Cardboard) -> Unit = {},
val onCardboardRecenter: () -> Unit = {},
val onGlassesRecenter: () -> Unit = {},
/** install, start or stop SteamVR. */
val onSteamVr: (String) -> Unit = {},
val onTextureAnisotropy: (Int?) -> Unit = {},
val onTextureLodBias: (String?) -> Unit = {},
@@ -271,17 +256,13 @@ class DrawerActions(
val pipAutoEnter: Boolean = false,
val onPip: () -> Unit = {},
val onPipAutoEnter: (Boolean) -> Unit = {},
/** Unfolded controls (on a foldable; null hides the row). */
val unfoldedControls: Boolean? = null,
val onUnfoldedControls: (Boolean) -> Unit = {},
val onShareLogs: () -> Unit,
val onStop: () -> Unit,
/** Stop with the dialog's button's bounds on screen, for the flood to grow out of; null falls back to [onStop]. */
val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null,
val onClose: () -> Unit,
/** Games tab: every Proton with what it uses; null until first read. */
val components: ComponentsManager.Snapshot? = null,
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
val onComponentsRefresh: () -> Unit = {},
val componentCatalog: List<ComponentsManager.CatalogItem> = emptyList(),
val componentCatalogAt: Long = 0,
@@ -290,9 +271,7 @@ class DrawerActions(
val componentDownloadRevision: Long = 0,
val onComponentCatalogRefresh: () -> Unit = {},
val onComponentDownload: (ComponentsManager.CatalogItem) -> Unit = {},
/** Installed games available for profile inspection in the session drawer. */
val gameProfiles: List<Pair<Long, String>> = emptyList(),
/** The selected game profile, or null for the Default profile. */
val selectedGameProfileId: Long? = null,
val selectedGameProfile: SelectedGameProfile? = null,
val gameProfilesLoaded: Boolean = false,
@@ -302,12 +281,9 @@ class DrawerActions(
val onSelectedGameProfileRefresh: () -> Unit = {},
val gameFexPresetSaving: Boolean = false,
val onGameFexPreset: (Long, String?) -> Unit = { _, _ -> },
/** Saves the selected game's Start without Steam (GameEnvironment.NO_STEAM). */
val gameNoSteamSaving: Boolean = false,
val onGameNoSteam: (Long, Boolean) -> Unit = { _, _ -> },
/** Swaps [value] ("orig:<build>" or a stored package file) into a Proton's component. */
val onComponentSwap: (protonId: String, comp: String, value: String) -> Unit = { _, _, _ -> },
/** Saves a stored package for a game, or null to inherit that component from the Default profile. */
val onGameComponent: (appId: Long, comp: String, file: String?) -> Unit = { _, _, _ -> },
)
@@ -352,8 +328,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
LaunchedEffect(open, controllerActive) {
if (open && !controllerActive) focusManager.clearFocus(force = true)
}
// The page focus was last put on: turning to another (LB, RB, a tab) starts it at its first
// option; anything else (a menu closing, the drawer opening again) goes back where it was.
var focusedPage by remember { mutableStateOf(page) }
LaunchedEffect(open, page, controllerActive, host.open, appToChooseDisplay, confirmStop) {
if (!open) {
@@ -364,7 +338,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (host.open != null || appToChooseDisplay != null || confirmStop) return@LaunchedEffect
val turned = page != focusedPage
focusedPage = page
// The page's top control: on Session that is Android apps, when it is shown.
val first = if (page == SessionDrawerPage.SESSION && a.isHomeApp) "apps" else page.firstControl
if (turned) focus.forget(page)
val target = focus.target(page) ?: first
@@ -382,8 +355,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { host.open = null; a.onClose() },
)
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
// A 4:3 or near-square screen (under 440dp tall) gets tighter padding and a shorter tab row,
// so the settings keep most of the height; a narrow one keeps some of the game in view.
val short = maxHeight < 440.dp
val sheetWidth = minOf(360.dp, maxWidth * 0.92f)
AnimatedVisibility(
@@ -505,7 +476,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
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)),
// Steam's touch controller is Steam's alone; elsewhere that choice behaves as Auto.
if (!a.steam && a.oscMode == SessionPrefs.OSC_STEAM_TOUCH) SessionPrefs.OSC_AUTO else a.oscMode,
chipModifier = focus.track(page, "osc"), onPick = a.onOsc)
a.onEditSteamTouch?.let { edit ->
@@ -746,7 +716,6 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
}
}
/** A compact shortcut into Steam, sharing the header with Stop. */
@Composable
private fun SteamActionPill(
description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier,
@@ -771,7 +740,6 @@ private fun SteamActionPill(
}
}
/** A bumper as a keycap, 44dp to touch; LB / RB on the pad turn the page too. */
@Composable
private fun DrawerBumper(label: String, description: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -795,13 +763,6 @@ private fun DrawerBumper(label: String, description: String, modifier: Modifier
}
}
/**
* The drawer's page tabs, QAM-style: one icon per page standing in a line in page order. The
* selected one steps forward - full size, bright, a soft glow - while the others step back to
* a little smaller and fade, and the whole line leans a little toward the selection. LB / RB still turn
* the page (the buttons beside it and the pad's bumpers); a tab can be tapped or picked with the
* pad like the dots it replaces.
*/
@Composable
private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPage>, modifier: Modifier = Modifier, compact: Boolean = false, onSelect: (SessionDrawerPage) -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -815,9 +776,6 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(),
) {
val tab = if (compact) 36f else 44f
// Fit the line to the room between LB and RB. Worst case is an end tab selected: full size
// ([tab] dp) and pushed outward by the lean, which scales with the spacing. So
// (count-1) * spacing * (1 + lean/spacingMax) + tab <= width
val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(24f, DRAWER_TAB_SPACING_DP)
val leanStep = DRAWER_TAB_LEAN_DP * spacing / DRAWER_TAB_SPACING_DP
val lean by animateFloatAsState(-(selectedIndex - middle) * leanStep, motion, label = "tabLean")
@@ -858,10 +816,8 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
}
}
/** The Look row's value when the rows below match no Look. */
private const val LOOK_CUSTOM = "custom"
/** Presets and simple effects first; detailed adjustments stay behind Advanced. */
@Composable
private fun ScreenEffectsGroup(
host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit,
@@ -926,7 +882,6 @@ private fun ScreenEffectsGroup(
}
}
/** Cardboard mode: the eyes, the lens and the virtual screen; everything applies live. */
@Composable
private fun CardboardGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val c = a.cardboard
@@ -978,7 +933,6 @@ private fun SteamVrRow(a: DrawerActions) {
}
}
/** Secondary-display modes are mutually exclusive and apply immediately. */
@Composable
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
@@ -1047,7 +1001,6 @@ private fun DrawerFexPresetRow(host: MenuHost, a: DrawerActions, modifier: Modif
}
}
/** A game's Start without Steam; only with a game selected - the Default profile has no such switch. */
@Composable
private fun DrawerNoSteamRow(host: MenuHost, a: DrawerActions, modifier: Modifier) {
val appId = a.selectedGameProfileId ?: return
@@ -1058,7 +1011,6 @@ private fun DrawerNoSteamRow(host: MenuHost, a: DrawerActions, modifier: Modifie
) { on -> a.onGameNoSteam(appId, on) }
}
/** Texture filtering on the Games page: DXVK options for the next DirectX 9-11 launch. */
@Composable
private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val inherited = a.selectedGameProfileId != null
@@ -1209,11 +1161,6 @@ private fun ProfileSummaryRow(label: String, value: String) {
}
}
/**
* The Games tab's components: quick swaps between what is already installed, per Proton. A swap
* into the Proton a running game uses waits until that game closes. Downloads below share the
* launcher's package store; importing and deleting stay on the Components page.
*/
@Composable
private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
@@ -1275,7 +1222,6 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val running = snap.protons.filter { it.inUseByGame }
var pick by rememberSaveable { mutableStateOf<String?>(null) }
val view = snap.protons.firstOrNull { it.proton.id == pick } ?: running.firstOrNull() ?: snap.protons.firstOrNull()
// Focusable, so the pad can climb from the Proton box up to it and the page scrolls it into view.
SettingsGroup(stringResource(R.string.drawer_running_now)) {
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value
@@ -1330,7 +1276,6 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val shown = options.firstOrNull { it.first == current }?.second
DrawerStackedChoice(
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
// The box already shows the choice: only say more when there is more to say.
st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
options, current,
note = if (view.inUseByGame) stringResource(R.string.comp_waits_long) else stringResource(R.string.comp_applies_long),
@@ -1345,7 +1290,6 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
)
}
/** Downloads only store packages; the profile/Proton choices above apply them separately. */
@Composable
internal fun ComponentDownloadsDrawerGroup(
host: MenuHost,
@@ -1423,10 +1367,6 @@ internal fun ComponentDownloadsDrawerGroup(
}
}
/**
* A choice for the drawer's narrow column: label, then the box across the full width, then the
* detail underneath - so a long Proton or package name never squeezes the text beside it.
*/
@Composable
private fun <T> DrawerStackedChoice(
host: MenuHost, key: String, label: String, hint: String?,
@@ -1460,7 +1400,6 @@ private fun <T> DrawerStackedChoice(
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
/** A close row of icons: inactive tabs stay legible while the active tab leads. */
private const val DRAWER_TAB_SPACING_DP = 48f
private const val DRAWER_TAB_LEAN_DP = 8f
@@ -1469,18 +1408,11 @@ private const val DRAWER_TAB_SIDE_SCALE = 0.8f
private const val DRAWER_TAB_SIDE_ALPHA = 0.8f
/** Room between the Stop pill and the box that steps out under it: the pull. */
private val StepPull = 6.dp
private val StepBoxCorner = 16.dp
private val StepFillet = 10.dp
private val StepBoxMaxWidth = 264.dp
/**
* Stop's confirm, grown out of the Stop pill at [pill] (px, in the sheet): a pull the pill's width
* drops out of it and a wider box steps out to the left under it for the choices, right edges
* flush, so Stop lands under the pill. Cancel, B and a tap outside fold it back into the pill,
* width first. [onStop] gets Stop's bounds on screen for the flood.
*/
@Composable
private fun StopConfirm(
open: Boolean,
@@ -1496,7 +1428,6 @@ private fun StopConfirm(
val tint = remember { Animatable(0f) }
val dim = remember { Animatable(0f) }
val items = remember { List(3) { Animatable(0f) } }
// Composed from the first open until it has folded back into the pill.
var shown by remember { mutableStateOf(false) }
var grown by remember { mutableStateOf(false) }
var content by remember { mutableStateOf<IntSize?>(null) }
@@ -1550,7 +1481,6 @@ private fun StopConfirm(
val p = pill ?: return
Box(Modifier.fillMaxSize()) {
// The rest of the sheet dims behind it, and a tap there cancels.
Box(
Modifier.fillMaxSize().graphicsLayer { alpha = dim.value }.background(Color(0x59000000))
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, enabled = open, onClick = onCancel),
@@ -1567,7 +1497,6 @@ private fun StopConfirm(
drawPath(path, lerp(hotFill, restFill, tint.value))
drawPath(path, colors.error.copy(alpha = lerp(0.9f, 0.55f, tint.value)), style = Stroke(rim))
}
// The pill's label rides on top, as the pull's handle.
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.offset { IntOffset(p.left.roundToInt(), p.top.roundToInt()) }
@@ -1585,7 +1514,6 @@ private fun StopConfirm(
.onSizeChanged { if (content != it) content = it }
.controllerBack(onCancel)
.onPreviewKeyEvent { e ->
// Keep a controller in here, as the dialog's own window used to.
if (e.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
when (e.key) {
Key.DirectionUp, Key.DirectionDown -> true
@@ -1624,7 +1552,6 @@ private fun StopConfirm(
}
}
/** One of the confirm's two choices: a capsule that fills when focused; Stop in the danger red. */
@Composable
private fun ConfirmChoice(label: String, danger: Boolean, enabled: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -117,7 +117,6 @@ import androidx.compose.ui.window.PopupProperties
private val RowShape = RoundedCornerShape(12.dp)
private val GroupShape = RoundedCornerShape(14.dp)
/** Whether a pad's A is held right now, as the activity sees it: a focus move waits for its release. */
internal object HeldKeys {
@Volatile var confirm = false
}
@@ -142,7 +141,6 @@ internal fun Modifier.controllerBack(onBack: () -> Unit): Modifier = onPreviewKe
}
}
/** LB and RB turn a page's tabs; the keys are taken whenever focus is anywhere inside [this]. */
internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event ->
val keyEvent = event.nativeKeyEvent
val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1
@@ -154,11 +152,6 @@ internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modif
}
}
/**
* A page's tabs with the pad's bumpers drawn beside them. The host turns them with LB/RB (see
* [bumpers]); the keycaps are for touch and stay out of the d-pad's path. The row scrolls sideways
* when a narrow page cannot fit every tab.
*/
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
internal fun TabStrip(
@@ -168,8 +161,6 @@ internal fun TabStrip(
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(12.dp)
// Tabs that overflow (long labels on a small phone) first close up; only what still does not
// fit scrolls. Once tight the row stays tight, so it cannot flip back and forth.
val scroll = rememberScrollState()
var tight by remember(tabs) { mutableStateOf(false) }
LaunchedEffect(scroll.maxValue) { if (scroll.maxValue in 1 until Int.MAX_VALUE) tight = true }
@@ -186,7 +177,6 @@ internal fun TabStrip(
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val pick = { onSelect(i) }
val tabShape = RoundedCornerShape(9.dp)
// The chosen tab scrolls fully into view, so one at the end is not left cut off.
val reveal = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() }
if (on) LaunchedEffect(Unit) { reveal.bringIntoView() }
Text(
@@ -209,7 +199,6 @@ internal fun TabStrip(
}
}
/** A bumper drawn as a keycap, 44dp to touch; the pad presses the real one. */
@Composable
private fun BumperKey(label: String, description: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -230,7 +219,6 @@ private fun BumperKey(label: String, description: String, onClick: () -> Unit) {
}
}
/** The narrowest a setting's value box gets; the session menu's sheet sets it lower. */
val LocalChipMinWidth = androidx.compose.runtime.compositionLocalOf { 150.dp }
class MenuHost {
@@ -240,7 +228,6 @@ class MenuHost {
@Composable
fun rememberMenuHost(): MenuHost = remember { MenuHost() }
/** Under the anchor with left edges aligned, kept on screen: a dropdown that belongs to a tab. */
private class BelowStartProvider(private val gap: Int) : PopupPositionProvider {
override fun calculatePosition(anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize): IntOffset {
var x = anchorBounds.left
@@ -267,7 +254,6 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
@Composable
fun AnchoredMenu(
open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null,
/** A tab's dropdown: under its anchor, left edges aligned, as wide as its entries (within [minWidth]..260 dp). */
compact: Boolean = false, minWidth: androidx.compose.ui.unit.Dp = 120.dp,
content: @Composable ColumnScope.(FocusRequester) -> Unit,
) {
@@ -283,8 +269,6 @@ fun AnchoredMenu(
android.util.Log.i("AnchoredMenu", "requested first option focus")
}
}
// Popup installs Android's window density. Keep the app scale from the anchor, including
// the matching dp window dimensions used to cap and scroll the menu.
val density = LocalDensity.current
val configuration = LocalConfiguration.current
val gap = with(density) { 6.dp.roundToPx() }
@@ -299,8 +283,6 @@ fun AnchoredMenu(
exit = fadeOut(Motion.tw(140)) + scaleOut(Motion.tw(140), targetScale = 0.96f, transformOrigin = TransformOrigin(if (compact) 0f else 1f, 0f)),
label = "menu",
) {
// A long list (a driver menu with its downloads) must not run off the screen: the menu is
// capped at most of the window's height and its entries scroll under the fixed title.
val maxHeight = (androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp * 0.86f).dp
Column(
modifier = Modifier
@@ -317,8 +299,6 @@ fun AnchoredMenu(
title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 6.dp),
)
// While entries remain below the fold the list fades out at the bottom over a down
// arrow, so a short screen (a phone in landscape) shows that the menu goes on.
val scroll = rememberScrollState()
Box(Modifier.weight(1f, fill = false)) {
Column(
@@ -368,7 +348,6 @@ fun MenuItem(
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift")
// A menu taller than the screen opens scrolled to the current choice, not past it.
val reveal = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() }
if (checked) LaunchedEffect(Unit) { reveal.bringIntoView() }
Row(
@@ -431,7 +410,6 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
// In a lifted sheet each group fades and rises in on its own beat.
Column(Modifier.fillMaxWidth().sheetPiece()) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -445,11 +423,6 @@ fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable
}
}
/**
* One setting: its label and [hint] with the [control] beside them. [hintLines] fixes the hint to
* that many lines, for a hint that changes with the value - the row keeps its height, so the rows
* under it stay put.
*/
@Composable
fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, control: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -459,7 +432,6 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
Text(hint ?: "", fontSize = size, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp),
minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis)
}
// A narrow page stacks the control under its label, so neither squeezes the other.
if (stacked || LocalNarrowPane.current) Column(
modifier = Modifier.fillMaxWidth().background(bg).padding(start = 14.dp, end = 14.dp, top = 11.dp, bottom = 12.dp),
) {
@@ -483,9 +455,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
fun <T> ChoiceRow(
host: MenuHost, key: String, label: String, hint: String?,
options: List<Pair<T, String>>, selected: T, enabled: Boolean = true, note: String? = null,
/** For the box itself - a page's FocusRequester for its first control. */
chipModifier: Modifier = Modifier,
/** See SettingsRow: a fixed height for a hint that changes with the choice. */
hintLines: Int? = null,
onPick: (T) -> Unit,
) {
@@ -505,7 +475,6 @@ fun <T> ChoiceRow(
}
}
/** A small "?" beside a value the app guessed and is not sure of; [description] says what to check. */
@Composable
fun UncertainMark(description: String) {
val colors = MaterialTheme.colorScheme
@@ -524,7 +493,6 @@ fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked
ToggleSwitch(checked, enabled, label, chipModifier.testTag("setting-$key")) { host.open = null; onChange(it) }
}
/** An on/off switch: one tap or one A press flips it, where a menu of On and Off took three. */
@Composable
fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = null, modifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -537,7 +505,6 @@ fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = nul
val onLabel = stringResource(R.string.widgets_on)
val offLabel = stringResource(R.string.widgets_off)
val shape = RoundedCornerShape(99.dp)
// 48dp tall to touch; the visible track sits inside it.
Box(
contentAlignment = Alignment.Center,
modifier = modifier
@@ -562,11 +529,6 @@ fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = nul
}
}
/**
* A bounded value as a track: the d-pad's left and right step it by [step] (held, it keeps
* going), a finger drags or taps it, and [format] prints the value beside it. [modifier] goes on
* the focusable part, for a page's focus tracking.
*/
@Composable
fun SliderRow(
label: String, hint: String?, value: Int, range: IntRange, step: Int = 1, enabled: Boolean = true,
@@ -599,7 +561,6 @@ fun ValueSlider(
var trackPx by remember { mutableIntStateOf(0) }
val text = format(value)
val shape = RoundedCornerShape(8.dp)
// Preserve off-grid preset values until the user adjusts; every input snaps to the same step.
fun stepped(v: Int) = (((v - range.first).toFloat() / step).roundToInt() * step + range.first).coerceIn(range.first, range.last)
fun fromX(x: Float) {
val width = trackPx - 2 * thumbInset
@@ -619,7 +580,6 @@ fun ValueSlider(
val left = keyEvent.keyCode == KeyEvent.KEYCODE_DPAD_LEFT
if (!left && keyEvent.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) false
else {
// Repeated key-down events let a held direction keep adjusting.
if (enabled && keyEvent.action == KeyEvent.ACTION_DOWN) {
val next = stepped(value + if (left) -step else step)
if (next != value) currentOnChange(next)
@@ -699,13 +659,10 @@ fun SettingsPage(
onBack: () -> Unit,
eyebrow: String? = null,
lede: String? = null,
/** A small control at the right of the title (the driver pages' refresh button). */
action: (@Composable () -> Unit)? = null,
/** Pass one held above the page to keep its scroll position across a page opened over it. */
scroll: androidx.compose.foundation.ScrollState? = null,
scrollContent: Boolean = true,
compactLayout: Boolean = false,
/** Fixed controls below the title, or beside Back when the title is omitted. */
header: (@Composable () -> Unit)? = null,
modifier: Modifier = Modifier,
content: @Composable ColumnScope.() -> Unit,
@@ -733,7 +690,6 @@ fun SettingsPage(
}
}
} else if (narrow) {
// Back and the title share one line: a 4:3 screen has no height to spare.
Rise(0) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
@@ -804,11 +760,6 @@ fun SettingsPage(
}
}
/**
* A short row of tabs with one chosen: a pill in the signal blue slides under the choice and its
* label turns to sit on it. Left and right move between tabs; a tap or A picks one. [selected]
* null leaves no tab chosen.
*/
@Composable
fun <T> SegmentedTabs(options: List<Pair<T, String>>, selected: T?, modifier: Modifier = Modifier, onPick: (T) -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -37,20 +37,9 @@ import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.sin
// The moves the stores made first, for any section: one selection shape that glides along a row
// (or down a column) of choices, and a pressed control that squashes into a dot and flies home.
/** Which way a [ChipGlide]'s choices run. */
internal enum class GlideAxis { Horizontal, Vertical }
/**
* The selection under a row of chips: [at] (in the row) of chip [index], in [tint]. A move to the
* next chip stretches it - the leading edge on the focus ring's lead spring, the trailing one a
* beat later on its trail spring - and a hop past chips stretches the same way, across them.
* Draw it over the chips: under them, their own rest fill hid it in flight. [axis] runs it down a column instead (the rail, a stack of layers). [corner] is the
* chips' own corner; null draws a capsule. [fill] and [outline] are the resting alphas. Not
* [visible], it fades away, and comes back on whichever chip it is on by then.
*/
@Composable
internal fun BoxScope.ChipGlide(
index: Int,
@@ -63,12 +52,9 @@ internal fun BoxScope.ChipGlide(
visible: Boolean = true,
) {
val density = androidx.compose.ui.platform.LocalDensity.current
// The two edges along the axis (left and right, or top and bottom), and the two across it.
val start = remember { Animatable(Float.NaN) }
val end = remember { Animatable(0f) }
val pinch = remember { Animatable(0f) }
// With a pad the focus ring fills what it holds, and is the only fill: a selection of the
// row's own, sliding on its own beat, trailed the ring and sat on items the pad had left.
val pad = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode == androidx.compose.ui.input.InputMode.Keyboard
@Suppress("NAME_SHADOWING") val visible = visible && !pad
val shown = remember { Animatable(if (visible) 1f else 0f) }
@@ -91,15 +77,12 @@ internal fun BoxScope.ChipGlide(
if (visibleNow.value) shown.snapTo(1f)
return@LaunchedEffect
}
// Away or on its way back: it goes straight to the chip, unseen.
if (!visibleNow.value || shown.value < 0.5f) {
start.snapTo(s); end.snapTo(e); pinch.snapTo(0f)
return@LaunchedEffect
}
coroutineScope {
run {
// Every move stretches across, however far: a long one used to go as a drop (which
// sat on chips already left) and then as a fade (a flash of no fill at all).
launch { pinch.animateTo(0f, Motion.sp(0.6f, 500f)) }
launch { shown.animateTo(1f, Motion.tw(120)) }
val forward = index > from
@@ -119,11 +102,9 @@ internal fun BoxScope.ChipGlide(
val size = shape.size
val round = minOf(size.width, size.height) / 2f
val r = CornerRadius(corner?.let { lerp(minOf(with(density) { it.toPx() }, round), round, p) } ?: round)
// A drop in flight is solid; on a chip it is the chip's tinted fill and outline.
val a = shown.value
drawRoundRect(tint.value.copy(alpha = lerp(fill, 0.9f, p) * a), at0, size, r)
if (outline > 0f) {
// Inside the chip's edge: a stroke on it would lose its outer half to a scrolling row's clip.
val w = with(density) { 1.dp.toPx() }
val inset = w / 2f
drawRoundRect(
@@ -134,11 +115,6 @@ internal fun BoxScope.ChipGlide(
}
}
/**
* The chosen one of a row of chips (or a column, [vertical]): a short bar of [color] along its foot
* (or its start edge). Not a fill or an outline, so it never reads as focus; with a pad the ring's
* own infill is the only fill. Goes inside the chip's clip.
*/
@Composable
internal fun Modifier.shownBar(on: Boolean, color: Color, vertical: Boolean = false): Modifier {
val shown = androidx.compose.animation.core.animateFloatAsState(if (on) 1f else 0f, Motion.tw(if (on) 140 else 100), label = "shownBar").value
@@ -156,11 +132,6 @@ internal fun Modifier.shownBar(on: Boolean, color: Color, vertical: Boolean = fa
}
}
/**
* Where a glide's shape is: its edges along the axis at [start] and [end] (either order), across
* it from [crossStart] to [crossEnd], pinched [pinch] of the way (0 to 1) into a drop [drop] each
* side of its centre. [vertical] runs the axis down instead of across.
*/
internal fun glideShape(start: Float, end: Float, crossStart: Float, crossEnd: Float, pinch: Float, drop: Float, vertical: Boolean): Rect {
val a0 = minOf(start, end)
val a1 = maxOf(start, end)
@@ -173,11 +144,6 @@ internal fun glideShape(start: Float, end: Float, crossStart: Float, crossEnd: F
return if (vertical) Rect(c0, s0, c1, s1) else Rect(s0, c0, s1, c1)
}
/**
* A dot on its way somewhere: from the control at [from] (root px) to the point [to] gives (root
* px, asked each frame, so a target that moves is followed). [color] null is the palette's signal
* blue. [onHalf] runs as it passes the top of its arc, [onLand] once it lands.
*/
internal class Flight(
val from: Rect,
val to: Density.() -> Offset?,
@@ -190,27 +156,20 @@ internal class Flight(
private companion object { var next = 0L }
}
/** Dots flying anywhere outside the Stores page (which keeps its own): a hop, a swap, a toggle. */
internal object Flights {
val all = mutableStateListOf<Flight>()
/** Sends [f], or with animations off just runs its ends. */
fun fly(f: Flight) {
if (Motion.scale == 0f) { f.onHalf(); f.onLand(); return }
all += f
}
}
/** [Flights] drawn over everything, in the space of an element at [origin] (root px). */
@Composable
internal fun FlightsLayer(origin: Offset) {
for (f in Flights.all.toList()) key(f.id) { FlightDot(f, origin) { Flights.all.remove(f) } }
}
/**
* One dot: the control squashes into a 14dp dot (width first, a little bloop), which then flies
* on an arc to its target, stretched along its path like the focus ring's drop.
*/
@Composable
internal fun FlightDot(f: Flight, origin: Offset, onDone: () -> Unit) {
val pal = LocalPalette.current
@@ -232,7 +191,6 @@ internal fun FlightDot(f: Flight, origin: Offset, onDone: () -> Unit) {
val b = (f.to(this) ?: return@Canvas) - origin
val v = t.value
if (v < 1f) {
// Squash: the width goes first, then the height, into the dot; a bloop at the end.
val w = lerp(from.width, 2 * r, (v * 1.4f).coerceAtMost(1f))
val h = lerp(from.height, 2 * r, ((v - 0.25f) / 0.75f).coerceIn(0f, 1f))
val k = 1f - 0.15f * sin(PI * v).toFloat()
@@ -254,10 +212,6 @@ internal fun FlightDot(f: Flight, origin: Offset, onDone: () -> Unit) {
}
}
/**
* A row that scrolls sideways fades out at an edge it has more past, instead of slicing a pill or
* a card through: the content's own alpha, so whatever is behind the row shows through.
*/
internal fun Modifier.edgeFade(scroll: androidx.compose.foundation.ScrollState, width: Dp = 28.dp): Modifier =
this.graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }
.drawWithContent {
@@ -5,10 +5,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
// The rows the lifted sheets add to what the session settings already had: frame generation,
// Performance and the link to the GPU drivers on Components.
/** Frame generation, moved here from Setup: it is how Play's games are drawn. */
@Composable
internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) {
val host = rememberMenuHost()
@@ -22,10 +19,6 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) {
}
}
/**
* Performance (CPU core assignment), opened from the sheet's Session chip: its page floods out of
* this row, and Back draws it into the row again with the sheet lifted where it was.
*/
@Composable
internal fun PerformanceLink(a: FrontEndActions, rail: String, tab: String) {
val id = "sheet:performance"
@@ -41,10 +34,6 @@ internal fun PerformanceLink(a: FrontEndActions, rail: String, tab: String) {
}
}
/**
* The GPU drivers in use, read only, and a link to where they are set: A hops to Components with
* the GPU drivers layer chosen, and B there comes back to this row.
*/
@Composable
internal fun DriversLink(a: FrontEndActions, summary: String?, rail: String, back: String) {
val id = "sheet:gpu-drivers"
@@ -68,23 +68,14 @@ import coil.size.Scale
import coil.transform.RoundedCornersTransformation
import kotlin.math.roundToInt
/** From this many games the Steam tab is a wall; fewer would only repeat the same covers. */
private const val WALL_MIN_GAMES = 4
private const val DRIFT_STEP_NS = 15_000_000L
/**
* The Steam tab: the library as a slowly drifting, tilted wall of capsules (a few games instead
* lean on their own; none, the DroidDeck mark wandering a blank wall), and over it the wordmark and the one thing to do here -
* Play. Everything about a single game lives on the Games tab.
*/
@Composable
internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
// A fixed order, ties included: the wall places each game by its position, so an order that
// came out differently from one read of the library to the next moved every capsule.
val games = remember(s.steamGames) { s.steamGames.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
val narrow = LocalNarrowPane.current
// Where the words and buttons sit, for the empty library's wandering mark to keep off.
var words by remember { mutableStateOf<Rect?>(null) }
val mode = com.droiddeck.launcher.session.SessionService.MODE_STEAM
val tabs = modeSheetTabs(steam = true).map { it to sheetTabLabel(it) }
@@ -93,7 +84,6 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
frameGen = { FrameGenGroup(s, a) },
performance = { PerformanceLink(a, "steam", SheetTab.SESSION) },
drivers = { summary -> DriversLink(a, summary, "steam", back) },
// Offline mode lives with Steam's other settings; Setup only checks the account.
account = { host ->
SettingsGroup(stringResource(R.string.setup_account)) {
ToggleRow(
@@ -126,8 +116,6 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
start = if (narrow) 20.dp else 44.dp, bottom = if (narrow) 20.dp else 44.dp,
background = {
when {
// The mark wanders over this fade, so it sinks with the wall: drawn a little oversized,
// it still reaches the pane's edges at the sink's 0.95.
games.isEmpty() -> EmptyLibrary(avoid = words) { Box(Modifier.fillMaxSize().graphicsLayer { scaleX = 1.06f; scaleY = 1.06f }) { WallFade() } }
games.size < WALL_MIN_GAMES -> CapsuleFan(games)
else -> CapsuleWall(games)
@@ -140,19 +128,16 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
modifier = Modifier.onPlaced { words = it.boundsInParent() },
) {
Wordmark(if (narrow) 30.dp else 40.dp)
// Said only when something stands between Play and Steam; a ready runtime needs no words.
if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s)
}
},
button = { click ->
// Enabled without a runtime: the session's loading screen installs it first.
PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, large = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.testTag("play-steam"), onClick = click)
},
rows = { tab -> a.modeSheet(mode, tab, extras) },
)
}
/** The wall fades out behind the words, and toward the bottom where the buttons sit. */
@Composable
internal fun WallFade() {
val colors = MaterialTheme.colorScheme
@@ -169,11 +154,6 @@ internal fun WallFade() {
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to colors.background.copy(alpha = 0.9f))))
}
/**
* Columns of capsules tilted a few degrees, alternate columns drifting up and down. Each column
* holds its run of covers twice and moves by exactly one run, so the loop has no seam. An empty
* library draws the same wall in blank capsules, slower.
*/
@Composable
internal fun CapsuleWall(
games: List<Library.SteamGame>,
@@ -185,37 +165,20 @@ internal fun CapsuleWall(
TiltedWall(games.size, driftMs, modifier) { i -> if (games.isEmpty()) blank else WallCapsule(artBrush(hueOf(games[i].name)), games[i].art) }
}
/**
* One capsule of a [TiltedWall]: its ground, the art laid over it once loaded, and an outline. A
* tile that is an app rather than a cover carries an [icon] instead (a drawable id or an image),
* drawn whole at the tile's centre, and a window's [bar] along its foot.
*/
internal class WallCapsule(val ground: Brush, val art: Any? = null, val edge: Color? = null, val icon: Any? = null, val bar: Color? = null)
/**
* [CapsuleWall]'s tilted, drifting columns for any [count] of capsules; [capsule] describes number i
* (0 until [count], or 0 for each blank one when [count] is 0). Each column is one drawing with the
* covers' corners cut into their bitmaps: a rounded clip under the tilt is rasterised on the CPU,
* for every capsule on every frame.
*/
@Composable
internal fun TiltedWall(
count: Int,
driftMs: Int,
modifier: Modifier = Modifier,
/** One tile's size, the gap between tiles and their corner: portrait capsules unless a wall says otherwise. */
capW: androidx.compose.ui.unit.Dp = 112.dp,
capH: androidx.compose.ui.unit.Dp = 168.dp,
gap: androidx.compose.ui.unit.Dp = 14.dp,
corner: androidx.compose.ui.unit.Dp = 10.dp,
capsule: (index: Int) -> WallCapsule,
) {
// Animations off in the system settings: a still wall.
val still = Motion.scale == 0f
// The wall moves a few pixels a step. Stepped on frames at most every 15 ms it looks the same as
// stepped on every frame, which on a 120 Hz screen drew it twice as often. The phase advances by
// the time since the last step over the period now, so a period that changes (Flathub's wall
// slowing while it sets up) changes the speed without the wall jumping.
val drift = remember { mutableFloatStateOf(0f) }
val period = androidx.compose.runtime.rememberUpdatedState(driftMs)
if (!still) LaunchedEffect(Unit) {
@@ -230,7 +193,6 @@ internal fun TiltedWall(
}
val density = LocalDensity.current
BoxWithConstraints(modifier.fillMaxSize()) {
// Centred on the page and big enough that, once tilted, it still covers every corner.
val tilt = Math.toRadians(13.0)
val cos = kotlin.math.cos(tilt).toFloat()
val sin = kotlin.math.sin(tilt).toFloat()
@@ -279,7 +241,6 @@ internal fun TiltedWall(
}
}
/** A cover sized for a capsule, its corners already cut, so it draws without a clip. */
@Composable
private fun rememberCapsuleArt(model: Any, size: Size, radius: Float): Painter {
val context = LocalContext.current
@@ -293,7 +254,6 @@ private fun rememberCapsuleArt(model: Any, size: Size, radius: Float): Painter {
)
}
/** An app's icon for a wall tile: a bundled drawable, or an image Coil loads. */
@Composable
private fun rememberIcon(model: Any): Painter =
if (model is Int) androidx.compose.ui.res.painterResource(model) else rememberAsyncImagePainter(model)
@@ -302,7 +262,6 @@ private fun DrawScope.drawCapsule(look: WallCapsule, art: Painter?, radius: Floa
drawRoundRect(look.ground, size = size, cornerRadius = CornerRadius(radius))
look.bar?.let { drawRect(it, Offset(0f, size.height - barH), Size(size.width, barH)) }
if (art != null && look.icon != null) {
// An app's icon whole at the tile's centre (above a window's bar), not cropped over it.
val side = minOf(size.width, size.height - (if (look.bar != null) barH else 0f)) * 0.5f
val cy = (size.height - (if (look.bar != null) barH else 0f)) / 2f
translate((size.width - side) / 2f, cy - side / 2f) { with(art) { draw(Size(side, side)) } }
@@ -312,7 +271,6 @@ private fun DrawScope.drawCapsule(look: WallCapsule, art: Painter?, radius: Floa
}
}
/** One to three games, each a large capsule leaning on the others and floating a little. */
@Composable
private fun CapsuleFan(games: List<Library.SteamGame>) {
val pal = LocalPalette.current
@@ -322,7 +280,6 @@ private fun CapsuleFan(games: List<Library.SteamGame>) {
transition.animateFloat(0f, 1f, infiniteRepeatable(tween(ms, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "float")
}
val still = Motion.scale == 0f
// Where each sits (share of the page), its height (share of the page's) and its lean; front first.
val slots = listOf(
FanSlot(0.54f, 0.14f, 0.62f, -9f),
FanSlot(0.70f, 0.24f, 0.56f, 5f),
@@ -65,17 +65,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
// End session's confirm, for any control: a pull drops out of the control and a wider box steps
// out under it for the choices, one edge flush with the control. Stop draws it from its pill on
// the drawer; the stores draw it from Install, the Library tab and a download's cancel.
/**
* The stair-step outline: the pill [p] on top, a box under it from [left] to the pill's right edge
* and down to [bottom], the pull between them [pullTop] (the box's top). Right edges are flush and
* the inside corner where the pull meets the box is rounded the other way. While the box is still
* no wider than the pill it is just the pill, stretched down. [pillCorner] is the control's own
* corner: a pill's is half its height.
*/
internal fun stepPath(
path: Path, p: Rect, left: Float, bottom: Float, pullTop: Float, box: Float, fillet: Float,
pillCorner: Float = minOf(p.height / 2f, p.width / 2f),
@@ -112,13 +102,10 @@ internal fun stepPath(
path.close()
}
/** [stepPath] for a box that steps out to the right of the pill, out to [right], left edges flush. */
internal fun stepPathRight(
path: Path, p: Rect, right: Float, bottom: Float, pullTop: Float, box: Float, fillet: Float,
pillCorner: Float = minOf(p.height / 2f, p.width / 2f),
) {
// Drawn as the left-hand outline about the pill's centre, which maps the pill onto itself,
// then mirrored back: x -> (p.left + p.right) - x.
val axis = p.left + p.right
stepPath(path, p, axis - right, bottom, pullTop, box, fillet, pillCorner)
path.transform(Matrix().apply { this[0, 0] = -1f; this[3, 0] = axis })
@@ -126,17 +113,12 @@ internal fun stepPathRight(
private fun lerpF(a: Float, b: Float, t: Float) = a + (b - a) * t
/** Which way the box steps out of its control. */
internal enum class StepSide {
/** Out to the left, right edges flush (a control at the right: Stop, a row's cancel). */
Left,
/** Out to the right, left edges flush (a control at the left: Install, a tab). */
Right,
}
/** The choices' side of a [StepOut]: each piece fades in on its own beat, and [first] takes focus. */
internal class StepOutScope(private val items: List<Animatable<Float, AnimationVector1D>>, val first: FocusRequester, val open: Boolean, val maxHeight: Dp) {
/** Piece [i] (0 first) of the box: it fades and rises in after the box has stepped out. */
fun Modifier.stepItem(i: Int): Modifier = graphicsLayer {
val v = items[i.coerceIn(0, items.lastIndex)].value
alpha = v
@@ -144,17 +126,10 @@ internal class StepOutScope(private val items: List<Animatable<Float, AnimationV
}
}
/** Room between the control and the box that steps out under it: the pull. */
private val OutPull = 6.dp
private val OutBoxCorner = 16.dp
private val OutFillet = 10.dp
/**
* A confirm or a short list grown out of the control at [pill] (px, in this element's space, which
* should fill the screen area it may cover): a pull the control's width drops out of it, then a
* box steps out to [side] for [content]. [onDismiss] (B, a tap outside) asks to fold it; it folds
* back width first once [open] is false, then [onClosed]. Exactly StopConfirm's springs.
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun StepOut(
@@ -181,13 +156,9 @@ internal fun StepOut(
var grown by remember { mutableStateOf(false) }
var measured by remember { mutableStateOf<IntSize?>(null) }
val first = remember { FocusRequester() }
// The control focus was on as it opened: focus goes back to it as it folds, not to wherever
// the screen puts a pad with nothing focused (the rail).
val glide = LocalFocusGlide.current
val opener = remember { arrayOfNulls<GlideSource>(1) }
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
// While the box grows or folds the ring keeps out (it flew across the moving shape) and comes
// back on whatever has focus once it has settled: the first choice, or the control again.
var moving by remember { mutableStateOf(false) }
if (moving) VeilRing()
val pull = with(density) { OutPull.toPx() }
@@ -199,13 +170,10 @@ internal fun StepOut(
val availableHeight = with(density) {
maxOf(hostHeight - pill.bottom - pull, pill.top - pull).coerceAtLeast(44.dp.toPx()).toDp()
}
// No room under the control (a row near the foot of the screen): it steps out upward
// instead, the same outline mirrored about the control.
val up = measured?.let { pill.bottom + pull + it.height > hostHeight && pill.top - pull - it.height >= 0f } ?: false
val room = if (side == StepSide.Left) pill.right else hostWidth - pill.left
val maxW = with(density) { maxWidth.toPx() }.coerceAtMost(room).coerceAtLeast(pill.width)
LaunchedEffect(open, measured) {
// Asked to close before it ever measured: nothing to fold.
if (!open && !grown) { onClosed(); return@LaunchedEffect }
val c = measured ?: return@LaunchedEffect
val rest = if (side == StepSide.Left) pill.left else pill.right
@@ -221,8 +189,6 @@ internal fun StepOut(
coroutineScope {
launch { dim.animateTo(1f, Motion.tw(260)) }
launch { tint.animateTo(1f, Motion.tw(200)) }
// Down and out together, on one spring: down first drew the control as a stick
// that then snapped out sideways.
moving = true
val down = launch { bottom.animateTo(boxBottom, Motion.sp(0.8f, 380f)) }
val across = launch { edge.animateTo(out, Motion.sp(0.8f, 380f)) }
@@ -242,8 +208,6 @@ internal fun StepOut(
coroutineScope {
pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } }
launch { delay(Motion.ms(60).toLong()); dim.animateTo(0f, Motion.tw(300)) }
// In and up together on a timed ease: width first left a tall tail under the
// control, and a damped spring's tail kept a nub of it on screen.
moving = true
launch { delay(Motion.ms(60).toLong()); edge.animateTo(rest, Motion.tw(240)) }
launch { delay(Motion.ms(60).toLong()); bottom.animateTo(pill.bottom, Motion.tw(240)) }
@@ -255,11 +219,9 @@ internal fun StepOut(
}
}
// Opened by touch and then answered with a pad: the pad starts in the box, not behind it.
LaunchedEffect(open, grown, inputMode.inputMode) {
if (open && grown && inputMode.inputMode == InputMode.Keyboard) { withFrameNanos { }; runCatching { first.requestFocus() } }
}
// The rest of the screen dims behind it, and a tap there folds it. Never a pad's stop.
Box(
Modifier.fillMaxSize().graphicsLayer { alpha = dim.value }.background(Color(0x59000000))
.focusProperties { canFocus = false }
@@ -276,11 +238,6 @@ internal fun StepOut(
if (side == StepSide.Left) stepPath(path, pill, edge.value, bottom.value, pill.bottom + pull, boxCorner, fillet, corner)
else stepPathRight(path, pill, edge.value, bottom.value, pill.bottom + pull, boxCorner, fillet, corner)
if (up) path.transform(Matrix().apply { this[1, 1] = -1f; this[3, 1] = pill.top + pill.bottom })
// Barely out of the control, the pull and its fillet drew a hook off the control's foot:
// the outline comes in over the first part of the way out (and goes over the last part
// of the way back), by how far along it is. A share of the way, not a distance: a box
// no wider than its control (a confirm under a full-width row) never got 24dp out, and
// was never drawn at all.
val a = measured?.let { c ->
val rest = if (side == StepSide.Left) pill.left else pill.right
val out = if (side == StepSide.Left) (pill.right - c.width).coerceAtLeast(0f) else (pill.left + c.width).coerceAtMost(hostWidth)
@@ -294,7 +251,6 @@ internal fun StepOut(
drawPath(path, lerp(hotFill, restFill, tint.value), alpha = a)
drawPath(path, accent.copy(alpha = lerpF(0.9f, 0.55f, tint.value) * a), style = Stroke(rim))
}
// The control's label rides on top, as the pull's handle.
if (grown) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.offset { IntOffset(pill.left.roundToInt(), pill.top.roundToInt()) }
@@ -308,7 +264,6 @@ internal fun StepOut(
.heightIn(max = availableHeight)
.onSizeChanged { if (measured != it) measured = it }
.controllerBack(onDismiss)
// A pad stays in the box until it is answered or folded, as it did in Stop's dialog.
.focusProperties { exit = { if (openNow.value) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup()
.verticalScroll(rememberScrollState())
@@ -317,10 +272,6 @@ internal fun StepOut(
}
}
/**
* One choice in a [StepOut]: a capsule that fills when focused, like Stop's Cancel and Stop. [danger]
* draws it in red; [icon] and [trailing] make it a row (a place to install to and its free space).
*/
@Composable
internal fun StepChoice(
label: String,
@@ -357,7 +308,6 @@ internal fun StepChoice(
}
}
/** A [StepOut]'s heading line, the first piece to fade in. */
@Composable
internal fun StepOutScope.StepTitle(text: String) {
Text(
@@ -366,7 +316,6 @@ internal fun StepOutScope.StepTitle(text: String) {
)
}
/** The choices of a [StepOut] stacked, each the box's width. */
@Composable
internal fun StepList(content: @Composable ColumnScope.() -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp), content = content)
@@ -7,12 +7,8 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.geometry.Offset
// The front end's confirms and short lists, each stepping out of the control that asked for it
// (StepOut): a sheet's Uninstall, a Components swap, a remove. The Stores page keeps its own, in
// StoresMotion; everything else asks here and is drawn over the whole screen.
internal object Steps {
/** The confirm or list stepping out of a control now, and whether it is open. */
var step by mutableStateOf<StepAsk?>(null)
private set
var open by mutableStateOf(false)
@@ -24,10 +20,8 @@ internal object Steps {
open = true
}
/** Folds the current one back into its control. */
fun fold() { open = false }
/** Drops it at once: the control it came from has gone. */
fun drop() {
step?.let { step = null; it.onDismiss() }
open = false
@@ -39,11 +33,9 @@ internal object Steps {
}
}
/** [Steps] drawn over an element at [origin] (root px) that fills the screen. */
@Composable
internal fun StepsLayer(origin: Offset) {
val ask = Steps.step ?: return
// Back (B, or the system's) folds what is stepped out, before it reaches the page under it.
androidx.activity.compose.BackHandler(enabled = Steps.open) { Steps.fold() }
key(ask) {
StepOut(
@@ -73,7 +73,6 @@ internal class AchievementsState(val list: List<Achievement>?, val reason: Reaso
companion object { val READING = AchievementsState(null, null, true) }
}
/** The cached list at once, then the store's answer (the cache stays if the store fails). */
@Composable
internal fun rememberAchievements(game: StoreAchievements.Game?): AchievementsState? {
val ctx = LocalContext.current.applicationContext
@@ -134,14 +133,12 @@ private fun AchievementGroupLabel(label: String) {
}
}
/** Unlocked (newest first), locked, then hidden ones not yet unlocked. */
private fun groups(list: List<Achievement>): List<Pair<Int, List<Achievement>>> = listOf(
R.string.achievements_group_unlocked to list.filter { it.unlocked }.sortedByDescending { it.unlockedAt },
R.string.achievements_group_locked to list.filter { !it.unlocked && !it.hidden },
R.string.achievements_group_hidden to list.filter { !it.unlocked && it.hidden },
).filter { it.second.isNotEmpty() }
/** Focusable so the pad can scroll the list. */
@Composable
internal fun AchievementRow(a: Achievement, compact: Boolean, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
@@ -200,7 +197,6 @@ internal fun StoreAchievementsSection(game: StoreAchievements.Game) {
internal fun StoreAchievementsSectionContent(label: String, state: AchievementsState) {
val colors = MaterialTheme.colorScheme
val list = state.list
// Hidden for games without achievements.
if (list.isNullOrEmpty() && !state.reading && state.reason != Reason.SIGNED_OUT && state.reason != Reason.UNREACHABLE) return
val narrow = LocalNarrowPane.current
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = 18.dp)) {
@@ -278,7 +274,7 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
verticalArrangement = Arrangement.spacedBy(6.dp),
) { achievementItems(list, short, first) }
LaunchedEffect(list.isNotEmpty()) {
withFrameNanos {} // rows lay out a frame after composition
withFrameNanos {}
runCatching { first.requestFocus() }
}
}
@@ -286,7 +282,6 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
}
}
/** [progress]: (unlocked, total), or null when unknown. */
@Composable
internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -17,16 +17,12 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.Store
// Where a game came from, as a small coloured chip: Steam, one of the stores, or an added folder.
/** Flathub's own accent, as each store has one, and the ink that reads on it. */
internal val FlathubTeal = Color(0xFF3FB8AF)
internal val FlathubInk = Color(0xFF04211F)
/** The Store rail section's source id, for its colours. */
internal const val FLATHUB = "flathub"
/** The chip's colours per source: a tinted ground and a readable ink on it, one pair per store. */
internal class SourceColours(val fill: Color, val ink: Color, val dot: Color)
internal fun sourceColours(source: String): SourceColours = when (source) {
@@ -47,7 +43,6 @@ internal fun sourceLabel(source: String): String = when (source) {
else -> stringResource(R.string.source_added)
}
/** The source chip itself; [small] for a list row, the regular size for a hero or a card. */
@Composable
internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifier = Modifier) {
val c = sourceColours(source)
@@ -59,7 +54,6 @@ internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifi
)
}
/** A status chip in the stores' colours: green for done ("Installed"), blue for busy, amber for a warning. */
@Composable
internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false) {
val pal = LocalPalette.current
@@ -69,13 +69,9 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
// A store game's facts under its hero: who made it and when, from the store; the Metacritic score
// and HowLongToBeat's times, looked up elsewhere by name. The store's facts are there at once; the
// looked-up ones hold their place while they come and step out if there is nothing to show.
internal class GameScores(val metacritic: Lookup<GameFacts.Metacritic>, val hltb: Lookup<GameFacts.Hltb>)
/** Both lookups at once and off the main thread, each landing on its own; what memory already has shows without a wait. */
@Composable
internal fun rememberGameScores(title: String?): GameScores {
val ctx = LocalContext.current.applicationContext
@@ -89,16 +85,10 @@ internal fun rememberGameScores(title: String?): GameScores {
return GameScores(metacritic, hltb)
}
/**
* The facts: who made it, when, and what critics made of it on the first row; how long it takes,
* across the page, on the second. A looked-up tile holds its place while it asks and steps out if
* the site does not have the game; nothing is drawn when there is nothing to say.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun StoreGameFacts(developer: String, publisher: String, releaseDate: String, scores: GameScores, modifier: Modifier = Modifier) {
val released = remember(releaseDate) { GameFacts.releaseLabel(releaseDate) }
// A studio that publishes itself is named once.
val publishedBy = publisher.takeUnless { it.isBlank() || it.trim().equals(developer.trim(), ignoreCase = true) }
val firstRow = developer.isNotBlank() || publishedBy != null || released != null || scores.metacritic != Lookup.None
if (!firstRow && scores.hltb == Lookup.None) return
@@ -123,10 +113,8 @@ internal fun StoreGameFacts(developer: String, publisher: String, releaseDate: S
}
}
/** A looked-up tile: in from the start (holding its place while it asks), out with a fade when there was nothing. */
@Composable
private fun <T> Looked(lookup: Lookup<T>, exit: ExitTransition, content: @Composable (Lookup<T>) -> Unit) {
// The last answer worth drawing, so the tile does not blank as it leaves.
var shown by remember { mutableStateOf(lookup) }
if (lookup != Lookup.None) shown = lookup
AnimatedVisibility(visible = lookup != Lookup.None, enter = fadeIn(), exit = fadeOut() + exit) { content(shown) }
@@ -135,10 +123,6 @@ private fun <T> Looked(lookup: Lookup<T>, exit: ExitTransition, content: @Compos
private val FactShape = RoundedCornerShape(12.dp)
private val ValueHeight = 24.dp
/**
* A label over its value; [fill] takes the row's whole width, for a value laid out across it. With
* a [link] it is a control like any other on the page: focus, hover and A or a tap open the page.
*/
@Composable
private fun FactTile(label: String, fill: Boolean = false, link: String? = null, value: @Composable () -> Unit) {
val pal = LocalPalette.current
@@ -166,7 +150,6 @@ private fun FactTile(label: String, fill: Boolean = false, link: String? = null,
private fun FactText(text: String) =
Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
/** Metacritic's own bands: green from 75, yellow from 50, red below. */
internal fun metacriticColour(score: Int): Color = when {
score >= 75 -> Color(0xFF66CC33)
score >= 50 -> Color(0xFFFFCC33)
@@ -180,7 +163,6 @@ private fun MetacriticBadge(score: Int) {
}
}
/** Each kind of run HowLongToBeat has times for, sharing the tile's width: the hours in full, what they are for beside them. */
@Composable
private fun HltbTimes(t: GameFacts.Hltb) {
val colors = MaterialTheme.colorScheme
@@ -201,7 +183,6 @@ private fun HltbTimes(t: GameFacts.Hltb) {
}
}
/** Where a value will be, breathing while it is asked for. */
@Composable
private fun Placeholder(width: Dp) {
val pulse by rememberInfiniteTransition(label = "fact").animateFloat(
@@ -210,7 +191,6 @@ private fun Placeholder(width: Dp) {
Box(Modifier.width(width).height(16.dp).alpha(pulse).clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line2))
}
// Previews: every state the row can be in, at a TV pane's width and a narrow one.
private val previewScores = GameScores(
Lookup.Found(GameFacts.Metacritic(93, "https://www.metacritic.com/game/the-witcher-3-wild-hunt/")),
@@ -272,7 +252,6 @@ private fun FactsPaperPreview() = FactsPreview(theme = Themes.PAPER) {
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
}
// The real hero reads the stores' live state, so this stands one in to show where the row sits.
@Preview(name = "Game page, facts in place", widthDp = 800, heightDp = 520)
@Composable
private fun FactsOnPagePreview() = FactsPreview {
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.ui
/** Vertical controller moves keep the same column, including across lazy item boundaries. */
internal fun storeGridNeighbor(index: Int, count: Int, columns: Int, direction: Int): Int? {
if (index !in 0 until count || columns < 1 || direction !in listOf(-1, 1)) return null
return (index + columns * direction).takeIf { it in 0 until count }
@@ -106,20 +106,13 @@ import com.droiddeck.launcher.store.FlathubApi
import com.droiddeck.launcher.store.StoreState
import kotlinx.coroutines.delay
// The Store rail section: Flathub's apps for this device's architecture, installed into the
// Linux runtime with Flatpak, and the ones already installed - in the stores' style, in Flathub's
// teal. Until Flatpak is set up it is the stores' sign-in hero: a wall of real app icons, one word,
// one button that becomes its own progress. Then a chip row, shelves of square cards that flood
// open into an app's page, and installs that fly home to the Installed chip.
private const val MODE_DISCOVER = "discover"
private const val MODE_INSTALLED = "installed"
private const val MODE_UPDATES = "updates"
/** One app as a card shows it: Flathub's summary or what Flatpak says is installed. */
private class CardApp(val id: String, val name: String, val icon: Any?, val summary: String? = null, val verified: Boolean = false)
/** Where the Installed chip is, for an install's dot to land in, and how many have landed. */
private object FlathubMotion {
var installedChip: Rect? = null
var landed by mutableIntStateOf(0)
@@ -131,8 +124,6 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
LaunchedEffect(s.ready) { StoreState.refresh(ctx) }
LaunchedEffect(Unit) { StoreState.loadSections() }
FlathubTheme {
// The storefront takes over from the hero once Flatpak is ready: the setup rail rings
// once, then the hero sinks away and the storefront rises.
var front by remember { mutableStateOf(StoreState.ready && s.ready) }
var ring by remember { mutableIntStateOf(0) }
LaunchedEffect(StoreState.ready, s.ready) {
@@ -156,11 +147,6 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
}
}
/**
* Flatpak is not set up yet: the stores' sign-in shape in teal. A tilted wall of the popular apps'
* icons (Flathub's public pages need no Flatpak) drifts behind, fading toward the words; one big
* button sets it up, and stretches into its own progress while it does.
*/
@Composable
private fun FlathubHero(s: FrontEndState, ring: Int) {
val ctx = LocalContext.current
@@ -174,7 +160,6 @@ private fun FlathubHero(s: FrontEndState, ring: Int) {
BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp)) {
val shape = RoundedCornerShape(20.dp)
Box(Modifier.fillMaxWidth().height(maxHeight.coerceAtLeast(320.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) {
// Slower while it sets up, as the empty wall drifts.
androidx.compose.animation.Crossfade(icons, animationSpec = Motion.tw(600), label = "flathubWall") { tiles ->
val ground = Brush.linearGradient(listOf(Color(0xFF0B2E2B), Color(0xFF0B2E2B)))
val edge = FlathubTeal.copy(alpha = 0.18f)
@@ -217,11 +202,6 @@ private fun FlathubHero(s: FrontEndState, ring: Int) {
}
}
/**
* Set up Flathub, and its own progress: while it sets up the button springs out to the full width
* and fills in teal from the left with how far it is, the stage and the figure inside it. Without
* a runtime it says what is missing instead.
*/
@Composable
private fun SetupButton(s: FrontEndState, busy: Boolean, full: Dp, ring: Int, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -240,7 +220,6 @@ private fun SetupButton(s: FrontEndState, busy: Boolean, full: Dp, ring: Int, on
}
return
}
// A pad keeps its place on the rail that took the button's.
if (ff != null) LaunchedEffect(Unit) { if (inputMode.inputMode == InputMode.Keyboard) focusSoon { ff.primary } }
val width = androidx.compose.ui.unit.lerp(restW.coerceAtLeast(120.dp), full, grow)
val shape = RoundedCornerShape(12.dp)
@@ -269,7 +248,6 @@ private fun SetupButton(s: FrontEndState, busy: Boolean, full: Dp, ring: Int, on
}
}
// ---- storefront ------------------------------------------------------------------------------------
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
@@ -285,9 +263,7 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
var openApp by rememberSaveable { mutableStateOf<String?>(null) }
val updates = StoreState.updates
if (mode == MODE_UPDATES && updates.isEmpty()) mode = MODE_INSTALLED
// Once a session is plenty: the Updates chip shows itself when there is something to update.
LaunchedEffect(StoreState.ready) { if (StoreState.ready && !StoreState.updatesChecked && !StoreState.checkingUpdates) StoreState.checkUpdates(ctx) }
// A search runs a beat after typing stops, or as a category is picked.
LaunchedEffect(query, category) {
if (query.isBlank() && category == null) { StoreState.clearSearch(); return@LaunchedEffect }
delay(350)
@@ -298,7 +274,6 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
val focusManager = LocalFocusManager.current
val keyboard = LocalSoftwareKeyboardController.current
val view = LocalView.current
// Cards, where they are, for the page that opens from one.
val cards = remember { HashMap<String, Rect>() }
var viewportAt by remember { mutableStateOf(Offset.Zero) }
var detail by remember { mutableStateOf<String?>(null) }
@@ -308,8 +283,6 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
LaunchedEffect(openApp) {
val id = openApp
if (id != null) {
// The grid stays composed for the return animation. Release its native search field
// before covering it, so its focus ring and keyboard do not follow onto the app page.
focusManager.clearFocus(force = true)
view.findFocus()?.clearFocus()
keyboard?.hide()
@@ -323,20 +296,17 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
detail = null; leaving = false; detailFrom = null
}
}
// Back on the grid: focus goes to the card the page came from.
LaunchedEffect(detail) {
if (detail != null || inputMode.inputMode != InputMode.Keyboard || ff == null) return@LaunchedEffect
val id = lastApp ?: return@LaunchedEffect
ff.items["tile:store:$id"]?.let { req -> focusSoon { req } }
}
BackHandler(enabled = openApp != null) { openApp = null }
// An app's card on Desktop asked for its page.
LaunchedEffect(StoreState.openRequest) { StoreState.openRequest?.let { openApp = it; StoreState.openRequest = null } }
val covering = detail != null && !leaving
val sink by animateFloatAsState(if (covering) 0.95f else 1f, if (covering) Motion.tw(480) else Motion.tw(460, 40), label = "flathubSink")
val fade by animateFloatAsState(if (covering) 0f else 1f, if (covering) Motion.tw(320, 80) else Motion.tw(300, 100), label = "flathubFade")
val modes = buildList { add(MODE_DISCOVER); add(MODE_INSTALLED); if (updates.isNotEmpty()) add(MODE_UPDATES) }
// LB / RB with a pad: focus goes to the new mode's chip; the cards it was on leave with the old mode.
val seenMode = remember { arrayOf(mode) }
LaunchedEffect(mode) {
if (seenMode[0] == mode) return@LaunchedEffect
@@ -354,7 +324,6 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
) {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
// A page of Desktop's: the way back to it, for a finger (B does the same).
val show = LocalShowSection.current
BackLink(stringResource(R.string.rail_desktop), compact = true) { show("desktop") }
Box(Modifier.weight(1f)) { FlathubChips(mode, modes, StoreState.installed.size, updates.size) { mode = it } }
@@ -386,7 +355,6 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
}
if (from == null) body()
else {
// The card's own icon, cropped over the tile as it grows: the page arrives in the app's colour.
val art = coil.compose.rememberAsyncImagePainter(
remember(icon) { coil.request.ImageRequest.Builder(ctx).data(icon).size(256, 256).build() },
)
@@ -397,10 +365,6 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
}
}
/**
* Discover, Installed (with its count) and Updates (when there are any): one selection glides under
* them in teal; the Installed count pops as an install's dot lands in it.
*/
@Composable
private fun FlathubChips(mode: String, modes: List<String>, installed: Int, updates: Int, onPick: (String) -> Unit) {
val pal = LocalPalette.current
@@ -415,7 +379,6 @@ private fun FlathubChips(mode: String, modes: List<String>, installed: Int, upda
val hot = rememberHot(src)
val shape = RoundedCornerShape(99.dp)
val on = m == mode
// Drawn by the row's glide by touch only; with a pad its own rest look and the bar.
val under = on && androidx.compose.ui.platform.LocalInputModeManager.current.inputMode != androidx.compose.ui.input.InputMode.Keyboard
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
@@ -446,15 +409,10 @@ private fun FlathubChips(mode: String, modes: List<String>, installed: Int, upda
}
}
}
// Over the chips: under them, their rest fill hid it as it crossed them.
ChipGlide(modes.indexOf(mode), bounds[mode], tint)
}
}
/**
* The card width for a width: room for a name on two lines and a two-line summary under the art,
* so a long name wraps instead of being cut to a few letters.
*/
private fun cardSize(width: Dp): Dp = when {
width >= 700.dp -> 164.dp
width >= 480.dp -> 148.dp
@@ -470,7 +428,6 @@ private fun Discover(
ModeHeader(
stringResource(R.string.store_tab_discover), query, onQuery, stringResource(R.string.store_search_placeholder),
) {
// The categories as small pills, at the right of the header.
val pills = rememberScrollState()
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp),
@@ -529,7 +486,6 @@ private fun UpdatesMode(cards: HashMap<String, Rect>, onOpen: (String) -> Unit)
Rise(2) { CardGrid(apps.map { CardApp(it.id, it.name, it.icon ?: StoreState.details[it.id]?.icon ?: FlathubApi.iconUrl(it.id), it.summary) }, cards, onOpen) }
}
/** A horizontal row of cards under a title, the stores' shelf; nothing while it is empty. */
@Composable
private fun Shelf(title: String, apps: List<CardApp>?, first: Boolean, cards: HashMap<String, Rect>, onOpen: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -546,7 +502,6 @@ private fun Shelf(title: String, apps: List<CardApp>?, first: Boolean, cards: Ha
}
}
/** The Installed and Updates modes, and search: a grid of the same cards. */
@Composable
private fun CardGrid(apps: List<CardApp>, cards: HashMap<String, Rect>, onOpen: (String) -> Unit) {
BoxWithConstraints(Modifier.fillMaxWidth().padding(top = 10.dp)) {
@@ -562,11 +517,6 @@ private fun CardGrid(apps: List<CardApp>, cards: HashMap<String, Rect>, onOpen:
}
}
/**
* One app: its icon over a blurred, darkened copy of itself (darkened only, before Android 12),
* with one status on the art - Get, ✓, or how far an install is - and under it the name, on two
* lines if it needs them, and what the app is.
*/
@Composable
private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<String, Rect>, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -595,7 +545,6 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<Strin
.clip(RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)).background(Color(0xFF0B2E2B)),
) {
if (app.icon != null) {
// The icon's own colour, blurred and darkened, as the card's ground.
AsyncImage(
model = app.icon, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.8f; scaleY = 1.8f; alpha = 0.55f }
@@ -604,7 +553,6 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<Strin
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.35f)))
AsyncImage(model = app.icon, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.size(artH * 0.62f))
} else Icon(Icons.Outlined.Apps, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(artH * 0.5f))
// One status, on the art: what A on the card leads to.
Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) {
when {
busy -> Box(Modifier.clip(RoundedCornerShape(99.dp)).background(Color.Black.copy(alpha = 0.55f)).padding(4.dp)) {
@@ -633,7 +581,6 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<Strin
)
if (app.verified) Icon(Icons.Outlined.Verified, stringResource(R.string.store_verified), tint = pal.signal, modifier = Modifier.padding(top = 2.dp).size(13.dp))
}
// Two lines kept for the summary even when it is short, so cards in a row line up.
Text(
app.summary.orEmpty(), fontSize = 12.sp, lineHeight = 15.sp, color = colors.onSurfaceVariant,
minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 3.dp),
@@ -642,11 +589,6 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<Strin
}
}
/**
* An app's page, flooded out of its card: its icon, name and what it is, one action (Install or
* Open, with Update beside it when there is one) and Website; then its screenshots and details.
* Install flies a dot to the Installed chip; Remove asks by stepping out of its button, in red.
*/
@Composable
private fun AppDetail(s: FrontEndState, a: FrontEndActions, id: String, onBack: () -> Unit) {
val ctx = LocalContext.current
@@ -688,7 +630,6 @@ private fun AppDetail(s: FrontEndState, a: FrontEndActions, id: String, onBack:
enabled = StoreState.busy == null && s.ready && (d == null || d.arches.isEmpty() || "aarch64" in d.arches),
) {
StoreState.install(ctx, id, name)
// The button squashes into a dot that flies to the Installed chip, whose count pops.
val from = at
if (from != null) Flights.fly(Flight(from, to = { FlathubMotion.installedChip?.center }, onLand = { FlathubMotion.landed++ }))
else FlathubMotion.landed++
@@ -749,7 +690,6 @@ private fun AppDetail(s: FrontEndState, a: FrontEndActions, id: String, onBack:
}
}
/** Remove, which asks first: are you sure steps out of it in red, Keep first, so a stray A costs nothing. */
@Composable
private fun RemoveButton(id: String, name: String, enabled: Boolean) {
val ctx = LocalContext.current
@@ -774,7 +714,6 @@ private fun RemoveButton(id: String, name: String, enabled: Boolean) {
}
}
/** A small text action at the right of a header. */
@Composable
private fun SmallLink(text: String, enabled: Boolean = true, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -790,7 +729,6 @@ private fun SmallLink(text: String, enabled: Boolean = true, onClick: () -> Unit
)
}
/** An app's icon from Flathub (a URL) or from its installed files; a placeholder until it loads. */
@Composable
internal fun AppIcon(model: Any?, name: String, size: Int) {
val colors = MaterialTheme.colorScheme
@@ -800,7 +738,6 @@ internal fun AppIcon(model: Any?, name: String, size: Int) {
}
}
/** A category pill: small, focusable, and filled when it is the one in use. */
@Composable
private fun PillButton(label: String, selected: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -41,7 +41,6 @@ import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
// A store game's own page: hero, the one main action, how it is launched and where it lives.
@Composable
internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: FrontEndActions, onBack: () -> Unit) {
@@ -52,8 +51,9 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
val id = key.substringAfter(':')
val item = (StoresState.library[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
val installed = StoresState.installedGame(store, id)
val download = StoresState.download("${store.id}:$id")?.takeIf { it.isActive }
// Removal asks twice: one stray press of A should not cost a download.
val rawDownload = StoresState.download("${store.id}:$id")
val download = rawDownload?.takeIf { it.isActive }
val failedDownload = rawDownload?.takeIf { it.state == DownloadState.FAILED }
val title = item?.title ?: installed?.sidecar?.title ?: id
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.padding(bottom = 12.dp)) {
@@ -61,13 +61,10 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
SourceChip(store.id)
}
}
// Out of a card, the hero holds still in its place: the card's flood lands on it, and a hero
// still rising in sat below where the flood had measured it (the art showed twice).
val hero: @Composable () -> Unit = {
androidx.compose.runtime.DisposableEffect(Unit) { onDispose { StoresMotion.heroAt = null } }
Box(
Modifier.fillMaxWidth().heightIn(min = if (narrow) 150.dp else 180.dp)
// The card it opened from floods onto this, and draws back into the card from it.
.onGloballyPositioned { StoresMotion.heroAt = it.boundsInRoot() }
.clip(Shape16).background(artBrush(hueOf(title))),
) {
@@ -75,24 +72,30 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.5f to colors.background.copy(alpha = 0.55f), 1f to Color.Transparent)))
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp)) {
// An install names where it went (internal storage, the card), a download where it is going.
val state = when {
installed != null -> stringResource(R.string.stores_eyebrow_installed) + " · " + com.droiddeck.launcher.stores.StoreInstallRoot.labelFor(ctx, installed.folder)
download != null && download.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + download.location
failedDownload != null && failedDownload.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + failedDownload.location
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
else -> stringResource(R.string.stores_eyebrow_store)
}
val size = (item?.sizeBytes ?: 0L).takeIf { it > 0 }?.let { " · " + formatBytes(it) } ?: ""
Text((state + size).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = pal.signal)
Text(title, fontSize = if (narrow) 24.sp else 30.sp, lineHeight = if (narrow) 27.sp else 33.sp, fontWeight = FontWeight.Black, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (!failedDownload?.error.isNullOrBlank()) {
Text(
failedDownload!!.error!!,
fontSize = 13.sp,
lineHeight = 17.sp,
fontWeight = FontWeight.Medium,
color = colors.error,
maxLines = 3,
overflow = TextOverflow.Ellipsis
)
}
Actions {
when {
installed != null -> {
// Launching, the prefix and the files belong to the Games tab, where every
// installed game has them; here an install only says it is in Steam and
// offers the one thing Games does not: removing it.
// The row keeps its shape: the chip stays, and Uninstall becomes its own
// progress in place while the files go; then the page reads Install again.
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
val gone = StoresState.uninstalling["${store.id}:$id"]
if (gone != null) SecondaryButton(stringResource(R.string.stores_uninstalling), enabled = false, progress = gone) {}
@@ -106,6 +109,16 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) { com.droiddeck.launcher.stores.download.DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { com.droiddeck.launcher.stores.download.DownloadQueue.cancel(ctx, download.key) }
}
failedDownload != null -> {
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) {
if (item != null) StoresState.requestInstall(ctx, item)
else com.droiddeck.launcher.stores.download.DownloadQueue.retry(ctx, failedDownload.key)
}
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) {
com.droiddeck.launcher.stores.download.DownloadQueue.clear(ctx, failedDownload.key)
}
}
item?.owned == true && StoresState.isUnfinished(item) -> {
InstallButton(stringResource(R.string.stores_resume_install)) { StoresState.requestInstall(ctx, item) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
@@ -123,7 +136,6 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
}
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
if (store == Store.GOG || store == Store.EPIC) {
// An owned game resolves to its library entry; the storefront's copy of it may know more.
val listed = 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()
@@ -131,8 +143,6 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
val scores = rememberGameScores(title.takeIf { it != id })
Rise(2) { StoreGameFacts(developer, publisher, releaseDate, scores) }
}
// Plain text only, and nothing at all when the store sent a template key instead of words.
// A description that is only the title again (some stores fill it so) is no description.
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
if (description.isNotBlank()) Rise(3) {
@@ -149,10 +159,6 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
if (achievements != null) Rise(4) { StoreAchievementsSection(achievements) }
}
/**
* Uninstall that asks the way Cancel does: a confirm steps out of it, naming the game and what
* goes (its size on disk), with Keep first so a stray A does nothing.
*/
@Composable
private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.InstalledStoreGame, enabled: Boolean, onUninstall: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -165,8 +171,6 @@ private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.I
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
SecondaryButton(remove, enabled = enabled) {
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot() ?: return@SecondaryButton
// It starts once the confirm has folded back into the button: started at once, the button
// turned into the progress under the fold and it drew back into a control that had gone.
var confirmed = false
StoresMotion.ask(StepAsk(anchor = at, side = StepSide.Right, accent = colors.error, items = 3, pillCorner = 12.dp, maxWidth = 340.dp,
onDismiss = { if (confirmed) onUninstall() }, handle = {
@@ -183,10 +187,6 @@ private fun UninstallButton(title: String, game: com.droiddeck.launcher.stores.I
}
}
/**
* Install (or Resume install) that says where it sits when pressed: where to install grows out of
* it, and the download it starts leaves it as a dot for the Downloads chip.
*/
@Composable
private fun InstallButton(label: String, onInstall: () -> Unit) {
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
@@ -92,9 +92,7 @@ import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.formatSpeed
// The Downloads chip: one queue for the three stores, its settings and the engine log.
/** The queue. Its settings (speed tier, downloads at a time) live in the chip row's cog only. */
@Composable
internal fun StoresDownloadsPane(s: FrontEndState, a: FrontEndActions) {
DownloadList(s, a)
@@ -106,21 +104,12 @@ private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
val pal = LocalPalette.current
val scope = rememberCoroutineScope()
val entries = StoresState.downloads
// Clearing: the finished rows go into the divider's X one by one, bottom first, and only then
// leave the queue.
var clearing by remember { mutableStateOf(false) }
// Under way on top; finished below a line whose X clears them all (rows only - a failed
// download's kept files stay until its game page's Clear).
// Under way first, then paused, then the queue in its order: a queued row sat above the one running.
val (active, finished) = entries.partition { it.isActive }.let { (on, off) ->
on.sortedWith(compareBy<DownloadEntry>({ when (it.state) { DownloadState.RUNNING -> 0; DownloadState.PAUSED -> 1; else -> 2 } }, { it.queuePosition })) to off
}
val finishedShown = if (clearing) emptyList() else finished
// Installs that stopped without the queue knowing (the app closed or was killed): the queue
// lives in memory, so after a restart they were only on their game's page. They resume here too.
val queued = entries.mapTo(HashSet()) { it.key }
// Matched against each store's library: one not read yet (Downloads opened first) is read from
// its cache, quietly, so the rows are there without visiting the store.
val ctx = LocalContext.current
val missing = StoresState.unfinished.map { it.store }.filter { StoresState.library[it] == null }.toSet()
LaunchedEffect(missing) { missing.forEach { StoresState.backend(it)?.syncLibrary(ctx, false) } }
@@ -135,9 +124,6 @@ private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
Text(stringResource(R.string.stores_downloads_empty), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
}
// The list changes only when rows come, go or change state; each row reads its own progress.
// A row pours out of the count's side (the right), and leaves the way it came; one that
// installed stays a beat for its bar to gather into Play first.
AnimatedRows(
active, key = { it.key },
enter = { i, later ->
@@ -178,9 +164,7 @@ private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
}
AnimatedRows(
finishedShown, key = { it.key },
// One that just finished joins after its row above has gathered; the rest are simply there.
enter = { i, later -> if (later) expandVertically(Motion.tw(300, GATHER_HOLD_MS)) + fadeIn(Motion.tw(220, GATHER_HOLD_MS + 50)) else fadeIn(Motion.tw(300, 60 * i.coerceAtMost(5))) },
// Into the X at the top right, bottom row first.
exit = { _, i, n ->
val wait = 60 * (n - 1 - i).coerceIn(0, 8)
scaleOut(Motion.tw(220, wait), targetScale = 0.2f, transformOrigin = TransformOrigin(1f, 0f)) +
@@ -193,7 +177,6 @@ private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
}
}
/** An install that stopped before it finished, from an earlier run: Resume picks it up, Clear deletes what it had. */
@Composable
private fun InterruptedRow(item: com.droiddeck.launcher.stores.CatalogItem) {
val ctx = LocalContext.current
@@ -207,13 +190,8 @@ private fun InterruptedRow(item: com.droiddeck.launcher.stores.CatalogItem) {
}
}
/** How long a row that installed holds for its bar to gather into Play before it moves under the line. */
private const val GATHER_HOLD_MS = 900
/**
* A row in the download card's look, shorter: the game's art behind it under the same dark wash,
* the copy in white. Finished and interrupted downloads read as the same thing as one under way.
*/
@Composable
private fun ArtStrip(cover: String?, name: String, content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit) {
val pal = LocalPalette.current
@@ -228,7 +206,6 @@ private fun ArtStrip(cover: String?, name: String, content: @Composable androidx
}
}
/** A finished download: its name and store, and Play when it installed - blooming out of a dot when it just did. */
@Composable
private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions, bloom: Boolean = false) {
val ctx = LocalContext.current
@@ -243,7 +220,6 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions,
}
}
/** Grows out of a dot (sp 0.5 / 300) after [waitMs], when [on]; otherwise just there. */
private fun Modifier.bloomIn(on: Boolean, waitMs: Int): Modifier = composed {
val k = remember { Animatable(if (on && Motion.scale > 0f) 0f else 1f) }
LaunchedEffect(Unit) {
@@ -255,10 +231,6 @@ private fun Modifier.bloomIn(on: Boolean, waitMs: Int): Modifier = composed {
graphicsLayer { scaleX = k.value; scaleY = k.value; alpha = k.value.coerceIn(0f, 1f) }
}
/**
* A row's action as a round icon button - the label is its description - sized like the old
* compact buttons and focusable by pad. [primary] fills it with the accent, [danger] in red.
*/
@Composable
internal fun RoundAction(
icon: androidx.compose.ui.graphics.vector.ImageVector, description: String, primary: Boolean = false, danger: Boolean = false,
@@ -280,10 +252,6 @@ internal fun RoundAction(
) { androidx.compose.material3.Icon(icon, description, tint = tint, modifier = Modifier.size(size * 0.5f)) }
}
/**
* Cancel as End session's confirm: the X drops a pull and Keep and Delete step out to its left,
* in red. Keep's rim runs out the four seconds after which it folds back by itself.
*/
@Composable
private fun CancelAction(onDelete: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -299,7 +267,6 @@ private fun CancelAction(onDelete: () -> Unit) {
) {
val left = remember { Animatable(1f) }
LaunchedEffect(Unit) {
// Wall-clock seconds, as before; the rim follows them when animations run.
if (Motion.scale > 0f) launch { left.animateTo(0f, androidx.compose.animation.core.tween((CANCEL_HOLD_MS / Motion.scale).toInt(), easing = LinearEasing)) }
delay(CANCEL_HOLD_MS.toLong())
StoresMotion.fold()
@@ -315,7 +282,6 @@ private fun CancelAction(onDelete: () -> Unit) {
private const val CANCEL_HOLD_MS = 4000
/** A capsule's outline drawn for [left] (1 to 0) of its length, clockwise from the top centre: time running out. */
private fun Modifier.timeRim(left: () -> Float, color: Color): Modifier = drawWithContent {
drawContent()
val v = left()
@@ -339,12 +305,11 @@ private fun Modifier.timeRim(left: () -> Float, color: Color): Modifier = drawWi
@Composable
private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val ink = Color.White
val dim = Color.White.copy(alpha = 0.72f)
// The game's wide art is the row: cropped to it, a dark wash from the left so the copy reads
// in white there, the art clear on the right.
Box(Modifier.fillMaxWidth().heightIn(min = 88.dp).clip(Shape12).background(Color(0xFF101318)).border(1.dp, pal.line, Shape12)) {
if (!d.cover.isNullOrEmpty()) AsyncImage(model = d.cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
else Spacer(Modifier.matchParentSize().background(artBrush(hueOf(d.name))))
@@ -362,8 +327,11 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
val meta = when (d.state) {
DownloadState.INSTALLED -> stringResource(R.string.stores_installed_chip)
DownloadState.CANCELLED -> stringResource(R.string.stores_dl_cancelled)
// The reason is in the engine log; the row only says what is kept for Resume.
DownloadState.FAILED -> if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone)) else stringResource(R.string.stores_dl_failed)
DownloadState.FAILED -> {
if (!d.error.isNullOrBlank()) stringResource(R.string.stores_dl_failed_reason, d.error)
else if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone))
else stringResource(R.string.stores_dl_failed)
}
DownloadState.PAUSED -> stringResource(R.string.stores_dl_paused)
DownloadState.QUEUED -> if (d.queuePosition > 0) stringResource(R.string.stores_dl_queued_at, d.queuePosition) else stringResource(R.string.stores_dl_queued)
DownloadState.RUNNING -> {
@@ -375,14 +343,14 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
}
}
}
Text(meta, fontSize = 12.sp, color = dim, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
val metaColor = if (d.state == DownloadState.FAILED) colors.error else dim
Text(meta, fontSize = 12.sp, color = metaColor, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
if (d.state == DownloadState.RUNNING && (d.stage == DownloadStage.DOWNLOAD || d.stage == DownloadStage.INSTALL) && d.speedBps > 0) {
Text(formatSpeed(d.speedBps), fontSize = 12.sp, color = dim, maxLines = 1)
if (d.etaSeconds >= 0) Text(eta(d.etaSeconds), fontSize = 12.sp, color = dim, maxLines = 1)
}
}
}
// The row's actions on the right, over the art: icons, their labels as descriptions.
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
when (d.state) {
DownloadState.RUNNING, DownloadState.QUEUED -> {
@@ -393,8 +361,10 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
CancelAction { DownloadQueue.cancel(ctx, d.key) }
}
DownloadState.FAILED -> RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
// Just installed (this row is on its way under the line): Play blooms where the bar gathered.
DownloadState.FAILED -> {
RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
CancelAction { DownloadQueue.clear(ctx, d.key) }
}
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
}
@@ -405,13 +375,6 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
}
}
/**
* One segment per stage - Manifest, Download, Verify, Install - equal widths: a passed or skipped
* stage full, the active one filling with its own progress (a sliver while it has nothing to count),
* the rest empty. Fills ride a spring; a stage that completes swells and settles (the bloop); a
* paused one breathes; and once the download has installed the four gather into one green line
* that draws up into a dot, where Play blooms.
*/
@Composable
private fun StageBar(d: DownloadEntry) {
val pal = LocalPalette.current
@@ -422,8 +385,6 @@ private fun StageBar(d: DownloadEntry) {
val fills = stages.mapIndexed { i, st ->
when {
actives[i] -> d.stageFraction.let { if (it < 0f) 0.04f else it }
// A stage a store skips or folds into another (Epic checks chunks while it fetches,
// Amazon writes while it downloads) reads complete once a later one has started.
d.passed(st) || st.ordinal < d.stage.ordinal || d.stage == DownloadStage.DONE -> 1f
else -> 0f
}
@@ -452,7 +413,6 @@ private fun StageBar(d: DownloadEntry) {
val cy = size.height / 2f
val g = gather.value
if (g < 0.5f) {
// The segments: the gaps close and every fill turns done-green as the gather starts.
val join = (g * 2f).coerceIn(0f, 1f)
val gap = 3.dp.toPx() * (1f - join)
val segW = (size.width - gap * 3f) / 4f
@@ -460,6 +420,7 @@ private fun StageBar(d: DownloadEntry) {
val x = i * (segW + gap)
drawRoundRect(colors.surfaceVariant, Offset(x, cy - h / 2f), Size(segW, h), CornerRadius(h / 2f))
val base = when {
d.state == DownloadState.FAILED -> colors.error
done[i] -> pal.good
actives[i] && paused -> pausedColor.copy(alpha = breath)
actives[i] && stages[i] == DownloadStage.VERIFY -> verifyColor
@@ -472,7 +433,6 @@ private fun StageBar(d: DownloadEntry) {
)
}
} else {
// One line drawing up into a dot at its right end.
val p = ((g - 0.5f) * 2f).coerceIn(0f, 1f)
val dot = 10.dp.toPx()
val left = androidx.compose.ui.util.lerp(0f, size.width - dot, p)
@@ -482,7 +442,6 @@ private fun StageBar(d: DownloadEntry) {
}
}
/** 1, or while [on] (and animations run), an alpha going 1 → 0.5 → 1 over the rail's live-dot period. */
@Composable
private fun breathing(on: Boolean): Float {
if (!on || Motion.scale == 0f) return 1f
@@ -497,10 +456,6 @@ private fun eta(seconds: Long): String = when {
else -> "~${seconds / 3600} h ${(seconds % 3600) / 60} m"
}
/**
* The queue's two knobs on one line - the speed tier on the left, downloads at a time on the
* right; it sits in the cog's popup. A narrow page puts them on two tight lines.
*/
@Composable
internal fun DownloadControls(s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
@@ -524,12 +479,6 @@ internal fun DownloadControls(s: FrontEndState, a: FrontEndActions) {
}
}
/**
* The chip row's cog: the section's own settings stepped out of it - which tab a store opens on,
* mature titles, the speed tier and how many at once, and the download engine. Their only home;
* Setup no longer repeats them. Every install is added to Steam; that is not a choice. [s] is
* read live, so a change shows at once in what is stepped out.
*/
internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<FrontEndState>, a: FrontEndActions, accent: androidx.compose.ui.graphics.Color): StepAsk =
StepAsk(
anchor = at, side = StepSide.Left, accent = accent, items = 2, maxWidth = 440.dp,
@@ -541,7 +490,6 @@ internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State<Fron
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
val st = s.value
// No OK: B or a tap outside folds it, and a pad starts on the first choice.
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)),
@@ -551,7 +499,6 @@ 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) }
}
// The queue's two knobs as one compact row, the same control the Downloads page has.
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { DownloadControls(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)) }
@@ -40,11 +40,6 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.formatBytes
/**
* "Install <game>:" over one row per place - internal storage, the card - each the action
* itself: icon, name, free space. Asked only when a card is there. The row picked last time
* starts focused, so a pad confirms the usual place with one press; nothing is chosen for the user.
*/
@Composable
internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
val ctx = LocalContext.current
@@ -72,10 +67,21 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
Rise(1) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
targets.forEachIndexed { i, t ->
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
val freeBytes = t.freeBytes
val isLow = com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, freeBytes)
val freeText = if (freeBytes < 0L) {
stringResource(R.string.stores_target_free_unknown)
} else if (isLow) {
stringResource(R.string.stores_storage_low, formatBytes(freeBytes), formatBytes(needed))
} else {
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
}
TargetRow(
label = if (t.removable) t.label else stringResource(R.string.stores_target_internal),
free = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
free = freeText,
removable = t.removable, focus = focus[i],
warning = isLow,
) {
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
StoresState.install(ctx, item, t.root)
@@ -88,7 +94,7 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
}
@Composable
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, onPick: () -> Unit) {
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, warning: Boolean = false, onPick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
@@ -104,6 +110,6 @@ private fun TargetRow(label: String, free: String, removable: Boolean, focus: Fo
) {
Icon(if (removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(22.dp))
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(free, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
Text(free, fontSize = 12.sp, color = if (warning) colors.error else colors.onSurfaceVariant, maxLines = 1)
}
}
@@ -47,13 +47,8 @@ import kotlin.math.atan2
import kotlin.math.max
import kotlin.math.sin
// The Stores section's moves, in the launcher's own vocabulary: an install bloops into a dot that
// flies to the Downloads chip, sign-in floods in the store's colour and comes home to the chip's
// dot, and the confirms step out of the control that asked (StepOut). Everything here is in root
// coordinates; the Stores page draws it in its own space.
internal object StoresMotion {
/** The Install (or Resume install) button last pressed, its label and when: a download that starts soon after flies from it. */
var installFrom: Rect? = null
private set
var installLabel: String = ""
@@ -66,28 +61,21 @@ internal object StoresMotion {
installAt = SystemClock.uptimeMillis()
}
/** The button just pressed, if it was pressed in the last few seconds; not consumed. */
fun recentInstall(): Rect? = installFrom.takeIf { SystemClock.uptimeMillis() - installAt < 5_000 }
/** The button a download that just started came from, once; stale after 20 s (a slow manifest). */
fun takeInstall(): Rect? = installFrom.takeIf { SystemClock.uptimeMillis() - installAt < 20_000 }.also { installAt = 0L }
/** Where the Downloads chip sits, for a download's dot to land in. */
var downloadsChip by mutableStateOf<Rect?>(null)
/** Bumped each time a dot lands: the chip's count and the rail's badge pop on it. */
var landed by mutableIntStateOf(0)
/** Dots in flight to the Downloads chip. */
val flights = mutableStateListOf<Flight>()
fun fly(from: Rect) {
if (Motion.scale == 0f || downloadsChip == null) { landed++; return }
// The count sits at the chip's right end.
flights += Flight(from, to = { downloadsChip?.let { Offset(it.right - 22.dp.toPx(), it.center.y) } }, onLand = { landed++ })
}
/** The confirm or list stepping out of a control on the Stores page now, and whether it is open. */
var step by mutableStateOf<StepAsk?>(null)
private set
var stepOpen by mutableStateOf(false)
@@ -99,14 +87,12 @@ internal object StoresMotion {
stepOpen = true
}
/** Drops whatever is stepped out or flooding, at once: the page it belonged to has gone. */
fun drop() {
step?.let { step = null; it.onDismiss() }
stepOpen = false
signIn = null
}
/** Folds the current one back into its control. */
fun fold() { stepOpen = false }
internal fun closed(a: StepAsk) {
@@ -114,24 +100,18 @@ internal object StoresMotion {
a.onDismiss()
}
/** A store's sign-in flooding the page, or draining back out of it. */
var signIn by mutableStateOf<SignInFlood?>(null)
/** Per store, bumped to send its chip's dot one pulse ring (signed in, picked). */
val pulses = androidx.compose.runtime.mutableStateMapOf<Store, Int>()
fun pulse(store: Store) { pulses[store] = (pulses[store] ?: 0) + 1 }
/** Where each store's dot sits on its chip, for a sign-in to come home to. */
val dots = HashMap<Store, Rect>()
/** Where the open game page's hero art sits (root px): what a card's flood lands on, and leaves from. */
var heroAt by mutableStateOf<Rect?>(null)
/** The open game page came out of a card: its hero holds still, for the card's flood to land on. */
var heroLands by mutableStateOf(false)
/** The card a game page is about to open from. */
private var card: CardMark? = null
private var cardAt = 0L
@@ -140,17 +120,11 @@ internal object StoresMotion {
cardAt = SystemClock.uptimeMillis()
}
/** The card game [key] was just opened from, once; a page opened another way shows without a flood. */
fun takeCard(key: String): CardMark? = card?.takeIf { it.key == key && SystemClock.uptimeMillis() - cardAt < 1_000 }.also { card = null }
}
/** A game card at [bounds] (root px) with corner [corner] (px) and its art, for the page it opens to flood out of. */
internal class CardMark(val key: String, val bounds: Rect, val corner: Float, val art: String?)
/**
* A confirm or short list for [StepOut] on the Stores page, asked by a control that sits at [anchor]
* (root px). [content] gets a close that folds it; [onDismiss] runs once it has folded, however.
*/
internal class StepAsk(
val anchor: Rect,
val side: StepSide,
@@ -164,22 +138,15 @@ internal class StepAsk(
)
internal class SignInFlood(val store: Store, val from: Rect, val start: Color, val color: Color) {
/** Covered and handed to the login page; waiting for the page to come back. */
var away by mutableStateOf(false)
/** Back from the login page: draining into [to]. */
var drainTo by mutableStateOf<Rect?>(null)
}
/** The dots flying to the Downloads chip, drawn over the page whose root offset is [origin]. */
@Composable
internal fun FlightLayer(origin: Offset) {
for (f in StoresMotion.flights.toList()) key(f.id) { FlightDot(f, origin) { StoresMotion.flights.remove(f) } }
}
/**
* Pops (1.3 to 1, with one ring) each time [trigger] changes: by default each time a download's
* dot lands, for the count on the chip and the rail; any other landing passes its own count.
*/
internal fun Modifier.landingPop(trigger: Int = StoresMotion.landed): Modifier = composed {
val pal = LocalPalette.current
val scale = remember { Animatable(1f) }
@@ -201,11 +168,6 @@ internal fun Modifier.landingPop(trigger: Int = StoresMotion.landed): Modifier =
}.graphicsLayer { scaleX = scale.value; scaleY = scale.value }
}
/**
* A pressed button in [start] stretching out over this element in [color] (LaunchFlood's move:
* each edge on its own loose spring, the furthest first, blobby in flight). [from] is in this
* element's px. Calls [onCovered] once, when nothing but [color] shows; then holds.
*/
@Composable
internal fun ColorFlood(from: Rect, start: Color, color: Color, onCovered: () -> Unit) {
val edges = remember { List(4) { Animatable(0f) } }
@@ -220,7 +182,6 @@ internal fun ColorFlood(from: Rect, start: Color, color: Color, onCovered: () ->
val lead = travel[i] / far
launch {
delay(Motion.ms((120 * (1f - lead)).toInt()).toLong())
// Overshoots past the edge, off the element, so the wobble is felt in the pull.
edge.animateTo(1f, if (Motion.scale == 0f) Motion.sp() else spring(dampingRatio = 0.48f, stiffness = lerp(110f, 190f, lead))) {
if (value >= 1f) reached[i] = true
}
@@ -237,10 +198,6 @@ internal fun ColorFlood(from: Rect, start: Color, color: Color, onCovered: () ->
}
}
/**
* [color] over the whole element drawing down into [to] (px, here), critically damped, the near
* edges first (PageFlood's way back), then fading out on it; [onDone] after.
*/
@Composable
internal fun ColorDrain(color: Color, to: Rect, toCorner: Float, onDone: () -> Unit) {
val edges = remember { List(4) { Animatable(1f) } }
@@ -270,7 +227,6 @@ internal fun ColorDrain(color: Color, to: Rect, toCorner: Float, onDone: () -> U
private fun Modifier.onSizeChangedCompat(onSize: (Size) -> Unit) =
onSizeChanged { onSize(Size(it.width.toFloat(), it.height.toFloat())) }
/** A rect from [r] with its edges [v] of the way to this scope's (left, top, right, bottom): blobby in flight. */
private fun DrawScope.drawFloodShape(r: Rect, restCorner: Float, v: List<Float>, color: Color) {
val left = lerp(r.left, 0f, v[0])
val top = lerp(r.top, 0f, v[1])
@@ -284,7 +240,6 @@ private fun DrawScope.drawFloodShape(r: Rect, restCorner: Float, v: List<Float>,
drawRoundRect(color, Offset(left, top), Size(w, h), CornerRadius(corner))
}
/** Sends one pulse ring out of a dot each time [trigger] changes after the first composition. */
internal fun Modifier.pulseRing(trigger: Int, color: Color): Modifier = composed {
val ring = remember { Animatable(1f) }
val seen = remember { intArrayOf(trigger) }
@@ -303,11 +258,6 @@ internal fun Modifier.pulseRing(trigger: Int, color: Color): Modifier = composed
}
}
/**
* [items] in a column where a row that comes enters with [enter] and a row that goes stays on to
* leave with [exit] (a Column has no item animations of its own). [content] gets the row and
* whether it came after the list was first shown.
*/
@Composable
internal fun <T> AnimatedRows(
items: List<T>,
@@ -322,7 +272,6 @@ internal fun <T> AnimatedRows(
val later = remember { mutableMapOf<Any, Boolean>() }
val mounted = remember { booleanArrayOf(false) }
val now = items.associateBy(key)
// Keep a leaving row where it was among the ones that stay.
val merged = ArrayList<Any>()
var j = 0
for (k in now.keys) {
@@ -133,24 +133,15 @@ import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
// The Stores section: GOG, Epic Games and Amazon Games libraries and storefronts, and one
// download queue for the three, in a single full-width pane.
/** The chip row's fourth entry, beside the three stores. */
private const val DOWNLOADS = "downloads"
private val TABS = listOf("store", "library", "installed")
/**
* The modes a store has, picked from its chip (A steps them out of it) or cycled with LB / RB:
* Store, Library and Installed. Amazon has no public catalog, so no Store.
*/
internal fun tabsFor(store: Store?): List<String> = if (store == Store.AMAZON) TABS.drop(1) else TABS
/** [tab] if [store] has it, else Library (the open-on Store choice on Amazon falls back there). */
internal fun tabFor(store: Store?, tab: String): String = if (tab in tabsFor(store)) tab else "library"
/** What the pane under the chips shows: a store's tab (signed in or not) or the downloads. */
private data class PaneKey(val chip: String, val tab: String, val signedIn: Boolean)
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class, androidx.compose.animation.ExperimentalAnimationApi::class)
@@ -164,26 +155,18 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
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) }
// The cog's settings read the front end's state live while stepped out.
val liveState = androidx.compose.runtime.rememberUpdatedState(s)
LaunchedEffect(StoresState.openDownloads) { if (StoresState.openDownloads) { chip = DOWNLOADS; StoresState.openDownloads = false } }
val store = Store.byId(chip)
// A tab this store does not have (Store or All on Amazon) reads as Library.
val shownTab = tabFor(store, tab)
val pane = PaneKey(
chip, if (store == null) "" else shownTab,
store == null || (StoresState.isSignedIn(store) && StoresState.expired[store] != true),
)
// Incoming and outgoing panes must not share a scroll state while both are on screen.
val grids = remember { HashMap<PaneKey, LazyGridState>() }
val grid = grids.getOrPut(pane) { LazyGridState() }
LaunchedEffect(Unit) { StoresState.refresh(ctx) }
// A store the account is signed into fills itself when its chip is on screen.
LaunchedEffect(chip, StoresState.accounts[store]) { if (store != null && StoresState.isSignedIn(store)) StoresState.open(ctx, store) }
// A pad's focus sits on something the page is about to replace - the card that opens a game,
// a tab's contents - and would be lost with it, leaving the next press to land on the rail.
// Each move says where focus goes next: into the game page's main action, back to the card
// it was opened from, or onto the first card of a tab or store just picked.
val ff = LocalFrontFocus.current
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
var focusMove by remember { mutableStateOf<Pair<String, Int>?>(null) }
@@ -192,15 +175,11 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
fun open(key: String) { lastOpened = key; openGame = key; move("detail") }
fun closeGame() { openGame = null; move("card") }
fun switchTab(to: String) { tab = to; move("first") }
// Picking a chip opens the tab Setup says (Library or Store); a tab the user switches to
// afterwards stays until another chip is picked.
val pickChip: (String) -> Unit = { id ->
chip = id; openGame = null; query = ""
if (id != DOWNLOADS) tab = tabFor(Store.byId(id), if (s.storesOpenTab == SessionPrefs.STORES_OPEN_STORE) "store" else "library")
move("first")
}
// A pad moving along the chips shows each store it stops on, without A: a beat after it
// settles, so sweeping past two chips does not open both. Focus stays on the chip.
var focusedChip by remember { mutableStateOf<String?>(null) }
LaunchedEffect(focusedChip) {
val id = focusedChip ?: return@LaunchedEffect
@@ -210,20 +189,15 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
if (id != DOWNLOADS) tab = tabFor(Store.byId(id), if (s.storesOpenTab == SessionPrefs.STORES_OPEN_STORE) "store" else "library")
}
}
// A store's chip steps its modes out of itself (End session's shape, in the store's colour);
// picking one shows that store in it. A store not signed in has none: its chip just opens it.
val pal = LocalPalette.current
fun openModes(st: Store, at: Rect?) {
// Another store's chip (a tap; a pad's focus has already shown it): that store.
if (chip != st.id) { pickChip(st.id); return }
// Not signed in: nothing to pick, so A goes on to its Sign in.
if (at == null || !StoresState.isSignedIn(st) || StoresState.expired[st] == true) { move("first"); return }
val modes = tabsFor(st)
val current = if (chip == st.id) shownTab else null
var picked = false
StoresMotion.ask(StepAsk(
anchor = at, side = StepSide.Right, accent = storePalette(pal, st).signal, items = modes.size,
// Folded: focus goes to the first card of what was picked, or back to the chip.
onDismiss = { move(if (picked) "first" else "item:storechip:${st.id}") },
handle = { ChipLabel(st, MaterialTheme.colorScheme.onBackground) },
) {
@@ -255,17 +229,10 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
BackHandler(enabled = openGame != null) { closeGame() }
val scroll = rememberScrollState()
val detailScroll = rememberScrollState()
// A store or tab just picked starts at the top. Closing a game page leaves the grid where it
// was, so the page draws back into the card it came from and focus lands on it.
LaunchedEffect(chip, tab) { scroll.scrollTo(0); grid.scrollToItem(0) }
LaunchedEffect(openGame) { detailScroll.scrollTo(0) }
LaunchedEffect(focusMove, openGame) {
if (inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard || ff == null) return@LaunchedEffect
// Looked up each frame, and asked again until focus is really there: what it goes to (the
// game page's action, the card under it) is composed and placed a frame or two after the
// move that asks for it, and a request before then is dropped without a word.
// A mode with nothing in it (Installed, none installed) has no first card: after a few
// frames focus goes to the store's chip rather than falling back to the rail.
var frames = 0
fun attached(id: String) = (ff.attached[id] ?: 0) > 0
fun target(): Pair<androidx.compose.ui.focus.FocusRequester, String?>? {
@@ -276,15 +243,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
kind == "card" -> lastOpened?.let { "card:$it" }?.let { id -> ff.items[id]?.takeIf { attached(id) }?.let { it to id } }
?: ff.firstTile.takeIf { ff.firstTileAttached > 0 }?.let { it to null }
kind == "first" -> ff.firstTile.takeIf { ff.firstTileAttached > 0 }?.let { it to null }
// A store not signed in: its Sign in.
?: ff.primary.takeIf { ff.primaryAttached > 0 }?.let { it to FrontFocus.PRIMARY }
?: "storechip:$chip".let { id -> ff.items[id]?.takeIf { ++frames > 12 && attached(id) }?.let { it to id } }
kind?.startsWith("item:") == true -> kind.removePrefix("item:").let { id -> ff.items[id]?.takeIf { attached(id) }?.let { it to id } }
else -> null
}
}
// The press that asked for this move must not land on where focus goes: its release
// would press that too (A on a chip went on to Sign in). Wait for A to come up.
repeat(60) { if (!HeldKeys.confirm) return@repeat; androidx.compose.runtime.withFrameNanos { } }
repeat(45) {
androidx.compose.runtime.withFrameNanos { }
@@ -294,9 +258,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
}
}
// The game page is a layer over the grid: it floods out of the card it was opened from (the
// cog's PageFlood, carrying the card's art), and Back draws it into that card again. [detail]
// outlives [openGame] while it draws back.
var detail by remember { mutableStateOf<String?>(null) }
var leaving by remember { mutableStateOf(false) }
var detailFrom by remember { mutableStateOf<Origin?>(null) }
@@ -337,9 +298,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
onNext = { if (openGame == null && chip != DOWNLOADS) { val t = tabsFor(store); switchTab(t[(t.indexOf(shownTab) + 1) % t.size]) } },
),
) {
// The chip row stays put and paints nothing - the page's background shows through it. What
// scrolls is clipped at the row's lower edge and, once scrolled, faded out there: the
// content's own alpha, not a colour laid over it.
Box(Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
StoreTheme(Store.byId(focusedChip ?: chip)) {
Rise(0) { StoreChips(chip, focusedChip, s.storeDownloadsActive, onStore = { st, at -> openModes(st, at) }, onDownloads = { if (chip != DOWNLOADS) pickChip(DOWNLOADS) else move("first") },
@@ -362,16 +320,11 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
)
},
) {
// Under a game page the grid stays composed - its scroll and the card to come back to
// stay put - but sinks away, and a pad can neither reach it nor be sent to it. Once the
// page starts drawing back the grid takes focus again, so it lands on the card at once.
val gridFocus = if (covering) null else ff
CompositionLocalProvider(LocalFrontFocus provides gridFocus) {
Column(
modifier = Modifier.fillMaxSize()
.graphicsLayer { scaleX = gridScale; scaleY = gridScale; alpha = gridAlpha }
// Always the same group, only its rule changes: a focus group added around
// the card that has focus leaves the focus tree refusing every request after.
.focusProperties { enter = { if (coveringNow.value) androidx.compose.ui.focus.FocusRequester.Cancel else androidx.compose.ui.focus.FocusRequester.Default } }
.focusGroup(),
) {
@@ -381,29 +334,20 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
transitionSpec = {
val sameStore = initialState.chip == targetState.chip && initialState.signedIn == targetState.signedIn
(if (sameStore && initialState.tab != targetState.tab) {
// LB / RB: the tab's contents leave the way the bumper points and the
// next tab's come in from the other side, the column nearest leading.
val dir = if (TABS.indexOf(targetState.tab) > TABS.indexOf(initialState.tab)) 1 else -1
(slideInHorizontally(Motion.sp(0.7f, Spring.StiffnessMediumLow)) { it / 6 * dir } + fadeIn(Motion.tw(220, 60)))
.togetherWith(slideOutHorizontally(Motion.tw(170)) { -it / 6 * dir } + fadeOut(Motion.tw(170)) + scaleOut(Motion.tw(170), targetScale = 0.97f))
} else {
// Another store: the shelf sinks away, the next rises in (the pane's own move).
(fadeIn(Motion.tw(300, 80)) + slideInVertically(Motion.tw(420, 80)) { it / 24 })
.togetherWith(fadeOut(Motion.tw(170)) + scaleOut(Motion.tw(170), targetScale = 0.97f))
}).using(SizeTransform(clip = false))
},
label = "storesPane",
) { k ->
// What is leaving is not where a pad's next move should land.
val outgoing = transition.targetState == androidx.compose.animation.EnterExitState.PostExit
CompositionLocalProvider(LocalFrontFocus provides if (outgoing) null else LocalFrontFocus.current) {
// AnimatedContent stacks its child in a Box: the pane's rows need their own column.
// A pad moving while the pane changes must land on what is coming, not on
// what is leaving: focus there vanishes with it. Same group always, only
// its rule changes (adding one around focus breaks the focus tree).
val leavingNow = androidx.compose.runtime.rememberUpdatedState(outgoing)
val st = Store.byId(k.chip)
// Keep the outgoing pane's palette stable while the next store comes in.
StoreTheme(st) {
Column(
Modifier.fillMaxSize()
@@ -413,7 +357,6 @@ 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 -> {}
// Signed out, or a sign-in that ran out (a launch could not get its code): sign in again.
!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) })
}
@@ -427,9 +370,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
val detailStore = Store.byId(key.substringBefore(':')) ?: store
StoreTheme(detailStore) {
val body: @Composable () -> Unit = {
// One focus group, so the pad walks the page's own controls - back, the hero's
// actions - and reaches the rail only with Left from them. It takes every touch,
// so nothing reaches the grid under it.
Column(
Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { } }
.verticalScroll(detailScroll).padding(top = 4.dp, bottom = 16.dp),
@@ -440,9 +380,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
val from = detailFrom
if (from == null) body()
else {
// Sized up front: the flood draws the art only once it knows its size, and a painter
// left to take its size from drawing would never load. The card's own bitmap stands
// in from the memory cache until the full one is decoded.
val art = detailArt?.let { url ->
coil.compose.rememberAsyncImagePainter(
remember(url) {
@@ -451,16 +388,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
},
)
}
// Onto the page's own hero art, not the whole pane: grown to the pane, the art
// then cut down to the hero's banner (and back out to the pane to close).
PageFlood(from, leaving, art, onto = { StoresMotion.heroAt }, ontoCorner = 16.dp) { body() }
}
}
}
}
}
// Over the whole page: an install's dot on its way to Downloads, a confirm stepping out of the
// control that asked for it, and a sign-in's flood.
FlightLayer(hostAt)
StoresMotion.step?.let { ask ->
key(ask) {
@@ -473,9 +406,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
}
SignInFloodLayer(hostAt)
}
// Leaving the section: nothing stays stepped out of a control that is no longer on screen.
androidx.compose.runtime.DisposableEffect(Unit) { onDispose { StoresMotion.drop() } }
// An install that started from a button here flies from it to the Downloads chip.
val activeKeys = StoresState.downloads.filter { it.isActive }.map { it.key }.toSet()
val seenActive = remember { mutableSetOf<String>().also { it.addAll(activeKeys) } }
LaunchedEffect(activeKeys) {
@@ -486,10 +417,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
StoresState.pendingInstall?.let { item -> InstallWhere(item) }
}
/**
* "Install <game>:" with a row per place, grown out of the Install button that asked (End
* session's step-out, in blue); the plain dialog when that button is not on screen.
*/
@Composable
private fun InstallWhere(item: CatalogItem) {
val ctx = LocalContext.current
@@ -511,15 +438,24 @@ private fun InstallWhere(item: CatalogItem) {
StepTitle(title)
StepList {
targets.forEachIndexed { i, t ->
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
val freeBytes = t.freeBytes
val isLow = com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, freeBytes)
val trailingText = if (freeBytes < 0L) {
stringResource(R.string.stores_target_free_unknown)
} else if (isLow) {
stringResource(R.string.stores_storage_low, formatBytes(freeBytes), formatBytes(needed))
} else {
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
}
StepChoice(
label = if (t.removable) t.label else internalLabel,
icon = if (t.removable) androidx.compose.material.icons.Icons.Outlined.SdCard else androidx.compose.material.icons.Icons.Outlined.Smartphone,
trailing = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
trailing = trailingText,
enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(1 + i).then(if (i == defaultIndex) Modifier.focusRequester(first) else Modifier),
) {
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
// The fold and the dot leave together: the download it starts flies from Install.
StoresMotion.markInstall(from, label)
StoresState.install(ctx, item, t.root)
StoresMotion.fold()
@@ -530,7 +466,6 @@ private fun InstallWhere(item: CatalogItem) {
}
}
/** A sign-in's flood: out of the button in the store's colour, and home again once the login page closes. */
@Composable
private fun SignInFloodLayer(hostAt: Offset) {
val f = StoresMotion.signIn ?: return
@@ -539,7 +474,6 @@ private fun SignInFloodLayer(hostAt: Offset) {
val density = androidx.compose.ui.platform.LocalDensity.current
key(f) {
var paused by remember { mutableStateOf(false) }
// Signed in: into the store's dot on its chip. Not (closed, or it failed): back into the button.
fun back() { if (f.drainTo == null) f.drainTo = if (StoresState.isSignedIn(f.store)) StoresMotion.dots[f.store] ?: f.from else f.from }
androidx.compose.runtime.DisposableEffect(lifecycle) {
val obs = androidx.lifecycle.LifecycleEventObserver { _, e ->
@@ -549,7 +483,6 @@ private fun SignInFloodLayer(hostAt: Offset) {
lifecycle.addObserver(obs)
onDispose { lifecycle.removeObserver(obs) }
}
// The store had no login page to open: nothing will come back, so drain now.
LaunchedEffect(f.away) { if (f.away) { delay(1_500); if (!paused) back() } }
val to = f.drainTo
if (to == null) ColorFlood(f.from.translate(-hostAt), f.start, f.color) {
@@ -568,27 +501,17 @@ private fun SignInFloodLayer(hostAt: Offset) {
}
}
// ---- the chip row -------------------------------------------------------------------------------
/**
* Four equal chips - the stores with a signed-in dot, Downloads with its count - and the cog. The
* selection is one shape that belongs to the row, not each chip's background: it glides from chip
* to chip like the focus ring, its leading edge first, tinted in the store's colour, and a hop
* past a chip goes as a drop.
*/
@Composable
private fun StoreChips(
selected: String, focused: String?, active: Int, onStore: (Store, Rect?) -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit,
/** The chip a pad's focus is on (null when it leaves the row): the page shows that store. */
onFocusChip: (String?) -> Unit,
) {
val pal = LocalPalette.current
val keys = Store.entries.map { it.id } + DOWNLOADS
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, Rect>() }
val rootBounds = remember { HashMap<String, Rect>() }
// The fill travels with focus; only the expensive pane change waits for the debounce.
val highlighted = focused ?: selected
// With a pad the row has no fill of its own: the focus ring's infill is the only one.
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode
val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard
val tint = androidx.compose.animation.animateColorAsState(
@@ -603,7 +526,6 @@ private fun StoreChips(
modifier = Modifier.weight(1f).onGloballyPositioned { bounds[store.id] = it.boundsInParent(); rootBounds[store.id] = it.boundsInRoot() },
lead = {
val c = sourceColours(store.id)
// A store's dot pulses when a sign-in lands (and, with the chip's lead, when picked).
Box(
Modifier.size(12.dp)
.onGloballyPositioned { StoresMotion.dots[store] = it.boundsInRoot() }
@@ -629,7 +551,6 @@ private fun StoreChips(
IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) }
}
}
// Over the chips: the fill is translucent, and the other chips' rest fill would hide it in flight.
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
}
@@ -649,15 +570,12 @@ private fun StoreChip(
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "chipScale")
val shape = RoundedCornerShape(99.dp)
val ink = if (on) colors.onBackground else if (hot) colors.onBackground else colors.onSurfaceVariant
// The chip whose page shows has a bar of its colour along its foot. Picking it pulses its
// lead (a store's dot, Downloads' icon).
var picked by remember { mutableStateOf(0) }
val wasOn = remember { booleanArrayOf(on) }
LaunchedEffect(on) {
if (on && !wasOn[0]) picked++
wasOn[0] = on
}
// The row's glide draws the look of the chip [under] it, so that one draws no rest state of its own.
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
modifier = modifier.paneItem("storechip:$key")
@@ -682,7 +600,6 @@ private fun StoreChip(
}
}
/** The chip row's cog: icon only, the chips' height; opens the section's settings. */
@Composable
private fun IconChip(icon: androidx.compose.ui.graphics.vector.ImageVector, description: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -703,18 +620,11 @@ internal fun CountPill(count: Int) {
val pal = LocalPalette.current
Text(
count.toString(), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = pal.onSignal, maxLines = 1,
// Pops as an install's dot lands in it.
modifier = Modifier.landingPop().clip(RoundedCornerShape(8.dp)).background(pal.signal).padding(horizontal = 6.dp, vertical = 1.dp),
)
}
// ---- sign-in -----------------------------------------------------------------------------------
/**
* No account for this store yet: the Steam tab's shape in the store's colour. A tilted wall of the
* store's own games drifts behind (its public storefront; blank capsules in its colour when it has
* none), fading out toward the words, and Sign in sits large at the foot. [height] is the pane's.
*/
@Composable
private fun SignInCard(store: Store, height: Dp) {
val ctx = LocalContext.current
@@ -722,9 +632,7 @@ private fun SignInCard(store: Store, height: Dp) {
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val c = sourceColours(store.id)
// The storefront needs no account; it is what the wall is made of.
LaunchedEffect(store) { StoresState.preview(ctx, store) }
// A handful of games would repeat down every column: under eight, the blank wall in its colour.
val art = remember(StoresState.shelves[store]) {
StoresState.shelves[store]?.all.orEmpty().filter { !it.mature }.mapNotNull { it.tallImageUrl ?: it.imageUrl }.distinct().take(48)
.takeIf { it.size >= 8 }.orEmpty()
@@ -733,11 +641,9 @@ private fun SignInCard(store: Store, height: Dp) {
val blank = WallCapsule(Brush.linearGradient(listOf(c.fill, colors.background)), edge = c.dot.copy(alpha = 0.22f))
val ground = SolidColor(c.fill)
Box(Modifier.fillMaxWidth().heightIn(min = height.coerceAtLeast(0.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) {
// The storefront arrives a moment after the page: its wall fades in over the blank one.
androidx.compose.animation.Crossfade(art, animationSpec = Motion.tw(600), label = "signInWall", modifier = Modifier.matchParentSize()) { tiles ->
TiltedWall(tiles.size, if (tiles.isEmpty()) 75_000 else 50_000) { i -> if (tiles.isEmpty()) blank else WallCapsule(ground, tiles[i]) }
}
// The wall gives way to the words: dark at the left and the foot, and the store's glow under them.
Box(
Modifier.matchParentSize().background(
Brush.horizontalGradient(
@@ -768,10 +674,6 @@ private fun SignInCard(store: Store, height: Dp) {
}
}
/**
* Sign in: the button floods the page in the store's colour (LaunchFlood's move), the login page
* opens on that colour, and the flood comes home into the store's dot once it closes.
*/
@Composable
private fun SignInButton(store: Store, large: Boolean = false) {
val ctx = LocalContext.current
@@ -786,7 +688,6 @@ private fun SignInButton(store: Store, large: Boolean = false) {
}
}
/** A square in the store's colour with its name on it: the stores ship no logo this app may bundle. */
@Composable
internal fun StoreLogo(store: Store, size: Dp) {
val c = sourceColours(store.id)
@@ -795,7 +696,6 @@ internal fun StoreLogo(store: Store, size: Dp) {
}
}
// ---- storefront --------------------------------------------------------------------------------
@Composable
private fun Storefront(
@@ -807,19 +707,14 @@ private fun Storefront(
val colors = MaterialTheme.colorScheme
val library = StoresState.library[store] ?: emptyList()
val shelves = StoresState.shelves[store]
// The Installed tab, its count and every card's installed mark come from the installs on disk.
val installedItems = remember(StoresState.installed, library) { com.droiddeck.launcher.stores.installedCards(store, StoresState.installed, library) }
val installedKeys = remember(installedItems) { installedItems.map { it.id }.toSet() + StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id } }
val q = query.trim().lowercase()
fun matches(i: CatalogItem) = q.isEmpty() || i.title.lowercase().contains(q)
// The storefront leaves out what the store rates or tags as adult unless the user shows it; owned games always show.
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.owned
fun shelf(l: List<CatalogItem>?) = l?.filter(::shown)
// The Store tab's search: the catalog the shelves brought and the library, each title once.
val everything = remember(library, shelves) { (library + (shelves?.all ?: emptyList())).distinctBy { it.id } }
// Installed is a mode of its own now, picked from the store's chip like Store and Library.
val installedOnly = tab == "installed"
// Until the cache is read (a moment, off the main thread) there is nothing to count or to say is missing.
val loaded = StoresState.library.containsKey(store)
val showGrid = tab != "store" || q.isNotEmpty()
val visible = remember(library, installedItems, everything, tab, q, s.storesShowMature) {
@@ -834,8 +729,6 @@ private fun Storefront(
tab == "library" && library.isEmpty() && StoresState.status[store] != null -> R.string.stores_library_loading
else -> R.string.stores_nothing_matches
})
// A lazy item can be recomposed or prefetched out of order; the first grid card is identified
// by its key, rather than whichever happens to compose first.
var firstPlaced = false
var columns by remember { mutableIntStateOf(1) }
val density = androidx.compose.ui.platform.LocalDensity.current
@@ -856,12 +749,11 @@ private fun Storefront(
val next = storeGridNeighbor(index, visible.size, columns, direction)
when {
direction == 0 || index < 0 -> false
next == null -> direction > 0 // The last row stays in its column; Up can reach the header.
next == null -> direction > 0
else -> {
if (key.action == KeyEvent.ACTION_DOWN) {
val target = "card:${visible[next].key}"
val targetIndex = headerItems + next
// Prefetched cards can accept focus without being on screen.
val visibleTarget = grid.layoutInfo.visibleItemsInfo.any { it.index == targetIndex }
if (!visibleTarget || (focus.attached[target] ?: 0) == 0 ||
runCatching { focus.items.getValue(target).requestFocus() }.isFailure) scope.launch {
@@ -900,7 +792,6 @@ private fun Storefront(
else -> stringResource(R.string.stores_search_library)
},
) {
// A purchase made elsewhere shows on a refresh; otherwise the library refreshes itself every six hours.
SmallTextButton(stringResource(R.string.stores_refresh)) { StoresState.open(ctx, store, force = true) }
val name = StoresState.accounts[store] ?: ""
SignOutButton(store, name)
@@ -932,15 +823,10 @@ private fun Storefront(
}
}
/**
* What the store is showing (Store, Library, Installed), a magnifier beside it that opens into the
* search field across the row, and [trailing] (the account) at the right, over a rule.
*/
@Composable
internal fun ModeHeader(title: String, query: String, onQuery: (String) -> Unit, placeholder: String, trailing: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
// Open while it holds a query; an empty field closes again once focus leaves it.
var searching by remember { mutableStateOf(query.isNotEmpty()) }
val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "searchOpen")
Column(Modifier.fillMaxWidth()) {
@@ -951,7 +837,6 @@ internal fun ModeHeader(title: String, query: String, onQuery: (String) -> Unit,
)
BoxWithConstraints(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
if (searching || open > 0.01f) {
// The field grows out of the magnifier, the row's width at most.
val w = androidx.compose.ui.unit.lerp(44.dp, maxWidth.coerceAtMost(520.dp), open)
Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) {
AdbTextField(
@@ -968,7 +853,6 @@ internal fun ModeHeader(title: String, query: String, onQuery: (String) -> Unit,
}
}
/** A store chip's face: its dot and short name, for what steps out of it to carry. */
@Composable
private fun ChipLabel(store: Store, ink: Color) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -977,7 +861,6 @@ private fun ChipLabel(store: Store, ink: Color) {
}
}
/** The page's accent in [store]'s own colour (GOG purple, Epic white, Amazon orange); [base] for none. */
internal fun storePalette(base: Palette, store: Store?): Palette {
val (accent, deep) = when (store) {
Store.GOG -> Color(0xFFC25BC8) to Color(0xFF9A3FA1)
@@ -993,14 +876,12 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
)
}
/** The Store section's accent: Flathub's teal, with its dark ink on it. */
internal fun flathubPalette(base: Palette): Palette = Palette(
base.id, base.label, base.detail, base.background, base.surface, base.surfaceVariant, base.line, base.line2,
base.onBackground, base.onSurfaceVariant, primary = FlathubTeal, primary2 = Color(0xFF2E958D), onPrimary = FlathubInk, signal = FlathubTeal,
good = base.good, error = base.error,
)
/** [content] with the focus ring, buttons, step-outs and the chip glide in Flathub's teal. */
@Composable
internal fun FlathubTheme(content: @Composable () -> Unit) {
val base = LocalPalette.current
@@ -1009,12 +890,10 @@ internal fun FlathubTheme(content: @Composable () -> Unit) {
CompositionLocalProvider(LocalPalette provides p) { MaterialTheme(colorScheme = scheme, typography = MaterialTheme.typography, content = content) }
}
/** [content] with the focus ring, buttons and step-outs in [store]'s colour. */
@Composable
internal fun StoreTheme(store: Store?, content: @Composable () -> Unit) {
val base = LocalPalette.current
val p = remember(base, store) { storePalette(base, store) }
// Downloads uses the base palette, but the provider stays in the same focus tree.
val scheme = MaterialTheme.colorScheme.copy(primary = p.primary, onPrimary = p.onPrimary)
CompositionLocalProvider(LocalPalette provides p) { MaterialTheme(colorScheme = scheme, typography = MaterialTheme.typography, content = content) }
}
@@ -1033,10 +912,6 @@ private fun SmallTextButton(text: String, key: String = text, onClick: () -> Uni
)
}
/**
* "<account> · sign out", which asks first: are you sure steps out of it (End session's shape, in
* red), Stay signed in first, so a stray A costs nothing.
*/
@Composable
private fun SignOutButton(store: Store, name: String) {
val ctx = LocalContext.current
@@ -1066,7 +941,6 @@ private fun SignOutButton(store: Store, name: String) {
}
}
/** The header's magnifier: a round button the search field opens out of. */
@Composable
internal fun SearchIcon(description: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -1082,7 +956,6 @@ internal fun SearchIcon(description: String, onClick: () -> Unit) {
) { Icon(Icons.Filled.Search, description, tint = if (hot) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
/** A horizontal row of cards under a title; nothing at all when the list is empty or not here yet. */
@Composable
private fun Shelf(title: String, items: List<CatalogItem>?, card: @Composable (CatalogItem) -> Unit) {
if (items.isNullOrEmpty()) return
@@ -1093,7 +966,6 @@ private fun Shelf(title: String, items: List<CatalogItem>?, card: @Composable (C
}
}
/** Only visible cards (and the grid's prefetch) compose; [empty] spans the row when there are none. */
private fun LazyGridScope.storeGrid(games: List<CatalogItem>, empty: String, card: @Composable (CatalogItem) -> Unit) {
if (games.isEmpty()) item(key = "empty", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.padding(vertical = 32.dp).fillMaxWidth(), contentAlignment = Alignment.Center) {
@@ -1103,19 +975,8 @@ private fun LazyGridScope.storeGrid(games: List<CatalogItem>, empty: String, car
else items(games, key = { it.key }, contentType = { "game" }) { card(it) }
}
/**
* A card's least width: shelf cards are this wide and a grid fits as many columns as the width
* allows at it (the columns then share the leftover), so a display-density setting changes the
* column count rather than the cards' size. 25% under the first 150 dp: five columns where there
* were four on the Pocket FIT.
*/
private val CardWidth = 112.dp
/**
* One title: its wide art, the title, a price or status line and one button that says the one
* thing to do next - Install with its size, Play, the download's progress, Get for free, or View
* on the store. Tapping the card itself opens the game's page.
*/
@Composable
private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: FrontEndActions, installedKeys: Set<String>, onOpen: (String) -> Unit, first: Boolean = false, navigation: Modifier = Modifier) {
val ctx = LocalContext.current
@@ -1127,14 +988,12 @@ private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: Front
val scale by animateFloatAsState(if (pressed) 0.985f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "cardScale")
val installed = item.id in installedKeys
val download = StoresState.download("${store.id}:${item.id}")?.takeIf { it.isActive }
// Where it sits, so the game page can flood out of it (and draw back into it).
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)) }
onOpen(item.key)
}
// A size the library did not give is looked up once the card is on screen or close to it.
val screen = with(androidx.compose.ui.platform.LocalDensity.current) { androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp.toPx() }
val ahead = screen / 2
Column(
@@ -1154,7 +1013,6 @@ private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: Front
}
}
/** A store's sync as a thin bar and its count ("25/55"); a moving bar when it has no count yet. */
@Composable
private fun SyncBar(line: String) {
val count = Regex("(\\d+)\\s*/\\s*(\\d+)").find(line)
@@ -1169,14 +1027,8 @@ private fun SyncBar(line: String) {
}
}
/** How tall the card's one line is, over the blurred foot of its art. */
private val CardStrip = 26.dp
/**
* The card is its art: sharp above, and under the one line a blurred, darkened copy of the same
* picture, placed so the two meet without a seam. Blur needs API 31; below it the copy is only
* darkened, more strongly.
*/
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun CardFace(item: CatalogItem, download: com.droiddeck.launcher.stores.download.DownloadEntry?, hot: Boolean, marker: @Composable () -> Unit) {
@@ -1196,7 +1048,6 @@ private fun CardFace(item: CatalogItem, download: com.droiddeck.launcher.stores.
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.matchParentSize().padding(horizontal = 8.dp),
) {
// A title too long for the strip scrolls through while the card has focus.
Text(
item.title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1,
overflow = if (hot) TextOverflow.Clip else TextOverflow.Ellipsis,
@@ -1205,7 +1056,6 @@ private fun CardFace(item: CatalogItem, download: com.droiddeck.launcher.stores.
marker()
}
}
// A soft edge where the sharp art meets the strip.
Spacer(Modifier.align(Alignment.BottomCenter).padding(bottom = CardStrip).fillMaxWidth().height(14.dp).background(Brush.verticalGradient(0f to Color.Transparent, 1f to Color.Black.copy(alpha = 0.35f))))
if (download != null) Box(Modifier.align(Alignment.BottomCenter).padding(start = 6.dp, end = 6.dp, bottom = CardStrip + 5.dp)) {
ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY)
@@ -1214,14 +1064,12 @@ private fun CardFace(item: CatalogItem, download: com.droiddeck.launcher.stores.
}
}
/** The card's right-hand value: done, resume, progress, size, or the price. */
@Composable
private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droiddeck.launcher.stores.download.DownloadEntry?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val small = 10.sp
when {
// Installed: its size on disk and a small check after it.
installed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
val ctx = LocalContext.current
val game = StoresState.installedGame(item.store, item.id)
@@ -1231,7 +1079,6 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
}
download != null -> Text("${download.percent}%", fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
item.owned && StoresState.isUnfinished(item) -> Text(stringResource(R.string.stores_resume), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
// The size in the title's own type; nothing until it is known.
item.owned -> com.droiddeck.launcher.stores.StoreSizes.size(item).takeIf { it > 0 }?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
item.isFree -> Text(stringResource(R.string.stores_free), fontSize = small, fontWeight = FontWeight.Bold, color = pal.good, maxLines = 1)
item.isDiscounted -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
@@ -1246,8 +1093,6 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
internal fun CardArt(item: CatalogItem, modifier: Modifier) {
val url = item.imageUrl ?: item.tallImageUrl
val colors = MaterialTheme.colorScheme
// A dark ground under the image, so art with transparency never ends in white, and a quiet
// fade into the card's surface at the foot.
Box(modifier.background(colors.surfaceVariant).then(if (url == null) Modifier.background(artBrush(hueOf(item.title))) else Modifier)) {
if (url != null) AsyncImage(model = url, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
else Text(item.title, fontSize = 10.sp, fontWeight = FontWeight.Black, color = Color.White, maxLines = 3, overflow = TextOverflow.Ellipsis, modifier = Modifier.align(Alignment.BottomStart).padding(6.dp))
@@ -1260,8 +1105,6 @@ internal fun ProgressBarThin(fraction: Float, paused: Boolean = false, verify: B
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val fill = when { done -> pal.good; paused -> Color(0xFFFFC24D); verify -> Color(0xFF9B6DFF); else -> pal.signal }
// The fill glides to each new value over a quarter second - progress arrives a few times a second
// and in steps - and is read only while drawing, so the bar animates without relayout.
val shown = androidx.compose.animation.core.animateFloatAsState(
fraction.coerceIn(0f, 1f), androidx.compose.animation.core.tween(250, easing = androidx.compose.animation.core.LinearEasing), label = "bar",
)
@@ -1278,7 +1121,6 @@ internal fun downloadLabel(d: com.droiddeck.launcher.stores.download.DownloadEnt
else -> if (d.stageFraction >= 0f) stringResource(R.string.stores_dl_active_percent, activeStageLabel(d), d.percent) else activeStageLabel(d)
}
/** The active stage as the row and the page name it: Checking (files already there), Downloading, Verifying, Installing. */
@Composable
internal fun activeStageLabel(d: com.droiddeck.launcher.stores.download.DownloadEntry): String = when (d.stage) {
DownloadStage.MANIFEST -> if (d.stageItemsTotal > 0) stringResource(R.string.stores_stage_checking) else stringResource(R.string.stores_stage_manifest)
@@ -1288,7 +1130,6 @@ internal fun activeStageLabel(d: com.droiddeck.launcher.stores.download.Download
DownloadStage.DONE -> stringResource(R.string.stores_stage_done)
}
/** Two taps: the first arms it ([confirm] shows), the second acts; it disarms itself after a few seconds. */
@Composable
internal fun ConfirmButton(label: String, confirm: String, compact: Boolean = false, onConfirm: () -> Unit) {
var armed by remember { mutableStateOf(false) }
@@ -1305,19 +1146,13 @@ internal fun stageLabel(stage: DownloadStage): String = when (stage) {
DownloadStage.DONE -> stringResource(R.string.stores_stage_done)
}
/** The game's web page, in the device's browser: this app buys nothing and claims nothing itself. */
internal fun openStoreUrl(ctx: android.content.Context, item: CatalogItem) = openUrl(ctx, item.storeUrl)
/** A web page in the browser; nothing when the URL is blank or no app can open it. */
internal fun openUrl(ctx: android.content.Context, url: String) {
if (url.isBlank()) return
runCatching { ctx.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
/**
* Launches an installed store game the way the Games tab does: through its Steam shortcut. The
* shortcut exists once the client has (re)started since the install; until then the user is told.
*/
internal fun launchStoreGame(ctx: android.content.Context, store: Store, id: String, s: FrontEndState, a: FrontEndActions) {
val game = s.steamGames.firstOrNull { it.source == store.id && it.storeId == id }
if (game == null) {
@@ -5,9 +5,7 @@ import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.StoresNative
// Controls the Stores section and its Setup group share.
/** Whether the native download engine is in this build, said where the stores are turned on. */
@Composable
internal fun StoresEngineRow() {
val version = StoresNative.version
@@ -5,10 +5,5 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
/**
* Compose test tags as Android resource ids below this node, so UI Automator (`uiautomator dump`,
* droiddeckctl ui-dump) sees stable ids such as `rail-steam` or `setting-logs` rather than only
* labels that change with the language. Tags are named in docs/agent-control.md.
*/
@OptIn(ExperimentalComposeUiApi::class)
fun Modifier.exposeTestTags(): Modifier = semantics { testTagsAsResourceId = true }
@@ -66,10 +66,6 @@ object Themes {
val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.GRAPHITE) }
/**
* Text and icons drawn on a [Palette.signal] fill: near-black where the blue is light enough that
* white would not read (Graphite's #1A9FFF gives white 2.8:1), white where it is deep.
*/
val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03111F) else Color.White
@Composable
@@ -20,17 +20,12 @@ import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
/**
* The DroidDeck mark as the loading indicator. Every loop the D's square half bends into an arc,
* the ring they make turns once around the ball, and the half straightens back into the D.
*/
@Composable
internal fun LogoThrobber(modifier: Modifier = Modifier, running: Boolean = true) {
val ink = MaterialTheme.colorScheme.onBackground
val ball = LocalPalette.current.signal
val loop = rememberInfiniteTransition(label = "throbber")
.animateFloat(0f, 1f, infiniteRepeatable(tween(LOOP_MS, easing = LinearEasing)), label = "loop")
// Animations off in the system settings, or nothing running: the plain D.
val still = !running || Motion.scale == 0f
val left = remember { Path() }
val right = remember { Path() }
@@ -64,7 +59,6 @@ internal fun LogoThrobber(modifier: Modifier = Modifier, running: Boolean = true
}
}
/** The ball of a throbber laid out in [bounds]: its centre and its radius, at rest. */
internal fun throbberBall(bounds: androidx.compose.ui.geometry.Rect): Pair<Offset, Float> {
val s = bounds.width / LogoShape.WIDTH
return Offset(bounds.left + (LogoShape.CX - LogoShape.LEFT) * s, bounds.top + LogoShape.CY * s) to LogoShape.BALL * s
@@ -74,12 +68,6 @@ private const val LOOP_MS = 1900
private val Settle = CubicBezierEasing(0.5f, 0f, 0.3f, 1f)
private val Turn = CubicBezierEasing(0.65f, 0f, 0.35f, 1f)
/**
* The logo's geometry in its SVG's own units (viewBox -55.98 0 239.92 223.72): a D of a square
* left side and a round right side, cut by a ring around the ball and split top and bottom.
* The left half is sampled along rays from the centre so it can bend, point for point, into the
* mirror of the right half's arc.
*/
internal object LogoShape {
const val LEFT = -55.98f
const val WIDTH = 239.92f
@@ -97,7 +85,6 @@ internal object LogoShape {
private fun at(a: Double, r: Float) = Pt((CX + r * cos(a)).toFloat(), (CY + r * sin(a)).toFloat())
private fun angle(x: Float, y: Float) = atan2((y - CY).toDouble(), (x - CX).toDouble())
// Angles taken the long way round, through the left: from about -94 degrees down to -266.
private fun leftward(a: Double) = if (a < 0) a else a - 2 * Math.PI
private val rays: List<Double> = run {
@@ -105,7 +92,6 @@ internal object LogoShape {
val topCorner = angle(SQUARE_X, 0f)
val bottomCorner = leftward(angle(SQUARE_X, HEIGHT))
val bottom = leftward(angle(SPLIT_LEFT, HEIGHT))
// The corners are rays of their own, so the square half keeps sharp corners.
fun span(a: Double, b: Double, n: Int) = List(n) { i -> a + (b - a) * i / (n - 1) }
span(top, topCorner, 9).dropLast(1) + span(topCorner, bottomCorner, 25).dropLast(1) + span(bottomCorner, bottom, 9)
}
@@ -148,7 +134,6 @@ internal object LogoShape {
List(40) { i -> at(innerFrom + (innerTo - innerFrom) * i / 39, INNER) }
}
/** The left half, [bend] of the way from the square D side (0) to the arc (1). */
fun left(path: Path, bend: Float, px: (Float, Float) -> Offset) {
path.reset()
square.forEachIndexed { i, q ->
@@ -68,16 +68,13 @@ import com.droiddeck.launcher.update.AppUpdates.Follow
import com.droiddeck.launcher.update.AppUpdates.Offer
import com.droiddeck.launcher.update.AppUpdates.Release
/** The Updates page: the latest build of each channel, the one followed, and an update in progress. */
class UpdatesState(
val catalog: AppUpdates.Catalog? = null,
val follow: Follow = Follow(Channel.STABLE),
val checking: Boolean = false,
val error: String? = null,
/** "Downloading", "Installing", ... while an update is under way; [percent] is -1 when unknown. */
val stage: String? = null,
val percent: Int = -1,
/** Explain "Install unknown apps" before sending the user to it. */
val askPermission: Boolean = false,
) {
val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow)
@@ -99,14 +96,11 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
val colors = MaterialTheme.colorScheme
Column(modifier = modifier) {
PageHeader(stringResource(R.string.upd_title)) {
// The build that is running, beside the title where it is always in view.
Text(
stringResource(R.string.upd_build, me.version, s.buildLabel), fontSize = 12.5.sp, color = colors.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).padding(top = 6.dp),
)
val checked = u.catalog?.checkedAt?.takeIf { it > 0 }
// The relative time comes capitalized to stand alone (Spanish "Hace 5 minutos"); here it
// ends a sentence.
if (!LocalNarrowPane.current) Text(
if (u.checking) stringResource(R.string.common_checking) else if (checked != null) stringResource(R.string.upd_checked, ago(checked).replaceFirstChar { it.lowercase() }) else stringResource(R.string.upd_not_checked),
fontSize = 13.sp, color = colors.onSurfaceVariant,
@@ -114,9 +108,6 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
ToolIcon(Icons.Outlined.Refresh, stringResource(R.string.store_check_updates), busy = u.checking, enabled = !u.checking && u.stage == null, onClick = ua.onCheck)
}
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
// Landscape has the width for channels and status side by side; a narrow pane, or a small
// phone's (where each channel's name and date would be cut to a word), stacks them. The
// Thor's top screen leaves about 690dp here and keeps them side by side.
val stacked = LocalNarrowPane.current || maxWidth < 600.dp
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
if (stacked) {
@@ -125,7 +116,6 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
ChannelLabel()
ChannelPicker(u, ua)
} else {
// The label sits over both columns, so the status card lines up with the first channel.
ChannelLabel()
Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) {
Box(Modifier.weight(1f)) { ChannelPicker(u, ua) }
@@ -148,7 +138,6 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
)
}
/** Where things stand, as a system updater says it: a status line, what you'd get, and one button. */
@Composable
private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed) {
val colors = MaterialTheme.colorScheme
@@ -216,7 +205,6 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
}
}
/** The change and its notes, two lines each; More opens the rest when either is cut short. */
@Composable
private fun ReleaseNotes(title: String, notes: String, key: String) {
val colors = MaterialTheme.colorScheme
@@ -246,7 +234,6 @@ private fun ReleaseNotes(title: String, notes: String, key: String) {
}
}
/** The headline for a build on offer: "DroidDeck 0.3.0", "New Preview build", "PR #93 test build". */
@Composable
private fun newBuild(f: Follow, r: Release) = when (f.channel) {
Channel.STABLE -> stringResource(R.string.upd_new_stable, r.version ?: r.tag)
@@ -254,14 +241,12 @@ private fun newBuild(f: Follow, r: Release) = when (f.channel) {
Channel.TEST -> stringResource(R.string.upd_new_test, r.pr)
}
/** A PR title as a sentence: "fix(steam): keep the client alive" -> "Keep the client alive". */
private fun changeTitle(t: String): String =
t.replace(Regex("""^[a-z]+(\([^)]*\))?!?:\s*"""), "").replaceFirstChar { it.uppercase() }
@Composable
private fun megabytes(bytes: Long) = stringResource(R.string.upd_mb, ((bytes + 524_288) / 1_048_576).toInt())
/** The three channels as cards to pick from; Test builds opens its list of PRs under it. */
@Composable
private fun ChannelLabel() {
Text(
@@ -297,7 +282,6 @@ private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
}
}
/** Read-only Preview history below the status card action; only the latest build is installable. */
@Composable
private fun PreviewHistory(catalog: AppUpdates.Catalog?, me: AppUpdates.Installed) {
val history = catalog?.let { AppUpdates.previewHistory(it, me) } ?: return
@@ -363,8 +347,6 @@ private fun ChannelCard(
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
// Focus shows at once, as on the Components page: no ripple, no fade. Selection is the radio
// dot, never a ring of its own: the ring is only ever focus.
val fill = if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -391,7 +373,6 @@ private fun ChannelCard(
}
}
/** The one mark of a chosen option: a filled dot in a ring, beside it. */
@Composable
private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.dp) {
val pal = LocalPalette.current
@@ -400,7 +381,6 @@ private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.d
}
}
/** One test build under Test builds: its PR, what it fixes, and how fresh it is. */
@Composable
private fun TestRow(t: Release, selected: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -52,15 +52,9 @@ import androidx.compose.runtime.withFrameNanos
import kotlinx.coroutines.withContext
import java.io.File
// Windows components for one added game, Bannerlator's list: what the game's folder suggests first,
// then everything that installs here, then the ones that need a Windows installer (not yet). Each
// one is a switch, downloaded the first time it is turned on for any game; the launch puts the
// picked ones into the game's prefix (droiddeck-wincomponents).
/** Bannerlator's detector names installers; here the DLL-copy twin is the one that installs. */
private fun installable(name: String, all: Map<String, WinComponents.Component>): String = WinComponents.installable(name, all)
/** A store as a list's owner names it in a reason line. */
@Composable
private fun originName(origin: String): String = stringResource(
when (origin) {
@@ -71,7 +65,6 @@ private fun originName(origin: String): String = stringResource(
},
)
/** Why a component was turned on by itself, from [WinComponents.AutoReason] (args: what the list called it, then the origin's own). */
@Composable
private fun autoReason(r: WinComponents.AutoReason): String = when (r.kind) {
WinCompSources.Origin.STEAM.name -> stringResource(R.string.wincomp_auto_steam, r.args.getOrElse(1) { "" }, r.args.getOrElse(2) { "" }, r.args.getOrElse(3) { "" })
@@ -81,7 +74,6 @@ private fun autoReason(r: WinComponents.AutoReason): String = when (r.kind) {
else -> ""
}
/** The reason line of a finding that is only recommended. */
@Composable
private fun findingReason(f: WinCompSources.Finding): String = when (f.origin) {
WinCompSources.Origin.FOLDER -> stringResource(
@@ -96,9 +88,7 @@ private fun findingReason(f: WinCompSources.Finding): String = when (f.origin) {
@Composable
internal fun WinComponentsDialog(
appKey: String, gameName: String, gameDir: File?, byPad: Boolean,
/** compatdata/<id>: what the prefix already has. [steamAppId]: a Steam title, whose appmanifest lists Steam's own redists. */
compat: File? = null, steamAppId: Int? = null,
/** The game as the Games tab has it: its source decides whose list is trusted ([WinCompSources]). */
game: com.droiddeck.launcher.frontend.Library.SteamGame? = null,
onClose: () -> Unit,
) {
@@ -106,33 +96,22 @@ internal fun WinComponentsDialog(
val coroutine = rememberCoroutineScope()
val shown = rememberShown(onClose)
val close = { shown.targetState = false }
// null while the catalog loads; empty when it could not be had.
var catalog by remember { mutableStateOf<Map<String, WinComponents.Component>?>(null) }
var offline by remember { mutableStateOf(false) }
var findings by remember { mutableStateOf(emptyList<WinCompSources.Finding>()) }
// Whether the game's list has been worked out at least once (kept from an earlier time counts).
var findingsKnown by remember { mutableStateOf(game == null) }
// "Loading the components" only when the catalog takes a while.
var slowCatalog by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { kotlinx.coroutines.delay(300); slowCatalog = true }
var installed by remember { mutableStateOf(emptySet<String>()) }
// Detector names (oalinst, physx...) already in the prefix from elsewhere.
var present by remember { mutableStateOf(emptySet<String>()) }
var selection by remember { mutableStateOf(WinComponents.selection(context, appKey)) }
val picks = selection.effective
// The row being worked on: its id, the latest progress (a dependency's while that installs
// first), and whether it is turning off rather than on. The row greys out and shows the bar
// the moment the switch is pressed, and only that row; the rest of the page stays as it is.
var busyId by remember { mutableStateOf<String?>(null) }
var progress by remember { mutableStateOf<WinComponents.Progress?>(null) }
var reverting by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
// The component the error is about, so it shows on its own row and not only at the bottom.
var failed by remember { mutableStateOf<String?>(null) }
var showWaiting by remember { mutableStateOf(false) }
// Done holds focus while the list loads, then the top switch takes it - opened by touch or by
// pad, so the d-pad always has somewhere to start; LB and RB jump between the sections, since
// the full list runs past sixty switches.
val recFocus = remember { FocusRequester() }
val recFocusAfterAuto = remember { FocusRequester() }
val activeFocus = remember { FocusRequester() }
@@ -145,10 +124,7 @@ internal fun WinComponentsDialog(
LaunchedEffect(Unit) {
val (entries, found) = withContext(Dispatchers.IO) {
val list = WinComponents.fetch(context)
// The source's list first (and what it turns on by itself, already installed), then the folder scan.
if (game != null) {
// The list kept from last time, at once; it is worked out again (and its components
// queued) on the background worker, which this page then follows.
com.droiddeck.launcher.frontend.AutoComponents.queueGame(context, game, asked = true)
val kept = com.droiddeck.launcher.frontend.AutoComponents.cachedFindings(context, appKey)
if (kept != null) findingsKnown = true
@@ -166,11 +142,7 @@ internal fun WinComponentsDialog(
present = withContext(Dispatchers.IO) { PrefixInstalledDetector.detect(compat) }
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
}
/** The user's own switch for [id]: kept apart from what was turned on by itself, and over it. */
// Automatic picks still downloading show on their rows; when one lands the page reads the picks again.
val autoDownloading by com.droiddeck.launcher.frontend.AutoComponents.downloading.collectAsState()
// Without a network a component not downloaded yet cannot be turned on; the rows say so and
// come back the moment the network does.
val online = rememberOnline()
val autoChanges by com.droiddeck.launcher.frontend.AutoComponents.changes.collectAsState()
val pendingGames by com.droiddeck.launcher.frontend.AutoComponents.pendingGames.collectAsState()
@@ -186,14 +158,10 @@ internal fun WinComponentsDialog(
coroutine.launch(Dispatchers.IO) { WinComponents.setUser(context, appKey, id, on) }
}
fun toggle(id: String, on: Boolean) {
// Switches stay enabled during a download - a disabled one drops the pad's focus - so a press
// then is ignored here; the busy row is greyed instead.
if (busyId != null) return
error = null
failed = null
if (!on) {
// Turning off is a saved pick, quick, but the row greys out until it is written so the
// press is seen to land; the files leave the prefix at the game's next launch.
busyId = id; reverting = true; progress = null
selection = WinComponents.Selection(selection.auto, selection.user + (id to false))
coroutine.launch {
@@ -219,21 +187,12 @@ internal fun WinComponentsDialog(
}
val all = catalog
// The first data is in: rows that show up from now on ease in.
var arrived by remember { mutableStateOf(false) }
LaunchedEffect(all != null && findingsKnown) { if (all != null && findingsKnown) { withFrameNanos { }; arrived = true } }
val here = if (all == null) emptySet() else present.map { installable(it, all) }.toSet()
fun supportOf(id: String): Support =
all?.get(id)?.let { WinComponents.support(it, all) } ?: if (id in installed) Support.READY else Support.UNSUPPORTED
// Turned on by itself for this game, each with its reason; then what is only recommended (the
// folder scan, a name match, an auto pick that cannot install here); then what the lists name
// that is no component here, by its own name.
// Still being worked out on the background worker: the page says so instead of "nothing found".
// Only before the game's list has ever been worked out: a list kept from before shows at once and
// is checked again quietly, its changes easing in.
val checking = game != null && !findingsKnown
// Automatic picks on their way (queued or downloading) sit in their section already, with
// their progress, and settle there when they land.
val turningOn = if (all == null) emptyMap() else findings.filter { it.auto && it.component != null }
.associateBy { installable(it.component!!, all) }
.filterKeys { it !in selection.auto && selection.user[it] != false && (it in pendingComponents || it in autoDownloading) }
@@ -244,10 +203,6 @@ internal fun WinComponentsDialog(
val suggestions = findings.filter { it.component == null }.distinctBy { it.origin to it.original }
val ready = all.orEmpty().values.filter { WinComponents.support(it, all.orEmpty()) == Support.READY }.map { it.name }
val extra = (installed + picks).filter { all?.containsKey(it) != true }
// What is turned on for this game gets its own section under the recommendations, which stay
// where they are; the rest of the list is everything else, so a component turned off goes back
// to its place in the alphabet. A component is listed once: the recommendations are left out
// of the full list too.
val recSet = recIds.map { installable(it.component!!, all.orEmpty()) }.toSet() + autoIds
val active = picks.filter { it !in recSet && (all?.containsKey(it) == true || it in installed) }.distinct()
.sortedBy { WinComponentNames.of(it).lowercase() }
@@ -263,12 +218,10 @@ internal fun WinComponentsDialog(
runCatching { sections[section].requestFocus() }
}
LaunchedEffect(all != null) {
// The dialog's window starts in touch mode, where a switch cannot hold focus at all.
inputMode.requestInputMode(InputMode.Keyboard)
section = 0
val target = if (all == null) doneFocus else sections.first()
switchFocused = false
// It animates in and the list composes over a few frames: ask until the switch has it.
repeat(60) {
withFrameNanos { }
runCatching { target.requestFocus() }
@@ -296,7 +249,6 @@ internal fun WinComponentsDialog(
support == Support.UNSUPPORTED -> stringResource(R.string.wincomp_unsupported)
else -> null
}
// The catalog key stays in the detail: it is what a log or a bug report names.
val detail = listOfNotNull(reason, c?.description?.takeIf { it.isNotEmpty() }, status, id).joinToString(" · ")
val offlineHere = !online && id !in installed
val usable = support == Support.READY && !offlineHere
@@ -323,13 +275,11 @@ internal fun WinComponentsDialog(
.onFocusChanged { if (it.isFocused) switchFocused = true },
) { on -> toggle(id, on) }
}
/** The section's requester goes to its first switch that can take focus. */
fun firstUsable(ids: List<String>, focus: FocusRequester): (String) -> FocusRequester? {
val first = ids.firstOrNull { supportOf(it) == Support.READY }
return { id -> focus.takeIf { id == first } }
}
// The lists only once the catalog is in, faded in once: no half list counted before it.
androidx.compose.animation.AnimatedVisibility(
visible = all != null,
enter = androidx.compose.animation.fadeIn(Motion.tw(220)),
@@ -429,7 +379,6 @@ internal fun WinComponentsDialog(
}
}
/** Once the page has its first data ([arrived]), a row that shows up eases in; the first ones are simply there. */
@Composable
private fun Arrive(arrived: Boolean, content: @Composable () -> Unit) {
val state = remember { androidx.compose.animation.core.MutableTransitionState(!arrived) }.apply { targetState = true }
@@ -442,7 +391,6 @@ private fun Arrive(arrived: Boolean, content: @Composable () -> Unit) {
) { content() }
}
/** Whether the default network is there and validated, followed live. */
@Composable
private fun rememberOnline(): Boolean {
val context = LocalContext.current
@@ -474,12 +422,6 @@ private fun Panel(content: @Composable androidx.compose.foundation.layout.Column
private fun Divider() =
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp).heightIn(min = 1.dp, max = 1.dp).background(LocalPalette.current.line))
/**
* One component: name, detail and its switch; while [busy] the row is greyed and a thin bar runs
* across it with [caption] above (the download, then the install, each 0..100 as [percent], or
* indeterminate at -1). The switch stays enabled while busy so a pad's focus does not drop; the
* press is ignored by the caller instead.
*/
@Composable
private fun ComponentRow(
name: String, detail: String, checked: Boolean, enabled: Boolean, dim: Boolean, busy: Boolean = false,
@@ -358,7 +358,6 @@ internal fun AdbTextField(
onFocusChange: (Boolean) -> Unit = {},
onNext: (() -> Unit)? = null,
onDone: (() -> Unit)? = null,
/** Takes focus (and the keyboard) once, as soon as it is shown: a field that opened on request. */
focusOnShow: Boolean = false,
) {
val context = LocalContext.current
@@ -17,10 +17,6 @@ import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import com.droiddeck.launcher.R
/**
* The DroidDeck wordmark from the README banner (artwork/droiddeck-banner-*.svg): the mark
* standing in as the D, then "roidDeck". Letters and D in the theme's ink, the ball in its blue.
*/
@Composable
internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
val ink = MaterialTheme.colorScheme.onBackground
@@ -34,7 +30,6 @@ internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
scale(k, k, Offset.Zero) {
translate(-BOX_X, -BOX_Y) {
drawPath(letters, ink)
// The mark's placement in the banner: translate(239.135 123.36) scale(0.527445) translate(31.98 0).
translate(239.135f, 123.36f) {
scale(MARK_SCALE, MARK_SCALE, Offset.Zero) {
translate(31.98f, 0f) {
@@ -49,7 +44,6 @@ internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
}
}
// The banner's own units: the wordmark spans x 239.135..1040.7 and y 120.02..243.2.
private const val BOX_X = 239.135f
private const val BOX_Y = 120.02f
private const val BOX_W = 1040.7f - 239.135f