diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt index 8af0ee0a7..0a62eeafb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt @@ -59,6 +59,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.blur import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.zIndex import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect @@ -97,11 +98,6 @@ import kotlinx.coroutines.withContext // 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. -/** What Desktop remembers between visits: how far down it was scrolled. */ -internal object DesktopMemory { - var scroll = 0 -} - /** The desktop's own chips: its session settings, then Files. */ private val DESKTOP_TABS = modeSheetTabs(steam = false) + SheetTab.FILES @@ -111,184 +107,167 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie val density = LocalDensity.current val narrow = LocalNarrowPane.current val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current LaunchedEffect(Unit) { UserAppsState.refresh(ctx) } - // Flathub's installed apps sit with the others in Your apps. + // Flathub's installed apps sit with the others on the dock. LaunchedEffect(s.ready, s.storeEnabled) { if (s.storeEnabled) com.droiddeck.launcher.store.StoreState.refresh(ctx) } val installed = s.emulators.filter { it.installed } - val available = s.emulators.filter { !it.installed } val apps = UserAppsState.items var adding by rememberSaveable { mutableStateOf(false) } - var sheetOpen by remember { mutableStateOf(false) } - // Where the page was scrolled, kept while one of its own pages (an emulator's, Flathub) is - // open: back on Desktop the page draws into its card where the card still is. - val scroll = rememberScrollState(DesktopMemory.scroll) - LaunchedEffect(scroll) { androidx.compose.runtime.snapshotFlow { scroll.value }.collect { DesktopMemory.scroll = it } } - val scope = androidx.compose.runtime.rememberCoroutineScope() - // Where the Your apps shelf ends, for a new emulator's dot to land. - var yourAppsAt by remember { mutableStateOf(null) } - var lastCardAt by remember { mutableStateOf(null) } 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(key: String, at: Rect?, art: Any?, page: String) { + fun openFrom(at: Rect?, art: Any?, page: String) { at?.let { PageOrigin.mark(Origin(it, 16f * density.density, art = art)) } onSelect(page) } - BoxWithConstraints(modifier.fillMaxSize().clipToBounds()) { - val paneH = maxHeight - Column(Modifier.fillMaxSize().verticalScroll(scroll, enabled = !sheetOpen)) { - // The wall stays inside the hero; the shelves sit on the page's own ground. - Box(Modifier.fillMaxWidth().height(paneH).clipToBounds()) { - LiftHero( - key = "desktop", tabs = tabs, - onOpen = { scope.launch { scroll.animateScrollTo(0) }; a.onDesktopSettings() }, - onPrimary = a.onDesktop, downOpens = false, onOpenChange = { sheetOpen = it }, - start = if (narrow) 20.dp else 44.dp, bottom = if (narrow) 20.dp else 44.dp, - background = { DesktopWall(installed.map { it.iconRes } + apps.mapNotNull { it.icon }) }, - scrim = { WallFade() }, - words = { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.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, - ) - Chip(stringResource(R.string.desktop_shell_kde), ok = true) - } - BusyChip(s) - } - }, - 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) - }, - rows = { tab -> - if (tab == SheetTab.FILES) DesktopFiles(s, a) - else a.modeSheet(mode, tab, SheetExtras()) - }, - ) + // 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, + modifier = modifier.clipToBounds(), + start = if (narrow) 20.dp else 44.dp, bottom = if (narrow) 20.dp else 44.dp, + background = { + DesktopWall(installed.map { it.iconRes } + apps.mapNotNull { it.icon }) + }, + 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, onAdd = { if (!s.busy) adding = true }, openFrom = ::openFrom) } - Column(Modifier.fillMaxWidth().padding(start = if (narrow) 16.dp else 22.dp, end = if (narrow) 16.dp else 22.dp, bottom = 24.dp)) { - // ---- Your apps: the emulators installed, and the apps added ---- - ShelfTitle(stringResource(R.string.user_apps_section), (installed.size + apps.size).takeIf { it > 0 }?.toString()) - val seen = remember { mutableSetOf() } - val mounted = remember { booleanArrayOf(false) } - val yourScroll = rememberScrollState() - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - modifier = Modifier.fillMaxWidth().onGloballyPositioned { yourAppsAt = it.boundsInRoot() }.edgeFade(yourScroll).horizontalScroll(yourScroll).padding(vertical = 2.dp), - ) { - val flatpaks = if (s.storeEnabled) com.droiddeck.launcher.store.StoreState.installed else emptyList() - val keys = installed.map { "emu:${it.id}" } + apps.map { "user:${it.key}" } + flatpaks.map { "flatpak:${it.id}" } - keys.forEachIndexed { i, k -> - key(k) { - // A card that arrives after the shelf 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))) { - val last = Modifier.then(if (i == keys.lastIndex) Modifier.onGloballyPositioned { lastCardAt = it.boundsInRoot() } else Modifier) - Box(last) { - val e = installed.firstOrNull { "emu:${it.id}" == k } - val flatpak = flatpaks.firstOrNull { "flatpak:${it.id}" == k } - val app = apps.firstOrNull { "user:${it.key}" == k } - if (e != null) { - val system = if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { c -> c.uppercase() } - DesktopCard( - k, e.name, - if (e.id == "retroarch") system else "$system · " + pluralStringResource(R.plurals.mode_added_count, e.games.size, e.games.size), - art = e.iconRes, first = i == 0, - ) { at -> openFrom(k, at, e.iconRes, k) } - } else if (flatpak != null) DesktopCard( - 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(k, 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 -> - openFrom(k, at, app.icon, k) - } - } - } - } - } - if (keys.isEmpty()) Text(stringResource(R.string.desktop_no_apps), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp)) - } - LaunchedEffect(Unit) { mounted[0] = true } - if (UserAppsState.working != null || UserAppsState.lastError != null) Box(Modifier.padding(top = 8.dp)) { UserAppsProgressLine() } - - // ---- Get more: the emulators not installed, adding an app, and Flathub ---- - ShelfTitle(stringResource(R.string.desktop_get_more), null) - val moreScroll = rememberScrollState() - Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().edgeFade(moreScroll).horizontalScroll(moreScroll).padding(vertical = 2.dp)) { - available.forEach { e -> - key(e.id) { - val pkgId = Library.packageId(e.id) - val pkg = pkgId?.let { id -> s.packages?.firstOrNull { it.id == id } } - val busyHere = pkg != null && s.packageBusyId == pkg.id - val canGet = pkg != null && !s.busy && s.packageBusyId == null && s.ready && !s.packageCatalogLoading && !s.sessionRunning - val system = if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { c -> c.uppercase() } - DesktopCard( - "emu:${e.id}", e.name, if (busyHere) (s.packageStage ?: stringResource(R.string.store_installing)) else system, - art = e.iconRes, badge = if (busyHere) null else stringResource(R.string.comp_get), - progress = if (busyHere) s.packagePercent else null, - ) { 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 shelf = yourAppsAt - val endAt = lastCardAt - Flights.fly(Flight(at, to = { - val r = shelf ?: return@Flight null - Offset(minOf((endAt?.right ?: r.left) + 70.dp.toPx(), r.right - 20.dp.toPx()), r.center.y) - })) - } else openFrom("emu:${e.id}", at, e.iconRes, "emu:${e.id}") - } - } - } - DesktopCard("add", stringResource(R.string.user_apps_add), stringResource(R.string.user_apps_add_detail), art = null, fallback = Icons.Filled.Add, accent = true) { if (!s.busy) adding = true } - if (s.storeEnabled) { - // Flathub's apps run in the desktop: its storefront is a page of Desktop's, - // flooding out of this card as an emulator's does. - DesktopCard("flathub", stringResource(R.string.flathub_name), stringResource(R.string.flathub_line), art = null, fallback = Icons.Outlined.Storefront, tint = FlathubTeal) { at -> - openFrom("flathub", at, null, "store") - } - } + }, + words = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.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, + ) + Chip(stringResource(R.string.desktop_shell_kde), ok = true) } + BusyChip(s) } - } - // Scrolled past the hero: it folds into a slim header with the word and a compact Open desktop. - val collapsed = with(density) { scroll.value > (paneH - 48.dp).toPx() } - AnimatedVisibility( - collapsed, - enter = fadeIn(Motion.tw(200)) + slideInVertically(Motion.tw(240)) { -it }, - exit = fadeOut(Motion.tw(160)) + slideOutVertically(Motion.tw(200)) { -it }, - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().height(48.dp).background(colors.background.copy(alpha = 0.96f)).padding(horizontal = if (narrow) 16.dp else 22.dp), - ) { - Text(stringResource(R.string.rail_desktop), fontSize = 20.sp, fontWeight = FontWeight.Black, color = colors.onBackground) - Spacer(Modifier.weight(1f)) - PrimaryButton(open, enabled = !s.busy, compact = true, onClick = a.onDesktop) - } - } - } + }, + 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) + }, + rows = { tab -> + if (tab == SheetTab.FILES) DesktopFiles(s, a) + else a.modeSheet(mode, tab, SheetExtras()) + }, + ) if (adding && !s.busy) AddAppDialog(s.ready, onDismiss = { adding = false }) { request, label -> UserAppsState.add(ctx, request, label) } } -/** A shelf's heading, with a count beside it. */ +/** + * The dock along the top of the Desktop hero: what runs in the desktop (emulators installed, apps + * added, Flathub's installed apps), then what can be added (emulators to get, Add, Flathub) - one + * row of cards that scrolls sideways, over the wall. It sinks back with the wall as the sheet lifts. + */ @Composable -private fun ShelfTitle(title: String, count: String?) { +private fun DesktopDock( + s: FrontEndState, a: FrontEndActions, installed: List, apps: List, + onAdd: () -> Unit, openFrom: (Rect?, Any?, String) -> Unit, +) { val colors = MaterialTheme.colorScheme - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 18.dp, bottom = 8.dp)) { - Text(title, fontSize = 16.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) - if (count != null) Text(count, fontSize = 13.sp, color = colors.onSurfaceVariant) + val pal = LocalPalette.current + val narrow = LocalNarrowPane.current + val available = s.emulators.filter { !it.installed } + val flatpaks = if (s.storeEnabled) com.droiddeck.launcher.store.StoreState.installed else emptyList() + 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(null) } + var dockAt by remember { mutableStateOf(null) } + val seen = remember { mutableSetOf() } + val mounted = remember { booleanArrayOf(false) } + LaunchedEffect(Unit) { mounted[0] = true } + val scroll = rememberScrollState() + Column(Modifier.fillMaxWidth().padding(top = if (narrow) 14.dp else 22.dp)) { + Text( + stringResource(R.string.user_apps_section).uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.6.sp, + color = colors.onSurfaceVariant, modifier = Modifier.padding(start = if (narrow) 20.dp else 44.dp, bottom = 8.dp), + ) + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.Top, + modifier = Modifier.fillMaxWidth().onGloballyPositioned { dockAt = it.boundsInRoot() } + .edgeFade(scroll).horizontalScroll(scroll).padding(start = if (narrow) 20.dp else 44.dp, end = 20.dp, top = 2.dp, bottom = 4.dp), + ) { + 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))) { + Box(if (i == keys.lastIndex) Modifier.onGloballyPositioned { lastAt = it.boundsInRoot() } else Modifier) { + val e = installed.firstOrNull { "emu:${it.id}" == k } + val flatpak = flatpaks.firstOrNull { "flatpak:${it.id}" == k } + val app = apps.firstOrNull { "user:${it.key}" == k } + if (e != null) { + val system = if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { c -> c.uppercase() } + DesktopCard( + k, e.name, + if (e.id == "retroarch") system else "$system · " + pluralStringResource(R.plurals.mode_added_count, e.games.size, e.games.size), + art = e.iconRes, first = i == 0, + ) { at -> openFrom(at, e.iconRes, k) } + } else if (flatpak != null) DesktopCard( + 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 -> + openFrom(at, app.icon, k) + } + } + } + } + } + // 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) { + val pkg = Library.packageId(e.id)?.let { id -> s.packages?.firstOrNull { it.id == id } } + val busyHere = pkg != null && s.packageBusyId == pkg.id + val canGet = pkg != null && !s.busy && s.packageBusyId == null && s.ready && !s.packageCatalogLoading && !s.sessionRunning + val system = if (e.systemRes != 0) stringResource(e.systemRes) else e.system.replaceFirstChar { c -> c.uppercase() } + DesktopCard( + "emu:${e.id}", e.name, if (busyHere) (s.packageStage ?: stringResource(R.string.store_installing)) else system, + 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 + val row = dockAt + Flights.fly(Flight(at, to = { + val r = row ?: return@Flight null + Offset((end?.right ?: r.left) + 70.dp.toPx(), r.center.y) + })) + } else openFrom(at, e.iconRes, "emu:${e.id}") + } + } + } + DesktopCard("add", stringResource(R.string.user_apps_add), stringResource(R.string.user_apps_add_detail), art = null, fallback = Icons.Filled.Add, accent = true) { onAdd() } + if (s.storeEnabled) { + // Flathub's apps run in the desktop: its storefront is a page of Desktop's, + // flooding out of this card as an emulator's does. + DesktopCard("flathub", stringResource(R.string.flathub_name), stringResource(R.string.flathub_line), art = null, fallback = Icons.Outlined.Storefront, tint = FlathubTeal) { at -> + openFrom(at, null, "store") + } + } + } + if (UserAppsState.working != null || UserAppsState.lastError != null) { + Box(Modifier.padding(start = if (narrow) 20.dp else 44.dp, end = 20.dp, top = 6.dp)) { UserAppsProgressLine() } + } } } @@ -325,7 +304,7 @@ private fun DesktopCard( val scale by animateFloatAsState(if (pressed) 0.96f else if (hot) 1.03f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "deskCard") val shape = RoundedCornerShape(16.dp) var artAt by remember { mutableStateOf(null) } - val width = if (LocalNarrowPane.current) 132.dp else 156.dp + val width = if (LocalNarrowPane.current) 116.dp else 132.dp val artH = width * 0.62f val ground = tint?.copy(alpha = 0.25f) ?: if (accent) pal.signal.copy(alpha = 0.12f) else colors.surfaceVariant Column( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 2387ed599..4acbe4591 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -496,8 +496,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com Hops.origin = null Hops.restore = null Hops.sinking = null - // Picked from the rail, Desktop starts at its hero; back from one of its pages it is where it was. - if (key == "desktop" && selected != "desktop") DesktopMemory.scroll = 0 selected = key } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index dcc527da3..f96eae98a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -60,6 +60,9 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.foundation.layout.wrapContentHeight +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.zIndex import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.focus.FocusDirection @@ -82,6 +85,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.boundsInParent import androidx.compose.ui.layout.boundsInRoot import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.res.stringResource @@ -129,6 +133,13 @@ internal object SheetTab { internal fun sheetTop(paneH: Float, buttonH: Float, minAbove: Float, ride: Float): Float = maxOf(paneH * 82f / 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>) { private var next = 1 @@ -172,8 +183,11 @@ 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. */ - scrim: @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, button: @Composable (onClick: () -> Unit) -> Unit, rows: @Composable (tab: String) -> Unit, @@ -206,6 +220,10 @@ internal fun LiftHero( var focusOnLift by remember { mutableStateOf(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() + val onOpenNow = rememberUpdatedState(onOpen) val pull = remember { Animatable(0f) } val sink = remember { Animatable(0f) } val lift = remember { Animatable(0f) } @@ -250,6 +268,14 @@ internal fun LiftHero( onDispose { lifecycle.removeObserver(obs) } } LaunchedEffect(open, launching) { + 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() } } + } else focusPlay() + return@LaunchedEffect + } if (open && !launching) { lipBack = false shown = true @@ -333,7 +359,104 @@ internal fun LiftHero( } } - BoxWithConstraints(modifier.fillMaxSize().onGloballyPositioned { heroAt = it.boundsInRoot().topLeft }) { + // 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 { + lift.snapTo(p); ride.snapTo(p); sink.snapTo(p.coerceIn(0f, 1f)); hot.snapTo(0f) + lipGone.snapTo(1f) + 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() { + drag.engaged = true + drag.from = if (open) 1f else 0f + drag.progress = drag.from + if (!open) { + shown = true + scope.launch { fold.snapTo(0f); foldTop.snapTo(0f) } + 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() } + val opens = when { + v < -flick -> true + v > flick -> false + drag.from > 0.5f -> drag.progress > 0.7f + else -> drag.progress > 0.3f + } + dragSettled = true + scope.launch { + val to = if (opens) 1f else 0f + coroutineScope { + launch { lift.animateTo(to, Motion.sp(if (opens) 0.7f else 1f, 380f)) } + launch { ride.animateTo(to, Motion.sp(if (opens) 0.7f else 0.55f, if (opens) 380f else 300f)) } + launch { sink.animateTo(to, Motion.tw(220)) } + pieces.forEachIndexed { i, piece -> launch { if (opens) delay(Motion.ms(i * 35).toLong()); piece.animateTo(to, Motion.tw(if (opens) 200 else 90)) } } + } + if (!opens) { shown = false; lipGone.snapTo(0f); hot.snapTo(1f); lipBack = false } + } + 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 { + if (!drag.engaged || available.y >= 0f) return Offset.Zero + val before = drag.progress + follow((before - available.y / travelPx[0]).coerceAtMost(1f)) + return Offset(0f, (drag.progress - before) * -travelPx[0]) + } + override fun onPostScroll(consumed: Offset, available: Offset, source: androidx.compose.ui.input.nestedscroll.NestedScrollSource): Offset { + if (available.y <= 0f || source != androidx.compose.ui.input.nestedscroll.NestedScrollSource.Drag || !openState.value || launchingState.value) return Offset.Zero + if (!drag.engaged) beginDrag() + follow((drag.progress - available.y / travelPx[0]).coerceIn(0f, 1f)) + return available + } + override suspend fun onPreFling(available: androidx.compose.ui.unit.Velocity): androidx.compose.ui.unit.Velocity { + if (!drag.engaged) return androidx.compose.ui.unit.Velocity.Zero + settleDrag(available.y) + return available + } + } + } + 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(Unit) { + val tracker = androidx.compose.ui.input.pointer.util.VelocityTracker() + var decided = false + detectVerticalDragGestures( + onDragStart = { tracker.resetTracking(); decided = false; drag.engaged = false }, + onDragEnd = { if (drag.engaged) settleDrag(tracker.calculateVelocity().y) }, + onDragCancel = { if (drag.engaged) settleDrag(0f) }, + ) { change, amount -> + if (launching) return@detectVerticalDragGestures + if (!decided) { + decided = true + // Up at rest opens; down when open closes. Anything else is not for the sheet. + if (if (open) amount > 0f else amount < 0f) beginDrag() + } + if (!drag.engaged) return@detectVerticalDragGestures + change.consume() + tracker.addPosition(change.uptimeMillis, change.position) + follow((drag.progress - amount / travelPx[0]).coerceIn(0f, 1.04f)) + } + }, + ) { val w = constraints.maxWidth.toFloat() val h = constraints.maxHeight.toFloat() val inset = with(density) { SheetInset.toPx() } @@ -342,22 +465,25 @@ internal fun LiftHero( 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) // The wall behind sinks back about the pane's centre. - Box(Modifier.fillMaxSize().graphicsLayer { val k = 1f - 0.05f * sink.value; scaleX = k; scaleY = k }) { background() } + val foot = h + Box(Modifier.fillMaxSize().clipToBounds().graphicsLayer { val k = 1f - 0.05f * sink.value; 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() + 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)) + Modifier.fillMaxSize() + .graphicsLayer { alpha = sink.value }.background(Color.Black.copy(alpha = 0.42f)) .focusProperties { canFocus = false } .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(h, openTop, lift.value) + val top = lerp(foot, openTop, lift.value) val sheetLeft = inset val sheetRight = w - inset val path = remember { Path() } @@ -371,7 +497,7 @@ internal fun LiftHero( val l = if (pill != null) lerp(sheetLeft, pill.left, f) else sheetLeft val r = if (pill != null) lerp(sheetRight, pill.right, f) else sheetRight val t = if (pill != null) lerp(top, pill.top, ft) else top - val b = if (pill != null) lerp(h + corner, pill.bottom, ft) else h + corner + val b = if (pill != null) lerp(foot + corner, pill.bottom, ft) else foot + corner val c = if (pill != null) lerp(corner, with(density) { 12.dp.toPx() }, ft) else corner val bc = if (ft > 0f) c else 0f path.reset() @@ -404,7 +530,7 @@ internal fun LiftHero( Box( Modifier .offset { IntOffset(sheetLeft.roundToInt(), top.roundToInt()) } - .size(with(density) { sheetW.toDp() }, with(density) { (h - openTop).coerceAtLeast(0f).toDp() }) + .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() } @@ -425,14 +551,7 @@ internal fun LiftHero( .zIndex(1f) .width(with(density) { (sheetW - chipsX - 16.dp.toPx()).coerceAtLeast(0f).toDp() }) .graphicsLayer { val v = pieces[0].value; alpha = v; translationY = (1f - v) * 6.dp.toPx() } - // A pull down on the chips folds the sheet; so does Up from them. - .pointerInput(Unit) { - var dy = 0f - detectVerticalDragGestures(onDragStart = { dy = 0f }) { change, amount -> - dy += amount - if (dy > 24.dp.toPx()) { change.consume(); close(); dy = Float.NEGATIVE_INFINITY } - } - } + // 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 @@ -443,8 +562,9 @@ internal fun LiftHero( Box( Modifier .offset { IntOffset(0, rowsY.roundToInt()) } + .nestedScroll(rowsPull) .fillMaxWidth() - .height(with(density) { (h - openTop - rowsY).coerceAtLeast(0f).toDp() }), + .height(with(density) { (foot - openTop - rowsY).coerceAtLeast(0f).toDp() }), ) { AnimatedContent( targetState = tab, @@ -484,14 +604,6 @@ internal fun LiftHero( .graphicsLayer { translationY = raise * ride.value } .onFocusChanged { playFocused = it.hasFocus } .hoverable(playSrc) - // A pull up from Play opens the sheet. - .pointerInput(Unit) { - var dy = 0f - detectVerticalDragGestures(onDragStart = { dy = 0f }) { change, amount -> - dy += amount - if (dy < -24.dp.toPx() && !open) { change.consume(); open = true; dy = 0f } - } - } .onPreviewKeyEvent { e -> val k = e.nativeKeyEvent if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN) false @@ -516,22 +628,17 @@ internal fun LiftHero( 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 = 22.dp + pull.value.dp val lift = { if (!open) open = true } Box( Modifier - .offset { IntOffset((r0.center.x - HandleWidth.toPx() / 2f).roundToInt(), (r0.bottom + raise * ride.value + (lipShow.value - 1f) * 8.dp.toPx()).roundToInt()) } + .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) } // 44dp to touch; the tab itself is the top 22. .heightIn(min = 44.dp) .semantics { contentDescription = settingsLabel } - .pointerInput(Unit) { - var dy = 0f - detectVerticalDragGestures(onDragStart = { dy = 0f }) { change, amount -> - dy += amount - if (dy < -24.dp.toPx() && !open) { change.consume(); open = true; dy = 0f } - } - } .then( if (downOpens) Modifier.focusProperties { canFocus = false } else Modifier.focusRequester(lipFocus).onFocusChanged { lipFocused = it.isFocused }.controllerConfirm(onClick = lift), @@ -546,11 +653,8 @@ internal fun LiftHero( } } -/** The handle's width: a small tab, not a sentence. */ -private val HandleWidth = 52.dp - /** - * The sheet's handle, tucked under Play: a small tab with a chevron that bobs up every so often, + * 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 @@ -574,14 +678,16 @@ private fun Handle(height: Dp) { ), label = "handleBob", ) - Box( - contentAlignment = Alignment.Center, - modifier = Modifier.width(HandleWidth).height(height).clip(shape).background(colors.surface) - .drawBorderSidesAndFoot(pal.line, 12.dp), + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.height(height).clip(shape).background(colors.surface) + .drawBorderSidesAndFoot(pal.line, 12.dp) + .padding(start = 14.dp, end = 10.dp), ) { + Text(stringResource(R.string.drawer_page_settings), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant, maxLines = 1) Icon( Icons.Filled.KeyboardArrowUp, null, tint = colors.onSurfaceVariant, - modifier = Modifier.size(18.dp).graphicsLayer { translationY = if (still) 0f else -3.dp.toPx() * lift }, + modifier = Modifier.size(16.dp).graphicsLayer { translationY = if (still) 0f else -3.dp.toPx() * lift }, ) } }