mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 13:55:58 +00:00
Merge upstream PC input and dual-screen updates
This commit is contained in:
commit
68b0396dfe
819 files changed
+43953
-6186
No files matched your search
@@ -68,6 +68,7 @@ import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.LogoPosition
|
||||
import com.droiddeck.launcher.frontend.SteamGameArt
|
||||
import com.droiddeck.launcher.frontend.SteamGridDb
|
||||
import com.droiddeck.launcher.frontend.SteamLaunchOptions
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -191,7 +192,7 @@ internal fun SteamGameArtEditor(
|
||||
game: com.droiddeck.launcher.frontend.Library.SteamGame, onClose: () -> Unit, onChanged: () -> Unit,
|
||||
) {
|
||||
val target = remember(game.appId) { ArtTarget.of(game) }
|
||||
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged)
|
||||
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged, launchAppId = game.appId)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -207,18 +208,25 @@ internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Uni
|
||||
@Composable
|
||||
private fun ArtOnlyEditor(
|
||||
name: String, target: ArtTarget?, refresh: Any?, describe: (Context) -> List<AddedGameArt.SlotState>,
|
||||
onClose: () -> Unit, onChanged: () -> Unit,
|
||||
onClose: () -> Unit, onChanged: () -> Unit, launchAppId: Int? = null,
|
||||
) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val scope = rememberCoroutineScope()
|
||||
val shown = rememberShown(onClose)
|
||||
val close = { shown.targetState = false }
|
||||
var version by remember { mutableIntStateOf(0) }
|
||||
var arts by remember { mutableStateOf<List<AddedGameArt.SlotState>>(emptyList()) }
|
||||
var artSlot by remember { mutableStateOf<AddedGameArt.Slot?>(null) }
|
||||
var logoOpen by remember { mutableStateOf(false) }
|
||||
var launchOptions by remember { mutableStateOf<String?>(null) }
|
||||
var launchVersion by remember { mutableIntStateOf(0) }
|
||||
var editingLaunch by remember { mutableStateOf<String?>(null) }
|
||||
var launchSaving by remember { mutableStateOf(false) }
|
||||
var launchError by remember { mutableStateOf<Int?>(null) }
|
||||
val position = rememberLogoPosition(target, version)
|
||||
LaunchedEffect(version, refresh) { if (target != null) arts = withContext(Dispatchers.IO) { describe(app) } }
|
||||
LaunchedEffect(launchAppId, launchVersion) { if (launchAppId != null) launchOptions = withContext(Dispatchers.IO) { SteamLaunchOptions.current(app, launchAppId) } }
|
||||
val first = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } }
|
||||
AppDialog(shown, close, "artEditor", wide = false, maxWidth = 460.dp) {
|
||||
@@ -228,10 +236,19 @@ private fun ArtOnlyEditor(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
|
||||
) {
|
||||
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp))
|
||||
if (launchAppId != null) {
|
||||
FieldRow(stringResource(R.string.edit_launch_options), focus = first, onClick = { if (!launchSaving) launchOptions?.let { editingLaunch = it } }) {
|
||||
val options = launchOptions
|
||||
if (options == null || launchSaving) Loading() else ValueText(options.ifEmpty { "—" }, muted = options.isEmpty())
|
||||
}
|
||||
val error = launchError
|
||||
if (error != null) Text(stringResource(error), fontSize = 12.sp, color = colors.error, modifier = Modifier.padding(start = 4.dp))
|
||||
else Text(stringResource(R.string.edit_launch_options_steam_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp))
|
||||
}
|
||||
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = if (launchAppId != null) 8.dp else 2.dp))
|
||||
for (slot in AddedGameArt.Slot.values()) key(slot) {
|
||||
val state = arts.firstOrNull { it.slot == slot }
|
||||
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER) first else null, onClick = { if (target != null) artSlot = slot }) {
|
||||
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER && launchAppId == null) first else null, onClick = { if (target != null) artSlot = slot }) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
SlotThumb(slot, state?.file)
|
||||
if (state != null) ValueText(artSourceLabel(state.source), muted = true) else Loading()
|
||||
@@ -241,6 +258,27 @@ private fun ArtOnlyEditor(
|
||||
PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
|
||||
}
|
||||
}
|
||||
val before = editingLaunch
|
||||
if (before != null && launchAppId != null) TextEntryDialog(stringResource(R.string.edit_launch_options), before, onDismiss = { editingLaunch = null }) { value ->
|
||||
if (launchSaving || value == before.trim()) return@TextEntryDialog
|
||||
launchSaving = true
|
||||
scope.launch {
|
||||
try {
|
||||
val saved = withContext(Dispatchers.IO) { SteamLaunchOptions.set(app, launchAppId, value, before) }
|
||||
launchError = when (saved) {
|
||||
SteamLaunchOptions.Saved.YES -> null
|
||||
SteamLaunchOptions.Saved.DESKTOP -> R.string.edit_launch_options_desktop
|
||||
SteamLaunchOptions.Saved.NO -> R.string.edit_launch_options_not_saved
|
||||
}
|
||||
if (saved == SteamLaunchOptions.Saved.YES) launchOptions = value else {
|
||||
launchOptions = null
|
||||
launchVersion++
|
||||
}
|
||||
} finally {
|
||||
launchSaving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
val chosen = target ?: return
|
||||
artSlot?.let { slot ->
|
||||
ArtChooserDialog(chosen, slot, arts.firstOrNull { it.slot == slot }, onBack = { artSlot = null }, onCloseAll = { artSlot = null; close() }) { version++; onChanged() }
|
||||
@@ -249,7 +287,6 @@ private fun ArtOnlyEditor(
|
||||
if (logoOpen && loaded != null) LogoPositionHost(chosen, arts, loaded, onBack = { logoOpen = false }, onCloseAll = { logoOpen = false; close() }) { version++; onChanged() }
|
||||
}
|
||||
|
||||
/** The position as last read; null until it has been read, so the screen never opens on a guess and saves it over the real one. */
|
||||
private class LoadedPosition(val value: LogoPosition.Value?)
|
||||
|
||||
@Composable
|
||||
@@ -262,7 +299,6 @@ private fun rememberLogoPosition(target: ArtTarget?, version: Int): LoadedPositi
|
||||
return position
|
||||
}
|
||||
|
||||
/** The "Adjust logo" screen for [target], over the game's background and logo as they are now. */
|
||||
@Composable
|
||||
private fun LogoPositionHost(
|
||||
target: ArtTarget, arts: List<AddedGameArt.SlotState>, start: LoadedPosition,
|
||||
|
||||
@@ -18,6 +18,7 @@ import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
@@ -86,7 +87,13 @@ import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -563,9 +570,10 @@ private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.D
|
||||
private fun AppTile(
|
||||
app: HomeApp.LaunchableApp, folderId: String?, first: Boolean,
|
||||
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
Box(modifier) {
|
||||
TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) {
|
||||
AppIcon(app, 52.dp)
|
||||
TileLabel(app.label)
|
||||
@@ -710,6 +718,7 @@ private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Uni
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
private fun FolderSheet(
|
||||
folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean,
|
||||
@@ -726,7 +735,27 @@ private fun FolderSheet(
|
||||
if (n.isNotEmpty() && n != folder.name) HomeFolders.rename(ctx, folder.id, n)
|
||||
renaming = false
|
||||
}
|
||||
val close = { if (renaming) commit(); onClose() }
|
||||
val firstApp = remember { FocusRequester() }
|
||||
val inputMode = LocalInputModeManager.current.inputMode
|
||||
val ff = LocalFrontFocus.current
|
||||
val grid = rememberLazyGridState()
|
||||
var closing by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(renaming, inputMode) {
|
||||
if (!renaming && !closing && inputMode == InputMode.Keyboard && apps.isNotEmpty()) {
|
||||
grid.scrollToItem(0)
|
||||
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
|
||||
if (!closing) runCatching { firstApp.requestFocus() }
|
||||
}
|
||||
}
|
||||
val close = {
|
||||
closing = true
|
||||
if (renaming) commit()
|
||||
onClose()
|
||||
if (inputMode == InputMode.Keyboard && ff != null) {
|
||||
runCatching { ff.items.getValue("tile:folder:${folder.id}").requestFocus() }
|
||||
.onFailure { runCatching { ff.firstTile.requestFocus() } }
|
||||
}
|
||||
}
|
||||
BackHandler { close() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
@@ -741,6 +770,13 @@ private fun FolderSheet(
|
||||
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
|
||||
.controllerBack(close)
|
||||
.focusProperties {
|
||||
exit = { dir ->
|
||||
if (dir == FocusDirection.Up || dir == FocusDirection.Down || dir == FocusDirection.Left || dir == FocusDirection.Right) FocusRequester.Cancel
|
||||
else FocusRequester.Default
|
||||
}
|
||||
}
|
||||
.focusGroup()
|
||||
.padding(16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) {
|
||||
@@ -759,11 +795,15 @@ private fun FolderSheet(
|
||||
}
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(92.dp),
|
||||
state = grid,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(apps, key = { it.key }) { app ->
|
||||
AppTile(app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder)
|
||||
AppTile(
|
||||
app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder,
|
||||
modifier = if (app === apps.first()) Modifier.focusRequester(firstApp) else Modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,16 +91,12 @@ import java.io.File
|
||||
|
||||
private enum class MovieTab { INSTALLED, IMPORT, REPO, SOUND }
|
||||
|
||||
/** Downloads run here rather than in a tab, so switching tabs or closing the settings does not cancel one halfway. */
|
||||
private val installScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
/** The downloads under way, by post id and percent; kept here so they are still known when the tab or the settings come back. */
|
||||
private val installProgress = mutableStateMapOf<String, Int>()
|
||||
|
||||
/** What the movie list looks like right now: every movie and the one Steam will play. */
|
||||
private class MovieSnapshot(val entries: List<BootMovieLibrary.Entry>, val selected: String)
|
||||
|
||||
/** The movie list, read again every couple of seconds so a movie picked, added or removed inside Steam shows up here too. */
|
||||
@Composable
|
||||
private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieSnapshot? {
|
||||
val app = LocalContext.current.applicationContext
|
||||
@@ -143,7 +139,6 @@ private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modif
|
||||
}
|
||||
}
|
||||
|
||||
/** The "Boot movie" settings group: Installed movies, Import your own movies, SteamDeckRepo and Sound. */
|
||||
@Composable
|
||||
internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
|
||||
var tab by rememberSaveable { mutableStateOf(MovieTab.INSTALLED) }
|
||||
@@ -179,7 +174,6 @@ private fun InstalledTab(a: ModeSettingsActions) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
val scope = rememberCoroutineScope()
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
// The report is for bug reports, so it shows only while Debugging tools is on (read each time this tab opens).
|
||||
val debugging = remember { com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(app) }
|
||||
if (debugging) {
|
||||
SettingsRow(stringResource(R.string.boot_movie_report), stringResource(R.string.boot_movie_report_hint)) {
|
||||
@@ -222,7 +216,6 @@ private fun movieSourceLabel(source: String): String = stringResource(
|
||||
},
|
||||
)
|
||||
|
||||
/** The installed movies as a list with covers; the one Steam plays is highlighted, and the list follows changes made in Steam. */
|
||||
@Composable
|
||||
private fun InstalledMoviesDialog(a: ModeSettingsActions, onDismiss: () -> Unit) {
|
||||
val app = LocalContext.current.applicationContext
|
||||
@@ -497,10 +490,8 @@ private fun RepoTab(a: ModeSettingsActions) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Downloads [post] and puts it among the installed movies; returns a message when it failed, null when it worked. */
|
||||
private fun install(app: android.content.Context, post: SteamDeckRepo.Post, onProgress: (Int) -> Unit): String? {
|
||||
val folder = File(app.cacheDir, "boot-movie-download").apply { mkdirs() }
|
||||
// Leftovers of a download that was cut short are cleared, and every download has a file of its own.
|
||||
folder.listFiles()?.forEach { if (System.currentTimeMillis() - it.lastModified() > 60 * 60 * 1000L) it.delete() }
|
||||
val file = File.createTempFile("movie-", ".webm", folder)
|
||||
return try {
|
||||
@@ -563,7 +554,6 @@ private const val AFTER_OPEN = 3
|
||||
private const val AFTER_INSTALL = 1
|
||||
private const val AFTER_USE = 2
|
||||
|
||||
/** Install and Use are different buttons in turn, and the button is disabled while installing; it takes focus back for the controller. */
|
||||
@Composable
|
||||
private fun RepoAction(
|
||||
installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean, modifier: Modifier, onInstall: () -> Unit, onUse: () -> Unit,
|
||||
@@ -593,7 +583,6 @@ private fun RepoAction(
|
||||
)
|
||||
}
|
||||
|
||||
/** A movie from SteamDeckRepo played straight from the site, so it can be checked before it is installed. */
|
||||
@Composable
|
||||
private fun PreviewDialog(
|
||||
post: SteamDeckRepo.Post, installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean,
|
||||
@@ -674,7 +663,6 @@ private fun MoviePreview(url: String, modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A dialog with one text box, for a search term or a page number; the Android keyboard comes up with it. */
|
||||
@Composable
|
||||
internal fun TextEntryDialog(
|
||||
title: String, initial: String, number: Boolean, confirm: String, onSubmit: (String) -> Unit, onDismiss: () -> Unit,
|
||||
@@ -697,7 +685,6 @@ internal fun TextEntryDialog(
|
||||
}
|
||||
}
|
||||
|
||||
/** Page buttons around the current page, which opens a box to type another page into; first and last page show their numbers. */
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun RepoPager(page: Int, last: Int?, hasMore: Boolean, onPage: (Int) -> Unit, onJump: () -> Unit) {
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.media.AudioManager
|
||||
import android.view.ViewGroup
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.RenderProcessGoneDetail
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebSettings
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SteamWebLogin
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private const val STEAM_CHAT = "https://steamcommunity.com/chat"
|
||||
private const val CHAT_PAGE_SCALE = 0.75f
|
||||
private val STEAM_HOSTS = listOf("steamcommunity.com", "steam-chat.com", "steampowered.com", "steamstatic.com", "steamcontent.com")
|
||||
|
||||
internal fun steamChatAllows(host: String?): Boolean =
|
||||
host != null && STEAM_HOSTS.any { host == it || host.endsWith(".$it") }
|
||||
|
||||
internal fun desktopUserAgent(webView: String?): String {
|
||||
val chrome = webView?.let { Regex("Chrome/[\\d.]+").find(it)?.value } ?: "Chrome/127.0.6533.103"
|
||||
return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) $chrome Safari/537.36"
|
||||
}
|
||||
|
||||
internal fun steamChatFitScript(cssWidth: Int, scale: Float): String {
|
||||
val zoom = "%.2f".format(java.util.Locale.US, scale)
|
||||
return "(function(){var m=document.querySelector('meta[name=viewport]');" +
|
||||
"if(!m){m=document.createElement('meta');m.name='viewport';document.head.appendChild(m);}" +
|
||||
"m.content='width=$cssWidth, initial-scale=$zoom';" +
|
||||
"if(!document.getElementById('dd-chat-fit')){var s=document.createElement('style');s.id='dd-chat-fit';" +
|
||||
"s.textContent='$STEAM_CHAT_FIT_CSS';document.head.appendChild(s);}" +
|
||||
"window.dispatchEvent(new Event('resize'));})()"
|
||||
}
|
||||
|
||||
internal const val STEAM_CHAT_FIT_CSS = ".chat_main>:has(~.chat_main_flex){display:none!important}" +
|
||||
".ChatRoomList_Empty{display:none!important}" +
|
||||
".chatRoomListContainer{height:auto!important;max-height:25vh!important}"
|
||||
|
||||
@Composable
|
||||
fun BottomChatPage() {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var chatOpen by remember { mutableStateOf(true) }
|
||||
var stopped by remember { mutableStateOf(false) }
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
DisposableEffect(lifecycle) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME && stopped) {
|
||||
stopped = false
|
||||
chatOpen = true
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
var fromSteam by remember { mutableStateOf<Boolean?>(null) }
|
||||
LaunchedEffect(chatOpen) {
|
||||
if (!chatOpen) {
|
||||
fromSteam = null
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val cookies = withContext(Dispatchers.IO) {
|
||||
SteamWebLogin.read(LinuxRuntime.rootDir(context), SessionState.steamClientArch, File(context.cacheDir, "steam-web-login"))
|
||||
}
|
||||
val manager = CookieManager.getInstance()
|
||||
for (c in cookies) suspendCancellableCoroutine { cont -> manager.setCookie("https://${c.host}", c.header) { cont.resume(Unit) } }
|
||||
manager.flush()
|
||||
fromSteam = cookies.any { it.header.startsWith("steamLoginSecure=") }
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (!chatOpen) {
|
||||
VoiceRow(context)
|
||||
Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)) {
|
||||
if (stopped) Text(stringResource(R.string.bottom_chat_stopped), fontSize = 13.sp, color = colors.onSurfaceVariant, textAlign = TextAlign.Center)
|
||||
Text(stringResource(R.string.bottom_chat_why), fontSize = 15.sp, color = colors.onBackground, textAlign = TextAlign.Center)
|
||||
BottomPillButton(stringResource(R.string.bottom_chat_open), "bottom-chat-open") {
|
||||
stopped = false
|
||||
chatOpen = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
VoiceRow(context, onClose = { chatOpen = false },
|
||||
note = if (fromSteam == false) stringResource(R.string.bottom_chat_not_signed_in) else "")
|
||||
Box(Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(14.dp))) {
|
||||
if (fromSteam != null) SteamChatView(onStopped = {
|
||||
stopped = true
|
||||
chatOpen = false
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceRow(context: Context, onClose: (() -> Unit)? = null, note: String = "") {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val audio = remember { context.getSystemService(Context.AUDIO_SERVICE) as AudioManager }
|
||||
val max = remember { audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1) }
|
||||
var volume by remember { mutableIntStateOf(audio.getStreamVolume(AudioManager.STREAM_MUSIC)) }
|
||||
fun step(direction: Int) {
|
||||
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, 0)
|
||||
volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (onClose != null) BottomPillButton(stringResource(R.string.bottom_chat_close), "bottom-chat-close", onClose)
|
||||
if (SessionState.micAvailable) {
|
||||
val on = SessionState.micEnabled
|
||||
BottomPillButton(stringResource(if (on) R.string.bottom_chat_mic_on else R.string.bottom_chat_mic_off), "bottom-chat-mic") {
|
||||
SessionService.setMicEnabled(context, !on)
|
||||
}
|
||||
}
|
||||
val hint = if (onClose == null && !SessionState.micAvailable) stringResource(R.string.bottom_chat_mic_unavailable) else note
|
||||
Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 3, modifier = Modifier.weight(1f))
|
||||
Text(stringResource(R.string.bottom_chat_volume, volume * 100 / max), fontSize = 14.sp, color = colors.onSurfaceVariant)
|
||||
BottomPillButton("−", "bottom-chat-volume-down") { step(AudioManager.ADJUST_LOWER) }
|
||||
BottomPillButton("+", "bottom-chat-volume-up") { step(AudioManager.ADJUST_RAISE) }
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
private fun SteamChatView(onStopped: () -> Unit) {
|
||||
AndroidView(factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
|
||||
setBackgroundColor(0xFF0A0B0D.toInt())
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.useWideViewPort = true
|
||||
settings.loadWithOverviewMode = true
|
||||
settings.userAgentString = desktopUserAgent(runCatching { WebSettings.getDefaultUserAgent(ctx) }.getOrNull())
|
||||
CookieManager.getInstance().setAcceptCookie(true)
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean =
|
||||
!steamChatAllows(request.url.host)
|
||||
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
val scale = view.resources.displayMetrics.density * CHAT_PAGE_SCALE
|
||||
if (view.width > 0) view.evaluateJavascript(steamChatFitScript((view.width / scale).roundToInt(), CHAT_PAGE_SCALE), null)
|
||||
}
|
||||
|
||||
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
||||
onStopped()
|
||||
return true
|
||||
}
|
||||
}
|
||||
loadUrl(STEAM_CHAT)
|
||||
}
|
||||
}, modifier = Modifier.fillMaxSize(), onRelease = { view ->
|
||||
CookieManager.getInstance().flush()
|
||||
view.destroy()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
class BottomPage(
|
||||
val id: String,
|
||||
@StringRes val label: Int,
|
||||
val icon: ImageVector,
|
||||
val content: @Composable () -> Unit,
|
||||
)
|
||||
|
||||
internal fun pickBottomPage(remembered: String?, ids: List<String>): String? =
|
||||
ids.firstOrNull { it == remembered } ?: ids.firstOrNull { it == DEFAULT_PAGE } ?: ids.firstOrNull()
|
||||
|
||||
internal object SessionBottomTab {
|
||||
private var session: String? = null
|
||||
private var tab: String? = null
|
||||
|
||||
@Synchronized
|
||||
fun picked(sessionId: String?): String? = tab.takeIf { sessionId != null && sessionId == session }
|
||||
|
||||
@Synchronized
|
||||
fun pick(sessionId: String?, id: String) {
|
||||
session = sessionId
|
||||
tab = id
|
||||
}
|
||||
}
|
||||
|
||||
internal fun pageForGameStart(ids: List<String>): String? = GAME_PAGE.takeIf { it in ids }
|
||||
|
||||
private const val DEFAULT_PAGE = "telemetry"
|
||||
private const val GAME_PAGE = "telemetry"
|
||||
private val MIN_TAB = 80.dp
|
||||
|
||||
@Composable
|
||||
internal fun BottomDashboard(
|
||||
pages: List<BottomPage>,
|
||||
remembered: String?,
|
||||
onPage: (String) -> Unit,
|
||||
bar: BottomBarModel? = null,
|
||||
gameStarts: Int = 0,
|
||||
strip: (@Composable (String?) -> Unit)? = null,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var current by remember { mutableStateOf(pickBottomPage(remembered, pages.map { it.id })) }
|
||||
val startsWhenOpened = remember { gameStarts }
|
||||
LaunchedEffect(gameStarts) {
|
||||
if (gameStarts != startsWhenOpened) pageForGameStart(pages.map { it.id })?.let { current = it }
|
||||
}
|
||||
val page = pages.firstOrNull { it.id == current } ?: pages.firstOrNull()
|
||||
Column(Modifier.fillMaxSize().background(colors.background)) {
|
||||
bar?.let { BottomScreenBar(it) }
|
||||
BoxWithConstraints(Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 8.dp).height(56.dp)) {
|
||||
val roomy = pages.isEmpty() || (maxWidth - 6.dp * (pages.size - 1)) / pages.size >= MIN_TAB
|
||||
Row(
|
||||
Modifier.fillMaxSize().then(if (roomy) Modifier else Modifier.horizontalScroll(rememberScrollState())),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
pages.forEach { p ->
|
||||
PageTab(p, p.id == page?.id, if (roomy) Modifier.weight(1f) else Modifier.width(MIN_TAB)) {
|
||||
current = p.id
|
||||
onPage(p.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(Modifier.weight(1f).fillMaxWidth().padding(horizontal = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
strip?.invoke(page?.id)
|
||||
Box(Modifier.weight(1f).fillMaxWidth().padding(bottom = 10.dp)) {
|
||||
if (page != null) page.content()
|
||||
else Text(stringResource(R.string.bottom_dashboard_empty), fontSize = 15.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.align(Alignment.Center))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PageTab(page: BottomPage, selected: Boolean, modifier: Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(14.dp)
|
||||
val name = stringResource(page.label)
|
||||
Column(
|
||||
modifier.fillMaxHeight().clip(shape)
|
||||
.background(if (selected) pal.signal else Color.Transparent)
|
||||
.border(1.dp, if (selected) pal.signal else pal.line, shape)
|
||||
.semantics { contentDescription = name }
|
||||
.clickable(role = Role.Tab, onClick = onClick).testTag("bottom-page-${page.id}")
|
||||
.padding(horizontal = 4.dp, vertical = 6.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
val tint = if (selected) pal.onSignal else colors.onBackground
|
||||
Icon(page.icon, contentDescription = null, tint = tint, modifier = Modifier.size(20.dp))
|
||||
Text(name, fontSize = 11.sp, lineHeight = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 2.dp))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Color
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import android.view.Gravity
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowInsets
|
||||
import android.graphics.RectF
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.LinearLayout
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.GuestKeys
|
||||
import com.droiddeck.launcher.input.InputSpace
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.BottomDesktop
|
||||
|
||||
@SuppressLint("ViewConstructor")
|
||||
class BottomDesktopPanel(
|
||||
context: Context,
|
||||
onClose: (() -> Unit)?,
|
||||
onMenu: (() -> Unit)?,
|
||||
steamButtons: Pair<() -> Unit, () -> Unit>?,
|
||||
onSwap: (() -> Unit)? = null,
|
||||
private val fullResolution: Boolean = false,
|
||||
) : LinearLayout(context), SurfaceHolder.Callback {
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private val area = FrameLayout(context).apply { clipChildren = true }
|
||||
private val state = mutableStateOf(BottomDesktop.state)
|
||||
private val status = ComposeView(context).apply {
|
||||
setContent { DroidDeckTheme { BottomDesktopStatus(state.value, ::startAgain) } }
|
||||
}
|
||||
private val keyboardHost = KeyboardHost(context) { event -> sendKey(event) }
|
||||
private var directTouch = SessionPrefs.bottomDesktopDirectTouch(context)
|
||||
private val touchMode = mutableStateOf(directTouch)
|
||||
private val trackpad = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), TrackpadInput()).apply {
|
||||
desktop = true
|
||||
}
|
||||
private var attached = false
|
||||
/** The surface was given to a compositor process; a new process cannot connect to it again. */
|
||||
private var surfaceUsed = false
|
||||
private var fullWidth = 0
|
||||
private var fullHeight = 0
|
||||
private var lastTouchY = 0f
|
||||
private var lastPressMs = 0L
|
||||
private var scrollRestX = 0f
|
||||
private var scrollRestY = 0f
|
||||
private val stateListener: () -> Unit = { showState() }
|
||||
|
||||
init {
|
||||
orientation = VERTICAL
|
||||
setBackgroundColor(Color.BLACK)
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
addView(bar(onClose, onMenu, steamButtons, onSwap), LayoutParams(-1, -2))
|
||||
area.addView(keyboardHost)
|
||||
addSurface()
|
||||
area.addView(status, FrameLayout.LayoutParams(-1, -1))
|
||||
addView(area, LayoutParams(-1, 0, 1f))
|
||||
keyboardHost.onImeChanged = { pan() }
|
||||
showTouchMode()
|
||||
}
|
||||
|
||||
private fun addSurface() {
|
||||
surfaceView = SurfaceView(context)
|
||||
surfaceView.holder.addCallback(this)
|
||||
@Suppress("ClickableViewAccessibility")
|
||||
surfaceView.setOnTouchListener { _, event -> onSurfaceTouch(event) }
|
||||
area.addView(surfaceView, 1, FrameLayout.LayoutParams(fullWidth.takeIf { it > 0 } ?: -1, fullHeight.takeIf { it > 0 } ?: -1))
|
||||
}
|
||||
|
||||
private fun bar(onClose: (() -> Unit)?, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?, onSwap: (() -> Unit)?): View =
|
||||
bottomScreenBarView(context) {
|
||||
val touch = touchMode.value
|
||||
BottomBarModel(
|
||||
context.getString(R.string.bottom_desktop_title,
|
||||
context.getString(if (touch) R.string.bottom_desktop_mode_touch else R.string.bottom_desktop_mode_trackpad)),
|
||||
onClose, onMenu, steamButtons?.first, steamButtons?.second,
|
||||
listOfNotNull(
|
||||
BarExtra(context.getString(if (touch) R.string.bottom_desktop_direct_touch else R.string.bottom_desktop_trackpad),
|
||||
icon = if (touch) R.drawable.ic_bottom_touch else R.drawable.ic_bottom_mouse) { setDirectTouch(!directTouch) },
|
||||
BarExtra(context.getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) { keyboardHost.toggle() },
|
||||
onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, onClick = it) },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun setDirectTouch(on: Boolean) {
|
||||
trackpad.cancel()
|
||||
BottomDesktop.sendTouch(3, -1, 0, 0)
|
||||
directTouch = on
|
||||
SessionPrefs.setBottomDesktopDirectTouch(context, on)
|
||||
showTouchMode()
|
||||
}
|
||||
|
||||
private fun showTouchMode() {
|
||||
touchMode.value = directTouch
|
||||
BottomDesktop.showCursor(!directTouch)
|
||||
if (!directTouch && surfaceView.width > 0) {
|
||||
trackpad.bounds = RectF(0f, 0f, surfaceView.width.toFloat(), surfaceView.height.toFloat())
|
||||
trackpad.place(surfaceView.width / 2f, surfaceView.height / 2f)
|
||||
movePointer(trackpad.x, trackpad.y)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
BottomDesktop.addListener(stateListener)
|
||||
BottomDesktop.setTextInputListener { focused ->
|
||||
val tapped = SystemClock.uptimeMillis() - lastPressMs < TEXT_FIELD_TAP_MS
|
||||
val hardKeyboard = resources.configuration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO
|
||||
if (focused && tapped && !hardKeyboard && !keyboardHost.shown) keyboardHost.show()
|
||||
else if (!focused && keyboardHost.shown) keyboardHost.hide()
|
||||
}
|
||||
showState()
|
||||
post { if (!keyboardHost.shown) requestFocus() }
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
BottomDesktop.removeListener(stateListener)
|
||||
BottomDesktop.setTextInputListener(null)
|
||||
keyboardHost.takeIf { it.shown }?.hide()
|
||||
trackpad.cancel()
|
||||
status.disposeComposition()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean =
|
||||
if (BottomDesktop.state == BottomDesktop.State.RUNNING && !PadBridge.isControllerKeyEvent(event) &&
|
||||
event.keyCode != KeyEvent.KEYCODE_BACK && sendKey(event)) true
|
||||
else super.dispatchKeyEvent(event)
|
||||
|
||||
private fun sendKey(event: KeyEvent): Boolean {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount > 0) return true
|
||||
if (GuestKeys.send(event, BottomDesktop::sendKey)) return true
|
||||
val ch = event.unicodeChar
|
||||
if (event.action == KeyEvent.ACTION_DOWN && ch > 0) {
|
||||
BottomDesktop.sendText(String(Character.toChars(ch)))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun startAgain() {
|
||||
if (surfaceUsed && !BottomDesktop.connected) {
|
||||
attached = false
|
||||
surfaceUsed = false
|
||||
area.removeView(surfaceView)
|
||||
addSurface()
|
||||
return
|
||||
}
|
||||
if (!attached) return
|
||||
attached = false
|
||||
syncSurface(surfaceView.holder)
|
||||
}
|
||||
|
||||
private fun showState() {
|
||||
state.value = BottomDesktop.state
|
||||
status.visibility = if (state.value == BottomDesktop.State.RUNNING) View.GONE else View.VISIBLE
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
super.onSizeChanged(w, h, oldw, oldh)
|
||||
post { holdSurfaceSize() }
|
||||
}
|
||||
|
||||
// The keyboard shrinks the window; the desktop keeps its size and slides up under it instead of being squeezed.
|
||||
private fun holdSurfaceSize() {
|
||||
val w = area.width
|
||||
val h = area.height
|
||||
if (w <= 0 || h <= 0) return
|
||||
if (w != fullWidth || h > fullHeight || !keyboardHost.shown) {
|
||||
fullWidth = w
|
||||
fullHeight = h
|
||||
val (desktopW, desktopH) = BottomDesktop.outputSizeFor(w, h, fullResolution)
|
||||
val (fitW, fitH) = if (w - desktopW in 0..1 && h - desktopH in 0..1) desktopW to desktopH
|
||||
else fitDesktop(w, h, desktopW, desktopH)
|
||||
surfaceView.layoutParams = if (fitW == w && fitH == h) FrameLayout.LayoutParams(w, h)
|
||||
else FrameLayout.LayoutParams(fitW, fitH, Gravity.CENTER_HORIZONTAL).apply { topMargin = (h - fitH) / 2 }
|
||||
surfaceView.post { syncSurface(surfaceView.holder) }
|
||||
}
|
||||
pan()
|
||||
}
|
||||
|
||||
private fun imeOverlap(): Int {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return 0
|
||||
if (area.height < fullHeight) return 0
|
||||
val ime = rootWindowInsets?.getInsets(WindowInsets.Type.ime())?.bottom ?: return 0
|
||||
if (ime <= 0) return 0
|
||||
val at = IntArray(2)
|
||||
area.getLocationInWindow(at)
|
||||
return (at[1] + area.height - (rootView.height - ime)).coerceIn(0, area.height)
|
||||
}
|
||||
|
||||
private fun pan() {
|
||||
val visible = area.height - imeOverlap()
|
||||
val hidden = (fullHeight - visible).coerceAtLeast(0)
|
||||
val anchor = if (directTouch) lastTouchY else trackpad.y
|
||||
surfaceView.translationY = if (hidden == 0 || !keyboardHost.shown) 0f
|
||||
else -(anchor - visible * 0.4f).coerceIn(0f, hidden.toFloat())
|
||||
}
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) = Unit
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = syncSurface(holder)
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
if (holder !== surfaceView.holder) return
|
||||
attached = false
|
||||
surfaceUsed = false
|
||||
BottomDesktop.detach(holder.surface)
|
||||
}
|
||||
|
||||
private fun syncSurface(holder: SurfaceHolder) {
|
||||
if (holder !== surfaceView.holder || fullWidth <= 0 || fullHeight <= 0 || !holder.surface.isValid) return
|
||||
val (width, height) = BottomDesktop.outputSizeFor(fullWidth, fullHeight, fullResolution)
|
||||
if (width <= 0 || height <= 0) return
|
||||
val frame = holder.surfaceFrame
|
||||
if (frame.width() != width || frame.height() != height) {
|
||||
val params = surfaceView.layoutParams
|
||||
if (params.width == width && params.height == height) holder.setSizeFromLayout() else holder.setFixedSize(width, height)
|
||||
return
|
||||
}
|
||||
if (attached) {
|
||||
BottomDesktop.resize(holder.surface, width, height)
|
||||
return
|
||||
}
|
||||
attached = true
|
||||
surfaceUsed = true
|
||||
BottomDesktop.attach(context, holder.surface, width, height, display?.refreshRate ?: 60f)
|
||||
showTouchMode()
|
||||
}
|
||||
|
||||
private fun onSurfaceTouch(event: MotionEvent): Boolean {
|
||||
val w = surfaceView.width
|
||||
val h = surfaceView.height
|
||||
if (w <= 0 || h <= 0 || BottomDesktop.state != BottomDesktop.State.RUNNING) return true
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_UP)
|
||||
lastPressMs = SystemClock.uptimeMillis()
|
||||
if (directTouch) return forwardTouch(event, w, h)
|
||||
val bounds = RectF(0f, 0f, w.toFloat(), h.toFloat())
|
||||
if (trackpad.bounds != bounds) {
|
||||
trackpad.bounds = bounds
|
||||
trackpad.place(trackpad.x, trackpad.y)
|
||||
}
|
||||
return trackpad.onTouch(event)
|
||||
}
|
||||
|
||||
private fun forwardTouch(event: MotionEvent, w: Int, h: Int): Boolean {
|
||||
val action = when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0
|
||||
MotionEvent.ACTION_MOVE -> 1
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> 2
|
||||
MotionEvent.ACTION_CANCEL -> { BottomDesktop.sendTouch(3, -1, 0, 0); return true }
|
||||
else -> return true
|
||||
}
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) lastTouchY = event.y
|
||||
if (action == 1) {
|
||||
for (i in 0 until event.pointerCount) send(1, event.getPointerId(i), event.getX(i), event.getY(i), w, h)
|
||||
} else {
|
||||
val i = event.actionIndex
|
||||
send(action, event.getPointerId(i), event.getX(i), event.getY(i), w, h)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun send(action: Int, id: Int, x: Float, y: Float, w: Int, h: Int) =
|
||||
BottomDesktop.sendTouch(action, id, InputSpace.x(x, w), InputSpace.y(y, h))
|
||||
|
||||
private fun movePointer(x: Float, y: Float) =
|
||||
BottomDesktop.sendPointer(InputSpace.x(x, surfaceView.width), InputSpace.y(y, surfaceView.height))
|
||||
|
||||
private inner class TrackpadInput : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) = movePointer(x, y)
|
||||
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
movePointer(x, y)
|
||||
BottomDesktop.sendScene(SCENE_BUTTON, button, if (pressed) 1 else 0)
|
||||
}
|
||||
|
||||
override fun onWheel(steps: Int) = BottomDesktop.sendScene(SCENE_WHEEL, steps)
|
||||
|
||||
override fun onScroll(dx: Float, dy: Float) {
|
||||
val (outW, outH) = BottomDesktop.outputSize
|
||||
scrollRestX += dx * outW / surfaceView.width.coerceAtLeast(1) * AXIS_UNITS_PER_PIXEL
|
||||
scrollRestY += dy * outH / surfaceView.height.coerceAtLeast(1) * AXIS_UNITS_PER_PIXEL
|
||||
val h = scrollRestX.toInt()
|
||||
val v = scrollRestY.toInt()
|
||||
if (h == 0 && v == 0) return
|
||||
scrollRestX -= h
|
||||
scrollRestY -= v
|
||||
BottomDesktop.sendScene(SCENE_AXIS, v, h)
|
||||
}
|
||||
|
||||
override fun onScrollEnd() {
|
||||
scrollRestX = 0f
|
||||
scrollRestY = 0f
|
||||
BottomDesktop.sendScene(SCENE_AXIS, 0, 0)
|
||||
}
|
||||
|
||||
override fun onZoom(steps: Int) {
|
||||
BottomDesktop.sendKey(KEY_LEFTCTRL, true)
|
||||
BottomDesktop.sendScene(SCENE_WHEEL, steps)
|
||||
BottomDesktop.sendKey(KEY_LEFTCTRL, false)
|
||||
}
|
||||
|
||||
override fun onThreeFingerTap(): Boolean {
|
||||
post { keyboardHost.toggle() }
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onLongPress() {
|
||||
performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
|
||||
|
||||
private companion object {
|
||||
const val SCENE_BUTTON = 3
|
||||
const val SCENE_WHEEL = 4
|
||||
const val SCENE_AXIS = 12
|
||||
const val KEY_LEFTCTRL = 29
|
||||
const val AXIS_UNITS_PER_PIXEL = 3f
|
||||
const val TEXT_FIELD_TAP_MS = 1_000L
|
||||
}
|
||||
}
|
||||
|
||||
internal fun fitDesktop(areaW: Int, areaH: Int, desktopW: Int, desktopH: Int): Pair<Int, Int> {
|
||||
if (areaW <= 0 || areaH <= 0 || desktopW <= 0 || desktopH <= 0) return areaW to areaH
|
||||
val widthLimited = areaW.toLong() * desktopH <= areaH.toLong() * desktopW
|
||||
val w = if (widthLimited) areaW else (desktopW.toLong() * areaH / desktopH).toInt()
|
||||
val h = if (widthLimited) (desktopH.toLong() * areaW / desktopW).toInt() else areaH
|
||||
return if (areaW - w <= 4 && areaH - h <= 4) areaW to areaH else w to h
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.BottomDesktop
|
||||
|
||||
/** What the bottom screen shows while the desktop is not drawing: the session loading screen's throbber and a line of text. */
|
||||
@Composable
|
||||
internal fun BottomDesktopStatus(state: BottomDesktop.State, onStart: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val starting = state == BottomDesktop.State.STARTING
|
||||
Box(Modifier.fillMaxSize().background(colors.background).blockTouches(), contentAlignment = Alignment.Center) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
modifier = Modifier.padding(horizontal = 32.dp),
|
||||
) {
|
||||
LogoThrobber(Modifier.width(if (starting) 96.dp else 76.dp), running = starting)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Text(
|
||||
stringResource(when (state) {
|
||||
BottomDesktop.State.ENDED -> R.string.bottom_desktop_ended
|
||||
BottomDesktop.State.FAILED -> R.string.bottom_desktop_failed
|
||||
BottomDesktop.State.OFF -> R.string.bottom_desktop_off
|
||||
else -> R.string.bottom_desktop_starting
|
||||
}),
|
||||
fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
textAlign = TextAlign.Center, modifier = Modifier.widthIn(max = 420.dp),
|
||||
)
|
||||
if (!starting) {
|
||||
Spacer(Modifier.height(20.dp))
|
||||
PrimaryButton(stringResource(R.string.bottom_desktop_start), main = true, onClick = onStart)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SteamDownload
|
||||
import com.droiddeck.launcher.session.SteamDownloads
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.formatSpeed
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
internal fun downloadRate(previousDone: Long, previousAt: Long, done: Long, at: Long): Long =
|
||||
if (previousDone < 0L || done <= previousDone || at <= previousAt) 0L else (done - previousDone) * 1000L / (at - previousAt)
|
||||
|
||||
private const val STEAM_POLL_MS = 2_000L
|
||||
|
||||
private class SteamRow(val download: SteamDownload, val rate: Long)
|
||||
|
||||
@Composable
|
||||
fun BottomDownloadsPage() {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var steam by remember { mutableStateOf<List<SteamRow>>(emptyList()) }
|
||||
LaunchedEffect(Unit) {
|
||||
var last = emptyMap<String, Pair<Long, Long>>()
|
||||
while (true) {
|
||||
val now = System.currentTimeMillis()
|
||||
val read = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
SteamDownloads.read(LinuxRuntime.rootDir(context), SessionState.steamLibraryMounts, SessionState.steamClientArch)
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
steam = read.map { d ->
|
||||
val before = last[d.appId]
|
||||
SteamRow(d, if (before == null) 0L else downloadRate(before.first, before.second, d.done, now))
|
||||
}
|
||||
last = read.associate { it.appId to (it.done to now) }
|
||||
delay(STEAM_POLL_MS)
|
||||
}
|
||||
}
|
||||
val store = StoresState.downloads.filter { it.isActive }
|
||||
if (steam.isEmpty() && store.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.bottom_downloads_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
return
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(steam, key = { "steam:${it.download.appId}:${it.download.shader}" }) { row ->
|
||||
val d = row.download
|
||||
val detail = when {
|
||||
d.shader -> stringResource(R.string.bottom_downloads_shader)
|
||||
d.paused -> stringResource(R.string.bottom_downloads_paused)
|
||||
d.total <= 0L -> stringResource(R.string.bottom_downloads_queued)
|
||||
else -> listOf("${formatBytes(d.done)} / ${formatBytes(d.total)}", formatSpeed(row.rate)).filter { it.isNotEmpty() }.joinToString(" · ")
|
||||
}
|
||||
BottomDownloadRow(d.name, stringResource(R.string.bottom_downloads_steam), detail,
|
||||
if (d.total > 0L) (d.done.toFloat() / d.total).coerceIn(0f, 1f) else null)
|
||||
}
|
||||
items(store, key = { "store:${it.key}" }) { entry ->
|
||||
val e = StoresState.download(entry.key) ?: entry
|
||||
val detail = when (e.state) {
|
||||
DownloadState.PAUSED -> stringResource(R.string.bottom_downloads_paused)
|
||||
DownloadState.QUEUED -> stringResource(R.string.bottom_downloads_queued)
|
||||
else -> listOf(
|
||||
if (e.bytesTotal > 0L) "${formatBytes(e.bytesDone)} / ${formatBytes(e.bytesTotal)}" else "",
|
||||
formatSpeed(e.speedBps),
|
||||
).filter { it.isNotEmpty() }.joinToString(" · ")
|
||||
}
|
||||
BottomDownloadRow(e.name, e.store.label, detail, e.stageFraction.takeIf { it >= 0f })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BottomDownloadRow(name: String, source: String, detail: String, fraction: Float?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(
|
||||
Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(source, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.padding(start = 8.dp))
|
||||
}
|
||||
if (fraction != null) LinearProgressIndicator(progress = { fraction }, modifier = Modifier.fillMaxWidth(), color = pal.signal)
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth(), color = pal.signal)
|
||||
if (detail.isNotEmpty()) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Presentation
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.view.Display
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
|
||||
class BottomGameScreen(
|
||||
private val activity: Activity,
|
||||
display: Display,
|
||||
private val callback: SurfaceHolder.Callback,
|
||||
private val onTouch: (MotionEvent) -> Boolean,
|
||||
) : Presentation(activity, display) {
|
||||
val surfaceView = SurfaceView(getContext())
|
||||
val holder: SurfaceHolder get() = surfaceView.holder
|
||||
|
||||
val hz: Float get() = display.mode.refreshRate
|
||||
|
||||
init {
|
||||
setCancelable(false)
|
||||
setCanceledOnTouchOutside(false)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val root = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) }
|
||||
root.addView(surfaceView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
|
||||
setContentView(root)
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
@Suppress("DEPRECATION")
|
||||
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
||||
or View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
surfaceView.setOnTouchListener { _, event -> onTouch(event) }
|
||||
surfaceView.holder.addCallback(callback)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean =
|
||||
activity.dispatchKeyEvent(event) || super.dispatchKeyEvent(event)
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean =
|
||||
activity.dispatchGenericMotionEvent(event) || super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
object GameScreenSwap {
|
||||
fun wanted(
|
||||
requested: Boolean,
|
||||
activityStarted: Boolean,
|
||||
sessionEnded: Boolean,
|
||||
inPip: Boolean,
|
||||
glassesOutput: Boolean,
|
||||
bottomScreenFree: Boolean,
|
||||
): Boolean = requested && activityStarted && !sessionEnded && !inPip && !glassesOutput && bottomScreenFree
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.provider.Settings
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.BottomNotifications
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
internal fun notificationAccessIntent(context: android.content.Context): Intent =
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
|
||||
Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS).putExtra(
|
||||
Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME,
|
||||
android.content.ComponentName(context, com.droiddeck.launcher.session.BottomNotificationListener::class.java).flattenToString(),
|
||||
)
|
||||
} else Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
|
||||
|
||||
@Composable
|
||||
fun BottomNotificationsPage(openSettings: ((Intent, () -> Boolean) -> Unit)?) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var granted by remember { mutableStateOf(BottomNotifications.granted(context)) }
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
granted = BottomNotifications.granted(context)
|
||||
delay(2_000L)
|
||||
}
|
||||
}
|
||||
if (!granted) {
|
||||
Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)) {
|
||||
Text(stringResource(R.string.bottom_notifications_why), fontSize = 15.sp, color = colors.onBackground, textAlign = TextAlign.Center)
|
||||
BottomPillButton(stringResource(R.string.bottom_notifications_allow), "bottom-notifications-allow") {
|
||||
val intent = notificationAccessIntent(context)
|
||||
if (openSettings != null) openSettings(intent) { BottomNotifications.granted(context) }
|
||||
else runCatching { context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val shown = BottomNotifications.items
|
||||
if (shown.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.bottom_notifications_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
return
|
||||
}
|
||||
val timeFormat = remember { android.text.format.DateFormat.getTimeFormat(context) }
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.bottom_notifications_count, shown.size), fontSize = 13.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f))
|
||||
BottomPillButton(stringResource(R.string.bottom_notifications_clear), "bottom-notifications-clear") { BottomNotifications.clear() }
|
||||
}
|
||||
LazyColumn(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(shown.toList(), key = { it.key }) { n ->
|
||||
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(n.app, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(timeFormat.format(java.util.Date(n.postedAt)), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (n.title.isNotBlank()) Text(n.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (n.text.isNotBlank()) Text(n.text, fontSize = 14.sp, color = colors.onBackground, maxLines = 4, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun BottomPillButton(label: String, tag: String, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Box(
|
||||
Modifier.height(40.dp).clip(RoundedCornerShape(20.dp)).background(pal.signal.copy(alpha = 0.16f))
|
||||
.clickable(role = Role.Button, onClick = onClick).testTag(tag).padding(horizontal = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Download
|
||||
import androidx.compose.material.icons.outlined.Forum
|
||||
import androidx.compose.material.icons.outlined.Speed
|
||||
import androidx.compose.material.icons.outlined.Notifications
|
||||
import androidx.compose.material.icons.outlined.PhotoLibrary
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
class BottomPageActions(
|
||||
val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null,
|
||||
val fps: () -> Float? = { null },
|
||||
val openSettings: ((intent: android.content.Intent, done: () -> Boolean) -> Unit)? = null,
|
||||
val runningGame: () -> String? = { null },
|
||||
)
|
||||
|
||||
internal const val BOTTOM_PAGE_TELEMETRY = "telemetry"
|
||||
|
||||
fun sessionBottomPages(actions: BottomPageActions): List<BottomPage> = listOf(
|
||||
BottomPage(BOTTOM_PAGE_TELEMETRY, R.string.bottom_page_telemetry, Icons.Outlined.Speed) { BottomTelemetryPage(actions.fps, actions.runningGame) },
|
||||
BottomPage("downloads", R.string.bottom_page_downloads, Icons.Outlined.Download) { BottomDownloadsPage() },
|
||||
BottomPage("notifications", R.string.bottom_page_notifications, Icons.Outlined.Notifications) { BottomNotificationsPage(actions.openSettings) },
|
||||
BottomPage("screenshots", R.string.bottom_page_screenshots, Icons.Outlined.PhotoLibrary) { BottomScreenshotsPage(actions.takeScreenshot) },
|
||||
BottomPage("chat", R.string.bottom_page_chat, Icons.Outlined.Forum) { BottomChatPage() },
|
||||
)
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.MoreHoriz
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
|
||||
internal class BarExtra(
|
||||
val description: String,
|
||||
val icon: Int? = null,
|
||||
val vector: ImageVector? = null,
|
||||
val active: Boolean = false,
|
||||
val tag: String? = null,
|
||||
val onClick: () -> Unit,
|
||||
)
|
||||
|
||||
internal class BottomBarModel(
|
||||
val title: String?,
|
||||
val onClose: (() -> Unit)?,
|
||||
val onMenu: (() -> Unit)?,
|
||||
val onSteam: (() -> Unit)?,
|
||||
val onQam: (() -> Unit)?,
|
||||
val extras: List<BarExtra> = emptyList(),
|
||||
val menuActive: Boolean = false,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun BottomScreenBar(model: BottomBarModel, modifier: Modifier = Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
BoxWithConstraints(modifier.fillMaxWidth().height(BAR_HEIGHT).blockTouches()) {
|
||||
val buttons = listOfNotNull(model.onClose, model.onMenu, model.onQam).size + model.extras.size
|
||||
val steamWidth = if (model.onSteam != null) STEAM_WIDTH + BAR_GAP else 0.dp
|
||||
val titleWidth = if (model.title != null) MIN_TITLE + BAR_GAP else 0.dp
|
||||
val needed = BAR_PAD * 2 + BUTTON * buttons + BAR_GAP * (buttons - 1).coerceAtLeast(0) + steamWidth + titleWidth
|
||||
val fits = maxWidth >= needed
|
||||
Row(
|
||||
Modifier.fillMaxSize().then(if (fits) Modifier else Modifier.horizontalScroll(rememberScrollState()))
|
||||
.padding(horizontal = BAR_PAD, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(BAR_GAP),
|
||||
) {
|
||||
model.onClose?.let {
|
||||
BarButton(stringResource(R.string.common_close), Modifier.testTag("bottom-bar-close"), vector = Icons.Outlined.Close, onClick = it)
|
||||
}
|
||||
if (model.title != null) Text(
|
||||
model.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
modifier = (if (fits) Modifier.weight(1f) else Modifier).padding(start = 4.dp),
|
||||
) else if (fits) Spacer(Modifier.weight(1f))
|
||||
model.extras.forEach { extra ->
|
||||
BarButton(extra.description, extra.tag?.let { Modifier.testTag(it) } ?: Modifier, icon = extra.icon, vector = extra.vector,
|
||||
active = extra.active, onClick = extra.onClick)
|
||||
}
|
||||
BarActions(model.onMenu, model.menuActive, model.onSteam, model.onQam)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun BarActions(
|
||||
onMenu: (() -> Unit)?,
|
||||
menuActive: Boolean,
|
||||
onSteam: (() -> Unit)?,
|
||||
onQam: (() -> Unit)?,
|
||||
menuModifier: Modifier = Modifier,
|
||||
steamModifier: Modifier = Modifier,
|
||||
qamModifier: Modifier = Modifier,
|
||||
qamInteraction: MutableInteractionSource? = null,
|
||||
onQamConfirm: (() -> Unit)? = null,
|
||||
) {
|
||||
onMenu?.let {
|
||||
BarButton(stringResource(R.string.touch_droiddeck_menu), menuModifier.testTag("bottom-bar-menu"), icon = R.drawable.ic_stat_session,
|
||||
active = menuActive, onClick = it)
|
||||
}
|
||||
onSteam?.let {
|
||||
BarButton(stringResource(R.string.drawer_steam_menu), steamModifier.testTag("bottom-bar-steam"), label = "STEAM", onClick = it)
|
||||
}
|
||||
onQam?.let {
|
||||
BarButton(stringResource(R.string.drawer_open_qam), qamModifier.testTag("bottom-bar-qam"), vector = Icons.Outlined.MoreHoriz,
|
||||
interactionSource = qamInteraction ?: remember { MutableInteractionSource() }, onConfirm = onQamConfirm, onClick = it)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun BarButton(
|
||||
description: String,
|
||||
modifier: Modifier = Modifier,
|
||||
icon: Int? = null,
|
||||
vector: ImageVector? = null,
|
||||
label: String? = null,
|
||||
active: Boolean = false,
|
||||
danger: Boolean = false,
|
||||
shortcut: String? = null,
|
||||
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
|
||||
onConfirm: (() -> Unit)? = null,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val hot = interactionSource.collectIsFocusedAsState().value || interactionSource.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(22.dp)
|
||||
val accent = if (danger) colors.error else pal.signal
|
||||
val tint = when {
|
||||
active -> pal.onSignal
|
||||
hot || danger -> accent
|
||||
else -> colors.onBackground
|
||||
}
|
||||
val fill = when {
|
||||
active -> pal.signal
|
||||
hot -> accent.copy(alpha = 0.14f)
|
||||
else -> Color.Transparent
|
||||
}
|
||||
val sized = if (label != null) Modifier.height(44.dp).widthIn(min = 44.dp) else Modifier.size(44.dp)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.then(sized).semantics { contentDescription = description }
|
||||
.clip(shape).background(fill)
|
||||
.glideBorder(hot, shape, accent, if (active) pal.signal else if (danger) colors.error.copy(alpha = 0.6f) else pal.line)
|
||||
.hoverable(interactionSource)
|
||||
.clickable(role = Role.Button, interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onConfirm ?: onClick),
|
||||
) {
|
||||
when {
|
||||
label != null -> Text(label, fontSize = 13.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = tint,
|
||||
maxLines = 1, modifier = Modifier.padding(horizontal = 14.dp))
|
||||
icon != null -> Icon(painterResource(icon), contentDescription = null, tint = tint, modifier = Modifier.size(20.dp))
|
||||
vector != null -> Icon(vector, contentDescription = null, tint = tint, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
if (shortcut != null) Text(
|
||||
shortcut, fontSize = 8.sp, lineHeight = 9.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.align(Alignment.BottomEnd).padding(end = 8.dp, bottom = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
internal val BAR_HEIGHT = 64.dp
|
||||
private val BAR_PAD = 12.dp
|
||||
private val BAR_GAP = 8.dp
|
||||
private val BUTTON = 44.dp
|
||||
private val STEAM_WIDTH = 80.dp
|
||||
private val MIN_TITLE = 72.dp
|
||||
|
||||
internal fun sessionBarModel(
|
||||
title: String?,
|
||||
onClose: (() -> Unit)?,
|
||||
onMenu: (() -> Unit)?,
|
||||
onSteam: () -> Unit,
|
||||
onQam: () -> Unit,
|
||||
extras: List<BarExtra> = emptyList(),
|
||||
): BottomBarModel {
|
||||
val steam = SessionState.mode == SessionService.MODE_STEAM
|
||||
return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras)
|
||||
}
|
||||
|
||||
internal fun bottomScreenBarView(context: Context, model: () -> BottomBarModel): ComposeView = ComposeView(context).apply {
|
||||
setContent { DroidDeckTheme { BottomScreenBar(model()) } }
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.BottomScreenshots
|
||||
import com.droiddeck.launcher.session.BottomShot
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
private const val SHOTS_POLL_MS = 5_000L
|
||||
|
||||
@Composable
|
||||
fun BottomScreenshotsPage(takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)?) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var shots by remember { mutableStateOf<List<BottomShot>>(emptyList()) }
|
||||
var refresh by remember { mutableIntStateOf(0) }
|
||||
var open by remember { mutableStateOf<BottomShot?>(null) }
|
||||
var status by remember { mutableStateOf<Int?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(refresh) {
|
||||
while (true) {
|
||||
shots = withContext(Dispatchers.IO) { BottomScreenshots.list(context, LinuxRuntime.rootDir(context)) }
|
||||
delay(SHOTS_POLL_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(status) {
|
||||
if (status != null) {
|
||||
delay(3_000L)
|
||||
status = null
|
||||
}
|
||||
}
|
||||
open?.let { shot ->
|
||||
Box(Modifier.fillMaxSize().clip(RoundedCornerShape(14.dp)).background(androidx.compose.ui.graphics.Color.Black)
|
||||
.clickable(role = Role.Button) { open = null }.testTag("bottom-shot-full")) {
|
||||
AsyncImage(ImageRequest.Builder(context).data(shot.model).build(), contentDescription = null,
|
||||
contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
return
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(status?.let { stringResource(it) } ?: stringResource(R.string.bottom_shots_where), fontSize = 13.sp,
|
||||
color = colors.onSurfaceVariant, maxLines = 2, modifier = Modifier.weight(1f).padding(end = 8.dp))
|
||||
if (takeScreenshot != null) BottomPillButton(stringResource(R.string.bottom_shots_take), "bottom-shots-take") {
|
||||
if (!busy) {
|
||||
busy = true
|
||||
takeScreenshot { ok ->
|
||||
busy = false
|
||||
status = if (ok) R.string.bottom_shots_saved else R.string.bottom_shots_failed
|
||||
refresh++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shots.isEmpty()) {
|
||||
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.bottom_shots_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
} else {
|
||||
LazyVerticalGrid(GridCells.Adaptive(150.dp), Modifier.weight(1f).fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(shots, key = { it.model.toString() }) { shot ->
|
||||
AsyncImage(
|
||||
ImageRequest.Builder(context).data(shot.model).size(480, 270).build(), contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).clip(RoundedCornerShape(10.dp))
|
||||
.background(LocalPalette.current.surface).clickable(role = Role.Button) { open = shot },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudConfig
|
||||
import com.droiddeck.launcher.hud.FrameStats
|
||||
import com.droiddeck.launcher.hud.GameFrameFeed
|
||||
import com.droiddeck.launcher.hud.HudFrames
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.hud.KeyValueSet
|
||||
import com.droiddeck.launcher.hud.MangoReadings
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.StripMetric
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
private const val STRIP_FRAME_MS = 33L
|
||||
private const val STRIP_METRICS_MS = 500L
|
||||
private const val STRIP_TEMP_PLAIN = 0xFFF2F5F9.toInt()
|
||||
|
||||
@Composable
|
||||
internal fun SessionBottomStrip(pageId: String?, fps: () -> Float?) {
|
||||
val context = LocalContext.current
|
||||
val frames = remember { GameFrameFeed(File(LinuxRuntime.rootDir(context), HudFrames.PATH)) }
|
||||
DisposableEffect(frames) { onDispose { frames.close() } }
|
||||
val page by rememberUpdatedState(pageId)
|
||||
var frameTick by remember { mutableIntStateOf(0) }
|
||||
var device by remember { mutableStateOf<HudMetrics.Snapshot?>(null) }
|
||||
var clock by remember { mutableStateOf("") }
|
||||
var onTabs by remember { mutableStateOf(SessionPrefs.bottomHud(context) && SessionPrefs.bottomStripOnTabs(context)) }
|
||||
var metrics by remember { mutableStateOf(SessionPrefs.bottomStripMetrics(context)) }
|
||||
var thresholds by remember { mutableStateOf<Map<HudMetrics.TempSensor, HudMetrics.Thresholds>>(emptyMap()) }
|
||||
val tempDisplay = remember { HudMetrics.TempDisplay.from(KeyValueSet(DroidDeckHudConfig.encode(DroidDeckHudConfig.load(context)))) }
|
||||
LaunchedEffect(frames) {
|
||||
while (isActive) {
|
||||
if (frames.poll(System.nanoTime()) || !frames.live) frameTick++
|
||||
delay(STRIP_FRAME_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
val reader = HudMetrics(context).apply { setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context))) }
|
||||
thresholds = withContext(Dispatchers.IO) {
|
||||
HudMetrics.TempSensor.values().mapNotNull { sensor -> runCatching { sensor to reader.resolveThresholds(sensor, tempDisplay) }.getOrNull() }.toMap()
|
||||
}
|
||||
while (isActive) {
|
||||
onTabs = SessionPrefs.bottomHud(context) && SessionPrefs.bottomStripOnTabs(context)
|
||||
metrics = SessionPrefs.bottomStripMetrics(context)
|
||||
if (onTabs && page != BOTTOM_PAGE_TELEMETRY) {
|
||||
if (StripMetric.GPU in metrics || StripMetric.VRAM in metrics) com.droiddeck.launcher.hud.BottomHudPresence.beat()
|
||||
device = withContext(Dispatchers.IO) { runCatching { reader.snapshot() }.getOrNull() }
|
||||
clock = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date())
|
||||
}
|
||||
delay(STRIP_METRICS_MS)
|
||||
}
|
||||
}
|
||||
if (!onTabs || pageId == BOTTOM_PAGE_TELEMETRY) return
|
||||
frameTick.let {
|
||||
val live = frames.live
|
||||
val stats = frames.stats
|
||||
val graph = FloatArray(FrameStats.GRAPH_FRAMES).also { if (live) stats.graph(it) }
|
||||
LineStrip(StripData(
|
||||
fps = if (live) stats.fps else fps(), device = device,
|
||||
fpsHistory = emptyList(), cpuHistory = emptyList(), gpuHistory = emptyList(), wattsHistory = emptyList(), clock = clock,
|
||||
engine = if (live && !frames.steamFocused) frames.engine else "",
|
||||
lows = if (live) stats.lows(System.nanoTime()) else null, graph = graph, metrics = metrics,
|
||||
fahrenheit = tempDisplay.fahrenheit,
|
||||
tempColor = { sensor, c ->
|
||||
thresholds[sensor]?.let { Color(HudMetrics.tempColor(c.toFloat(), it, tempDisplay, STRIP_TEMP_PLAIN)) } ?: Color(STRIP_TEMP_PLAIN)
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Resources
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.SwitchDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.CpuCores
|
||||
import com.droiddeck.launcher.frontend.AddedGameArt
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.frontend.SteamGameArt
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudConfig
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudHost
|
||||
import com.droiddeck.launcher.hud.FrameStats
|
||||
import com.droiddeck.launcher.hud.GameFrameFeed
|
||||
import com.droiddeck.launcher.hud.HudFrames
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.hud.KeyValueSet
|
||||
import com.droiddeck.launcher.hud.MangoReadings
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStatusFiles
|
||||
import com.droiddeck.launcher.session.GameTelemetry
|
||||
import com.droiddeck.launcher.session.HwmonComponent
|
||||
import com.droiddeck.launcher.input.SteamTouchConfig
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SpeedUnit
|
||||
import com.droiddeck.launcher.session.StatsDash
|
||||
import com.droiddeck.launcher.session.StatsHud
|
||||
import com.droiddeck.launcher.session.StatsStrip
|
||||
import com.droiddeck.launcher.session.Telemetry
|
||||
import com.droiddeck.launcher.session.TelemetryOutput
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.URL
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
private const val DRAW_MS = 66L
|
||||
private const val TELEMETRY_STALE_MS = 3_000L
|
||||
private const val METRICS_MS = 500L
|
||||
private const val THUNDER_MS = 500L
|
||||
private const val THUNDER_RETRY_MS = 3_000L
|
||||
private const val ELITE_MS = 1_000L
|
||||
private const val ELITE_SEARCH_MS = 10_000L
|
||||
private const val OUTPUT_SCAN_MS = 3_000L
|
||||
private const val PERF_N = 60
|
||||
private const val FRAME_MS = 33L
|
||||
private const val MINUTE_NS = 60_000_000_000L
|
||||
private const val TEMP_PLAIN = 0xFFF2F5F9.toInt()
|
||||
|
||||
private class PortTraffic {
|
||||
@Volatile var packets = 0L
|
||||
@Volatile var length = 0
|
||||
@Volatile var readable = true
|
||||
}
|
||||
|
||||
private data class UnknownTraffic(val port: Int, val packets: Long, val length: Int)
|
||||
|
||||
@Composable
|
||||
fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val scope = rememberCoroutineScope()
|
||||
var outputs by remember { mutableStateOf<List<TelemetryOutput.Game>>(emptyList()) }
|
||||
var menuGames by remember { mutableStateOf<List<TelemetryOutput.MenuGame>>(emptyList()) }
|
||||
var running by remember { mutableStateOf<String?>(null) }
|
||||
var gameName by remember { mutableStateOf<String?>(null) }
|
||||
val steamClient = remember { if (SessionState.mode == SessionService.MODE_STEAM) SessionPrefs.activeSteamClientArch(context) else null }
|
||||
var outputFailed by remember { mutableStateOf<String?>(null) }
|
||||
var rescan by remember { mutableIntStateOf(0) }
|
||||
var auto by remember { mutableStateOf(SessionPrefs.telemetryAuto(context)) }
|
||||
val latest = remember { AtomicReference<Pair<Long, Telemetry>?>(null) }
|
||||
var race by remember { mutableStateOf<Telemetry?>(null) }
|
||||
var fpsNow by remember { mutableStateOf<Float?>(null) }
|
||||
var device by remember { mutableStateOf<HudMetrics.Snapshot?>(null) }
|
||||
var thunder by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) }
|
||||
var elite by remember { mutableStateOf<GameStatusFiles.Elite?>(null) }
|
||||
var busyPorts by remember { mutableStateOf<Set<Int>>(emptySet()) }
|
||||
val traffic = remember { GameTelemetry.PORTS.associateWith { PortTraffic() } }
|
||||
var unknown by remember { mutableStateOf<List<UnknownTraffic>>(emptyList()) }
|
||||
var strip by remember { mutableStateOf(StatsStrip.from(SessionPrefs.statsStrip(context))) }
|
||||
var dash by remember { mutableStateOf(StatsDash.from(SessionPrefs.statsDash(context))) }
|
||||
val speedUnit = SpeedUnit.from(SessionPrefs.statsSpeedUnit(context))
|
||||
val shownUnit = speedUnit.resolve(Resources.getSystem().configuration.locales[0].country)
|
||||
val fpsHistory = remember { History(PERF_N) }
|
||||
val cpuHistory = remember { History(PERF_N) }
|
||||
val gpuHistory = remember { History(PERF_N) }
|
||||
val wattsHistory = remember { History(PERF_N) }
|
||||
val throttleTrace = remember { History(TRACE_N) }
|
||||
val brakeTrace = remember { History(TRACE_N) }
|
||||
val speedTrace = remember { History(TRACE_N) }
|
||||
var perfTick by remember { mutableIntStateOf(0) }
|
||||
var traceTick by remember { mutableIntStateOf(0) }
|
||||
var clock by remember { mutableStateOf("") }
|
||||
val frames = remember { GameFrameFeed(File(LinuxRuntime.rootDir(context), HudFrames.PATH)) }
|
||||
DisposableEffect(frames) { onDispose { frames.close() } }
|
||||
val currentFps = { if (frames.live) frames.stats.fps else fps() }
|
||||
var hud by remember { mutableStateOf(StatsHud.from(SessionPrefs.statsHud(context))) }
|
||||
var hudOn by remember { mutableStateOf(SessionPrefs.bottomHud(context)) }
|
||||
var hudTick by remember { mutableIntStateOf(0) }
|
||||
var fanRpm by remember { mutableStateOf<Long?>(null) }
|
||||
var gpuName by remember { mutableStateOf("") }
|
||||
var proton by remember { mutableStateOf<String?>(null) }
|
||||
var playedSeconds by remember { mutableStateOf<Long?>(null) }
|
||||
var cover by remember { mutableStateOf<File?>(null) }
|
||||
var coreGroups by remember { mutableStateOf<List<CoreGroup>>(emptyList()) }
|
||||
var thresholds by remember { mutableStateOf<Map<HudMetrics.TempSensor, HudMetrics.Thresholds>>(emptyMap()) }
|
||||
val tempDisplay = remember { HudMetrics.TempDisplay.from(KeyValueSet(DroidDeckHudConfig.encode(DroidDeckHudConfig.load(context)))) }
|
||||
val gameCores = remember { CpuCores.parse(SessionPrefs.gameCpus(context)) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
for (port in GameTelemetry.PORTS) launch(Dispatchers.IO) {
|
||||
val socket = runCatching {
|
||||
DatagramSocket(null).apply {
|
||||
reuseAddress = true
|
||||
soTimeout = 500
|
||||
bind(InetSocketAddress(GameTelemetry.LISTEN_ADDRESS, port))
|
||||
}
|
||||
}.getOrNull()
|
||||
if (socket == null) {
|
||||
withContext(Dispatchers.Main) { busyPorts = busyPorts + port }
|
||||
return@launch
|
||||
}
|
||||
val seen = traffic.getValue(port)
|
||||
socket.use {
|
||||
val data = ByteArray(2048)
|
||||
val packet = DatagramPacket(data, data.size)
|
||||
while (isActive) {
|
||||
try {
|
||||
packet.length = data.size
|
||||
it.receive(packet)
|
||||
val t = GameTelemetry.parse(port, data, packet.length)
|
||||
seen.packets++
|
||||
seen.length = packet.length
|
||||
seen.readable = t != null
|
||||
if (t != null) latest.set(System.currentTimeMillis() to t)
|
||||
} catch (_: SocketTimeoutException) {
|
||||
} catch (_: java.io.IOException) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
while (isActive) {
|
||||
val reading = latest.get()
|
||||
race = reading?.takeIf { System.currentTimeMillis() - it.first < TELEMETRY_STALE_MS }?.second
|
||||
race?.let { r ->
|
||||
throttleTrace.add(r.throttle ?: 0f)
|
||||
brakeTrace.add(r.brake ?: 0f)
|
||||
speedTrace.add(r.speedKmh ?: 0f)
|
||||
traceTick++
|
||||
}
|
||||
fpsNow = currentFps()
|
||||
unknown = traffic.filter { (_, t) -> t.packets > 0 && !t.readable }.map { (port, t) -> UnknownTraffic(port, t.packets, t.length) }
|
||||
delay(DRAW_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(frames) {
|
||||
while (isActive) {
|
||||
if (frames.poll(System.nanoTime())) hudTick++
|
||||
delay(FRAME_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
val metrics = HudMetrics(context).apply { setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context))) }
|
||||
val fanPath = withContext(Dispatchers.IO) { runCatching { HwmonComponent.fanSource() }.getOrNull() }
|
||||
gpuName = withContext(Dispatchers.IO) { runCatching { GpuInfo.detect().displayName(context) }.getOrDefault("") }
|
||||
coreGroups = withContext(Dispatchers.IO) { coreGroups() }
|
||||
thresholds = withContext(Dispatchers.IO) {
|
||||
HudMetrics.TempSensor.values().mapNotNull { sensor -> runCatching { sensor to metrics.resolveThresholds(sensor, tempDisplay) }.getOrNull() }.toMap()
|
||||
}
|
||||
var protonPid = 0
|
||||
while (isActive) {
|
||||
device = withContext(Dispatchers.IO) { runCatching { metrics.snapshot() }.getOrNull() }
|
||||
fanRpm = fanPath?.let { path -> withContext(Dispatchers.IO) { HwmonComponent.readRpm(path) } }
|
||||
val pid = if (frames.live && !frames.steamFocused) frames.pid else 0
|
||||
if (pid == 0) {
|
||||
protonPid = 0
|
||||
if (!frames.live) proton = null
|
||||
} else if (pid != protonPid) {
|
||||
val name = withContext(Dispatchers.IO) { DroidDeckHudHost.protonName(pid) }
|
||||
proton = name
|
||||
if (name != null) protonPid = pid
|
||||
}
|
||||
playedSeconds = if (pid > 0 && running != null) withContext(Dispatchers.IO) { processSeconds(pid) } else null
|
||||
val sampledAt = android.os.SystemClock.elapsedRealtime()
|
||||
currentFps()?.takeIf { it > 0f }?.let { fpsHistory.add(it, sampledAt) }
|
||||
device?.let { s ->
|
||||
s.cpuPercent?.let { cpuHistory.add(it.toFloat(), sampledAt) }
|
||||
s.gpuPercent?.let { gpuHistory.add(it.toFloat(), sampledAt) }
|
||||
s.battery?.watts?.takeIf { it > 0f }?.let { wattsHistory.add(it) }
|
||||
}
|
||||
clock = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date())
|
||||
hudOn = SessionPrefs.bottomHud(context)
|
||||
if (hudOn) com.droiddeck.launcher.hud.BottomHudPresence.beat()
|
||||
perfTick++
|
||||
delay(METRICS_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
while (isActive) {
|
||||
val rows = withContext(Dispatchers.IO) { runCatching { GameStatusFiles.warThunder(httpGet(GameStatusFiles.WAR_THUNDER_STATE)) }.getOrNull() }
|
||||
thunder = rows.orEmpty()
|
||||
delay(if (rows == null) THUNDER_RETRY_MS else THUNDER_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
var file: File? = null
|
||||
var searchedAt = 0L
|
||||
while (isActive) {
|
||||
val now = System.currentTimeMillis()
|
||||
if (file == null && now - searchedAt > ELITE_SEARCH_MS) {
|
||||
searchedAt = now
|
||||
file = withContext(Dispatchers.IO) {
|
||||
runCatching { GameStatusFiles.eliteStatusFile(LinuxRuntime.rootDir(context), SessionState.steamLibraryMounts) }.getOrNull()
|
||||
}
|
||||
}
|
||||
val f = file
|
||||
elite = if (f != null && now - f.lastModified() < 60_000L) {
|
||||
withContext(Dispatchers.IO) { runCatching { GameStatusFiles.elite(f.readText()) }.getOrNull() }
|
||||
} else null
|
||||
delay(ELITE_MS)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
menuGames = withContext(Dispatchers.IO) {
|
||||
runCatching { Library.steamGames(context).mapNotNull { TelemetryOutput.MENU_GAMES[it.appId] }.distinct() }.getOrDefault(emptyList())
|
||||
}
|
||||
}
|
||||
LaunchedEffect(running) {
|
||||
val id = running?.toLongOrNull()
|
||||
gameName = if (id == null) null
|
||||
else withContext(Dispatchers.IO) { runCatching { SteamTouchConfig.gameName(context, id.toInt()) }.getOrNull() }
|
||||
cover = if (id == null) null else withContext(Dispatchers.IO) { runCatching { gameCover(context, id.toInt()) }.getOrNull() }
|
||||
}
|
||||
LaunchedEffect(rescan) {
|
||||
while (isActive) {
|
||||
outputs = withContext(Dispatchers.IO) { runCatching { TelemetryOutput.scan(Library.compatdataDirs(context)) }.getOrDefault(emptyList()) }
|
||||
running = runningGame()
|
||||
delay(OUTPUT_SCAN_MS)
|
||||
}
|
||||
}
|
||||
|
||||
val title = if (running != null) gameName else steamClient?.let { stringResource(steamClientLabel(it)) }
|
||||
val noData = race == null && thunder.isEmpty() && elite == null
|
||||
BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
val viewport = maxHeight
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (!hudOn) Unit
|
||||
else if (noData) hudTick.let {
|
||||
perfTick.let {
|
||||
val now = System.nanoTime()
|
||||
val live = frames.live
|
||||
val stats = frames.stats
|
||||
val graph = FloatArray(FrameStats.GRAPH_FRAMES).also { if (live) stats.graph(it) }
|
||||
val hz = (frames.refreshMilliHz + 499) / 1000
|
||||
val data = HudData(
|
||||
fps = fpsNow, avgFps = if (live) stats.averageFps() else null, lows = if (live) stats.lows(now) else FrameStats.Lows.EMPTY,
|
||||
graph = graph, slowPerMinute = if (live) stats.slowFrames(now, MINUTE_NS) else null,
|
||||
engine = if (live && !frames.steamFocused) frames.engine else "",
|
||||
resolution = if (frames.outputWidth > 0 && frames.outputHeight > 0) {
|
||||
"${frames.outputWidth}x${frames.outputHeight}" + (if (hz > 0) " @ ${hz}Hz" else "")
|
||||
} else "",
|
||||
refreshHz = hz, proton = proton, device = device, gpuName = gpuName, fanRpm = fanRpm,
|
||||
title = title, cover = cover, played = playedSeconds?.let(::playedText), clock = clock,
|
||||
fpsHistory = fpsHistory.snapshot(), cpuHistory = cpuHistory.snapshot(), gpuHistory = gpuHistory.snapshot(),
|
||||
historySeconds = maxOf(fpsHistory.spanSeconds(), cpuHistory.spanSeconds(), gpuHistory.spanSeconds()),
|
||||
coreGroups = coreGroups, gameCores = gameCores, fahrenheit = tempDisplay.fahrenheit,
|
||||
tempColor = { sensor, c ->
|
||||
thresholds[sensor]?.let { Color(HudMetrics.tempColor(c.toFloat(), it, tempDisplay, TEMP_PLAIN)) } ?: Color(TEMP_PLAIN)
|
||||
},
|
||||
redC = { thresholds[it]?.redC },
|
||||
)
|
||||
StatsHudView(hud, data, Modifier.fillMaxWidth().height(viewport)) {
|
||||
hud = hud.next()
|
||||
SessionPrefs.setStatsHud(context, hud.id)
|
||||
}
|
||||
}
|
||||
} else hudTick.let {
|
||||
perfTick.let {
|
||||
val live = frames.live
|
||||
val graph = FloatArray(FrameStats.GRAPH_FRAMES).also { if (live) frames.stats.graph(it) }
|
||||
val data = StripData(
|
||||
fpsNow, device, fpsHistory.snapshot(), cpuHistory.snapshot(), gpuHistory.snapshot(), wattsHistory.snapshot(), clock, title,
|
||||
engine = if (live && !frames.steamFocused) frames.engine else "",
|
||||
lows = if (live) frames.stats.lows(System.nanoTime()) else null, graph = graph,
|
||||
metrics = SessionPrefs.bottomStripMetrics(context), fahrenheit = tempDisplay.fahrenheit,
|
||||
tempColor = { sensor, c ->
|
||||
thresholds[sensor]?.let { Color(HudMetrics.tempColor(c.toFloat(), it, tempDisplay, TEMP_PLAIN)) } ?: Color(TEMP_PLAIN)
|
||||
},
|
||||
)
|
||||
StatsStripView(strip, data) {
|
||||
strip = strip.next()
|
||||
SessionPrefs.setStatsStrip(context, strip.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
race?.let { r ->
|
||||
val shown = dash.resolve(r.source)
|
||||
traceTick.let {
|
||||
RaceDashView(shown, r, TraceData(throttleTrace.snapshot(), brakeTrace.snapshot(), speedTrace.snapshot()), shownUnit) {
|
||||
dash = StatsDash.tapped(shown)
|
||||
SessionPrefs.setStatsDash(context, dash.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (thunder.isNotEmpty()) {
|
||||
if (FlightLabels.drawable(thunder)) FlightDash(thunder)
|
||||
else TelemetryCard(stringResource(R.string.bottom_telemetry_war_thunder)) { ValueGrid(thunder.take(GameStatusFiles.WAR_THUNDER_ROWS)) }
|
||||
}
|
||||
elite?.let { e ->
|
||||
if (e.pips != null || e.fuelMain != null) ShipDash(e)
|
||||
else TelemetryCard(stringResource(R.string.bottom_telemetry_elite)) {
|
||||
ValueGrid(listOfNotNull(
|
||||
e.fuelMain?.let { stringResource(R.string.bottom_telemetry_fuel) to "%.1f t".format(it) },
|
||||
e.cargo?.let { stringResource(R.string.bottom_telemetry_cargo) to "%.0f t".format(it) },
|
||||
e.pips?.takeIf { it.size == 3 }?.let { p ->
|
||||
stringResource(R.string.bottom_telemetry_pips) to p.joinToString(" · ") { "%.1f".format(it / 2f) }
|
||||
},
|
||||
e.legal?.let { stringResource(R.string.bottom_telemetry_legal) to it },
|
||||
e.balance?.let { stringResource(R.string.bottom_telemetry_balance) to "%,d CR".format(it) },
|
||||
))
|
||||
}
|
||||
}
|
||||
if (outputs.isNotEmpty() || menuGames.isNotEmpty()) TelemetryCard(stringResource(R.string.bottom_telemetry_send_title)) {
|
||||
if (outputs.isNotEmpty()) SwitchRow(stringResource(R.string.bottom_telemetry_send_auto), stringResource(R.string.bottom_telemetry_send_auto_hint), auto, true) { want ->
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) {
|
||||
SessionPrefs.setTelemetryAuto(context, want)
|
||||
if (want) TelemetryOutput.applyAutomatic(context, running)
|
||||
else TelemetryOutput.restoreTargets(outputs, running).forEach { TelemetryOutput.set(it, false) }
|
||||
}
|
||||
auto = want
|
||||
rescan++
|
||||
}
|
||||
}
|
||||
for (game in outputs) {
|
||||
val locked = TelemetryOutput.isRunning(game.prefixId, running)
|
||||
val hint = if (locked) stringResource(R.string.bottom_telemetry_send_close, game.name) else null
|
||||
SwitchRow(game.name, hint, game.on, !locked) { want ->
|
||||
scope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
val key = TelemetryOutput.key(game)
|
||||
val off = SessionPrefs.telemetryOff(context)
|
||||
SessionPrefs.setTelemetryOff(context, if (want) off - key else off + key)
|
||||
TelemetryOutput.set(game, want)
|
||||
}
|
||||
outputFailed = if (ok) null else game.name
|
||||
rescan++
|
||||
}
|
||||
}
|
||||
}
|
||||
for (game in menuGames) {
|
||||
Text(stringResource(R.string.bottom_telemetry_send_menu, game.name, game.setting, game.port), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (outputs.isNotEmpty()) Text(stringResource(R.string.bottom_telemetry_send_note), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
outputFailed?.let { Text(stringResource(R.string.bottom_telemetry_send_failed, it), fontSize = 12.sp, color = colors.error) }
|
||||
}
|
||||
for (u in unknown) {
|
||||
Text(stringResource(R.string.bottom_telemetry_unknown_format, u.port, u.packets, u.length), fontSize = 13.sp,
|
||||
color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
if (busyPorts.isNotEmpty()) {
|
||||
Text(stringResource(R.string.bottom_telemetry_port_busy, busyPorts.sorted().joinToString()), fontSize = 13.sp,
|
||||
color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun processSeconds(pid: Int): Long? = runCatching {
|
||||
val fields = File("/proc/$pid/stat").readText().substringAfterLast(')').trim().split(' ')
|
||||
val startTicks = fields[19].toLong()
|
||||
val uptime = File("/proc/uptime").readText().substringBefore(' ').toDouble()
|
||||
(uptime - startTicks.toDouble() / Os.sysconf(OsConstants._SC_CLK_TCK)).toLong()
|
||||
}.getOrNull()?.takeIf { it >= 0 }
|
||||
|
||||
private fun playedText(seconds: Long): String =
|
||||
if (seconds >= 3600) "%d:%02d:%02d".format(seconds / 3600, seconds / 60 % 60, seconds % 60) else "%d:%02d".format(seconds / 60, seconds % 60)
|
||||
|
||||
private fun gameCover(context: Context, appId: Int): File? =
|
||||
SteamGameArt.chosenFile(context, appId, AddedGameArt.Slot.COVER)
|
||||
?: Library.steamCacheImage(File(SessionPrefs.activeSteamRoot(context), "appcache/librarycache"), appId, listOf("library_capsule.jpg", "library_600x900.jpg"))
|
||||
|
||||
private fun coreGroups(): List<CoreGroup> {
|
||||
val out = mutableListOf<CoreGroup>()
|
||||
for (core in CpuCores.all) {
|
||||
val ghz = CpuCores.maxGhz(core)
|
||||
val last = out.lastOrNull()
|
||||
if (last != null && last.maxGhz == ghz) out[out.lastIndex] = CoreGroup(last.cores + core, ghz) else out += CoreGroup(listOf(core), ghz)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun httpGet(url: String): String {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 300
|
||||
c.readTimeout = 500
|
||||
return try {
|
||||
c.inputStream.bufferedReader().use { it.readText() }
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun steamClientLabel(arch: String): Int = if (arch == "x86_64") R.string.stats_steam_client_x86 else R.string.stats_steam_client_arm
|
||||
|
||||
@Composable
|
||||
private fun SwitchRow(title: String, hint: String?, checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(
|
||||
Modifier.fillMaxWidth().toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChange).padding(vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f).padding(end = 12.dp)) {
|
||||
Text(title, fontSize = 15.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (hint != null) Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
val pal = LocalPalette.current
|
||||
Switch(checked, null, enabled = enabled, colors = SwitchDefaults.colors(
|
||||
disabledCheckedTrackColor = pal.primary.copy(alpha = 0.45f),
|
||||
disabledCheckedThumbColor = colors.background,
|
||||
disabledCheckedBorderColor = pal.primary.copy(alpha = 0.45f),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun TelemetryCard(title: String, content: @Composable () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal)
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ValueGrid(rows: List<Pair<String, String>>) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
rows.chunked(2).forEach { pair ->
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
pair.forEach { (k, v) ->
|
||||
Row(Modifier.weight(1f)) {
|
||||
Text(k, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(v, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
if (pair.size == 1) Box(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun lapTime(seconds: Float): String {
|
||||
val total = kotlin.math.round(seconds * 1000.0).toLong()
|
||||
return "%d:%02d.%03d".format(total / 60_000, total / 1000 % 60, total % 1000)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Typeface
|
||||
import android.os.Bundle
|
||||
import android.text.TextPaint
|
||||
import android.text.TextUtils
|
||||
import android.util.TypedValue
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.QuestXrActivity
|
||||
|
||||
object BuildWatermark {
|
||||
private const val TITLE_LIMIT = 80
|
||||
|
||||
fun lines(
|
||||
pr: Int = BuildConfig.PR_NUMBER,
|
||||
ci: Boolean = BuildConfig.CI_BUILD,
|
||||
commit: String = BuildConfig.SOURCE_COMMIT,
|
||||
title: String = BuildConfig.PR_TITLE,
|
||||
branch: String = BuildConfig.BUILD_BRANCH,
|
||||
): List<String>? {
|
||||
if (ci && pr <= 0) return null
|
||||
val hash = commit.take(7).ifEmpty { "unknown" }
|
||||
val head = if (pr > 0) "PR-$pr | $hash" else "LOCAL | $hash"
|
||||
val detail = (if (pr > 0) title else branch).trim()
|
||||
return if (detail.isEmpty()) listOf(head) else listOf(head, truncate(detail))
|
||||
}
|
||||
|
||||
private fun truncate(text: String) =
|
||||
if (text.length <= TITLE_LIMIT) text else text.take(TITLE_LIMIT - 1).trimEnd() + "…"
|
||||
|
||||
fun install(app: Application) {
|
||||
val lines = lines() ?: return
|
||||
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
|
||||
if (activity is QuestXrActivity) return
|
||||
val decor = activity.window.decorView as? ViewGroup ?: return
|
||||
if (decor.findViewWithTag<View>(TAG) != null) return
|
||||
val margin = (8 * activity.resources.displayMetrics.density).toInt()
|
||||
decor.addView(
|
||||
MarkView(activity, lines).apply { tag = TAG },
|
||||
FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
Gravity.BOTTOM or Gravity.END,
|
||||
).apply { setMargins(margin, margin, margin, margin) },
|
||||
)
|
||||
}
|
||||
|
||||
override fun onActivityStarted(activity: Activity) = Unit
|
||||
override fun onActivityResumed(activity: Activity) = Unit
|
||||
override fun onActivityPaused(activity: Activity) = Unit
|
||||
override fun onActivityStopped(activity: Activity) = Unit
|
||||
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
|
||||
override fun onActivityDestroyed(activity: Activity) = Unit
|
||||
})
|
||||
}
|
||||
|
||||
private const val TAG = "build-watermark"
|
||||
|
||||
private class MarkView(context: Context, private val lines: List<String>) : View(context) {
|
||||
private var shown = lines
|
||||
private val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = 0xE6FFFFFF.toInt()
|
||||
typeface = Typeface.MONOSPACE
|
||||
textSize = TypedValue.applyDimension(
|
||||
TypedValue.COMPLEX_UNIT_SP, 9f, context.resources.displayMetrics,
|
||||
)
|
||||
setShadowLayer(1.5f * context.resources.displayMetrics.density, 0f, 0f, 0xFF000000.toInt())
|
||||
textAlign = Paint.Align.RIGHT
|
||||
}
|
||||
private val backdrop = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = 0x66303030 }
|
||||
private val lineHeight get() = paint.fontSpacing
|
||||
|
||||
init {
|
||||
isClickable = false
|
||||
isFocusable = false
|
||||
importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||
setLayerType(LAYER_TYPE_SOFTWARE, null)
|
||||
}
|
||||
|
||||
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
|
||||
val pad = paddingForShadow() * 2
|
||||
val limit = if (MeasureSpec.getMode(widthSpec) == MeasureSpec.UNSPECIFIED) Float.MAX_VALUE
|
||||
else (MeasureSpec.getSize(widthSpec) - pad).coerceAtLeast(0).toFloat()
|
||||
shown = lines.map { TextUtils.ellipsize(it, paint, limit, TextUtils.TruncateAt.END).toString() }
|
||||
val width = shown.maxOf { paint.measureText(it) }.toInt() + pad
|
||||
setMeasuredDimension(width, (lineHeight * shown.size).toInt() + pad)
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val pad = paddingForShadow()
|
||||
val radius = 3f * resources.displayMetrics.density
|
||||
canvas.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), radius, radius, backdrop)
|
||||
shown.forEachIndexed { i, line ->
|
||||
canvas.drawText(line, width - pad.toFloat(), pad - paint.ascent() + lineHeight * i, paint)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: android.view.MotionEvent) = false
|
||||
|
||||
private fun paddingForShadow() = (3 * resources.displayMetrics.density).toInt()
|
||||
}
|
||||
}
|
||||
@@ -40,10 +40,8 @@ import kotlinx.coroutines.delay
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.getValue
|
||||
|
||||
/** A grid of cards with a game page that floods out of the opened card and drains back into it. */
|
||||
internal val LocalDetailFloor = compositionLocalOf<() -> Float> { { Float.MAX_VALUE } }
|
||||
|
||||
/** How far the host reaches past the page's padding, so a game page can paint to the screen edge and still inset its content. */
|
||||
internal class DetailInset(val horizontal: Dp, val top: Dp)
|
||||
internal val LocalDetailInset = compositionLocalOf { DetailInset(0.dp, 0.dp) }
|
||||
|
||||
|
||||
@@ -43,7 +43,6 @@ import kotlin.math.atan2
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.min
|
||||
|
||||
/** A small colour square; pressing it opens the colour picker. */
|
||||
@Composable
|
||||
internal fun ColorCube(color: Color, description: String, focus: FocusRequester? = null, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
@@ -59,7 +58,6 @@ internal fun ColorCube(color: Color, description: String, focus: FocusRequester?
|
||||
)
|
||||
}
|
||||
|
||||
/** Colour wheel (touch), hue / saturation / brightness sliders (controller and touch) and a hex box for one colour. */
|
||||
@Composable
|
||||
internal fun ColorPickerDialog(title: String, initial: Int, onDismiss: () -> Unit, onApply: (Int) -> Unit) {
|
||||
val shown = rememberShown(onDismiss)
|
||||
@@ -117,7 +115,6 @@ private fun Swatch(color: Color) {
|
||||
Box(Modifier.size(48.dp).clip(shape).background(color).border(1.dp, LocalPalette.current.line2, shape))
|
||||
}
|
||||
|
||||
/** Hue around the circle and saturation out from the middle, at full brightness; brightness has its own slider. */
|
||||
@Composable
|
||||
private fun ColorWheel(hue: Float, sat: Float, value: Float, onPick: (hue: Float, sat: Float) -> Unit) {
|
||||
val rim = MaterialTheme.colorScheme.onBackground
|
||||
|
||||
@@ -930,7 +930,6 @@ private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapsh
|
||||
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
|
||||
}
|
||||
|
||||
// The rows to show: each stable row carries its paired nightly (if any), and a paired nightly has no row of its own.
|
||||
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
|
||||
val available = availableFor(l, catalog, snapshot)
|
||||
val pairs = ComponentsManager.nightlyPairs(available)
|
||||
@@ -1456,7 +1455,6 @@ private fun GetLine(
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
// Stable | Nightly in the same box as SmallButton: one focus stop, A (or a tap) flips it.
|
||||
@Composable
|
||||
private fun ChannelToggle(nightly: Boolean, enabled: Boolean, onFlip: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
@@ -44,6 +44,7 @@ class DeckControlsPanel(
|
||||
private val inputRole: InputRole = InputRole.SECONDARY,
|
||||
private val portraitDock: Boolean = false,
|
||||
private val onMenu: (() -> Unit)? = null,
|
||||
private val onSwap: (() -> Unit)? = null,
|
||||
) : LinearLayout(context) {
|
||||
private enum class Tab(val label: Int) { GAMEPAD(R.string.deck_tab_gamepad), GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
|
||||
|
||||
@@ -51,12 +52,20 @@ class DeckControlsPanel(
|
||||
private val content = FrameLayout(context)
|
||||
val deckControls = pad == null || SessionState.deckPad
|
||||
private val tabViews = HashMap<Tab, TextView>()
|
||||
private val topBar: View by lazy { topBar() }
|
||||
private val topBar: View by lazy { tabsRow() }
|
||||
|
||||
init {
|
||||
orientation = VERTICAL
|
||||
setBackgroundColor(Color.BLACK)
|
||||
addView(topBar, LayoutParams(LayoutParams.MATCH_PARENT, dp(64)))
|
||||
val title = context.getString(when {
|
||||
customLayout != null -> R.string.input_custom_controls
|
||||
deckControls -> R.string.second_mode_deck_controls
|
||||
else -> R.string.deck_tab_gamepad
|
||||
})
|
||||
val extras = listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, onClick = it) })
|
||||
addView(bottomScreenBarView(context) { sessionBarModel(title, onClose, onMenu, onSteamMenu, onQam, extras) },
|
||||
LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
|
||||
addView(topBar, LayoutParams(LayoutParams.MATCH_PARENT, dp(52)))
|
||||
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
|
||||
if (customLayout != null && pad != null) renderCustom(pad, customLayout)
|
||||
else select(if (pad != null && !deckControls) Tab.GAMEPAD else if (pad != null) selectedWithPad else selected)
|
||||
@@ -114,11 +123,10 @@ class DeckControlsPanel(
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
private fun topBar(): View = LinearLayout(context).apply {
|
||||
private fun tabsRow(): View = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
setPadding(dp(12), dp(10), dp(12), dp(6))
|
||||
addView(roundButton("×", context.getString(R.string.deck_close), onClose))
|
||||
gravity = Gravity.CENTER
|
||||
setPadding(dp(12), 0, dp(12), dp(8))
|
||||
val tabs = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
background = outline(CORNER_PILL, SURFACE)
|
||||
@@ -144,16 +152,7 @@ class DeckControlsPanel(
|
||||
overScrollMode = View.OVER_SCROLL_NEVER
|
||||
addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44)))
|
||||
}
|
||||
addView(centre, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f))
|
||||
onMenu?.let {
|
||||
addView(menuButton(context, it))
|
||||
addView(space(dp(8)))
|
||||
}
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) {
|
||||
addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true))
|
||||
addView(space(dp(8)))
|
||||
addView(roundButton("•••", context.getString(R.string.drawer_open_qam), onQam, wide = true))
|
||||
}
|
||||
addView(centre, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
|
||||
private fun select(tab: Tab) {
|
||||
@@ -177,7 +176,7 @@ class DeckControlsPanel(
|
||||
}
|
||||
content.removeAllViews()
|
||||
pad?.releaseTouch(this)
|
||||
topBar.visibility = if (tab == Tab.GAMEPAD) View.GONE else View.VISIBLE
|
||||
topBar.visibility = if (tab == Tab.GAMEPAD || tabViews.size < 2) View.GONE else View.VISIBLE
|
||||
content.addView(
|
||||
when (tab) {
|
||||
Tab.GRIPS -> gripsGrid()
|
||||
@@ -244,10 +243,6 @@ class DeckControlsPanel(
|
||||
place(pill("RB") { st, d -> st.press(PadState.RB, d) }, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER)
|
||||
place(pill("RT") { st, d -> st.rightTrigger = if (d) 1f else 0f }, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER)
|
||||
place(pill("VIEW") { st, d -> st.press(PadState.SELECT, d) }, GamepadGeometry.Slot.VIEW)
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) {
|
||||
place(centreTap("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu), GamepadGeometry.Slot.STEAM)
|
||||
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
|
||||
}
|
||||
place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU)
|
||||
if (deckControls) place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
|
||||
GamepadGeometry.Slot.PANELS)
|
||||
@@ -309,14 +304,12 @@ class DeckControlsPanel(
|
||||
show()
|
||||
}
|
||||
|
||||
/** Whether a finger going down at ([x], [y]) lands on one of the panel's controls. */
|
||||
fun takesTouchAt(x: Float, y: Float): Boolean = controlUnder(this, x, y)
|
||||
|
||||
// Every control here takes the touches it gets: buttons and tabs (clickable), the scrolling tab strip,
|
||||
// and the drawn surfaces, pads and face buttons. The layouts around them do not.
|
||||
private fun controlUnder(view: View, x: Float, y: Float): Boolean {
|
||||
if (view.visibility != VISIBLE || x < 0f || y < 0f || x >= view.width || y >= view.height) return false
|
||||
if (view.isClickable || view is HorizontalScrollView || view is Surface || view is DirectionPad || view is FaceButtons) return true
|
||||
if (view.isClickable || view is HorizontalScrollView || view is Surface || view is DirectionPad || view is FaceButtons ||
|
||||
view is androidx.compose.ui.platform.ComposeView) return true
|
||||
val group = view as? ViewGroup ?: return false
|
||||
return (group.childCount - 1 downTo 0).any { i ->
|
||||
val child = group.getChildAt(i)
|
||||
@@ -324,11 +317,6 @@ class DeckControlsPanel(
|
||||
}
|
||||
}
|
||||
|
||||
private fun roundButton(label: String, description: String, onClick: () -> Unit, wide: Boolean = false) =
|
||||
roundButton(context, label, description, onClick, wide)
|
||||
|
||||
private fun space(width: Int) = View(context).apply { layoutParams = LayoutParams(width, 1) }
|
||||
|
||||
private fun outline(radius: Float, fill: Int) = outline(context, radius, fill)
|
||||
|
||||
private fun filled(radius: Float, fill: Int) = GradientDrawable().apply {
|
||||
@@ -772,10 +760,13 @@ class DeckControlsPanel(
|
||||
}
|
||||
}
|
||||
|
||||
internal fun menuButton(context: Context, onClick: () -> Unit) = android.widget.ImageView(context).apply {
|
||||
setImageResource(R.drawable.ic_stat_session)
|
||||
internal fun menuButton(context: Context, onClick: () -> Unit) =
|
||||
iconButton(context, R.drawable.ic_stat_session, context.getString(R.string.touch_droiddeck_menu), onClick)
|
||||
|
||||
internal fun iconButton(context: Context, icon: Int, description: String, onClick: () -> Unit) = android.widget.ImageView(context).apply {
|
||||
setImageResource(icon)
|
||||
setColorFilter(TEXT)
|
||||
contentDescription = context.getString(R.string.touch_droiddeck_menu)
|
||||
contentDescription = description
|
||||
scaleType = android.widget.ImageView.ScaleType.CENTER_INSIDE
|
||||
val pad = dp(context, 11)
|
||||
setPadding(pad, pad, pad, pad)
|
||||
|
||||
+67
-19
@@ -1,14 +1,20 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
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.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.hud.FusionSize
|
||||
import com.droiddeck.launcher.hud.DroidDeckHudSize
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.StripMetric
|
||||
|
||||
/** Bannerlator's Fusion HUD settings (DeckOverlaySettings): one row per key of the HUD's config string. */
|
||||
@Composable
|
||||
internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val cfg = a.hudConfig
|
||||
fun on(key: String) = cfg[key] == "1"
|
||||
fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback
|
||||
@@ -16,19 +22,23 @@ internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String)
|
||||
SettingsGroup(stringResource(R.string.drawer_hud)) {
|
||||
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud)
|
||||
if (!a.hudOn) return@SettingsGroup
|
||||
val size = FusionSize.from(cfg["hudSize"])
|
||||
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
||||
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint),
|
||||
listOf(
|
||||
FusionSize.FULL to stringResource(R.string.hud_size_full),
|
||||
FusionSize.TILES to stringResource(R.string.hud_size_tiles),
|
||||
FusionSize.PILL to stringResource(R.string.hud_size_pill),
|
||||
FusionSize.MINIMAL to stringResource(R.string.hud_size_minimal),
|
||||
FusionSize.MEGA to stringResource(R.string.hud_size_mega),
|
||||
DroidDeckHudSize.FULL to stringResource(R.string.hud_size_full),
|
||||
DroidDeckHudSize.TILES to stringResource(R.string.hud_size_tiles),
|
||||
DroidDeckHudSize.PILL to stringResource(R.string.hud_size_pill),
|
||||
DroidDeckHudSize.MINIMAL to stringResource(R.string.hud_size_minimal),
|
||||
DroidDeckHudSize.MEGA to stringResource(R.string.hud_size_mega),
|
||||
DroidDeckHudSize.STRIP to stringResource(R.string.hud_size_strip),
|
||||
),
|
||||
size, chipModifier = track("hud-size")) { a.onHudSetting("hudSize", it.token) }
|
||||
ToggleRow(host, "hud-locked", stringResource(R.string.hud_locked), stringResource(R.string.hud_locked_hint), on("hudLocked"),
|
||||
chipModifier = track("hud-locked")) { a.onHudSetting("hudLocked", flag(it)) }
|
||||
ToggleRow(host, "hud-snap", stringResource(R.string.hud_snap), stringResource(R.string.hud_snap_hint), on("hudSnap"),
|
||||
chipModifier = track("hud-snap")) { a.onHudSetting("hudSnap", flag(it)) }
|
||||
}
|
||||
if (a.dashboardAvailable && a.secondScreenDisplays.isNotEmpty()) BottomStripSettings(host, track)
|
||||
if (!a.hudOn) return
|
||||
|
||||
SettingsGroup(stringResource(R.string.hud_group_look)) {
|
||||
@@ -47,7 +57,7 @@ internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String)
|
||||
if (cfg["hudOutlineAccent"] == "0") "0" else "1", chipModifier = track("hud-outline-color")) { a.onHudSetting("hudOutlineAccent", it) }
|
||||
}
|
||||
|
||||
val size = FusionSize.from(cfg["hudSize"])
|
||||
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
||||
val chips = size.supportedChips() + EXTRA[size].orEmpty()
|
||||
SettingsGroup(stringResource(R.string.hud_group_metrics)) {
|
||||
for (metric in METRICS) {
|
||||
@@ -84,7 +94,7 @@ internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String)
|
||||
}
|
||||
}
|
||||
|
||||
SettingsGroup(stringResource(R.string.hud_group_more), detail = stringResource(R.string.hud_credit)) {
|
||||
SettingsGroup(stringResource(R.string.hud_group_more)) {
|
||||
ActionRow(stringResource(R.string.hud_export), stringResource(R.string.hud_export_hint),
|
||||
stringResource(R.string.hud_export_button), onClick = a.onHudExport, modifier = track("hud-export"))
|
||||
ActionRow(stringResource(R.string.hud_reset), null, stringResource(R.string.hud_reset_button),
|
||||
@@ -94,12 +104,51 @@ internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String)
|
||||
|
||||
private fun flag(on: Boolean) = if (on) "1" else "0"
|
||||
|
||||
// The Pill also draws the battery temperature and watts.
|
||||
private val EXTRA = mapOf(FusionSize.PILL to setOf("Temp", "Power"))
|
||||
@Composable
|
||||
private fun BottomStripSettings(host: MenuHost, track: (String) -> Modifier) {
|
||||
val context = LocalContext.current
|
||||
var hudOn by remember { mutableStateOf(SessionPrefs.bottomHud(context)) }
|
||||
var onTabs by remember { mutableStateOf(SessionPrefs.bottomStripOnTabs(context)) }
|
||||
var shown by remember { mutableStateOf(SessionPrefs.bottomStripMetrics(context)) }
|
||||
SettingsGroup(stringResource(R.string.bottom_hud_group)) {
|
||||
ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), null, hudOn,
|
||||
chipModifier = track("bottom-hud")) { on ->
|
||||
hudOn = on
|
||||
SessionPrefs.setBottomHud(context, on)
|
||||
}
|
||||
ToggleRow(host, "bottom-strip-tabs", stringResource(R.string.bottom_strip_tabs), null, onTabs,
|
||||
enabled = hudOn, chipModifier = track("bottom-strip-tabs")) { on ->
|
||||
onTabs = on
|
||||
SessionPrefs.setBottomStripOnTabs(context, on)
|
||||
}
|
||||
for ((metric, label) in BOTTOM_STRIP_ROWS) {
|
||||
ToggleRow(host, "bottom-strip-${metric.id}", stringResource(label), null, metric in shown,
|
||||
enabled = hudOn, chipModifier = track("bottom-strip-${metric.id}")) { on ->
|
||||
shown = if (on) shown + metric else shown - metric
|
||||
SessionPrefs.setBottomStripMetric(context, metric, on)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val BOTTOM_STRIP_ROWS = listOf(
|
||||
StripMetric.ENGINE to R.string.hud_metric_engine,
|
||||
StripMetric.GRAPH to R.string.hud_metric_graph,
|
||||
StripMetric.LOWS to R.string.bottom_strip_lows,
|
||||
StripMetric.LOW001 to R.string.hud_metric_low001,
|
||||
StripMetric.GPU to R.string.hud_metric_gpu,
|
||||
StripMetric.GPU_TEMP to R.string.hud_metric_gpu_temp,
|
||||
StripMetric.CPU to R.string.hud_metric_cpu,
|
||||
StripMetric.CPU_TEMP to R.string.bottom_strip_cpu_temp,
|
||||
StripMetric.VRAM to R.string.hud_metric_vram,
|
||||
StripMetric.RAM to R.string.hud_metric_ram,
|
||||
StripMetric.CLOCK to R.string.hud_metric_clock,
|
||||
)
|
||||
|
||||
private val EXTRA = mapOf(DroidDeckHudSize.PILL to setOf("Temp", "Power"))
|
||||
|
||||
private class HudMetric(val chip: String, val key: String, val label: Int)
|
||||
|
||||
// FusionSize.supportedChips() names; Wrapper and DX version have nothing to show in DroidDeck.
|
||||
private val METRICS = listOf(
|
||||
HudMetric("FPS", "showFPS", R.string.drawer_hud_fps),
|
||||
HudMetric("FPS graph", "showFPSGraph", R.string.hud_metric_graph),
|
||||
@@ -124,10 +173,9 @@ private val METRICS = listOf(
|
||||
HudMetric("Clock", "showClock", R.string.hud_metric_clock),
|
||||
)
|
||||
|
||||
// Switches a size lists but never draws (FusionHudView): the Pill and Minimal always show the FPS, the
|
||||
// Pill has no graph, Tiles has no graph and no 0.01% low.
|
||||
private val HIDDEN = mapOf(
|
||||
FusionSize.PILL to setOf("FPS", "FPS graph"),
|
||||
FusionSize.MINIMAL to setOf("FPS"),
|
||||
FusionSize.TILES to setOf("FPS graph", "0.01% low"),
|
||||
DroidDeckHudSize.PILL to setOf("FPS", "FPS graph"),
|
||||
DroidDeckHudSize.MINIMAL to setOf("FPS"),
|
||||
DroidDeckHudSize.TILES to setOf("FPS graph", "0.01% low"),
|
||||
DroidDeckHudSize.STRIP to setOf("FPS"),
|
||||
)
|
||||
@@ -64,20 +64,23 @@ class DualPanelModel(
|
||||
object DualScreenPanel {
|
||||
var model by mutableStateOf<DualPanelModel?>(null)
|
||||
private var displayId = -1
|
||||
private var presentation: DualScreenPresentation? = null
|
||||
set(value) { field = value; available = value != null || activity != null || launching }
|
||||
private var activity: DualScreenActivity? = null
|
||||
set(value) { field = value; available = value != null || launching }
|
||||
set(value) { field = value; available = value != null || presentation != null || launching }
|
||||
private var launching = false
|
||||
set(value) { field = value; available = value || activity != null }
|
||||
set(value) { field = value; available = value || activity != null || presentation != null }
|
||||
private var ownerTask = -1
|
||||
private var ownerYielded = false
|
||||
private var ownerPaused = false
|
||||
|
||||
var typing by mutableStateOf<TypingRequest?>(null)
|
||||
private set
|
||||
var typingShown by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
val shownOn: Int get() = if (activity != null || launching) displayId else -1
|
||||
val attached: Boolean get() = activity != null
|
||||
val shownOn: Int get() = if (presentation != null || activity != null || launching) displayId else -1
|
||||
val attached: Boolean get() = presentation != null || activity != null
|
||||
var available by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
@@ -120,7 +123,20 @@ object DualScreenPanel {
|
||||
displayId = display
|
||||
ownerTask = task
|
||||
ownerYielded = false
|
||||
ownerPaused = false
|
||||
launching = true
|
||||
val host = context as? ComponentActivity
|
||||
val target = host?.getSystemService(Context.DISPLAY_SERVICE)
|
||||
?.let { (it as android.hardware.display.DisplayManager).getDisplay(display) }
|
||||
if (host != null && target != null) {
|
||||
val shown = runCatching { DualScreenPresentation(host, target).also { it.show() } }
|
||||
if (shown.isSuccess) {
|
||||
presentation = shown.getOrThrow()
|
||||
launching = false
|
||||
return
|
||||
}
|
||||
android.util.Log.w("DualScreenPanel", "bottom panel presentation failed; falling back to an activity", shown.exceptionOrNull())
|
||||
}
|
||||
val intent = Intent(context, DualScreenActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
runCatching {
|
||||
@@ -132,6 +148,8 @@ object DualScreenPanel {
|
||||
stopTyping()
|
||||
launching = false
|
||||
displayId = -1
|
||||
presentation?.dismiss()
|
||||
presentation = null
|
||||
activity?.finishAndRemoveTask()
|
||||
activity = null
|
||||
}
|
||||
@@ -142,26 +160,36 @@ object DualScreenPanel {
|
||||
|
||||
internal fun attach(host: DualScreenActivity): Boolean {
|
||||
if (!launching && activity == null) return false
|
||||
presentation?.dismiss()
|
||||
presentation = null
|
||||
if (activity !== host) activity?.finishAndRemoveTask()
|
||||
activity = host
|
||||
launching = false
|
||||
return true
|
||||
}
|
||||
|
||||
// The panel resumes when an app opens over the owner on the primary screen; pulling the owner back would hide that app.
|
||||
fun yieldTo(task: Int, app: Boolean) {
|
||||
if (ownerTask == task) ownerYielded = app
|
||||
}
|
||||
|
||||
internal fun returnFocus(context: Context) {
|
||||
if (ownerYielded) return
|
||||
val task = ownerTask.takeIf { it >= 0 } ?: return
|
||||
fun opensOutside(own: String, target: String?): Boolean = target != null && target != own
|
||||
|
||||
fun ownerPaused(task: Int, paused: Boolean) {
|
||||
if (ownerTask == task) ownerPaused = paused
|
||||
}
|
||||
|
||||
internal fun focusTask(fromPanel: Boolean): Int? {
|
||||
if (ownerYielded || (ownerPaused && !fromPanel)) return null
|
||||
return ownerTask.takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
internal fun returnFocus(context: Context, fromPanel: Boolean = false) {
|
||||
val task = focusTask(fromPanel) ?: return
|
||||
runCatching { (context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(task, 0) }
|
||||
}
|
||||
|
||||
internal fun reclaimFocus(context: Context) {
|
||||
if (ownerYielded) return
|
||||
val task = ownerTask.takeIf { it >= 0 } ?: return
|
||||
val task = focusTask(true) ?: return
|
||||
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
|
||||
runCatching {
|
||||
manager.appTasks.firstOrNull {
|
||||
@@ -177,6 +205,13 @@ object DualScreenPanel {
|
||||
displayId = -1
|
||||
}
|
||||
}
|
||||
|
||||
internal fun detach(host: DualScreenPresentation) {
|
||||
if (presentation === host) {
|
||||
presentation = null
|
||||
displayId = -1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DualScreenActivity : ComponentActivity() {
|
||||
@@ -209,10 +244,10 @@ class DualScreenActivity : ComponentActivity() {
|
||||
runCatching { (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(taskId, 0) }
|
||||
} else {
|
||||
unfocusPending = true
|
||||
DualScreenPanel.returnFocus(this)
|
||||
DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
window.decorView.postDelayed({
|
||||
if (!unfocusPending || DualScreenPanel.typingShown) return@postDelayed
|
||||
if (window.decorView.hasWindowFocus()) DualScreenPanel.returnFocus(this) else dropFocus()
|
||||
if (window.decorView.hasWindowFocus()) DualScreenPanel.returnFocus(this, fromPanel = true) else dropFocus()
|
||||
}, 400)
|
||||
}
|
||||
}
|
||||
@@ -228,9 +263,19 @@ class DualScreenActivity : ComponentActivity() {
|
||||
if (!DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this)
|
||||
}
|
||||
|
||||
private var topResumed = false
|
||||
|
||||
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
|
||||
super.onTopResumedActivityChanged(isTopResumedActivity)
|
||||
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this)
|
||||
topResumed = isTopResumedActivity
|
||||
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN && topResumed && !DualScreenPanel.typingShown) {
|
||||
DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
@@ -251,6 +296,7 @@ class DualScreenActivity : ComponentActivity() {
|
||||
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) DualScreenPanel.finishTyping()
|
||||
return true
|
||||
}
|
||||
if (topResumed && !DualScreenPanel.typingShown && event.action == KeyEvent.ACTION_DOWN) DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Presentation
|
||||
import android.os.Bundle
|
||||
import android.view.Display
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.lifecycle.setViewTreeViewModelStoreOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
|
||||
internal class DualScreenPresentation(
|
||||
private val host: ComponentActivity,
|
||||
display: Display,
|
||||
) : Presentation(host, display) {
|
||||
private var content: ComposeView? = null
|
||||
|
||||
init {
|
||||
setCancelable(false)
|
||||
setCanceledOnTouchOutside(false)
|
||||
setOnDismissListener { DualScreenPanel.detach(this) }
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
|
||||
applyImmersiveMode()
|
||||
val decor = window?.decorView ?: return
|
||||
decor.setViewTreeLifecycleOwner(host)
|
||||
decor.setViewTreeViewModelStoreOwner(host)
|
||||
decor.setViewTreeSavedStateRegistryOwner(host)
|
||||
decor.setViewTreeOnBackPressedDispatcherOwner(host)
|
||||
val view = ComposeView(context)
|
||||
content = view
|
||||
view.setContent {
|
||||
val model = DualScreenPanel.model
|
||||
val request = DualScreenPanel.typing
|
||||
val typingOn = request != null && DualScreenPanel.typingShown
|
||||
LaunchedEffect(typingOn) { acceptFocus(typingOn) }
|
||||
DroidDeckTheme(model?.theme, appScale = model?.appScale ?: AppUiPrefs.DEFAULT_SCALE) {
|
||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
|
||||
if (request != null && typingOn) TypingPanel(request) {
|
||||
if (DualScreenPanel.typing === request) DualScreenPanel.finishTyping()
|
||||
} else if (model != null) DualPanelContent(model)
|
||||
}
|
||||
}
|
||||
}
|
||||
setContentView(view)
|
||||
}
|
||||
|
||||
private fun acceptFocus(on: Boolean) {
|
||||
val window = window ?: return
|
||||
if (on) {
|
||||
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
content?.requestFocus()
|
||||
} else {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
host.window?.decorView?.requestFocus()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) applyImmersiveMode()
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun onBackPressed() {
|
||||
if (DualScreenPanel.typingShown) DualScreenPanel.finishTyping()
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (DualScreenPanel.typingShown && event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
|
||||
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) DualScreenPanel.finishTyping()
|
||||
return true
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
private fun applyImmersiveMode() {
|
||||
@Suppress("DEPRECATION")
|
||||
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
||||
or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,6 @@ internal class FocusGlide(view: View?) {
|
||||
private set
|
||||
|
||||
fun accepts(view: View): Boolean {
|
||||
// DropdownMenu recreates its popup view after closing.
|
||||
if (this.view == null || deferredWindow && this.view !== view && host?.isAttached != true) this.view = view
|
||||
return this.view === view
|
||||
}
|
||||
|
||||
@@ -465,7 +465,8 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
|
||||
val ctx = LocalContext.current
|
||||
val narrow = LocalNarrowPane.current
|
||||
var editing by rememberSaveable(app.key) { mutableStateOf(false) }
|
||||
val x86 = (app.arch == "x86_64" || app.arch == "i386") && app.fex != com.droiddeck.launcher.runtime.LinuxFex.OFF
|
||||
val x86 = (app.arch == "x86_64" || app.arch == "i386") && app.fex != com.droiddeck.launcher.runtime.LinuxFex.OFF &&
|
||||
app.kind != UserApps.Kind.FLATPAK
|
||||
val fexReady by produceState<Boolean?>(null, app.key, x86, s.sessionRunning) {
|
||||
value = if (x86) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.droiddeck.launcher.runtime.LinuxFex.ready(ctx) } else true
|
||||
}
|
||||
|
||||
@@ -74,7 +74,6 @@ internal fun UninstallEpicLauncher(s: FrontEndState, a: FrontEndActions) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A skipped sync is not a success: "0 files" used to show for a signed-out store or cloud saves turned off. */
|
||||
internal fun cloudMessage(context: android.content.Context, r: com.droiddeck.launcher.stores.CloudSaves.Result): String = when (r.result) {
|
||||
"ok" -> when {
|
||||
r.conflicts > 0 -> context.getString(R.string.cloud_conflict_files, r.conflicts)
|
||||
@@ -202,7 +201,6 @@ internal fun BusyChip(s: FrontEndState) {
|
||||
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)
|
||||
s.removalPending -> Chip(stringResource(R.string.runtime_removal_incomplete), ok = false)
|
||||
!s.ready -> Chip(stringResource(R.string.games_runtime_first_play), ok = false)
|
||||
s.available != null && s.available != s.installed -> Chip(stringResource(R.string.games_runtime_update), ok = false)
|
||||
else -> Chip(stringResource(R.string.games_runtime_ready), ok = true)
|
||||
}
|
||||
|
||||
@@ -203,7 +203,7 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
|
||||
}
|
||||
|
||||
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) || com.droiddeck.launcher.sync.Syncthing.needsAttention
|
||||
|
||||
@Composable
|
||||
private fun NavigationItems(
|
||||
|
||||
@@ -133,7 +133,7 @@ class FrontEndState(
|
||||
val dualScreen: Boolean = false,
|
||||
val dualScreenDevice: Boolean = false,
|
||||
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
val dualScreenLauncher: Boolean = true,
|
||||
val dualScreenSessions: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
val dualScreenControls: Boolean = true,
|
||||
val packages: List<PackageRow>? = null,
|
||||
val packageCatalogLoading: Boolean = false,
|
||||
@@ -149,6 +149,10 @@ class FrontEndState(
|
||||
val oscMode: String = SessionPrefs.OSC_AUTO,
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
|
||||
val adreno: Boolean = true,
|
||||
val vkBridge: Boolean = false,
|
||||
val vkBridgeSafe: Boolean = true,
|
||||
val bridgeProtonDxvk: Boolean = false,
|
||||
val showPhantomGate: Boolean = false,
|
||||
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
|
||||
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
|
||||
@@ -166,7 +170,7 @@ class FrontEndState(
|
||||
val sgdbUserKey: Boolean = false,
|
||||
val storesShowMature: Boolean = false,
|
||||
val storesSort: String = SessionPrefs.STORES_SORTS.first(),
|
||||
val storesView: String = SessionPrefs.STORES_VIEWS.first(),
|
||||
val storesView: String = SessionPrefs.DEFAULT_STORES_VIEW,
|
||||
val storeDownloadsActive: Int = 0,
|
||||
val updates: UpdatesState = UpdatesState(),
|
||||
)
|
||||
@@ -205,6 +209,9 @@ class FrontEndActions(
|
||||
val onInstallPackage: (String) -> Unit,
|
||||
val onRemovePackage: (String) -> Unit,
|
||||
val onRuntime: () -> Unit,
|
||||
val onVkBridge: (Boolean) -> Unit = {},
|
||||
val onVkBridgeSafe: (Boolean) -> Unit = {},
|
||||
val onBridgeProtonDxvk: (Boolean) -> Unit = {},
|
||||
val onFrameGenPick: (FrameGen.Mode) -> Unit,
|
||||
val onImportLossless: () -> Unit,
|
||||
val onProtons: () -> Unit,
|
||||
@@ -238,7 +245,7 @@ class FrontEndActions(
|
||||
val onLauncherFullscreen: (Boolean) -> Unit = {},
|
||||
val onAnimationsEnabled: (Boolean) -> Unit = {},
|
||||
val onDualScreenMode: (String) -> Unit = {},
|
||||
val onDualScreenLauncher: (Boolean) -> Unit = {},
|
||||
val onDualScreenSessions: (String) -> Unit = {},
|
||||
val onDualScreenControls: (Boolean) -> Unit = {},
|
||||
val onDownloadSource: (String) -> Unit = {},
|
||||
val onDownloadMirror: (String) -> Unit = {},
|
||||
@@ -291,8 +298,6 @@ internal object Motion {
|
||||
if (scale == 0f) snap() else spring(damping, stiffness)
|
||||
}
|
||||
|
||||
private val Shape10 = RoundedCornerShape(10.dp)
|
||||
|
||||
internal val Shape12 = RoundedCornerShape(12.dp)
|
||||
|
||||
internal fun hueOf(name: String) = (name.hashCode().toUInt() % 360u).toFloat()
|
||||
@@ -312,13 +317,6 @@ internal fun Rise(i: Int, modifier: Modifier = Modifier, content: @Composable ()
|
||||
) { content() }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Modifier.staggerIn(i: Int): Modifier {
|
||||
val t = remember { Animatable(0f) }
|
||||
LaunchedEffect(Unit) { t.animateTo(1f, Motion.tw(360, i * 30)) }
|
||||
return graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 10.dp.toPx() }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Modifier.shine(trigger: Boolean, strength: Float = 0.22f): Modifier {
|
||||
val x = remember { Animatable(-1f) }
|
||||
@@ -435,6 +433,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
"stores:downloads" -> { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" }
|
||||
"components" -> a.onComponents(true)
|
||||
"setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" }
|
||||
com.droiddeck.launcher.sync.SyncthingService.NAV -> com.droiddeck.launcher.sync.Syncthing.requestOpen()
|
||||
"setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" }
|
||||
else -> selected = target
|
||||
}
|
||||
@@ -554,6 +553,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
LaunchedEffect(com.droiddeck.launcher.storage.StorageState.openRequests) {
|
||||
if (com.droiddeck.launcher.storage.StorageState.openPending) showRailPage("setup", true)
|
||||
}
|
||||
LaunchedEffect(com.droiddeck.launcher.sync.Syncthing.openRequests) {
|
||||
if (com.droiddeck.launcher.sync.Syncthing.openPending) showRailPage("setup", true)
|
||||
}
|
||||
val onRailFocus: (String) -> Unit = { key ->
|
||||
if (key != railSelection) showRailPage(key, false)
|
||||
}
|
||||
@@ -706,6 +708,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
StoreTheme(com.droiddeck.launcher.stores.Store.XBOX) { XboxStoreDialogs() }
|
||||
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
|
||||
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
|
||||
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
|
||||
StepsLayer(screenAt)
|
||||
|
||||
appToChooseDisplay?.let { app ->
|
||||
|
||||
@@ -93,7 +93,8 @@ internal object SetupTabs {
|
||||
var openLauncher = false
|
||||
var openOverview = false
|
||||
}
|
||||
private const val GLASSES_TAB = 5
|
||||
private const val GLASSES_TAB = 6
|
||||
private const val SYNC_TAB = 4
|
||||
|
||||
@Composable
|
||||
private fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
|
||||
@@ -170,7 +171,7 @@ internal fun SetupPanel(
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() }
|
||||
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED
|
||||
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED || s.vkBridge
|
||||
val gpuName = remember { DeviceSupport.gpuName(ctx) }
|
||||
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val signedIn = s.offlineAccount != null
|
||||
@@ -190,7 +191,7 @@ internal fun SetupPanel(
|
||||
onDismiss = { editDownloadProxy = false },
|
||||
onSave = { a.onDownloadProxy(it); editDownloadProxy = false },
|
||||
)
|
||||
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_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
|
||||
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_storage), stringResource(R.string.setup_tab_sync), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
|
||||
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
|
||||
SetupTabs.openLauncher = false
|
||||
if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false }
|
||||
@@ -210,6 +211,18 @@ internal fun SetupPanel(
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(com.droiddeck.launcher.sync.Syncthing.openRequests) {
|
||||
if (com.droiddeck.launcher.sync.Syncthing.openPending) {
|
||||
com.droiddeck.launcher.sync.Syncthing.openPending = false
|
||||
tab = SYNC_TAB
|
||||
}
|
||||
}
|
||||
var syncAdvanced by rememberSaveable { mutableStateOf(false) }
|
||||
if (syncAdvanced) {
|
||||
androidx.activity.compose.BackHandler { syncAdvanced = false }
|
||||
SyncAdvancedPage(host) { syncAdvanced = false }
|
||||
return
|
||||
}
|
||||
LaunchedEffect(tab) {
|
||||
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
@@ -219,7 +232,7 @@ internal fun SetupPanel(
|
||||
val runtimeOk = s.ready && !s.busy && !s.removalPending
|
||||
val checks = listOf(gpuOk, runtimeOk, !limitBlocks, signedIn)
|
||||
val passing = checks.count { it }
|
||||
var showChecks by rememberSaveable { mutableStateOf(false) }
|
||||
var showChecks by rememberSaveable { mutableStateOf(s.vkBridge) }
|
||||
Rise(0, Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().bumpers(
|
||||
@@ -236,17 +249,49 @@ internal fun SetupPanel(
|
||||
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
CheckRow(
|
||||
if (gpuOk) CheckState.OK else CheckState.WARN,
|
||||
when (gpu.support) {
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_supported)
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested)
|
||||
when {
|
||||
gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_supported)
|
||||
gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested)
|
||||
s.vkBridge -> stringResource(R.string.setup_gpu_bridged)
|
||||
else -> stringResource(R.string.setup_gpu_unsupported)
|
||||
},
|
||||
when (gpu.support) {
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.displayName(ctx), gpuName)
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
|
||||
else -> stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
|
||||
else -> if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
|
||||
else stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
|
||||
},
|
||||
divider = divider || (!s.adreno && s.vkBridge),
|
||||
action = if (s.adreno) null else { {
|
||||
SecondaryButton(
|
||||
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
|
||||
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
|
||||
)
|
||||
} },
|
||||
)
|
||||
if (!s.adreno && s.vkBridge) CheckRow(
|
||||
CheckState.OK,
|
||||
stringResource(R.string.setup_bridge_safe),
|
||||
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on_detail else R.string.setup_bridge_safe_off_detail),
|
||||
divider = divider,
|
||||
action = {
|
||||
SecondaryButton(
|
||||
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on else R.string.setup_bridge_safe_off),
|
||||
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridgeSafe(!s.vkBridgeSafe) },
|
||||
)
|
||||
},
|
||||
)
|
||||
if (!s.adreno && s.vkBridge) CheckRow(
|
||||
CheckState.OK,
|
||||
stringResource(R.string.setup_bridge_dxvk),
|
||||
stringResource(if (s.bridgeProtonDxvk) R.string.setup_bridge_dxvk_proton_detail else R.string.setup_bridge_dxvk_auto_detail),
|
||||
divider = divider,
|
||||
action = {
|
||||
SecondaryButton(
|
||||
stringResource(if (s.bridgeProtonDxvk) R.string.setup_bridge_dxvk_proton else R.string.setup_bridge_dxvk_auto),
|
||||
enabled = !s.sessionRunning, compact = true, onClick = { a.onBridgeProtonDxvk(!s.bridgeProtonDxvk) },
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
val runtimeCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
@@ -422,21 +467,23 @@ internal fun SetupPanel(
|
||||
s.launcherFullscreen,
|
||||
) { a.onLauncherFullscreen(it) }
|
||||
if (s.dualScreenDevice) {
|
||||
ChoiceRow(
|
||||
host, "dual-screen", stringResource(R.string.setup_dual_screen), stringResource(R.string.setup_dual_screen_hint),
|
||||
listOf(
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
|
||||
),
|
||||
s.dualScreenMode, onPick = a.onDualScreenMode,
|
||||
val dualModes = listOf(
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
|
||||
)
|
||||
}
|
||||
if (s.dualScreenDevice && s.dualScreenMode != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
ToggleRow(host, "dual-screen-menu", stringResource(R.string.setup_dual_screen_menu),
|
||||
stringResource(R.string.setup_dual_screen_menu_hint), s.dualScreenLauncher) { a.onDualScreenLauncher(it) }
|
||||
ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls),
|
||||
stringResource(R.string.setup_dual_screen_controls_hint), s.dualScreenControls) { a.onDualScreenControls(it) }
|
||||
ChoiceRow(
|
||||
host, "dual-screen", stringResource(R.string.setup_dual_screen_launcher), stringResource(R.string.setup_dual_screen_launcher_hint),
|
||||
dualModes, s.dualScreenMode, onPick = a.onDualScreenMode,
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "dual-screen-sessions", stringResource(R.string.setup_dual_screen_sessions), stringResource(R.string.setup_dual_screen_sessions_hint),
|
||||
dualModes, s.dualScreenSessions, onPick = a.onDualScreenSessions,
|
||||
)
|
||||
if (s.dualScreenSessions != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls),
|
||||
stringResource(R.string.setup_dual_screen_controls_hint), s.dualScreenControls) { a.onDualScreenControls(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -492,7 +539,8 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
STORAGE_TAB -> StoragePanel(s, a)
|
||||
4 -> {
|
||||
SYNC_TAB -> SyncPanel(host, runtimeOk) { syncAdvanced = true }
|
||||
5 -> {
|
||||
SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) {
|
||||
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
|
||||
ToggleRow(
|
||||
@@ -688,7 +736,6 @@ private fun GameSettingsCard(host: MenuHost, game: com.droiddeck.launcher.fronte
|
||||
GameSettingsMenus(host, game, state)
|
||||
}
|
||||
|
||||
/** The per-game settings menus, opened by setting [MenuHost.open] to [GAME_SETTINGS_MENU]. */
|
||||
@Composable
|
||||
internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame, state: GameSettingsState) {
|
||||
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
@@ -897,14 +944,12 @@ private fun LanguageRow(host: MenuHost, chosen: String, onPick: (String) -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
/** How fast Inner Gamer cycles its colours. */
|
||||
@Composable
|
||||
private fun RgbSpeedRow() {
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
SliderRow(stringResource(R.string.theme_rgb_speed), stringResource(R.string.theme_rgb_speed_hint), Themes.rgbSpeed, 1..Themes.RGB_SPEEDS) { Themes.setRgbSpeed(ctx, it) }
|
||||
}
|
||||
|
||||
/** The two colours of the Gradient theme, each a small square that opens the colour picker. */
|
||||
@Composable
|
||||
private fun GradientColorRows() {
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
|
||||
@@ -264,23 +264,3 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
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)
|
||||
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
|
||||
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
|
||||
val cornerPx = with(androidx.compose.ui.platform.LocalDensity.current) { (if (size > 48.dp) 14.dp else 12.dp).toPx() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.paneItem("cog").downToFirstTile().size(size).onGloballyPositioned { placed[0] = it }.clip(if (size > 48.dp) Shape14 else Shape12).background(Color.White.copy(alpha = 0.03f)).glideBorder(hot, if (size > 48.dp) Shape14 else Shape12, pal.signal, pal.line2)
|
||||
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current) {
|
||||
placed[0]?.takeIf { it.isAttached }?.let { PageOrigin.mark(Origin(it.boundsInRoot(), cornerPx)) }
|
||||
spins++
|
||||
onClick()
|
||||
},
|
||||
) { Icon(Icons.Filled.Settings, stringResource(R.string.drawer_page_settings), tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(if (size > 48.dp) 20.dp else 18.dp).rotate(rot)) }
|
||||
}
|
||||
@@ -98,6 +98,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltApi
|
||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
@@ -115,7 +116,6 @@ import java.io.File
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.getValue
|
||||
|
||||
/** What a game page shows: `app:<appId>` for a game in the library, `[app:]<store>:<id>` for a store product. */
|
||||
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
|
||||
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
|
||||
appId != null -> games.firstOrNull { it.appId == appId }
|
||||
@@ -140,7 +140,7 @@ internal enum class GameTab { ABOUT, ACHIEVEMENTS, LAUNCH, SAVES, INSTALL }
|
||||
|
||||
@Composable
|
||||
internal fun GameDetail(
|
||||
key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, hopRail: String?, onBack: () -> Unit,
|
||||
key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, hopRail: String?, onBack: () -> Unit, inStore: Boolean = false,
|
||||
) {
|
||||
val narrow = LocalNarrowPane.current
|
||||
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
|
||||
@@ -195,7 +195,6 @@ internal fun GameDetail(
|
||||
var inPage by remember(key) { mutableStateOf(false) }
|
||||
var onStrip by remember(key) { mutableStateOf(false) }
|
||||
var dropped by remember(key) { mutableStateOf(0) }
|
||||
// A tab's content is swapped or refreshed under the focused row; focus goes back to the tabs, not to the rail.
|
||||
LaunchedEffect(dropped) {
|
||||
if (dropped == 0) return@LaunchedEffect
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
@@ -220,6 +219,7 @@ internal fun GameDetail(
|
||||
if (!s.shortcutPicker) CompositionLocalProvider(LocalPillButtons provides true) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (installed != null && installed.sidecar.store == Store.ITCH) ItchCheckButton(installed)
|
||||
if (installed != null && installed.sidecar.store == Store.GAMEJOLT) GameJoltCheckButton(installed)
|
||||
RemoveButton(title, game, installed, a)
|
||||
}
|
||||
}
|
||||
@@ -234,7 +234,7 @@ internal fun GameDetail(
|
||||
color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked) }
|
||||
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore) }
|
||||
}
|
||||
}
|
||||
if (StoresMotion.heroLands) header() else Rise(1) { header() }
|
||||
@@ -319,7 +319,6 @@ private fun GameStatusLine(source: String, game: Library.SteamGame?, item: Catal
|
||||
}
|
||||
}
|
||||
|
||||
/** One frosted pill that holds the game's actions and its headline scores. */
|
||||
@Composable
|
||||
private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) {
|
||||
Row(
|
||||
@@ -385,7 +384,7 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
|
||||
@Composable
|
||||
internal fun GameActions(
|
||||
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
|
||||
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false,
|
||||
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false, inStore: Boolean = false,
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
val storeKey = if (store != null && id != null) "${store.id}:$id" else null
|
||||
@@ -412,10 +411,16 @@ internal fun GameActions(
|
||||
if (compactMenu) GameMoreMenu(game, a) else {
|
||||
FileButtons(game, a)
|
||||
GameShortcutMenu(game, a)
|
||||
EditArtButton(game)
|
||||
}
|
||||
}
|
||||
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (inStore && store == Store.GAMEJOLT && installed != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
|
||||
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
|
||||
}
|
||||
}
|
||||
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
|
||||
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
|
||||
if (store == Store.XBOX && installed != null && id != null) {
|
||||
@@ -438,6 +443,7 @@ internal fun GameActions(
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
}
|
||||
if (game != null && !compactMenu) EditArtButton(game)
|
||||
}
|
||||
download != null -> {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
@@ -485,7 +491,7 @@ internal fun GameActions(
|
||||
}
|
||||
if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
item != null && item.store == Store.ITCH && item.isFree -> {
|
||||
item != null && (item.store == Store.ITCH || item.store == Store.GAMEJOLT) && item.isFree -> {
|
||||
InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
@@ -500,7 +506,6 @@ internal fun GameActions(
|
||||
}
|
||||
}
|
||||
|
||||
/** Xbox Cloud Gaming rows the user added to the Library, for games not installed here. */
|
||||
@Composable
|
||||
internal fun rememberXboxCloudRows(s: FrontEndState): List<Library.SteamGame> {
|
||||
val ctx = LocalContext.current
|
||||
@@ -535,7 +540,6 @@ private fun XboxInstalledStream(id: String, title: String, item: CatalogItem?) {
|
||||
private fun XboxLibraryButton(id: String, item: CatalogItem?) {
|
||||
val ctx = LocalContext.current
|
||||
LaunchedEffect(Unit) { XboxCloudGames.load(ctx) }
|
||||
// Add and Remove replace each other; the controller focus moves to the new button instead of getting lost.
|
||||
val slot = remember { FocusRequester() }
|
||||
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -572,7 +576,6 @@ private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The pencil opens the editor each kind of game always had: the shortcut editor for added games, art for the rest. */
|
||||
@Composable
|
||||
private fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? {
|
||||
val ctx = LocalContext.current
|
||||
@@ -593,7 +596,6 @@ private fun EditArtButton(g: Library.SteamGame) {
|
||||
IconAction(Icons.Outlined.Edit, stringResource(R.string.game_edit_art), "game:edit", onClick = open)
|
||||
}
|
||||
|
||||
/** Narrow screens keep one More button in the capsule instead of a row of small ones. */
|
||||
@Composable
|
||||
private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) {
|
||||
var open by remember(g.gameId) { mutableStateOf(false) }
|
||||
@@ -932,7 +934,6 @@ private fun InstallTab(game: Library.SteamGame?, installed: InstalledStoreGame?,
|
||||
}
|
||||
}
|
||||
|
||||
/** Text a controller has to land on to bring it into view: focusable, with the focus ring. */
|
||||
@Composable
|
||||
internal fun Modifier.readable(): Modifier {
|
||||
val pal = LocalPalette.current
|
||||
@@ -953,7 +954,6 @@ internal fun FactRow(label: String, value: String, labelWidth: androidx.compose.
|
||||
}
|
||||
}
|
||||
|
||||
/** Store installs are measured by [StoreSizes]; Steam and added games by walking their folder once. */
|
||||
@Composable
|
||||
internal fun diskSize(installed: InstalledStoreGame?, folder: File): Long? {
|
||||
val ctx = LocalContext.current
|
||||
|
||||
@@ -55,13 +55,8 @@ import coil.request.ImageRequest
|
||||
import coil.size.Precision
|
||||
import kotlin.math.max
|
||||
|
||||
/** Buttons in a capsule render as pills; elsewhere they keep their rounded-rectangle shape. */
|
||||
internal val LocalPillButtons = compositionLocalOf { false }
|
||||
|
||||
/**
|
||||
* The page's blurred art, shared so frosted surfaces can draw the part of it behind them.
|
||||
* Coordinates are read when drawing, so a surface and the backdrop always agree on where they are.
|
||||
*/
|
||||
internal class GlassBackdrop {
|
||||
var painter: Painter? = null
|
||||
var coords: LayoutCoordinates? = null
|
||||
@@ -79,7 +74,6 @@ internal class GlassBackdrop {
|
||||
scope.drawCover(art, size, if (light) LightAmbient else DarkAmbient)
|
||||
}
|
||||
|
||||
/** Drawn inside a layer, so it fades what was painted before it toward the page's end. */
|
||||
fun fadeBottom(scope: DrawScope, size: Size) {
|
||||
val fade = minOf(size.height * 0.5f, with(scope) { 240.dp.toPx() })
|
||||
if (size.height <= 0f) return
|
||||
@@ -121,7 +115,6 @@ private fun ambientRequest(ctx: android.content.Context, model: Any?): ImageRequ
|
||||
|
||||
private const val AmbientPixels = 6
|
||||
|
||||
/** How washed-out the art is: average brightness less its saturation, from a tiny decode, so pale art is dimmed while dark and vivid art are left alone. */
|
||||
@Composable
|
||||
private fun rememberArtBrightness(model: Any?): Float {
|
||||
val ctx = LocalContext.current
|
||||
@@ -148,10 +141,6 @@ private fun rememberArtBrightness(model: Any?): Float {
|
||||
private const val SamplePixels = 8
|
||||
private const val SaturationWeight = 0.6
|
||||
|
||||
/**
|
||||
* A page whose game art fills the background: a blurred wash behind everything and the sharp art
|
||||
* across the top, fading into the page. Surfaces inside draw frosted glass over the wash.
|
||||
*/
|
||||
@Composable
|
||||
internal fun GameBackdrop(
|
||||
art: Any?, ambient: Any?, fallbackHue: Float,
|
||||
@@ -241,7 +230,6 @@ private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, onPlaced: (and
|
||||
private val ArtMin = 220.dp
|
||||
private val ArtMax = 340.dp
|
||||
|
||||
/** A frosted surface: the page's wash behind it, a dark tint, and a thin rim. Plain surface when there is no backdrop. */
|
||||
@Composable
|
||||
internal fun Modifier.glass(shape: Shape, lift: Float = 0f): Modifier {
|
||||
val g = LocalGlass.current
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowse
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowseState
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltQuery
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltBrowseBar(showMature: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
val query = GameJoltBrowseState.query
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(Unit) { if (GameJoltBrowseState.items.isEmpty()) GameJoltBrowseState.more(ctx) }
|
||||
fun toggle(set: Set<String>, value: String): Set<String> = if (value in set) set - value else set + value
|
||||
Column(Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ChipRow {
|
||||
BrowseDropdown(sectionLabel(query.section)) { first, close ->
|
||||
GameJoltBrowse.sections.forEachIndexed { index, section ->
|
||||
MenuItem(sectionLabel(section), query.section == section, focusRequester = if (index == 0) first else null) {
|
||||
GameJoltBrowseState.choose(ctx, query.copy(section = section))
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
BrowseDropdown(priceLabel(query.price)) { first, close ->
|
||||
GameJoltBrowse.prices.forEachIndexed { index, price ->
|
||||
MenuItem(priceLabel(price), query.price == price, focusRequester = if (index == 0) first else null) {
|
||||
GameJoltBrowseState.choose(ctx, query.copy(price = price))
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
val anyPlatform = stringResource(R.string.stores_itch_platform_any)
|
||||
BrowseDropdown(browseSummary(GameJoltBrowse.systems.filter { it in query.os }.map { systemLabel(it) }, anyPlatform)) { first, _ ->
|
||||
MenuItem(anyPlatform, query.os.isEmpty(), focusRequester = first) { GameJoltBrowseState.choose(ctx, query.copy(os = emptySet())) }
|
||||
for (os in GameJoltBrowse.systems) MenuItem(systemLabel(os), os in query.os) { GameJoltBrowseState.choose(ctx, query.copy(os = toggle(query.os, os))) }
|
||||
}
|
||||
BrowseDropdown(browseSummary(GameJoltBrowse.browsers.filter { it in query.browser }.map { browserLabel(it) }, stringResource(R.string.stores_gamejolt_filter_browser))) { first, _ ->
|
||||
GameJoltBrowse.browsers.forEachIndexed { index, browser ->
|
||||
MenuItem(browserLabel(browser), browser in query.browser, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(browser = toggle(query.browser, browser))) }
|
||||
}
|
||||
}
|
||||
val maturities = GameJoltBrowse.maturities.filter { showMature || it != "adult" }
|
||||
BrowseDropdown(browseSummary(maturities.filter { it in query.maturity }.map { maturityLabel(it) }, stringResource(R.string.stores_gamejolt_filter_maturity))) { first, _ ->
|
||||
maturities.forEachIndexed { index, maturity ->
|
||||
MenuItem(maturityLabel(maturity), maturity in query.maturity, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(maturity = toggle(query.maturity, maturity))) }
|
||||
}
|
||||
}
|
||||
BrowseDropdown(browseSummary(GameJoltBrowse.statuses.filter { it in query.status }.map { statusLabel(it) }, stringResource(R.string.stores_gamejolt_filter_status))) { first, _ ->
|
||||
GameJoltBrowse.statuses.forEachIndexed { index, status ->
|
||||
MenuItem(statusLabel(status), status in query.status, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(status = toggle(query.status, status))) }
|
||||
}
|
||||
}
|
||||
val partners = stringResource(R.string.stores_gamejolt_partners)
|
||||
BrowseDropdown(if (query.partners) partners else stringResource(R.string.stores_gamejolt_filter_partners)) { first, _ ->
|
||||
MenuItem(partners, query.partners, focusRequester = first) { GameJoltBrowseState.choose(ctx, query.copy(partners = !query.partners)) }
|
||||
}
|
||||
}
|
||||
ChipRow {
|
||||
for (tag in query.tags) BrowseChip("$tag ✕", true) { GameJoltBrowseState.choose(ctx, query.copy(tags = query.tags - tag)) }
|
||||
BrowseChip(stringResource(R.string.stores_itch_tag_add), false) { picking = true }
|
||||
}
|
||||
}
|
||||
if (picking) TextEntryDialog(
|
||||
stringResource(R.string.stores_itch_tag_title), "", number = false, confirm = stringResource(R.string.common_ok),
|
||||
onSubmit = { value -> GameJoltBrowse.tagSlug(value).takeIf { it.isNotEmpty() }?.let { GameJoltBrowseState.choose(ctx, query.copy(tags = (query.tags + it).distinct())) } },
|
||||
onDismiss = { picking = false }, id = "gamejolt-tag",
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltLoadMore() {
|
||||
val ctx = LocalContext.current
|
||||
val count = GameJoltBrowseState.items.size
|
||||
LaunchedEffect(Unit) { GameJoltBrowseState.more(ctx) }
|
||||
if (GameJoltBrowseState.loading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 12.dp))
|
||||
else if (GameJoltBrowseState.failed) Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
|
||||
BrowseChip(stringResource(R.string.stores_dl_retry), false) { GameJoltBrowseState.more(ctx, retry = true) }
|
||||
}
|
||||
else if (!GameJoltBrowseState.ended && count > 0) Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
|
||||
BrowseChip(stringResource(R.string.stores_itch_load_more), false) { GameJoltBrowseState.more(ctx) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun sectionLabel(section: String): String = stringResource(
|
||||
when (section) {
|
||||
GameJoltBrowse.SECTION_HOT -> R.string.stores_gamejolt_section_hot
|
||||
GameJoltBrowse.SECTION_BEST -> R.string.stores_gamejolt_section_best
|
||||
GameJoltBrowse.SECTION_NEW -> R.string.stores_gamejolt_section_new
|
||||
else -> R.string.stores_gamejolt_section_featured
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun priceLabel(price: String): String = stringResource(
|
||||
when (price) {
|
||||
GameJoltBrowse.PRICE_FREE -> R.string.stores_itch_price_free
|
||||
GameJoltBrowse.PRICE_SALE -> R.string.stores_itch_price_sale
|
||||
GameJoltBrowse.PRICE_PAID -> R.string.stores_itch_price_paid
|
||||
GameJoltBrowse.PRICE_UNDER_5 -> R.string.stores_itch_price_under_5
|
||||
GameJoltBrowse.PRICE_UNDER_15 -> R.string.stores_itch_price_under_15
|
||||
GameJoltBrowse.PRICE_UNDER_30 -> R.string.stores_gamejolt_price_under_30
|
||||
else -> R.string.stores_itch_price_any
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun systemLabel(os: String): String = stringResource(
|
||||
when (os) {
|
||||
"windows" -> R.string.stores_itch_platform_windows
|
||||
"mac" -> R.string.stores_itch_platform_macos
|
||||
"linux" -> R.string.stores_itch_platform_linux
|
||||
else -> R.string.stores_gamejolt_os_other
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun browserLabel(browser: String): String = when (browser) {
|
||||
"html" -> "HTML"
|
||||
"flash" -> "Flash"
|
||||
else -> "Unity"
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun maturityLabel(maturity: String): String = stringResource(
|
||||
when (maturity) {
|
||||
"everyone" -> R.string.stores_gamejolt_maturity_everyone
|
||||
"teen" -> R.string.stores_gamejolt_maturity_teen
|
||||
else -> R.string.stores_gamejolt_maturity_adult
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun statusLabel(status: String): String = stringResource(
|
||||
when (status) {
|
||||
"complete" -> R.string.stores_gamejolt_status_complete
|
||||
else -> R.string.stores_gamejolt_status_early
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltApi
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBuild
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
private const val CHOOSE = "choose"
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltVersionButton(installed: InstalledStoreGame, enabled: Boolean) {
|
||||
SecondaryButton(stringResource(R.string.stores_itch_pick_title), enabled = enabled) {
|
||||
val sidecar = installed.sidecar
|
||||
val paid = sidecar.extra["paid"] == "1"
|
||||
StoresState.gameJoltPicking = CatalogItem(
|
||||
store = Store.GAMEJOLT, id = sidecar.id, title = sidecar.title, imageUrl = sidecar.cover, isFree = !paid,
|
||||
storeUrl = GameJoltApi.pageUrl("game", sidecar.id),
|
||||
extra = mapOf("gameId" to (sidecar.extra["gameId"] ?: sidecar.id), CHOOSE to "1"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltBuildPicker(requested: CatalogItem, onDismiss: () -> Unit) {
|
||||
val item = requested.copy(owned = requested.owned || StoresState.library[Store.GAMEJOLT].orEmpty().any { it.id == requested.id && it.owned })
|
||||
val ctx = LocalContext.current
|
||||
val app = ctx.applicationContext
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
var loaded by remember(requested) { mutableStateOf<List<GameJoltBuild>?>(null) }
|
||||
var failed by remember(requested) { mutableStateOf(false) }
|
||||
|
||||
val install: (GameJoltBuild) -> Unit = install@{ build ->
|
||||
if (!shown.targetState) return@install
|
||||
val tagged = item.copy(
|
||||
extra = item.extra + mapOf("buildId" to build.id),
|
||||
sizeBytes = build.size.takeIf { it > 0 } ?: item.sizeBytes,
|
||||
)
|
||||
close()
|
||||
StoresState.requestInstall(ctx, tagged)
|
||||
}
|
||||
|
||||
LaunchedEffect(requested) {
|
||||
val gameId = item.extra["gameId"].orEmpty().ifEmpty { item.id }
|
||||
val result = withContext(Dispatchers.IO) { GameJoltBuilds.load(app, gameId) }
|
||||
if (result == null) { failed = true; return@LaunchedEffect }
|
||||
loaded = result
|
||||
if ((item.isFree || item.owned) && item.extra[CHOOSE] != "1" && shown.targetState) result.singleOrNull()?.takeIf { it.installable }?.let { install(it) }
|
||||
}
|
||||
|
||||
AppDialog(shown, close, "gameJoltBuilds", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(stringResource(R.string.stores_itch_pick_title), close)
|
||||
Text(item.title, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val list = loaded
|
||||
when {
|
||||
failed -> Text(stringResource(R.string.stores_gamejolt_pick_failed), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
list == null -> LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 8.dp))
|
||||
list.isEmpty() -> Text(stringResource(R.string.stores_itch_pick_none), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
for (build in list) key(build.id) { BuildRow(item, build) { install(build) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BuildRow(item: CatalogItem, build: GameJoltBuild, onInstall: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val linux = "linux" in build.platforms && !build.installable
|
||||
val canInstall = build.installable && (item.isFree || item.owned)
|
||||
val names = build.platforms.map { platformName(it) }
|
||||
val detail = listOfNotNull(
|
||||
names.joinToString(", "),
|
||||
build.size.takeIf { it > 0 }?.let { formatBytes(it) },
|
||||
build.version.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · ")
|
||||
ListRow(enabled = !linux, onClick = { if (canInstall) onInstall() else openStoreUrl(ctx, item) }) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(build.filename.ifBlank { build.packageTitle.ifBlank { item.title } }, fontSize = 13.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
val label = when {
|
||||
canInstall -> stringResource(R.string.stores_install)
|
||||
linux -> stringResource(R.string.stores_itch_build_linux_soon)
|
||||
else -> stringResource(R.string.stores_gamejolt_build_open)
|
||||
}
|
||||
Text(label, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun platformName(platform: String): String = stringResource(
|
||||
when (platform) {
|
||||
"windows" -> R.string.stores_itch_build_windows
|
||||
"linux" -> R.string.stores_itch_build_linux
|
||||
"osx" -> R.string.stores_itch_build_macos
|
||||
"other" -> R.string.stores_gamejolt_os_other
|
||||
else -> R.string.stores_itch_build_web
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
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.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdate
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltCheckButton(installed: InstalledStoreGame) {
|
||||
val ctx = LocalContext.current
|
||||
IconAction(Icons.Filled.Refresh, stringResource(R.string.store_check_updates), "game:check-updates", enabled = GameJoltUpdates.checkingKey == null, frosted = true) {
|
||||
GameJoltUpdates.checkGame(ctx, installed)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltUpdateButton(installed: InstalledStoreGame, enabled: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
val update = GameJoltUpdates.available[installed.key] ?: return
|
||||
var asking by remember { mutableStateOf(false) }
|
||||
SecondaryButton(stringResource(R.string.common_update), enabled = enabled) {
|
||||
if (update.replaced) asking = true else GameJoltUpdates.start(ctx, installed, update)
|
||||
}
|
||||
if (asking) GameJoltReplacedDialog(installed, update) { asking = false }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameJoltReplacedDialog(installed: InstalledStoreGame, update: GameJoltUpdate, onDismiss: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
AppDialog(shown, close, "gameJoltUpdate", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(installed.sidecar.title, close)
|
||||
Text(
|
||||
stringResource(R.string.stores_itch_update_replaced, update.filename.ifBlank { update.buildId }),
|
||||
fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
PrimaryButton(stringResource(R.string.common_update)) {
|
||||
close()
|
||||
GameJoltUpdates.start(ctx, installed, update)
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.common_cancel)) { close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,6 @@ internal fun filterGestureActions(actions: List<GestureAction>, query: String, g
|
||||
action.title.contains(word, ignoreCase = true) || action.id.removePrefix("key_").replace('_', ' ').contains(word, ignoreCase = true)
|
||||
}
|
||||
}.sortedWith(compareBy<GestureAction> { it.group.ordinal }.thenComparator { a, b ->
|
||||
// Function keys follow their numeric sequence; names use the UI locale.
|
||||
if (a.group == GestureActionGroup.FUNCTION) {
|
||||
a.id.removePrefix("key_F").toInt().compareTo(b.id.removePrefix("key_F").toInt())
|
||||
} else collator.compare(a.title, b.title)
|
||||
|
||||
@@ -28,7 +28,6 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
/** Actions for the phone while the picture is on the glasses. Null hides the button. */
|
||||
internal class GlassesPhoneActions(
|
||||
val onRecenter: (() -> Unit)?,
|
||||
val onRecenterJoyCons: (() -> Unit)?,
|
||||
|
||||
@@ -18,13 +18,36 @@ import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupPositionProvider
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
|
||||
internal object KeyWindows {
|
||||
private val views = java.util.concurrent.CopyOnWriteArrayList<android.view.View>()
|
||||
|
||||
fun add(view: android.view.View) {
|
||||
views.remove(view)
|
||||
views.add(view)
|
||||
}
|
||||
|
||||
fun remove(view: android.view.View) { views.remove(view) }
|
||||
|
||||
fun topOn(displayId: Int): android.view.View? =
|
||||
views.lastOrNull { it.isAttachedToWindow && it.display?.displayId == displayId }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun TrackKeyWindow() {
|
||||
val view = androidx.compose.ui.platform.LocalView.current
|
||||
androidx.compose.runtime.DisposableEffect(view) {
|
||||
KeyWindows.add(view)
|
||||
onDispose { KeyWindows.remove(view) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GlideDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Dialog(onDismissRequest, properties) { FocusGlideHost(content = content) }
|
||||
Dialog(onDismissRequest, properties) { TrackKeyWindow(); FocusGlideHost(content = content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -34,7 +57,10 @@ internal fun GlidePopup(
|
||||
properties: PopupProperties = PopupProperties(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Popup(popupPositionProvider, onDismissRequest, properties) { FocusGlideHost(content = content) }
|
||||
Popup(popupPositionProvider, onDismissRequest, properties) {
|
||||
if (properties.focusable) TrackKeyWindow()
|
||||
FocusGlideHost(content = content)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -225,7 +225,6 @@ internal fun GpuDriversBody(
|
||||
val scroll = rememberScrollState()
|
||||
val scope = rememberCoroutineScope()
|
||||
val placed = remember { arrayOfNulls<LayoutCoordinates>(2) }
|
||||
// Focusing the top mode shows as much of the in-use card above it as fits, without hiding the mode itself.
|
||||
val revealCard = {
|
||||
val (viewport, top) = placed
|
||||
if (viewport != null && top != null && viewport.isAttached && top.isAttached) scope.launch {
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
@@ -19,6 +20,7 @@ import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -27,6 +29,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -44,16 +47,29 @@ internal fun ItchBrowseBar() {
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
Column(Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ChipRow {
|
||||
for (sort in ItchBrowse.sorts) BrowseChip(sortLabel(sort), query.sort == sort) { ItchBrowseState.choose(ctx, query.copy(sort = sort)) }
|
||||
}
|
||||
ChipRow {
|
||||
for (price in ItchBrowse.prices) BrowseChip(priceLabel(price), query.price == price) { ItchBrowseState.choose(ctx, query.copy(price = price)) }
|
||||
}
|
||||
ChipRow {
|
||||
BrowseChip(stringResource(R.string.stores_itch_platform_any), query.platforms.isEmpty()) { ItchBrowseState.choose(ctx, query.copy(platforms = emptySet())) }
|
||||
for (platform in ItchBrowse.platformNames) {
|
||||
val on = platform in query.platforms
|
||||
BrowseChip(platformLabel(platform), on) { ItchBrowseState.choose(ctx, query.copy(platforms = if (on) query.platforms - platform else query.platforms + platform)) }
|
||||
BrowseDropdown(sortLabel(query.sort)) { first, close ->
|
||||
ItchBrowse.sorts.forEachIndexed { index, sort ->
|
||||
MenuItem(sortLabel(sort), query.sort == sort, focusRequester = if (index == 0) first else null) {
|
||||
ItchBrowseState.choose(ctx, query.copy(sort = sort))
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
BrowseDropdown(priceLabel(query.price)) { first, close ->
|
||||
ItchBrowse.prices.forEachIndexed { index, price ->
|
||||
MenuItem(priceLabel(price), query.price == price, focusRequester = if (index == 0) first else null) {
|
||||
ItchBrowseState.choose(ctx, query.copy(price = price))
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
val anyPlatform = stringResource(R.string.stores_itch_platform_any)
|
||||
BrowseDropdown(browseSummary(ItchBrowse.platformNames.filter { it in query.platforms }.map { platformLabel(it) }, anyPlatform)) { first, _ ->
|
||||
MenuItem(anyPlatform, query.platforms.isEmpty(), focusRequester = first) { ItchBrowseState.choose(ctx, query.copy(platforms = emptySet())) }
|
||||
for (platform in ItchBrowse.platformNames) {
|
||||
val on = platform in query.platforms
|
||||
MenuItem(platformLabel(platform), on) { ItchBrowseState.choose(ctx, query.copy(platforms = if (on) query.platforms - platform else query.platforms + platform)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
ChipRow {
|
||||
@@ -83,7 +99,7 @@ internal fun ItchLoadMore() {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChipRow(content: @Composable () -> Unit) {
|
||||
internal fun ChipRow(content: @Composable () -> Unit) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).selectableGroup(),
|
||||
@@ -91,7 +107,22 @@ private fun ChipRow(content: @Composable () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BrowseChip(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
internal fun BrowseDropdown(text: String, content: @Composable ColumnScope.(FocusRequester, () -> Unit) -> Unit) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
CompositionLocalProvider(LocalChipMinWidth provides 0.dp) { ValueChip(text, expanded) { expanded = !expanded } }
|
||||
AnchoredMenu(expanded, onDismiss = { expanded = false }, compact = true, minWidth = 160.dp) { first -> content(first) { expanded = false } }
|
||||
}
|
||||
}
|
||||
|
||||
internal fun browseSummary(labels: List<String>, empty: String): String = when (labels.size) {
|
||||
0 -> empty
|
||||
1, 2 -> labels.joinToString(", ")
|
||||
else -> "${labels.first()} +${labels.size - 1}"
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun BrowseChip(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
|
||||
@@ -102,7 +102,8 @@ import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollection
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltCollections
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollections
|
||||
import com.droiddeck.launcher.stores.itch.ItchUpdates
|
||||
import com.droiddeck.launcher.stores.gog.GogMaintenance
|
||||
@@ -112,7 +113,6 @@ import com.droiddeck.launcher.stores.sortGames
|
||||
import kotlinx.coroutines.launch
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
/** One owned game: installed ones carry their [game], store products not installed yet only their [item]. */
|
||||
internal class LibraryEntry(
|
||||
val key: String, val source: String, val title: String,
|
||||
val game: Library.SteamGame?, val item: CatalogItem?, val installed: Boolean,
|
||||
@@ -120,7 +120,6 @@ internal class LibraryEntry(
|
||||
val storeKey: String? get() = item?.key ?: game?.storeId?.let { "${game.source}:$it" }
|
||||
}
|
||||
|
||||
/** Installed games first claim their store product, so a game owned and installed shows once. */
|
||||
internal fun libraryEntries(
|
||||
games: List<Library.SteamGame>, owned: Map<Store, List<CatalogItem>>, installedStore: Set<String>,
|
||||
): List<LibraryEntry> {
|
||||
@@ -144,22 +143,21 @@ internal fun libraryEntries(
|
||||
return out.distinctBy { it.key }
|
||||
}
|
||||
|
||||
internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>): List<LibraryEntry> {
|
||||
internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>, store: Store = Store.ITCH): List<LibraryEntry> {
|
||||
val keys = items.map { it.key }.toSet()
|
||||
val itch = all.filter { it.source == Store.ITCH.id }
|
||||
val have = itch.mapNotNull { it.storeKey }.toSet()
|
||||
return itch.filter { it.storeKey in keys } +
|
||||
items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), Store.ITCH.id, it.title, null, it, false) }
|
||||
val own = all.filter { it.source == store.id }
|
||||
val have = own.mapNotNull { it.storeKey }.toSet()
|
||||
return own.filter { it.storeKey in keys } +
|
||||
items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), store.id, it.title, null, it, false) }
|
||||
}
|
||||
|
||||
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
|
||||
|
||||
internal const val LIBRARY_ALL = "all"
|
||||
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>): List<String> =
|
||||
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet()): List<String> =
|
||||
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED)
|
||||
.filter { source -> entries.any { it.source == source } }
|
||||
.filter { source -> source in always || entries.any { it.source == source } }
|
||||
|
||||
/** Survives leaving the page, so Stores can open the Library on one store's owned games. */
|
||||
internal object LibraryDisplay {
|
||||
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
|
||||
var level by mutableIntStateOf(2)
|
||||
@@ -228,7 +226,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) }
|
||||
var collectionShows by remember { mutableStateOf<Pair<String, Boolean>?>(null) }
|
||||
val setShowUninstalled = { show: Boolean ->
|
||||
val picked = ItchCollections.selected.takeIf { LibraryView.source == Store.ITCH.id }
|
||||
val picked = when (LibraryView.source) {
|
||||
Store.ITCH.id -> ItchCollections.selected
|
||||
Store.GAMEJOLT.id -> GameJoltCollections.selected
|
||||
else -> null
|
||||
}
|
||||
if (picked != null) collectionShows = picked to show
|
||||
else {
|
||||
showUninstalled = show
|
||||
@@ -236,21 +238,32 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
}
|
||||
}
|
||||
val itchSignedIn = owned.containsKey(Store.ITCH)
|
||||
val listed = librarySources(all, SessionPrefs.storesTabOrder(ctx))
|
||||
val sources = if (itchSignedIn && Store.ITCH.id !in listed) listed + Store.ITCH.id else listed
|
||||
val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT)
|
||||
val sources = librarySources(all, SessionPrefs.storesTabOrder(ctx), listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn }).toSet())
|
||||
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
|
||||
val q = LibraryView.query.trim().lowercase()
|
||||
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
|
||||
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) {
|
||||
ItchCollections.load(ctx)
|
||||
ItchUpdates.check(ctx)
|
||||
} }
|
||||
val collection = if (source == Store.ITCH.id) ItchCollections.chosen() else null
|
||||
val pool = if (collection == null) all else collectionEntries(all, ItchCollections.gamesOf(collection.id).orEmpty())
|
||||
LaunchedEffect(source, itchSignedIn, gameJoltSignedIn) {
|
||||
if (source == Store.ITCH.id && itchSignedIn) {
|
||||
ItchCollections.load(ctx)
|
||||
ItchUpdates.check(ctx)
|
||||
}
|
||||
if (source == Store.GAMEJOLT.id && gameJoltSignedIn) {
|
||||
GameJoltCollections.load(ctx)
|
||||
GameJoltUpdates.check(ctx)
|
||||
}
|
||||
}
|
||||
val collectionId = when (source) {
|
||||
Store.ITCH.id -> ItchCollections.chosen()?.id
|
||||
Store.GAMEJOLT.id -> GameJoltCollections.chosen()?.id
|
||||
else -> null
|
||||
}
|
||||
val collectionItems = collectionId?.let { if (source == Store.GAMEJOLT.id) GameJoltCollections.gamesOf(it) else ItchCollections.gamesOf(it) }
|
||||
val pool = if (collectionId == null) all else collectionEntries(all, collectionItems.orEmpty(), Store.byId(source) ?: Store.ITCH)
|
||||
val matching = pool.filter {
|
||||
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
|
||||
}
|
||||
val listUninstalled = if (collection == null) showUninstalled else collectionShows?.takeIf { it.first == collection.id }?.second ?: true
|
||||
val listUninstalled = if (collectionId == null) showUninstalled else collectionShows?.takeIf { it.first == collectionId }?.second ?: true
|
||||
val candidates = if (listUninstalled) matching else matching.filter { it.installed }
|
||||
val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed }
|
||||
val sort = s.storesSort
|
||||
@@ -335,7 +348,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
kotlinx.coroutines.delay(Motion.ms(240).toLong())
|
||||
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
|
||||
}
|
||||
if (all.isEmpty() && open == null && !itchSignedIn) {
|
||||
if (all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
|
||||
LibraryEmpty(s, a, modifier)
|
||||
return
|
||||
}
|
||||
@@ -456,7 +469,7 @@ private fun LibraryGrid(
|
||||
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = source == Store.ITCH.id) }
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }) }
|
||||
}
|
||||
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(1) { LibraryFilters(sources, source, onSource) }
|
||||
@@ -517,7 +530,7 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
|
||||
@Composable
|
||||
private fun LibraryHeader(
|
||||
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Store?,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
@@ -535,7 +548,7 @@ private fun LibraryHeader(
|
||||
) {
|
||||
DisplayButton()
|
||||
if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
|
||||
if (collections) CollectionsButton()
|
||||
if (collections != null) CollectionsButton(collections)
|
||||
SortButton(s, a)
|
||||
ViewButton(s, a)
|
||||
GameFileFolderActions(s, a)
|
||||
@@ -728,7 +741,7 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?, showDownlo
|
||||
}
|
||||
}
|
||||
|
||||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available } == true ||
|
||||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available } == true ||
|
||||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
|
||||
|
||||
@Composable
|
||||
@@ -797,7 +810,6 @@ internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.gra
|
||||
) { Icon(icon, null, tint = if (hot) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(18.dp)) }
|
||||
}
|
||||
|
||||
/** Choosing Library in the rail lands on the first game, as Play Steam does on the Steam page. */
|
||||
@Composable
|
||||
internal fun Modifier.paneEntry(): Modifier {
|
||||
val ff = LocalFrontFocus.current ?: return this
|
||||
@@ -867,16 +879,21 @@ private fun LibraryFilterButton(showUninstalled: Boolean?, onShowUninstalled: (B
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CollectionsButton() {
|
||||
private fun CollectionsButton(store: Store) {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val title = stringResource(R.string.itch_collections)
|
||||
val all = stringResource(R.string.stores_tab_all)
|
||||
var at by remember { mutableStateOf<Rect?>(null) }
|
||||
val gameJolt = store == Store.GAMEJOLT
|
||||
val chosenTitle = if (gameJolt) GameJoltCollections.chosen()?.title else ItchCollections.chosen()?.title
|
||||
val selectedId = if (gameJolt) GameJoltCollections.selected else ItchCollections.selected
|
||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
||||
HeaderIconButton(title + " · " + (ItchCollections.chosen()?.title ?: all), CollectionsIcon, "itch-collections") {
|
||||
HeaderIconButton(title + " · " + (chosenTitle ?: all), CollectionsIcon, "${store.id}-collections") {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
val choices = listOf<ItchCollection?>(null) + ItchCollections.list
|
||||
val choices = listOf<Pair<String, String>?>(null) + if (gameJolt) GameJoltCollections.list.map { c ->
|
||||
c.id to (c.title + (GameJoltCollections.gamesOf(c.id)?.let { " (" + it.size + ")" }.orEmpty()))
|
||||
} else ItchCollections.list.map { c -> c.id to (c.title + " (" + c.count + ")") }
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = choices.size,
|
||||
handle = { Icon(CollectionsIcon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
@@ -884,12 +901,12 @@ private fun CollectionsButton() {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
choices.forEachIndexed { i, c ->
|
||||
val picked = c?.id == ItchCollections.selected
|
||||
val picked = c?.first == selectedId
|
||||
StepChoice(
|
||||
c?.let { it.title + " (" + it.count + ")" } ?: all, selected = picked, enabled = open,
|
||||
c?.second ?: all, selected = picked, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (picked) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
ItchCollections.select(ctx, c?.id)
|
||||
if (gameJolt) GameJoltCollections.select(ctx, c?.first) else ItchCollections.select(ctx, c?.first)
|
||||
Steps.fold()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,7 +460,7 @@ internal fun LiftHero(
|
||||
scrim { sink.value }
|
||||
if (shown || open) Box(
|
||||
Modifier.fillMaxSize()
|
||||
.graphicsLayer { alpha = sink.value }.background(Color.Black.copy(alpha = 0.42f))
|
||||
.overhang().graphicsLayer { alpha = sink.value }.background(Color.Black.copy(alpha = 0.42f))
|
||||
.focusProperties { canFocus = false }
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, enabled = open && !launching) { close() },
|
||||
)
|
||||
|
||||
@@ -57,10 +57,8 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
/** Steam's library hero is 3840 x 1240, so the preview keeps that shape. */
|
||||
private const val HERO_RATIO = 3840f / 1240f
|
||||
|
||||
/** The gap Steam leaves between the pinned logo and the edge of the hero, as a share of the hero's width. */
|
||||
private const val EDGE = 0.03f
|
||||
|
||||
@Composable
|
||||
@@ -86,10 +84,6 @@ private fun LogoPosition.Pin.alignment(): Alignment = when (this) {
|
||||
internal fun logoPositionSummary(value: LogoPosition.Value?): String =
|
||||
if (value == null) stringResource(R.string.logo_pos_default) else "${value.pin.label()} · ${value.widthPct}%"
|
||||
|
||||
/**
|
||||
* Where a game's logo sits on its background in Steam's library: the logo box is [Value.widthPct] x [Value.heightPct] of the
|
||||
* background, pinned to one of five places, and the logo is drawn as large as fits in it.
|
||||
*/
|
||||
@Composable
|
||||
private fun LogoPreview(hero: File?, logo: File?, value: LogoPosition.Value) {
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
@@ -130,7 +124,6 @@ private fun PinChip(label: String, selected: Boolean, focus: FocusRequester?, on
|
||||
}
|
||||
}
|
||||
|
||||
/** The "Adjust logo" screen: the game's background with its logo on it, where to pin the logo and how large to draw it. */
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun LogoPositionDialog(
|
||||
|
||||
@@ -68,11 +68,15 @@ class ModeSettings(
|
||||
val pipSupported: Boolean = false,
|
||||
val pipAutoEnter: Boolean = false,
|
||||
val oscMode: String?,
|
||||
val backHold: Boolean = true,
|
||||
val backActionsInverted: Boolean = false,
|
||||
val directAudio: Boolean?,
|
||||
val mic: Boolean?,
|
||||
val gameStorage: String? = null,
|
||||
val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(),
|
||||
val steamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Entry> = emptyList(),
|
||||
val foundSteamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Found> = emptyList(),
|
||||
val allFilesAccessMissing: Boolean = false,
|
||||
val storageDiagnostics: Boolean = false,
|
||||
val fexPreset: String? = null,
|
||||
val forceSsbs: Boolean = false,
|
||||
@@ -80,16 +84,14 @@ class ModeSettings(
|
||||
val picturePosition: String? = null,
|
||||
val stretch16x9: Boolean? = null,
|
||||
val steamClientArch: String? = null,
|
||||
/** Steam only: a game launched from the front end returns there when it closes; null hides the row. */
|
||||
val returnAfterGame: Boolean? = null,
|
||||
/** Steam only: the client's Shader Pre-Caching setting; null hides the row. */
|
||||
val shaderPrecache: Boolean? = null,
|
||||
val steamRepairQueued: Boolean = false,
|
||||
val mangoapp: Boolean = true,
|
||||
val steamController: String? = null,
|
||||
val unfoldedControls: Boolean? = null,
|
||||
val unfoldedControlsWithController: Boolean = false,
|
||||
val runSteamAtStartup: Boolean = false,
|
||||
val startupSession: String = SessionPrefs.STARTUP_OFF,
|
||||
val bootMovie: String? = null,
|
||||
val bootMovieSound: Boolean = true,
|
||||
val bootMovieCustomName: String? = null,
|
||||
@@ -118,12 +120,18 @@ class ModeSettingsActions(
|
||||
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
val onOsc: (String) -> Unit,
|
||||
val onBackHold: (Boolean) -> Unit = {},
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onDirectAudio: (Boolean) -> Unit,
|
||||
val onMic: (Boolean) -> Unit,
|
||||
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
|
||||
val onPickGameStorageFolder: () -> Unit = {},
|
||||
val onStorageDiagnostics: (Boolean) -> Unit = {},
|
||||
val onAddSteamLibrary: () -> Unit = {},
|
||||
val onAddFoundSteamLibrary: (path: String) -> Unit = {},
|
||||
val onAllowAllFilesAccess: () -> Unit = {},
|
||||
val onRenameSteamLibrary: (id: String, label: String) -> Unit = { _, _ -> },
|
||||
val onRemoveSteamLibrary: (id: String) -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit = {},
|
||||
val onForceSsbs: (Boolean) -> Unit = {},
|
||||
val onSyncBackend: (String) -> Unit = {},
|
||||
@@ -137,7 +145,7 @@ class ModeSettingsActions(
|
||||
val onSteamController: (String) -> Unit = {},
|
||||
val onUnfoldedControls: (Boolean) -> Unit = {},
|
||||
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
|
||||
val onRunSteamAtStartup: (Boolean) -> Unit = {},
|
||||
val onStartupSession: (String) -> Unit = {},
|
||||
val onBootMovie: (String) -> Unit = {},
|
||||
val onBootMovieSound: (Boolean) -> Unit = {},
|
||||
val onImportBootMovie: () -> Unit = {},
|
||||
@@ -154,15 +162,12 @@ class ModeSettingsActions(
|
||||
val onDismiss: () -> Unit,
|
||||
)
|
||||
|
||||
/** "2610 r3" from droiddeck-fex-update's FEX_TAG line (fex-2610-r3), the build x86 programs fall back to. */
|
||||
internal fun fexVersionOf(script: String): String? =
|
||||
Regex("""(?m)^FEX_TAG=(fex-\d+-r\d+)\s*$""").find(script)?.let { fexVersionOfTag(it.groupValues[1]) }
|
||||
|
||||
/** "2610 r5" from a tag such as fex-2610-r5. */
|
||||
internal fun fexVersionOfTag(tag: String): String? =
|
||||
Regex("""fex-(\d+)-r(\d+)""").matchEntire(tag.trim())?.let { "${it.groupValues[1]} r${it.groupValues[2]}" }
|
||||
|
||||
/** The build installed in the runtime, else the one fex.json names, else the one the launcher pins. */
|
||||
@Composable
|
||||
private fun x64FexVersion(context: android.content.Context): String? = remember {
|
||||
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context)
|
||||
@@ -223,7 +228,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
}
|
||||
if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) ||
|
||||
com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) {
|
||||
val canStretch = s.resolution != com.droiddeck.launcher.session.SessionDisplay.FOLLOW_SCREEN &&
|
||||
val canStretch = !com.droiddeck.launcher.session.SessionDisplay.isFollow(s.resolution) &&
|
||||
com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize)
|
||||
ChoiceRow(host, "game-fit", stringResource(R.string.display_game_fit),
|
||||
stringResource(if (canStretch) R.string.display_game_fit_hint else R.string.display_game_fit_unavailable),
|
||||
@@ -296,6 +301,10 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
stringResource(R.string.unfolded_controls_with_controller_hint),
|
||||
s.unfoldedControlsWithController, onChange = a.onUnfoldedControlsWithController,
|
||||
)
|
||||
if (steam) ToggleRow(
|
||||
host, "back-hold", stringResource(R.string.back_hold),
|
||||
stringResource(R.string.back_hold_hint), s.backHold, onChange = a.onBackHold,
|
||||
)
|
||||
if (steam) ChoiceRow(
|
||||
host, "back-actions", stringResource(R.string.mode_back), stringResource(SessionPrefs.backActionsOrder(s.backActionsInverted)),
|
||||
listOf(
|
||||
@@ -303,7 +312,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU),
|
||||
), s.backActionsInverted, onPick = a.onBackActionsInverted,
|
||||
)
|
||||
if (steam && s.steamController in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) {
|
||||
if (steam && s.backHold && s.steamController in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) {
|
||||
Note(stringResource(R.string.back_native_qam_hint))
|
||||
}
|
||||
PhysicalShortcutRows()
|
||||
@@ -350,11 +359,15 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
|
||||
s.pipAutoEnter, onChange = a.onPipAutoEnter)
|
||||
}
|
||||
if (steam) SettingsGroup(stringResource(R.string.mode_startup)) {
|
||||
ToggleRow(
|
||||
host, "steam-startup", stringResource(R.string.mode_steam_startup),
|
||||
stringResource(R.string.mode_steam_startup_hint),
|
||||
s.runSteamAtStartup, onChange = a.onRunSteamAtStartup,
|
||||
SettingsGroup(stringResource(R.string.mode_startup)) {
|
||||
ChoiceRow(
|
||||
host, "startup-session", stringResource(R.string.mode_startup_session),
|
||||
stringResource(R.string.mode_startup_session_hint),
|
||||
listOf(
|
||||
SessionPrefs.STARTUP_OFF to stringResource(R.string.common_never),
|
||||
SessionPrefs.STARTUP_STEAM to stringResource(R.string.rail_steam),
|
||||
SessionPrefs.STARTUP_DESKTOP to stringResource(R.string.rail_desktop),
|
||||
), s.startupSession, onPick = a.onStartupSession,
|
||||
)
|
||||
}
|
||||
extras.performance()
|
||||
@@ -401,6 +414,47 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
onChange = a.onStorageDiagnostics,
|
||||
)
|
||||
}
|
||||
if (s.gameStorage != null) SettingsGroup(stringResource(R.string.libraries_title), detail = stringResource(R.string.libraries_applies_next)) {
|
||||
var renaming by remember { mutableStateOf<com.droiddeck.launcher.session.SteamLibraries.Entry?>(null) }
|
||||
for (library in s.steamLibraries) {
|
||||
val attached = library.host.isDirectory
|
||||
SettingsRow(library.label, if (attached) library.path else stringResource(R.string.libraries_missing, library.path)) {
|
||||
Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton(stringResource(R.string.libraries_rename), compact = true) { renaming = library }
|
||||
SecondaryButton(stringResource(R.string.edit_remove), compact = true) { a.onRemoveSteamLibrary(library.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) for (found in s.foundSteamLibraries) {
|
||||
SettingsRow(
|
||||
found.label,
|
||||
stringResource(R.string.libraries_found_hint, pluralStringResource(R.plurals.mode_added_count, found.games, found.games), found.shown),
|
||||
) {
|
||||
SecondaryButton(stringResource(R.string.libraries_add_found), compact = true) { a.onAddFoundSteamLibrary(found.path) }
|
||||
}
|
||||
}
|
||||
if (s.allFilesAccessMissing && s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) {
|
||||
SettingsRow(stringResource(R.string.libraries_access_title), stringResource(R.string.libraries_access_hint)) {
|
||||
SecondaryButton(stringResource(R.string.libraries_access_allow), compact = true, onClick = a.onAllowAllFilesAccess)
|
||||
}
|
||||
}
|
||||
SettingsRow(
|
||||
stringResource(R.string.libraries_add),
|
||||
if (s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) stringResource(R.string.libraries_hint)
|
||||
else stringResource(R.string.libraries_full, com.droiddeck.launcher.session.SteamLibraries.MAX),
|
||||
) {
|
||||
SecondaryButton(
|
||||
stringResource(R.string.mode_choose_folder),
|
||||
enabled = s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX,
|
||||
onClick = a.onAddSteamLibrary,
|
||||
)
|
||||
}
|
||||
renaming?.let { library ->
|
||||
TextEntryDialog(stringResource(R.string.libraries_rename_title), library.label, onDismiss = { renaming = null }) { name ->
|
||||
a.onRenameSteamLibrary(library.id, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (tab == SheetTab.STEAM && steam) {
|
||||
extras.account(host)
|
||||
@@ -665,3 +719,23 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun CustomFollowScaleDialog(initial: Float?, onSave: (Float) -> Unit, onDismiss: () -> Unit) {
|
||||
var text by remember { mutableStateOf(initial?.let(com.droiddeck.launcher.session.SessionDisplay::formatScale) ?: "") }
|
||||
val parsed = com.droiddeck.launcher.session.SessionDisplay.parseFollowScale(text)
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.display_follow_screen_scaled, "…")) },
|
||||
text = {
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
text, { v -> text = v.filter { it.isDigit() || it == '.' || it == ',' }.take(4) },
|
||||
label = { Text("÷") }, singleLine = true, isError = parsed == null && text.isNotEmpty(),
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Decimal),
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = { androidx.compose.material3.TextButton(enabled = parsed != null, onClick = { parsed?.let(onSave) }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_use)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -21,7 +21,6 @@ internal object PageSwipe {
|
||||
var direction by mutableIntStateOf(0)
|
||||
}
|
||||
|
||||
// Runs on the Final pass so carousels, sliders, scrollers and widgets that consumed the drag keep it.
|
||||
@Composable
|
||||
internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier {
|
||||
val enabledNow by rememberUpdatedState(enabled)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.PC_KEY_HIDDEN_GROUPS
|
||||
import com.droiddeck.launcher.input.PC_KEY_ROWS
|
||||
import com.droiddeck.launcher.input.PC_MODIFIERS
|
||||
import com.droiddeck.launcher.input.PcKey
|
||||
@@ -35,6 +36,7 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -45,12 +47,14 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.key.nativeKeyCode
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -98,10 +102,17 @@ fun PcKeyboard(
|
||||
}
|
||||
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
|
||||
|
||||
val prefsContext = LocalContext.current
|
||||
remember { PcKeyboardPrefs.load(prefsContext) }
|
||||
val hiddenCodes = PcKeyboardPrefs.hiddenKeys.flatMap { PC_KEY_HIDDEN_GROUPS[it].orEmpty() }.toSet()
|
||||
val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() }
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
|
||||
val rowHeight = ((maxHeight * 0.47f - 24.dp - 3.dp * 6 - 10.dp) / 6).coerceIn(24.dp, 44.dp)
|
||||
val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
|
||||
.coerceIn(20.dp, 56.dp)
|
||||
Box(
|
||||
Modifier.fillMaxWidth()
|
||||
.graphicsLayer { alpha = PcKeyboardPrefs.opacity / 100f }
|
||||
.background(Color(0xE6101418), RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
|
||||
.border(1.dp, pal.line2, RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); waitForUpOrCancellation()?.consume() } }
|
||||
@@ -115,7 +126,7 @@ fun PcKeyboard(
|
||||
Spacer(Modifier.width(8.dp))
|
||||
HeaderButton(stringResource(R.string.pckb_hide), onClose)
|
||||
}
|
||||
PC_KEY_ROWS.forEachIndexed { r, row ->
|
||||
rows.forEachIndexed { r, row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) {
|
||||
row.forEachIndexed { i, key ->
|
||||
val state = mods[key.code] ?: MOD_OFF
|
||||
@@ -126,11 +137,13 @@ fun PcKeyboard(
|
||||
key.label.length == 1 && key.label[0].isLetter() && (shifted xor capsOn) -> key.label.uppercase()
|
||||
else -> key.label
|
||||
}
|
||||
KeyCap(
|
||||
label, key.weight, lit, locked = state == MOD_LOCKED,
|
||||
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
|
||||
onDown = { press(key) }, onUp = { release(key) },
|
||||
)
|
||||
key(key.code) {
|
||||
KeyCap(
|
||||
label, key.weight, lit, locked = state == MOD_LOCKED,
|
||||
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
|
||||
onDown = { press(key) }, onUp = { release(key) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -164,8 +177,11 @@ private fun RowScope.KeyCap(
|
||||
awaitEachGesture {
|
||||
awaitFirstDown().consume()
|
||||
down = true; onDown()
|
||||
waitForUpOrCancellation()?.consume()
|
||||
down = false; onUp()
|
||||
try {
|
||||
waitForUpOrCancellation()?.consume()
|
||||
} finally {
|
||||
down = false; onUp()
|
||||
}
|
||||
}
|
||||
}
|
||||
.onPreviewKeyEvent { e ->
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.input.PC_KEY_HIDDEN_GROUPS
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
internal object PcKeyboardPrefs {
|
||||
var size by mutableStateOf(SessionPrefs.PC_KEYBOARD_SIZE_DEFAULT)
|
||||
private set
|
||||
var opacity by mutableStateOf(SessionPrefs.PC_KEYBOARD_OPACITY_DEFAULT)
|
||||
private set
|
||||
var hiddenKeys by mutableStateOf(emptySet<String>())
|
||||
private set
|
||||
|
||||
fun load(context: Context) {
|
||||
size = SessionPrefs.pcKeyboardSize(context)
|
||||
opacity = SessionPrefs.pcKeyboardOpacity(context)
|
||||
hiddenKeys = SessionPrefs.pcKeyboardHiddenKeys(context).filter { it in PC_KEY_HIDDEN_GROUPS }.toSet()
|
||||
}
|
||||
|
||||
fun setSize(context: Context, percent: Int) {
|
||||
size = percent
|
||||
SessionPrefs.setPcKeyboardSize(context, percent)
|
||||
}
|
||||
|
||||
fun setOpacity(context: Context, percent: Int) {
|
||||
opacity = percent
|
||||
SessionPrefs.setPcKeyboardOpacity(context, percent)
|
||||
}
|
||||
|
||||
fun toggleHiddenKey(context: Context, group: String, on: Boolean) {
|
||||
hiddenKeys = if (on) hiddenKeys + group else hiddenKeys - group
|
||||
SessionPrefs.setPcKeyboardHiddenKeys(context, hiddenKeys)
|
||||
}
|
||||
}
|
||||
@@ -179,7 +179,6 @@ private fun CaptureShortcutKeys(onKey: (KeyEvent) -> Boolean) {
|
||||
val window = (LocalView.current.parent as DialogWindowProvider).window
|
||||
DisposableEffect(window) {
|
||||
val previous = window.callback
|
||||
// Capture before dialog navigation so Back and gamepad buttons can be assigned.
|
||||
window.callback = object : Window.Callback by previous {
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean =
|
||||
currentOnKey(event) || previous.dispatchKeyEvent(event)
|
||||
|
||||
@@ -20,22 +20,34 @@ fun ResolutionRow(
|
||||
val size = SessionDisplay.resolveChoice(panel, choice, portrait)
|
||||
val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait)
|
||||
val choices = SessionDisplay.resolutionOptions(panel)
|
||||
val selected = if (choice == SessionDisplay.FOLLOW_SCREEN) choice
|
||||
val customFollow = SessionDisplay.isFollow(choice) && choice !in choices
|
||||
val selected = if (SessionDisplay.isFollow(choice)) choice
|
||||
else if (size == screen) SessionDisplay.MATCH_SCREEN else choice
|
||||
var editCustom by remember { mutableStateOf(false) }
|
||||
var editFollow by remember { mutableStateOf(false) }
|
||||
val options = choices.map { value ->
|
||||
val dimensions = SessionDisplay.resolveChoice(panel, value, portrait)
|
||||
value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second)
|
||||
else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen)
|
||||
else if (SessionDisplay.isFollow(value)) stringResource(R.string.display_follow_screen_scaled,
|
||||
SessionDisplay.formatScale(SessionDisplay.followScale(value) ?: 1f)) + " (${dimensions.first}×${dimensions.second})"
|
||||
else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
|
||||
else "${dimensions.first}×${dimensions.second}"
|
||||
} + (custom to if (selected in choices) stringResource(R.string.mode_res_custom)
|
||||
} + listOf(SessionDisplay.FOLLOW_CUSTOM to stringResource(R.string.display_follow_screen_scaled,
|
||||
if (customFollow) SessionDisplay.formatScale(SessionDisplay.followScale(choice) ?: 1f) else "…"
|
||||
) + if (customFollow) " (${size.first}×${size.second})" else "") + (custom to if (selected in choices) stringResource(R.string.mode_res_custom)
|
||||
else stringResource(R.string.mode_res_custom_value, size.first, size.second))
|
||||
ChoiceRow(host, "resolution", stringResource(R.string.display_resolution),
|
||||
stringResource(R.string.common_applies_next_session),
|
||||
options, if (selected in choices) selected else custom, chipModifier = chipModifier,
|
||||
onPick = { value -> if (value == custom) editCustom = true else onPick(value) })
|
||||
options, if (selected in choices) selected else if (customFollow) SessionDisplay.FOLLOW_CUSTOM else custom, chipModifier = chipModifier,
|
||||
onPick = { value ->
|
||||
if (value == custom) editCustom = true
|
||||
else if (value == SessionDisplay.FOLLOW_CUSTOM) editFollow = true
|
||||
else onPick(value) })
|
||||
if (editCustom) CustomResolutionDialog(size,
|
||||
onSave = { value -> editCustom = false; onPick("${value.first}x${value.second}") },
|
||||
onDismiss = { editCustom = false })
|
||||
if (editFollow) CustomFollowScaleDialog(SessionDisplay.followScale(choice)?.takeIf { it > 1f },
|
||||
onSave = { value -> editFollow = false; onPick(SessionDisplay.followScaled(value)) },
|
||||
onDismiss = { editFollow = false })
|
||||
}
|
||||
@@ -2,48 +2,31 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import android.app.Presentation
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.Gravity
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowInsets
|
||||
import android.view.WindowManager
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.Button
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.HorizontalScrollView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.lifecycle.setViewTreeViewModelStoreOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
import com.droiddeck.launcher.input.InputProfiles
|
||||
import com.droiddeck.launcher.input.InputSurfaceLayout
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
import com.droiddeck.launcher.session.BottomDesktop
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SessionTerminal
|
||||
import com.termux.terminal.TerminalEmulator
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
|
||||
class SecondScreenPresentation(
|
||||
private val sessionActivity: SessionActivity,
|
||||
@@ -59,27 +42,27 @@ class SecondScreenPresentation(
|
||||
private val onKeyboardClosed: () -> Unit = {},
|
||||
private val onMenu: (() -> Unit)? = null,
|
||||
private val menu: (@androidx.compose.runtime.Composable () -> Unit)? = null,
|
||||
private val dashboard: (@androidx.compose.runtime.Composable () -> Unit)? = null,
|
||||
private val onSwap: (() -> Unit)? = null,
|
||||
private val onMenuTouched: () -> Unit = {},
|
||||
) : Presentation(sessionActivity, display) {
|
||||
private val frame = FrameLayout(context)
|
||||
private var menuView: androidx.compose.ui.platform.ComposeView? = null
|
||||
private var dashboardView: androidx.compose.ui.platform.ComposeView? = null
|
||||
var menuShown = false
|
||||
private set
|
||||
private val root = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setBackgroundColor(Color.rgb(15, 18, 22))
|
||||
setBackgroundColor(Color.BLACK)
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
private var currentMode = SecondScreenMode.NONE
|
||||
private var keyboardHost: KeyboardHost? = null
|
||||
private var keyboardButton: TextView? = null
|
||||
private val keyboardShown = androidx.compose.runtime.mutableStateOf(false)
|
||||
private var keyboardPending = false
|
||||
private var imeSeen = false
|
||||
private var fieldKeyboard = false
|
||||
private var terminalSession: TerminalSession? = null
|
||||
private var terminalView: TerminalView? = null
|
||||
private var terminalPid = -1
|
||||
private var ctrlActive = false
|
||||
private var altActive = false
|
||||
private var terminalPanel: SessionTerminalPanel? = null
|
||||
private var created = false
|
||||
|
||||
init {
|
||||
@@ -115,10 +98,10 @@ class SecondScreenPresentation(
|
||||
|
||||
private fun showPendingKeyboard() {
|
||||
keyboardPending = false
|
||||
keyboardButton?.text = context.getString(R.string.second_hide_keyboard)
|
||||
keyboardShown.value = true
|
||||
val host = keyboardHost ?: return
|
||||
for (delay in longArrayOf(150L, 450L)) root.postDelayed({
|
||||
val host = keyboardHost
|
||||
if (host != null && !imeSeen && showsKeyboard) host.show()
|
||||
if (keyboardHost === host && keyboardShown.value && !imeSeen && showsKeyboard) host.show()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
@@ -134,7 +117,7 @@ class SecondScreenPresentation(
|
||||
fieldKeyboard = false
|
||||
imeSeen = false
|
||||
keyboardHost?.takeIf { it.shown }?.hide()
|
||||
keyboardButton?.text = context.getString(R.string.second_show_keyboard)
|
||||
keyboardShown.value = false
|
||||
onKeyboardClosed()
|
||||
}
|
||||
|
||||
@@ -144,6 +127,10 @@ class SecondScreenPresentation(
|
||||
if (created) renderMode()
|
||||
}
|
||||
|
||||
fun retryTerminal() {
|
||||
if (created && isShowing && currentMode == SecondScreenMode.TERMINAL && terminalPanel?.ready != true) renderMode()
|
||||
}
|
||||
|
||||
val showsKeyboard: Boolean get() = isShowing && !menuShown && currentMode == SecondScreenMode.KEYBOARD_TRACKPAD
|
||||
|
||||
val showsControls: Boolean get() = isShowing && currentMode != SecondScreenMode.NONE
|
||||
@@ -154,12 +141,8 @@ class SecondScreenPresentation(
|
||||
menuShown = on
|
||||
if (on) {
|
||||
keyboardHost?.takeIf { it.shown }?.hide()
|
||||
window?.decorView?.let { decor ->
|
||||
decor.setViewTreeLifecycleOwner(sessionActivity)
|
||||
decor.setViewTreeViewModelStoreOwner(sessionActivity)
|
||||
decor.setViewTreeSavedStateRegistryOwner(sessionActivity)
|
||||
decor.setViewTreeOnBackPressedDispatcherOwner(sessionActivity)
|
||||
}
|
||||
keyboardShown.value = false
|
||||
ownComposeViews()
|
||||
val view = menuView ?: androidx.compose.ui.platform.ComposeView(context).apply {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
@@ -178,12 +161,25 @@ class SecondScreenPresentation(
|
||||
}
|
||||
}
|
||||
|
||||
private fun ownComposeViews() {
|
||||
window?.decorView?.let { decor ->
|
||||
decor.setViewTreeLifecycleOwner(sessionActivity)
|
||||
decor.setViewTreeViewModelStoreOwner(sessionActivity)
|
||||
decor.setViewTreeSavedStateRegistryOwner(sessionActivity)
|
||||
decor.setViewTreeOnBackPressedDispatcherOwner(sessionActivity)
|
||||
}
|
||||
}
|
||||
|
||||
fun focusMenu(): Boolean = menuView?.requestFocus() == true
|
||||
|
||||
fun dispatchMenuKey(event: KeyEvent): Boolean = menuView?.dispatchKeyEvent(event) == true
|
||||
fun dispatchMenuKey(event: KeyEvent): Boolean {
|
||||
KeyWindows.topOn(display.displayId)?.let { return it.rootView.dispatchKeyEvent(event) }
|
||||
return menuView?.dispatchKeyEvent(event) == true
|
||||
}
|
||||
|
||||
fun closeControls() {
|
||||
showMenu(false)
|
||||
closeDashboard()
|
||||
closeTerminal()
|
||||
keyboardHost?.hide()
|
||||
keyboardHost = null
|
||||
@@ -191,11 +187,19 @@ class SecondScreenPresentation(
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
val forward = menuShown || currentMode != SecondScreenMode.TERMINAL || PadBridge.isControllerKeyEvent(event)
|
||||
val ownKeys = currentMode == SecondScreenMode.TERMINAL || currentMode == SecondScreenMode.DASHBOARD ||
|
||||
currentMode == SecondScreenMode.DESKTOP
|
||||
val back = event.keyCode == KeyEvent.KEYCODE_BACK && currentMode == SecondScreenMode.DASHBOARD
|
||||
val forward = menuShown || !ownKeys || back || PadBridge.isControllerKeyEvent(event)
|
||||
if (forward && sessionActivity.dispatchKeyEvent(event)) return true
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
if (menuShown && event.actionMasked == MotionEvent.ACTION_DOWN) onMenuTouched()
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (PadBridge.isControllerMotionEvent(event) && sessionActivity.dispatchGenericMotionEvent(event)) return true
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
@@ -222,193 +226,99 @@ class SecondScreenPresentation(
|
||||
fieldKeyboard = false
|
||||
keyboardHost?.hide()
|
||||
keyboardHost = null
|
||||
keyboardButton = null
|
||||
keyboardShown.value = false
|
||||
keyboardPending = false
|
||||
imeSeen = false
|
||||
closeTerminal()
|
||||
closeDashboard()
|
||||
root.removeAllViews()
|
||||
val mode = if (currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) SecondScreenMode.NONE
|
||||
else currentMode
|
||||
ownComposeViews()
|
||||
val mode = when {
|
||||
currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> SecondScreenMode.NONE
|
||||
currentMode == SecondScreenMode.DASHBOARD && dashboard == null -> SecondScreenMode.NONE
|
||||
currentMode == SecondScreenMode.DESKTOP && !BottomDesktop.available() -> SecondScreenMode.NONE
|
||||
else -> currentMode
|
||||
}
|
||||
if (mode == SecondScreenMode.NONE) return
|
||||
|
||||
when (mode) {
|
||||
SecondScreenMode.KEYBOARD_TRACKPAD -> renderKeyboardAndTrackpad()
|
||||
SecondScreenMode.TERMINAL -> renderTerminal()
|
||||
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam, pad, onMenu = onMenu), weightParams())
|
||||
SecondScreenMode.CUSTOM_CONTROLS -> {
|
||||
val profile = InputProfiles.active(context, SessionState.mode == SessionService.MODE_DESKTOP)
|
||||
root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam, pad,
|
||||
InputSurfaceLayout.read(context, profile.id), onMenu = onMenu), weightParams())
|
||||
InputSurfaceLayout.read(context, profile.id), onMenu = onMenu, onSwap = onSwap), weightParams())
|
||||
keyboardHost = KeyboardHost(context) { sessionActivity.dispatchKeyEvent(it) }.also { root.addView(it, ViewGroup.LayoutParams(1, 1)) }
|
||||
}
|
||||
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam, pad, onMenu = onMenu, onSwap = onSwap), weightParams())
|
||||
SecondScreenMode.DASHBOARD -> renderDashboard()
|
||||
SecondScreenMode.DESKTOP -> {
|
||||
root.addView(BottomDesktopPanel(context, onClose, onMenu,
|
||||
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap), weightParams())
|
||||
}
|
||||
SecondScreenMode.NONE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun bar(mode: SecondScreenMode, extras: () -> List<BarExtra> = { emptyList() }) {
|
||||
root.addView(bottomScreenBarView(context) {
|
||||
sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras())
|
||||
}, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
|
||||
private fun renderDashboard() {
|
||||
val content = dashboard ?: return
|
||||
bar(SecondScreenMode.DASHBOARD) {
|
||||
listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) })
|
||||
}
|
||||
val view = androidx.compose.ui.platform.ComposeView(context).apply { setContent { content() } }
|
||||
dashboardView = view
|
||||
root.addView(view, weightParams())
|
||||
}
|
||||
|
||||
private fun closeDashboard() {
|
||||
dashboardView?.disposeComposition()
|
||||
dashboardView = null
|
||||
}
|
||||
|
||||
private fun renderKeyboardAndTrackpad() {
|
||||
val panel = FrameLayout(context)
|
||||
panel.addView(trackpadView(), FrameLayout.LayoutParams(-1, -1))
|
||||
val controls = LinearLayout(context).apply {
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
setPadding(dp(12), dp(10), dp(12), dp(6))
|
||||
setBackgroundColor(Color.BLACK)
|
||||
}
|
||||
fun gap() = View(context).apply { layoutParams = LinearLayout.LayoutParams(dp(8), 1) }
|
||||
controls.addView(DeckControlsPanel.roundButton(context, "×", context.getString(R.string.deck_close), onClose))
|
||||
controls.addView(TextView(context).apply {
|
||||
text = context.getString(R.string.second_trackpad)
|
||||
textSize = 14f
|
||||
typeface = android.graphics.Typeface.create(android.graphics.Typeface.DEFAULT, android.graphics.Typeface.BOLD)
|
||||
setTextColor(Color.rgb(0x7A, 0x80, 0x8A))
|
||||
setPadding(dp(14), 0, dp(8), 0)
|
||||
isSingleLine = true
|
||||
}, LinearLayout.LayoutParams(0, -2, 1f))
|
||||
lateinit var keyboardButton: TextView
|
||||
keyboardButton = DeckControlsPanel.roundButton(context, context.getString(R.string.second_show_keyboard),
|
||||
context.getString(R.string.second_show_keyboard), {
|
||||
val host = keyboardHost
|
||||
if (host != null) {
|
||||
bar(SecondScreenMode.KEYBOARD_TRACKPAD) {
|
||||
listOf(BarExtra(context.getString(if (keyboardShown.value) R.string.second_hide_keyboard else R.string.second_show_keyboard),
|
||||
icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") {
|
||||
keyboardHost?.let { host ->
|
||||
host.toggle()
|
||||
keyboardButton.text = context.getString(if (host.shown) R.string.second_hide_keyboard else R.string.second_show_keyboard)
|
||||
keyboardShown.value = host.shown
|
||||
}
|
||||
}, wide = true)
|
||||
controls.addView(keyboardButton)
|
||||
this.keyboardButton = keyboardButton
|
||||
onMenu?.let {
|
||||
controls.addView(gap())
|
||||
controls.addView(DeckControlsPanel.menuButton(context, it))
|
||||
})
|
||||
}
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) {
|
||||
controls.addView(gap())
|
||||
controls.addView(DeckControlsPanel.roundButton(context, "STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true))
|
||||
controls.addView(gap())
|
||||
controls.addView(DeckControlsPanel.roundButton(context, "•••", context.getString(R.string.drawer_open_qam), onQam, wide = true))
|
||||
}
|
||||
panel.addView(controls, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
|
||||
root.addView(panel, weightParams())
|
||||
root.addView(trackpadView(), weightParams())
|
||||
val host = KeyboardHost(context) { event ->
|
||||
val handled = sessionActivity.dispatchKeyEvent(event)
|
||||
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
|
||||
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
|
||||
handled
|
||||
}
|
||||
host.onImeChanged = { visible -> if (!visible && keyboardShown.value) keyboardClosed() }
|
||||
keyboardHost = host
|
||||
root.addView(host, ViewGroup.LayoutParams(1, 1))
|
||||
}
|
||||
|
||||
private fun trackpadView(): View = TrackpadView(context)
|
||||
private fun trackpadView(): View = SessionTrackpadView(context, sendPointer, sendButton, sendWheel, pointerPosition)
|
||||
|
||||
private fun renderTerminal() {
|
||||
val bar = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
setPadding(dp(8), dp(4), dp(8), dp(4))
|
||||
setBackgroundColor(Color.rgb(27, 32, 38))
|
||||
}
|
||||
bar.addView(Button(context).apply {
|
||||
text = "×"
|
||||
contentDescription = context.getString(R.string.deck_close)
|
||||
minWidth = dp(48)
|
||||
setOnClickListener { onClose() }
|
||||
})
|
||||
bar.addView(TextView(context).apply {
|
||||
text = context.getString(R.string.second_terminal)
|
||||
textSize = 14f
|
||||
setTextColor(Color.WHITE)
|
||||
}, LinearLayout.LayoutParams(0, -2, 1f))
|
||||
bar.addView(Button(context).apply {
|
||||
text = context.getString(R.string.drawer_keyboard)
|
||||
setOnClickListener { showTerminalKeyboard() }
|
||||
})
|
||||
root.addView(bar, LinearLayout.LayoutParams(-1, -2))
|
||||
|
||||
val terminalClient = TerminalClient()
|
||||
val view = TerminalView(context, null).apply {
|
||||
setTerminalViewClient(terminalClient)
|
||||
setTextSize(dp(14))
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
terminalView = view
|
||||
val session = SessionTerminal.create(terminalClient)
|
||||
if (session == null) {
|
||||
root.addView(TextView(context).apply {
|
||||
text = context.getString(R.string.second_terminal_not_ready)
|
||||
setTextColor(Color.WHITE)
|
||||
gravity = Gravity.CENTER
|
||||
}, LinearLayout.LayoutParams(-1, 0, 1f))
|
||||
return
|
||||
}
|
||||
terminalSession = session
|
||||
|
||||
val keyStrip = HorizontalScrollView(context).apply { isHorizontalScrollBarEnabled = false }
|
||||
val keys = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; setPadding(dp(4), dp(2), dp(4), dp(2)) }
|
||||
fun key(label: String, input: String, onClick: ((Button) -> Unit)? = null) {
|
||||
val button = Button(context).apply {
|
||||
text = label
|
||||
setOnClickListener { if (onClick != null) onClick(this) else session.write(input) }
|
||||
}
|
||||
keys.addView(button)
|
||||
}
|
||||
val ctrl = context.getString(R.string.pckb_key_ctrl)
|
||||
val alt = context.getString(R.string.pckb_key_alt)
|
||||
key(context.getString(R.string.pckb_key_esc), "\u001b")
|
||||
key(context.getString(R.string.second_key_tab), "\t")
|
||||
key(ctrl, "") { button ->
|
||||
ctrlActive = !ctrlActive
|
||||
button.text = if (ctrlActive) context.getString(R.string.second_key_on, ctrl) else ctrl
|
||||
}
|
||||
key(alt, "") { button ->
|
||||
altActive = !altActive
|
||||
button.text = if (altActive) context.getString(R.string.second_key_on, alt) else alt
|
||||
}
|
||||
key("↑", "\u001b[A")
|
||||
key("↓", "\u001b[B")
|
||||
key("←", "\u001b[D")
|
||||
key("→", "\u001b[C")
|
||||
key(context.getString(R.string.second_key_ctrl_c), "\u0003")
|
||||
key(context.getString(R.string.second_key_ctrl_d), "\u0004")
|
||||
keyStrip.addView(keys)
|
||||
root.addView(keyStrip, LinearLayout.LayoutParams(-1, -2))
|
||||
|
||||
root.addView(view, LinearLayout.LayoutParams(-1, 0, 1f))
|
||||
view.attachSession(session)
|
||||
|
||||
view.post {
|
||||
registerTerminalPid()
|
||||
view.requestFocus()
|
||||
showTerminalKeyboard()
|
||||
}
|
||||
}
|
||||
|
||||
private fun showTerminalKeyboard() {
|
||||
terminalView?.let { view ->
|
||||
view.requestFocus()
|
||||
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
|
||||
.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
|
||||
private fun registerTerminalPid() {
|
||||
val pid = terminalSession?.pid ?: -1
|
||||
if (pid > 1 && pid != terminalPid) {
|
||||
terminalPid = pid
|
||||
SessionService.registerTerminalProcess(context, pid)
|
||||
bar(SecondScreenMode.TERMINAL) {
|
||||
listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard, tag = "bottom-keyboard") {
|
||||
terminalPanel?.showKeyboard()
|
||||
})
|
||||
}
|
||||
val panel = SessionTerminalPanel(context)
|
||||
terminalPanel = panel
|
||||
root.addView(panel, weightParams())
|
||||
}
|
||||
|
||||
private fun closeTerminal() {
|
||||
terminalView?.let { view ->
|
||||
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
|
||||
.hideSoftInputFromWindow(view.windowToken, 0)
|
||||
}
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: (terminalSession?.pid ?: -1)
|
||||
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
|
||||
terminalPid = -1
|
||||
terminalSession = null
|
||||
terminalView = null
|
||||
ctrlActive = false
|
||||
altActive = false
|
||||
terminalPanel?.close()
|
||||
terminalPanel = null
|
||||
}
|
||||
|
||||
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
|
||||
@@ -424,112 +334,4 @@ class SecondScreenPresentation(
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
}
|
||||
|
||||
private inner class TrackpadView(context: Context) : View(context) {
|
||||
private val gestures = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(),
|
||||
object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) {
|
||||
sendPointer(x, y, width.toFloat(), height.toFloat())
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
sendPointer(x, y, width.toFloat(), height.toFloat())
|
||||
sendButton(button, pressed)
|
||||
}
|
||||
|
||||
override fun onWheel(steps: Int) = sendWheel(steps)
|
||||
override fun onLongPress() { performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS) }
|
||||
})
|
||||
|
||||
init { isFocusable = true }
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
gestures.bounds = android.graphics.RectF(0f, 0f, w.toFloat(), h.toFloat())
|
||||
if (oldw == 0 || oldh == 0) gestures.place(w / 2f, h / 2f)
|
||||
}
|
||||
|
||||
private val surface = android.graphics.RectF()
|
||||
private val fill = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(0x0A, 0x0B, 0x0D) }
|
||||
private val edge = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = android.graphics.Paint.Style.STROKE
|
||||
color = Color.rgb(0x26, 0x29, 0x2E)
|
||||
strokeWidth = resources.displayMetrics.density
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
canvas.drawColor(Color.BLACK)
|
||||
val inset = dp(12).toFloat()
|
||||
surface.set(inset, dp(72).toFloat(), width - inset, height - inset)
|
||||
if (surface.height() <= inset) return
|
||||
val radius = dp(20).toFloat()
|
||||
canvas.drawRoundRect(surface, radius, radius, fill)
|
||||
canvas.drawRoundRect(surface, radius, radius, edge)
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) pointerPosition()?.let {
|
||||
gestures.place(it.x * width, it.y * height)
|
||||
}
|
||||
return gestures.onTouch(event)
|
||||
}
|
||||
}
|
||||
|
||||
private inner class TerminalClient : TerminalSessionClient, TerminalViewClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {
|
||||
terminalView?.onScreenUpdated()
|
||||
}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = Unit
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: finishedSession.pid
|
||||
if (pid > 1) SessionService.terminalProcessExited(context, pid)
|
||||
terminalPid = -1
|
||||
terminalView?.onScreenUpdated()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
(context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager)
|
||||
.setPrimaryClip(android.content.ClipData.newPlainText("Terminal", text))
|
||||
}
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val clip = (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).primaryClip
|
||||
if (clip != null && clip.itemCount > 0) session.write(clip.getItemAt(0).coerceToText(context).toString())
|
||||
}
|
||||
override fun onBell(session: TerminalSession) {
|
||||
terminalView?.performHapticFeedback(android.view.HapticFeedbackConstants.KEYBOARD_TAP)
|
||||
}
|
||||
override fun onColorsChanged(changedSession: TerminalSession) {
|
||||
terminalView?.invalidate()
|
||||
}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {
|
||||
terminalView?.setTerminalCursorBlinkerRate(if (state) 600 else 0)
|
||||
}
|
||||
override fun getTerminalCursorStyle(): Int = TerminalEmulator.TERMINAL_CURSOR_STYLE_BLOCK
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, e.message, e) }
|
||||
|
||||
override fun onScale(scale: Float): Float = 1f
|
||||
override fun onSingleTapUp(e: MotionEvent) = showTerminalKeyboard()
|
||||
override fun shouldBackButtonBeMappedToEscape(): Boolean = true
|
||||
override fun shouldEnforceCharBasedInput(): Boolean = false
|
||||
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
|
||||
override fun isTerminalViewSelected(): Boolean = true
|
||||
override fun copyModeChanged(copyMode: Boolean) = Unit
|
||||
override fun onKeyDown(keyCode: Int, e: KeyEvent, session: TerminalSession): Boolean = false
|
||||
override fun onKeyUp(keyCode: Int, e: KeyEvent): Boolean = false
|
||||
override fun onLongPress(event: MotionEvent): Boolean = false
|
||||
override fun readControlKey(): Boolean = ctrlActive
|
||||
override fun readAltKey(): Boolean = altActive
|
||||
override fun readShiftKey(): Boolean = false
|
||||
override fun readFnKey(): Boolean = false
|
||||
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession): Boolean = false
|
||||
override fun onEmulatorSet() {
|
||||
terminalView?.onScreenUpdated()
|
||||
registerTerminalPid()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package com.droiddeck.launcher.ui
|
||||
internal enum class SessionDrawerPage(val firstControl: String) {
|
||||
CONTROLLER("touch"),
|
||||
GLASSES("glasses-game"),
|
||||
SECOND_SCREEN("second-screen:none"),
|
||||
SECOND_SCREEN("second-screen:keyboard-trackpad"),
|
||||
DISPLAY("fg"),
|
||||
HUD("hud"),
|
||||
EFFECTS("look"),
|
||||
|
||||
@@ -29,8 +29,11 @@ import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Terminal
|
||||
import androidx.compose.material.icons.outlined.Dashboard
|
||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||
import androidx.compose.material.icons.outlined.Keyboard
|
||||
import androidx.compose.material.icons.outlined.AutoFixHigh
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
@@ -151,6 +154,7 @@ import com.droiddeck.launcher.gpu.SteamVr
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.input.PC_KEY_GROUP_IDS
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_CLICK
|
||||
@@ -220,6 +224,8 @@ class DrawerActions(
|
||||
val micAvailable: Boolean = false,
|
||||
val micEnabled: Boolean = false,
|
||||
val onMicEnabled: (Boolean) -> Unit = {},
|
||||
val backHold: Boolean = true,
|
||||
val onBackHold: (Boolean) -> Unit = {},
|
||||
val backActionsInverted: Boolean,
|
||||
val backDoubleTapMs: Int = 500,
|
||||
val onBackDoubleTapMs: (Int) -> Unit = {},
|
||||
@@ -240,6 +246,12 @@ class DrawerActions(
|
||||
val textureAnisotropy: Int? = 0,
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenNone: Boolean = true,
|
||||
val gameOnBottom: Boolean = false,
|
||||
val gameSwapAvailable: Boolean = false,
|
||||
val onGameOnBottom: (Boolean) -> Unit = {},
|
||||
val dashboardAvailable: Boolean = false,
|
||||
val desktopAvailable: Boolean = false,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
@@ -270,6 +282,8 @@ class DrawerActions(
|
||||
val onLowLatency: (Boolean) -> Unit = {},
|
||||
val evdevMouse: Boolean = false,
|
||||
val onEvdevMouse: (Boolean) -> Unit = {},
|
||||
val relativeMouseMode: Int = 0,
|
||||
val onRelativeMouseMode: (Int) -> Unit = {},
|
||||
val directCursor: Boolean = false,
|
||||
val onDirectCursor: (Boolean) -> Unit = {},
|
||||
val onTouch: (String) -> Unit,
|
||||
@@ -309,6 +323,7 @@ class DrawerActions(
|
||||
val onStop: () -> Unit,
|
||||
val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null,
|
||||
val onClose: () -> Unit,
|
||||
val onDismissScreen: (() -> Unit)? = null,
|
||||
val components: ComponentsManager.Snapshot? = null,
|
||||
val onComponentsRefresh: () -> Unit = {},
|
||||
val componentCatalog: List<ComponentsManager.CatalogItem> = emptyList(),
|
||||
@@ -412,7 +427,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
val first = when {
|
||||
page == SessionDrawerPage.GLASSES -> "glasses-tab-$glassesTab"
|
||||
page == SessionDrawerPage.SESSION && a.isHomeApp -> "apps"
|
||||
page == SessionDrawerPage.SECOND_SCREEN -> "second-screen:${a.secondScreenMode.id}"
|
||||
page == SessionDrawerPage.SECOND_SCREEN -> "second-screen:" +
|
||||
(if (a.secondScreenMode == SecondScreenMode.NONE && !a.secondScreenNone) SecondScreenMode.KEYBOARD_TRACKPAD else a.secondScreenMode).id
|
||||
else -> page.firstControl
|
||||
}
|
||||
if (turned) focus.forget(page)
|
||||
@@ -442,7 +458,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
|
||||
val short = maxHeight < 440.dp
|
||||
val sheetWidth = if (docked) maxWidth else minOf(360.dp, maxWidth * 0.92f)
|
||||
val sheetWidth = if (docked) maxWidth else minOf(420.dp, maxWidth * 0.92f)
|
||||
val narrow = sheetWidth < 320.dp
|
||||
AnimatedVisibility(
|
||||
open,
|
||||
@@ -461,52 +477,52 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
.padding(12.dp),
|
||||
) {
|
||||
val roomyHeader = sheetWidth >= 408.dp
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp)
|
||||
.then(if (roomyHeader) Modifier else Modifier.horizontalScroll(rememberScrollState())),
|
||||
) {
|
||||
if (docked) {
|
||||
SteamActionPill(
|
||||
stringResource(R.string.common_close), Icons.Outlined.Close, focus.track(page, "close"),
|
||||
) { host.open = null; a.onClose() }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
BottomScreenModes(a, focus.track(page, "bottom-modes")) { host.open = null }
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
SteamActionPill(
|
||||
stringResource(R.string.common_close), Icons.Outlined.Close, focus.track(page, "close"),
|
||||
) { host.open = null; (a.onDismissScreen ?: a.onClose)() }
|
||||
if (roomyHeader) Spacer(Modifier.weight(1f))
|
||||
SteamActionPill(
|
||||
stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"),
|
||||
) { host.open = null; a.onPause() }
|
||||
if (a.pipSupported) SteamActionPill(
|
||||
stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"),
|
||||
) { host.open = null; a.onPip() }
|
||||
if (a.steam && a.onSteamMenu != null && a.onQam != null) {
|
||||
val qamInteraction = remember { MutableInteractionSource() }
|
||||
var qamStartedOnPress by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(qamInteraction) {
|
||||
qamInteraction.interactions.collect { interaction ->
|
||||
if (interaction is PressInteraction.Press) {
|
||||
qamStartedOnPress = true
|
||||
host.open = null
|
||||
a.onQam.invoke()
|
||||
}
|
||||
StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
|
||||
val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null
|
||||
val qamInteraction = remember { MutableInteractionSource() }
|
||||
var qamStartedOnPress by remember { mutableStateOf(false) }
|
||||
if (steamActions) LaunchedEffect(qamInteraction) {
|
||||
qamInteraction.interactions.collect { interaction ->
|
||||
if (interaction is PressInteraction.Press) {
|
||||
qamStartedOnPress = true
|
||||
host.open = null
|
||||
a.onQam?.invoke()
|
||||
} else if (interaction is PressInteraction.Cancel) {
|
||||
qamStartedOnPress = false
|
||||
}
|
||||
}
|
||||
SteamActionPill(stringResource(R.string.drawer_steam_menu), Icons.Outlined.Home, focus.track(page, "steam"), shortcut = "⧉") {
|
||||
host.open = null
|
||||
a.onSteamMenu.invoke()
|
||||
}
|
||||
SteamActionPill(
|
||||
stringResource(R.string.drawer_open_qam), Icons.Outlined.MoreHoriz, focus.track(page, "qam"),
|
||||
interactionSource = qamInteraction, shortcut = "☰",
|
||||
onConfirm = { host.open = null; a.onQam.invoke() },
|
||||
) {
|
||||
host.open = null
|
||||
if (!qamStartedOnPress) a.onQam.invoke()
|
||||
qamStartedOnPress = false
|
||||
}
|
||||
}
|
||||
StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
|
||||
BarActions(
|
||||
onMenu = { host.open = null; a.onClose() }, menuActive = true,
|
||||
onSteam = if (steamActions) ({ host.open = null; a.onSteamMenu?.invoke() }) else null,
|
||||
onQam = if (steamActions) ({
|
||||
host.open = null
|
||||
if (!qamStartedOnPress) a.onQam?.invoke()
|
||||
qamStartedOnPress = false
|
||||
}) else null,
|
||||
menuModifier = focus.track(page, "menu"),
|
||||
steamModifier = focus.track(page, "steam"),
|
||||
qamModifier = focus.track(page, "qam"),
|
||||
qamInteraction = qamInteraction,
|
||||
onQamConfirm = { host.open = null; a.onQam?.invoke() },
|
||||
)
|
||||
}
|
||||
a.onAchievements?.let { show ->
|
||||
DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) {
|
||||
@@ -534,7 +550,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)),
|
||||
) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) {
|
||||
when (page) {
|
||||
SessionDrawerPage.HUD -> FusionHudSettings(host, a) { key -> focus.track(page, key) }
|
||||
SessionDrawerPage.HUD -> DroidDeckHudSettings(host, a) { key -> focus.track(page, key) }
|
||||
SessionDrawerPage.DISPLAY -> {
|
||||
SettingsGroup(stringResource(R.string.drawer_page_display)) {
|
||||
val fgOpen = host.open == "fg"
|
||||
@@ -588,6 +604,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
|
||||
ActionRow(stringResource(R.string.input_settings), null, stringResource(R.string.ctrl_edit), a.onInputSettings,
|
||||
modifier = focus.track(page, "input-settings"))
|
||||
if (a.touchActive == SessionPrefs.TOUCH_PAD)
|
||||
RelativeMouseRow(host, a, focus.track(page, "relative-mouse"))
|
||||
if (a.touchActive == SessionPrefs.TOUCH_DIRECT)
|
||||
ToggleRow(host, "direct-cursor", stringResource(R.string.drawer_direct_cursor),
|
||||
null, a.directCursor,
|
||||
@@ -609,7 +627,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
SecondaryButton(stringResource(R.string.ctrl_edit),
|
||||
SecondaryButton(stringResource(R.string.ctrl_edit), enabled = a.screenKeysShown,
|
||||
modifier = focus.track(page, "screen-keys"), onClick = a.onScreenKeys)
|
||||
a.onScreenLayouts?.let { open ->
|
||||
SecondaryButton(stringResource(R.string.screen_key_layout),
|
||||
@@ -642,6 +660,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
chipModifier = focus.track(page, "keyboard-button"), onChange = a.onKeyboardButton)
|
||||
}
|
||||
}
|
||||
if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold),
|
||||
stringResource(R.string.back_hold_hint), a.backHold,
|
||||
chipModifier = focus.track(page, "back-hold"), onChange = a.onBackHold)
|
||||
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), null,
|
||||
listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)),
|
||||
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
|
||||
@@ -665,6 +686,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
ToggleRow(host, "evdev-mouse", stringResource(R.string.drawer_evdev_mouse),
|
||||
null, a.evdevMouse,
|
||||
chipModifier = focus.track(page, "evdev-mouse"), onChange = a.onEvdevMouse)
|
||||
if (a.touchActive != SessionPrefs.TOUCH_PAD)
|
||||
RelativeMouseRow(host, a, focus.track(page, "relative-mouse"))
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.drawer_keyboard)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
|
||||
@@ -675,6 +698,28 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
host.open = null; a.onKeyboard()
|
||||
}
|
||||
}
|
||||
val keyboardContext = LocalContext.current
|
||||
remember { PcKeyboardPrefs.load(keyboardContext) }
|
||||
SliderRow(
|
||||
stringResource(R.string.pckb_size), stringResource(R.string.pckb_size_hint),
|
||||
PcKeyboardPrefs.size, SessionPrefs.PC_KEYBOARD_SIZE_RANGE, step = 1,
|
||||
format = { "$it%" }, modifier = focus.track(page, "pckb-size"),
|
||||
onChange = { PcKeyboardPrefs.setSize(keyboardContext, it) })
|
||||
SliderRow(
|
||||
stringResource(R.string.pckb_opacity), stringResource(R.string.pckb_opacity_hint),
|
||||
PcKeyboardPrefs.opacity, SessionPrefs.PC_KEYBOARD_OPACITY_RANGE, step = 5,
|
||||
format = { "$it%" }, modifier = focus.track(page, "pckb-opacity"),
|
||||
onChange = { PcKeyboardPrefs.setOpacity(keyboardContext, it) })
|
||||
MultiRow(
|
||||
host, "pckb-hidden", stringResource(R.string.pckb_hidden_keys),
|
||||
stringResource(R.string.pckb_hidden_keys_hint),
|
||||
listOf(
|
||||
0 to stringResource(R.string.pckb_group_function),
|
||||
1 to stringResource(R.string.pckb_group_nav),
|
||||
2 to stringResource(R.string.pckb_group_arrows),
|
||||
),
|
||||
PC_KEY_GROUP_IDS.filterValues { it in PcKeyboardPrefs.hiddenKeys }.keys,
|
||||
onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) })
|
||||
}
|
||||
}
|
||||
SessionDrawerPage.SECOND_SCREEN -> {
|
||||
@@ -870,67 +915,15 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
|
||||
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
val stopDescription = stringResource(R.string.stop_session)
|
||||
val stopLabel = stringResource(R.string.drawer_stop)
|
||||
var iconOnly by remember(stopLabel, androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp) { mutableStateOf(false) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center,
|
||||
modifier = modifier.heightIn(min = 44.dp).widthIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
|
||||
.clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f))
|
||||
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.padding(start = 12.dp, end = 14.dp),
|
||||
.padding(horizontal = 12.dp),
|
||||
) {
|
||||
Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp))
|
||||
if (!iconOnly) Text(
|
||||
stopLabel, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error,
|
||||
maxLines = 1, softWrap = false, onTextLayout = { if (it.hasVisualOverflow) iconOnly = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BottomScreenModes(a: DrawerActions, modifier: Modifier, onPick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val modes = buildList {
|
||||
if (com.droiddeck.launcher.session.SessionState.deckPad) add(SecondScreenMode.DECK_CONTROLS to Icons.Outlined.SportsEsports)
|
||||
add(SecondScreenMode.KEYBOARD_TRACKPAD to Icons.Outlined.Keyboard)
|
||||
add(SecondScreenMode.TERMINAL to Icons.Outlined.Terminal)
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = modifier.focusGroup().clip(RoundedCornerShape(26.dp)).border(1.dp, pal.line, RoundedCornerShape(26.dp)).padding(4.dp),
|
||||
) {
|
||||
modes.forEach { (mode, icon) ->
|
||||
val selected = a.secondScreenMode == mode
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
val pick = { onPick(); a.onSecondScreenMode(mode) }
|
||||
val label = stringResource(mode.label)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(width = 52.dp, height = 40.dp).semantics { contentDescription = label }
|
||||
.clip(shape)
|
||||
.background(when {
|
||||
selected -> pal.signal
|
||||
hot -> pal.signal.copy(alpha = 0.14f)
|
||||
else -> Color.Transparent
|
||||
})
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.hoverable(source)
|
||||
.selectable(selected, interactionSource = source, indication = LocalIndication.current, role = Role.Tab, onClick = pick)
|
||||
.controllerConfirm(onClick = pick),
|
||||
) {
|
||||
Icon(icon, contentDescription = null, modifier = Modifier.size(22.dp),
|
||||
tint = when {
|
||||
selected -> colors.background
|
||||
hot -> pal.signal
|
||||
else -> colors.onBackground
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -941,27 +934,7 @@ private fun SteamActionPill(
|
||||
onConfirm: (() -> Unit)? = null,
|
||||
shortcut: String? = null,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val hot = interactionSource.collectIsFocusedAsState().value || interactionSource.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(22.dp)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.size(44.dp).semantics { contentDescription = description }
|
||||
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.hoverable(interactionSource)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onConfirm ?: onClick),
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp))
|
||||
if (shortcut != null) Text(
|
||||
shortcut, fontSize = 8.sp, lineHeight = 9.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.align(Alignment.BottomEnd).padding(end = 8.dp, bottom = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
) = BarButton(description, modifier, vector = icon, shortcut = shortcut, interactionSource = interactionSource, onConfirm = onConfirm, onClick = onClick)
|
||||
|
||||
@Composable
|
||||
private fun DrawerBumper(label: String, description: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
@@ -1188,12 +1161,17 @@ private fun SteamVrRow(a: DrawerActions) {
|
||||
}
|
||||
}
|
||||
|
||||
internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boolean, desktop: Boolean): List<SecondScreenMode> =
|
||||
(if (none) listOf(SecondScreenMode.NONE) else emptyList()) + listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.TERMINAL) +
|
||||
(if (deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) +
|
||||
(if (dashboard) listOf(SecondScreenMode.DASHBOARD) else emptyList()) +
|
||||
(if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList())
|
||||
|
||||
@Composable
|
||||
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val modes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.TERMINAL) +
|
||||
if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()
|
||||
val modes = secondScreenModes(a.secondScreenNone, com.droiddeck.launcher.session.SessionState.deckPad, a.dashboardAvailable, a.desktopAvailable)
|
||||
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
|
||||
Column(Modifier.fillMaxWidth().selectableGroup()) {
|
||||
modes.forEach { mode ->
|
||||
@@ -1221,6 +1199,20 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
|
||||
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
|
||||
chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay)
|
||||
}
|
||||
if (a.gameSwapAvailable || a.gameOnBottom) SettingsGroup(stringResource(R.string.swap_game_screen_group)) {
|
||||
ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
|
||||
listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom)),
|
||||
a.gameOnBottom, chipModifier = track("game-screen"), onPick = a.onGameOnBottom)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RelativeMouseRow(host: MenuHost, a: DrawerActions, modifier: Modifier) {
|
||||
ChoiceRow(host, "relative-mouse", stringResource(R.string.drawer_relative_mouse), null,
|
||||
listOf(com.droiddeck.launcher.input.TouchGestureConfig.RELATIVE_MOUSE_AUTO to stringResource(R.string.drawer_relative_mouse_auto),
|
||||
com.droiddeck.launcher.input.TouchGestureConfig.RELATIVE_MOUSE_ON to stringResource(R.string.drawer_relative_mouse_on),
|
||||
com.droiddeck.launcher.input.TouchGestureConfig.RELATIVE_MOUSE_OFF to stringResource(R.string.drawer_relative_mouse_off)),
|
||||
a.relativeMouseMode, chipModifier = modifier, onPick = a.onRelativeMouseMode)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -1595,7 +1587,6 @@ internal fun ComponentDownloadsDrawerGroup(
|
||||
}
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null },
|
||||
title = ComponentsManager.LABEL.getValue(comp)) { firstItemFocus ->
|
||||
// A nightly paired with a stable build rides on that row; Stable/Nightly tabs beside the row pick which one.
|
||||
val pairs = ComponentsManager.nightlyPairs(items)
|
||||
val rows = items.filter { it !in pairs.values }
|
||||
fun shown(row: ComponentsManager.CatalogItem) = pairs[row]?.takeIf { nightlyPicked[row.file] == true } ?: row
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.HorizontalScrollView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionTerminal
|
||||
import com.termux.terminal.TerminalEmulator
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import com.termux.view.TerminalView
|
||||
import com.termux.view.TerminalViewClient
|
||||
|
||||
class SessionTrackpadView(
|
||||
context: Context,
|
||||
private val sendPointer: (x: Float, y: Float, width: Float, height: Float) -> Unit,
|
||||
private val sendButton: (button: Int, pressed: Boolean) -> Unit,
|
||||
private val sendWheel: (steps: Int) -> Unit,
|
||||
private val pointerPosition: () -> androidx.compose.ui.geometry.Offset? = { null },
|
||||
) : View(context) {
|
||||
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
|
||||
|
||||
private val gestures = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(),
|
||||
object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) {
|
||||
sendPointer(x, y, width.toFloat(), height.toFloat())
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
sendPointer(x, y, width.toFloat(), height.toFloat())
|
||||
sendButton(button, pressed)
|
||||
}
|
||||
|
||||
override fun onWheel(steps: Int) = sendWheel(steps)
|
||||
override fun onLongPress() { performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS) }
|
||||
})
|
||||
|
||||
init {
|
||||
isFocusable = true
|
||||
setBackgroundColor(Color.BLACK)
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
gestures.bounds = android.graphics.RectF(0f, 0f, w.toFloat(), h.toFloat())
|
||||
if (oldw == 0 || oldh == 0) gestures.place(w / 2f, h / 2f)
|
||||
}
|
||||
|
||||
private val surface = android.graphics.RectF()
|
||||
private val fill = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(0x0A, 0x0B, 0x0D) }
|
||||
private val edge = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = android.graphics.Paint.Style.STROKE
|
||||
color = Color.rgb(0x26, 0x29, 0x2E)
|
||||
strokeWidth = resources.displayMetrics.density
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val inset = dp(12).toFloat()
|
||||
surface.set(inset, 0f, width - inset, height - inset)
|
||||
if (surface.height() <= inset) return
|
||||
val radius = dp(20).toFloat()
|
||||
canvas.drawRoundRect(surface, radius, radius, fill)
|
||||
canvas.drawRoundRect(surface, radius, radius, edge)
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) pointerPosition()?.let {
|
||||
gestures.place(it.x * width, it.y * height)
|
||||
}
|
||||
return gestures.onTouch(event)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
gestures.cancel()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
|
||||
class SessionTerminalPanel(context: Context) : LinearLayout(context) {
|
||||
private var terminalSession: TerminalSession? = null
|
||||
private var terminalView: TerminalView? = null
|
||||
private var terminalPid = -1
|
||||
private var ctrlActive = false
|
||||
private var altActive = false
|
||||
|
||||
val ready: Boolean get() = terminalSession != null
|
||||
|
||||
init {
|
||||
orientation = VERTICAL
|
||||
setBackgroundColor(Color.BLACK)
|
||||
build()
|
||||
}
|
||||
|
||||
private fun build() {
|
||||
val terminalClient = TerminalClient()
|
||||
val view = TerminalView(context, null).apply {
|
||||
setTerminalViewClient(terminalClient)
|
||||
setTextSize(dp(14))
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
terminalView = view
|
||||
val session = SessionTerminal.create(terminalClient)
|
||||
if (session == null) {
|
||||
addView(TextView(context).apply {
|
||||
text = context.getString(R.string.second_terminal_not_ready)
|
||||
setTextColor(Color.WHITE)
|
||||
gravity = Gravity.CENTER
|
||||
}, LayoutParams(-1, 0, 1f))
|
||||
return
|
||||
}
|
||||
terminalSession = session
|
||||
|
||||
val keyStrip = HorizontalScrollView(context).apply { isHorizontalScrollBarEnabled = false }
|
||||
val keys = LinearLayout(context).apply { orientation = HORIZONTAL; setPadding(dp(12), 0, dp(12), dp(8)) }
|
||||
fun key(label: String, input: String, onClick: ((TextView) -> Unit)? = null) {
|
||||
lateinit var button: TextView
|
||||
button = DeckControlsPanel.roundButton(context, label, label, { if (onClick != null) onClick(button) else session.write(input) }, wide = true)
|
||||
if (keys.childCount > 0) keys.addView(View(context), LinearLayout.LayoutParams(dp(8), 1))
|
||||
keys.addView(button)
|
||||
}
|
||||
val ctrl = context.getString(R.string.pckb_key_ctrl)
|
||||
val alt = context.getString(R.string.pckb_key_alt)
|
||||
key(context.getString(R.string.pckb_key_esc), "\u001b")
|
||||
key(context.getString(R.string.second_key_tab), "\t")
|
||||
key(ctrl, "") { button ->
|
||||
ctrlActive = !ctrlActive
|
||||
button.text = if (ctrlActive) context.getString(R.string.second_key_on, ctrl) else ctrl
|
||||
}
|
||||
key(alt, "") { button ->
|
||||
altActive = !altActive
|
||||
button.text = if (altActive) context.getString(R.string.second_key_on, alt) else alt
|
||||
}
|
||||
key("↑", "\u001b[A")
|
||||
key("↓", "\u001b[B")
|
||||
key("←", "\u001b[D")
|
||||
key("→", "\u001b[C")
|
||||
key(context.getString(R.string.second_key_ctrl_c), "\u0003")
|
||||
key(context.getString(R.string.second_key_ctrl_d), "\u0004")
|
||||
keyStrip.addView(keys)
|
||||
addView(keyStrip, LayoutParams(-1, -2))
|
||||
|
||||
addView(view, LayoutParams(-1, 0, 1f))
|
||||
view.attachSession(session)
|
||||
|
||||
view.post {
|
||||
registerTerminalPid()
|
||||
view.requestFocus()
|
||||
showKeyboard()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
close()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
fun showKeyboard() {
|
||||
terminalView?.let { view ->
|
||||
view.requestFocus()
|
||||
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
|
||||
.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
|
||||
private fun registerTerminalPid() {
|
||||
val pid = terminalSession?.pid ?: -1
|
||||
if (pid > 1 && pid != terminalPid) {
|
||||
terminalPid = pid
|
||||
SessionService.registerTerminalProcess(context, pid)
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
terminalView?.let { view ->
|
||||
(context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
|
||||
.hideSoftInputFromWindow(view.windowToken, 0)
|
||||
}
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: (terminalSession?.pid ?: -1)
|
||||
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
|
||||
terminalPid = -1
|
||||
terminalSession = null
|
||||
terminalView = null
|
||||
ctrlActive = false
|
||||
altActive = false
|
||||
}
|
||||
|
||||
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
|
||||
|
||||
private inner class TerminalClient : TerminalSessionClient, TerminalViewClient {
|
||||
override fun onTextChanged(changedSession: TerminalSession) {
|
||||
terminalView?.onScreenUpdated()
|
||||
}
|
||||
override fun onTitleChanged(changedSession: TerminalSession) = Unit
|
||||
override fun onSessionFinished(finishedSession: TerminalSession) {
|
||||
val pid = terminalPid.takeIf { it > 1 } ?: finishedSession.pid
|
||||
if (pid > 1) SessionService.terminalProcessExited(context, pid)
|
||||
terminalPid = -1
|
||||
terminalView?.onScreenUpdated()
|
||||
}
|
||||
override fun onCopyTextToClipboard(session: TerminalSession, text: String) {
|
||||
(context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager)
|
||||
.setPrimaryClip(android.content.ClipData.newPlainText("Terminal", text))
|
||||
}
|
||||
override fun onPasteTextFromClipboard(session: TerminalSession) {
|
||||
val clip = (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).primaryClip
|
||||
if (clip != null && clip.itemCount > 0) session.write(clip.getItemAt(0).coerceToText(context).toString())
|
||||
}
|
||||
override fun onBell(session: TerminalSession) {
|
||||
terminalView?.performHapticFeedback(android.view.HapticFeedbackConstants.KEYBOARD_TAP)
|
||||
}
|
||||
override fun onColorsChanged(changedSession: TerminalSession) {
|
||||
terminalView?.invalidate()
|
||||
}
|
||||
override fun onTerminalCursorStateChange(state: Boolean) {
|
||||
terminalView?.setTerminalCursorBlinkerRate(if (state) 600 else 0)
|
||||
}
|
||||
override fun getTerminalCursorStyle(): Int = TerminalEmulator.TERMINAL_CURSOR_STYLE_BLOCK
|
||||
override fun logError(tag: String, message: String) { Log.e(tag, message) }
|
||||
override fun logWarn(tag: String, message: String) { Log.w(tag, message) }
|
||||
override fun logInfo(tag: String, message: String) { Log.i(tag, message) }
|
||||
override fun logDebug(tag: String, message: String) { Log.d(tag, message) }
|
||||
override fun logVerbose(tag: String, message: String) { Log.v(tag, message) }
|
||||
override fun logStackTraceWithMessage(tag: String, message: String, e: Exception) { Log.e(tag, message, e) }
|
||||
override fun logStackTrace(tag: String, e: Exception) { Log.e(tag, e.message, e) }
|
||||
|
||||
override fun onScale(scale: Float): Float = 1f
|
||||
override fun onSingleTapUp(e: MotionEvent) = showKeyboard()
|
||||
override fun shouldBackButtonBeMappedToEscape(): Boolean = true
|
||||
override fun shouldEnforceCharBasedInput(): Boolean = false
|
||||
override fun shouldUseCtrlSpaceWorkaround(): Boolean = false
|
||||
override fun isTerminalViewSelected(): Boolean = true
|
||||
override fun copyModeChanged(copyMode: Boolean) = Unit
|
||||
override fun onKeyDown(keyCode: Int, e: KeyEvent, session: TerminalSession): Boolean = false
|
||||
override fun onKeyUp(keyCode: Int, e: KeyEvent): Boolean = false
|
||||
override fun onLongPress(event: MotionEvent): Boolean = false
|
||||
override fun readControlKey(): Boolean = ctrlActive
|
||||
override fun readAltKey(): Boolean = altActive
|
||||
override fun readShiftKey(): Boolean = false
|
||||
override fun readFnKey(): Boolean = false
|
||||
override fun onCodePoint(codePoint: Int, ctrlDown: Boolean, session: TerminalSession): Boolean = false
|
||||
override fun onEmulatorSet() {
|
||||
terminalView?.onScreenUpdated()
|
||||
registerTerminalPid()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,6 @@ import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/** The last game frame, captured as the session left the screen, and where it sat in the overlay. */
|
||||
class PausedFrame(val image: ImageBitmap, val bounds: android.graphics.Rect)
|
||||
|
||||
private const val CARD_SCALE = 0.82f
|
||||
@@ -125,7 +124,6 @@ fun SessionPausedOverlay(
|
||||
onFrameNeeded()
|
||||
withTimeoutOrNull(FRAME_WAIT_MS) { snapshotFlow { currentFrame }.first { it != null } }
|
||||
}
|
||||
// Pausing mostly happens while the screen is off or the app is away, so it appears already settled.
|
||||
press.snapTo(1f)
|
||||
ring.snapTo(0f)
|
||||
lift.snapTo(1f)
|
||||
|
||||
@@ -26,6 +26,7 @@ import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
@@ -262,6 +263,7 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
fun AnchoredMenu(
|
||||
open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null,
|
||||
@@ -287,6 +289,20 @@ fun AnchoredMenu(
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Popup(popupPositionProvider = provider, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) {
|
||||
TrackKeyWindow()
|
||||
val popupInput = LocalInputModeManager.current
|
||||
LaunchedEffect(open, inputMode) {
|
||||
if (!open || inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
popupInput.requestInputMode(InputMode.Keyboard)
|
||||
repeat(8) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
if (runCatching { firstItemFocus.captureFocus() }.getOrDefault(false)) {
|
||||
firstItemFocus.freeFocus()
|
||||
return@LaunchedEffect
|
||||
}
|
||||
runCatching { firstItemFocus.requestFocus() }
|
||||
}
|
||||
}
|
||||
CompositionLocalProvider(LocalDensity provides density, LocalConfiguration provides configuration) {
|
||||
AnimatedVisibility(
|
||||
visibleState = state,
|
||||
@@ -371,11 +387,12 @@ fun MenuItem(
|
||||
.background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent)
|
||||
.glideBorder(hot && enabled, RoundedCornerShape(8.dp), pal.signal)
|
||||
.alpha(if (enabled) 1f else 0.4f)
|
||||
.semantics { selected = checked }
|
||||
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 9.dp),
|
||||
) {
|
||||
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f))
|
||||
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f).clearAndSetSemantics {})
|
||||
if (leading != null) {
|
||||
leading()
|
||||
Spacer(Modifier.width(8.dp))
|
||||
@@ -489,10 +506,11 @@ fun <T> ChoiceRow(
|
||||
options: List<Pair<T, String>>, selected: T, enabled: Boolean = true, note: String? = null,
|
||||
chipModifier: Modifier = Modifier,
|
||||
hintLines: Int? = null,
|
||||
stacked: Boolean = false,
|
||||
onPick: (T) -> Unit,
|
||||
) {
|
||||
val open = host.open == key
|
||||
SettingsRow(label, hint, highlighted = open, hintLines = hintLines) {
|
||||
SettingsRow(label, hint, highlighted = open, hintLines = hintLines, stacked = stacked) {
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
|
||||
@@ -0,0 +1,583 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.StrokeJoin
|
||||
import androidx.compose.ui.graphics.drawscope.DrawScope
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextMeasurer
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.drawText
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.GameStatusFiles
|
||||
import com.droiddeck.launcher.session.GameTelemetry
|
||||
import com.droiddeck.launcher.session.SpeedUnit
|
||||
import com.droiddeck.launcher.session.StatsDash
|
||||
import com.droiddeck.launcher.session.Telemetry
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sin
|
||||
|
||||
private val DASH_H = 290.dp
|
||||
internal const val TRACE_N = 150
|
||||
|
||||
internal class TraceData(val throttle: List<Float>, val brake: List<Float>, val speed: List<Float>)
|
||||
|
||||
@Composable
|
||||
internal fun RaceDashView(style: StatsDash, t: Telemetry, trace: TraceData, unit: SpeedUnit, onTap: () -> Unit) {
|
||||
Box(Modifier.fillMaxWidth().clickable(onClick = onTap)) {
|
||||
when (style) {
|
||||
StatsDash.AUTO, StatsDash.SPEEDOMETER -> SpeedometerDash(t, unit)
|
||||
StatsDash.CIRCUIT -> CircuitDash(t, unit)
|
||||
StatsDash.TRACE -> TraceDash(t, trace, unit)
|
||||
StatsDash.DIALS -> DialsDash(t, unit)
|
||||
StatsDash.GLANCE -> GlanceDash(t, unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun polar(cx: Float, cy: Float, r: Float, deg: Float): Offset {
|
||||
val a = Math.toRadians((deg - 90f).toDouble())
|
||||
return Offset(cx + r * cos(a).toFloat(), cy + r * sin(a).toFloat())
|
||||
}
|
||||
|
||||
private const val DIAL_START = -125f
|
||||
private const val DIAL_SWEEP = 250f
|
||||
|
||||
private fun dialAngle(v: Float, max: Float) = DIAL_START + DIAL_SWEEP * (v / max).coerceIn(0f, 1f)
|
||||
|
||||
private fun DrawScope.dialFace(
|
||||
cx: Float, cy: Float, r: Float, max: Float, major: Float, label: (Float) -> String,
|
||||
measurer: TextMeasurer, labelStyle: TextStyle, tick: Color, minor: Color, track: Color, red: Float?, redColor: Color,
|
||||
) {
|
||||
val box = Size(2 * r, 2 * r)
|
||||
val tl = Offset(cx - r, cy - r)
|
||||
drawArc(track, DIAL_START - 90f, DIAL_SWEEP, false, topLeft = tl, size = box, style = Stroke(6.dp.toPx(), cap = StrokeCap.Round))
|
||||
if (red != null && red < max) {
|
||||
drawArc(redColor, dialAngle(red, max) - 90f, dialAngle(max, max) - dialAngle(red, max), false, topLeft = tl, size = box, style = Stroke(6.dp.toPx()))
|
||||
}
|
||||
val steps = (max / (major / 2f)).roundToInt()
|
||||
for (i in 0..steps) {
|
||||
val v = i * major / 2f
|
||||
val isMajor = i % 2 == 0
|
||||
val deg = dialAngle(v, max)
|
||||
drawLine(if (isMajor) tick else minor, polar(cx, cy, r - (if (isMajor) 14.dp else 7.dp).toPx(), deg), polar(cx, cy, r - 2.dp.toPx(), deg),
|
||||
strokeWidth = (if (isMajor) 2.5f else 1.2f).dp.toPx())
|
||||
if (isMajor) {
|
||||
val layout = measurer.measure(label(v), labelStyle)
|
||||
val p = polar(cx, cy, r - 27.dp.toPx(), deg)
|
||||
drawText(layout, topLeft = Offset(p.x - layout.size.width / 2f, p.y - layout.size.height / 2f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun DrawScope.needle(cx: Float, cy: Float, len: Float, deg: Float, color: Color, hub: Color) {
|
||||
drawLine(color, Offset(cx, cy), polar(cx, cy, len, deg), strokeWidth = 4.dp.toPx(), cap = StrokeCap.Round)
|
||||
drawCircle(hub, radius = 7.dp.toPx(), center = Offset(cx, cy))
|
||||
}
|
||||
|
||||
private fun speedValue(t: Telemetry, unit: SpeedUnit): Float = (t.speedKmh ?: 0f) * unit.perKmh
|
||||
|
||||
private fun speedScale(speed: Float, unit: SpeedUnit): Float =
|
||||
if (unit == SpeedUnit.MPH) (if (speed > 130f) 200f else 140f) else (if (speed > 210f) 320f else 220f)
|
||||
|
||||
private fun rpmScale(t: Telemetry): Float = max(t.maxRpm ?: 9000f, t.rpm ?: 0f)
|
||||
|
||||
private fun speedText(t: Telemetry, unit: SpeedUnit) = t.speedKmh?.let { "%.0f".format(it * unit.perKmh) } ?: "–"
|
||||
|
||||
@Composable
|
||||
private fun unitAndGear(t: Telemetry, unit: SpeedUnit) = "${unit.label} · ${stringResource(R.string.stats_gear)} ${t.gear ?: "–"}"
|
||||
|
||||
@Composable
|
||||
private fun SpeedometerDash(t: Telemetry, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.primary
|
||||
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_speed), Modifier.weight(1.55f).fillMaxHeight()) {
|
||||
Box(Modifier.fillMaxWidth().weight(1f)) {
|
||||
SpeedDial(t, unit, Modifier.fillMaxSize())
|
||||
Column(Modifier.align(Alignment.BottomCenter), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(speedText(t, unit), fontSize = 44.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent)
|
||||
Text(unitAndGear(t, unit), fontSize = 16.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Text(t.rpm?.let { "%,.0f rpm".format(it) } ?: "", fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_pedals), Modifier.fillMaxWidth().weight(1f)) { Pedals(t, Modifier.fillMaxWidth().weight(1f)) }
|
||||
if (t.gLat != null && t.gLon != null) {
|
||||
StatsCard(stringResource(R.string.stats_gforce), Modifier.fillMaxWidth().weight(1f)) { GForce(t, Modifier.fillMaxWidth().weight(1f)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SpeedDial(t: Telemetry, unit: SpeedUnit, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val measurer = rememberTextMeasurer()
|
||||
val labelStyle = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
|
||||
val speed = speedValue(t, unit)
|
||||
val vmax = speedScale(speed, unit)
|
||||
val rpmFraction = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
|
||||
Canvas(modifier) {
|
||||
val r = min(size.width * 0.42f, size.height * 0.47f)
|
||||
val cx = size.width / 2f
|
||||
val cy = r + 12.dp.toPx()
|
||||
dialFace(cx, cy, r, vmax, 20f, { "%.0f".format(it) }, measurer, labelStyle, colors.onBackground, colors.onSurfaceVariant, pal.line, null, StatsColors.brake)
|
||||
val rr = r + 9.dp.toPx()
|
||||
val box = Size(2 * rr, 2 * rr)
|
||||
val tl = Offset(cx - rr, cy - rr)
|
||||
drawArc(pal.line, DIAL_START - 90f, DIAL_SWEEP, false, topLeft = tl, size = box, style = Stroke(5.dp.toPx(), cap = StrokeCap.Round))
|
||||
if (rpmFraction > 0f) drawArc(if (rpmFraction > 0.9f) StatsColors.brake else pal.primary, DIAL_START - 90f, DIAL_SWEEP * rpmFraction, false,
|
||||
topLeft = tl, size = box, style = Stroke(5.dp.toPx(), cap = StrokeCap.Round))
|
||||
needle(cx, cy, r - 16.dp.toPx(), dialAngle(speed, vmax), colors.onBackground, pal.primary)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Pedals(t: Telemetry, modifier: Modifier) {
|
||||
Row(modifier, horizontalArrangement = Arrangement.SpaceEvenly) {
|
||||
PedalBar("THR", t.throttle, StatsColors.throttle)
|
||||
PedalBar("BRK", t.brake, StatsColors.brake)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PedalBar(label: String, value: Float?, color: Color) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(value?.let { "${(it * 100).roundToInt()}%" } ?: "–", fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Box(Modifier.weight(1f).width(26.dp).clip(RoundedCornerShape(6.dp)).background(pal.line)) {
|
||||
Box(Modifier.fillMaxWidth().fillMaxHeight((value ?: 0f).coerceIn(0f, 1f)).align(Alignment.BottomCenter).background(color))
|
||||
}
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GForce(t: Telemetry, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val g = kotlin.math.hypot(t.gLat ?: 0f, t.gLon ?: 0f)
|
||||
Box(modifier) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val steerH = if (t.steer != null) 10.dp.toPx() else 0f
|
||||
val r = min(size.width / 2f, (size.height - steerH) / 2f) - 2.dp.toPx()
|
||||
val cx = size.width / 2f
|
||||
val cy = (size.height - steerH) / 2f
|
||||
for (k in listOf(1f, 0.62f, 0.24f)) drawCircle(pal.line, radius = r * k, center = Offset(cx, cy), style = Stroke(1.dp.toPx()))
|
||||
drawLine(pal.line, Offset(cx - r, cy), Offset(cx + r, cy), strokeWidth = 1.dp.toPx())
|
||||
drawLine(pal.line, Offset(cx, cy - r), Offset(cx, cy + r), strokeWidth = 1.dp.toPx())
|
||||
val gx = (t.gLat ?: 0f).coerceIn(-2f, 2f) / 2f * r
|
||||
val gy = (t.gLon ?: 0f).coerceIn(-2f, 2f) / 2f * r
|
||||
drawCircle(colors.onBackground, radius = 6.dp.toPx(), center = Offset(cx + gx, cy - gy))
|
||||
t.steer?.let { s ->
|
||||
val y = size.height - 3.dp.toPx()
|
||||
drawLine(pal.line, Offset(cx - r, y), Offset(cx + r, y), strokeWidth = 5.dp.toPx(), cap = StrokeCap.Round)
|
||||
drawLine(pal.primary, Offset(cx, y), Offset(cx + s * r, y), strokeWidth = 5.dp.toPx(), cap = StrokeCap.Round)
|
||||
}
|
||||
}
|
||||
Text("%.1f G".format(g), fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, modifier = Modifier.align(Alignment.TopEnd))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CircuitDash(t: Telemetry, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.primary
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(null, Modifier.fillMaxWidth()) { ShiftLights(t, Modifier.fillMaxWidth().height(20.dp)) }
|
||||
Row(Modifier.fillMaxWidth().height(DASH_H - 48.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_timing), Modifier.weight(1f).fillMaxHeight()) {
|
||||
KvRow(stringResource(R.string.bottom_telemetry_lap), t.lap?.let { lap -> t.laps?.let { "$lap / $it" } ?: "$lap" } ?: "–")
|
||||
KvRow(stringResource(R.string.bottom_telemetry_position), t.position?.let { "P$it" } ?: "–")
|
||||
KvRow(stringResource(R.string.bottom_telemetry_this_lap), t.currentLapS?.let { lapTime(it) } ?: "–")
|
||||
KvRow(stringResource(R.string.bottom_telemetry_last_lap), t.lastLapS?.let { lapTime(it) } ?: "–")
|
||||
t.bestLapS?.let { KvRow(stringResource(R.string.stats_best_lap), lapTime(it), accent) }
|
||||
}
|
||||
StatsCard("", Modifier.weight(1.2f).fillMaxHeight()) {
|
||||
Column(Modifier.fillMaxWidth().weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Text(speedText(t, unit), fontSize = 72.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent)
|
||||
Text(unitAndGear(t, unit), fontSize = 24.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Text(t.rpm?.let { rpm -> t.maxRpm?.let { "%,.0f / %,.0f rpm".format(rpm, it) } ?: "%,.0f rpm".format(rpm) } ?: "",
|
||||
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
val fuel = t.fuel
|
||||
val tires = t.tireTempsC?.takeIf { it.size == 4 }
|
||||
if (fuel != null || tires != null) Column(Modifier.weight(0.9f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (fuel != null) StatsCard(stringResource(R.string.bottom_telemetry_fuel), Modifier.fillMaxWidth().weight(1f)) {
|
||||
Bar(fuel, colors.onBackground, Modifier.fillMaxWidth().height(14.dp))
|
||||
Text("${(fuel * 100).roundToInt()}%", fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (tires != null) StatsCard(stringResource(R.string.stats_tires), Modifier.fillMaxWidth().weight(1.3f)) { Tires(tires, Modifier.fillMaxWidth().weight(1f)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ShiftLights(t: Telemetry, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val ratio = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
|
||||
val lit = (((ratio - 0.6f) / 0.35f).coerceIn(0f, 1f) * 15).roundToInt()
|
||||
val flash = ratio > 0.95f && (System.currentTimeMillis() / 120) % 2 == 0L
|
||||
Canvas(modifier) {
|
||||
val step = size.width / 15f
|
||||
val r = min(size.height / 2f, step / 2f - 2.dp.toPx())
|
||||
for (i in 0 until 15) {
|
||||
val c = when {
|
||||
flash -> pal.primary
|
||||
i >= lit -> pal.line
|
||||
i < 5 -> StatsColors.shiftGreen
|
||||
i < 10 -> StatsColors.warn
|
||||
i < 13 -> StatsColors.brake
|
||||
else -> pal.primary
|
||||
}
|
||||
drawCircle(c, radius = r, center = Offset(step * i + step / 2f, size.height / 2f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun KvRow(label: String, value: String, valueColor: Color = MaterialTheme.colorScheme.onBackground) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), maxLines = 1)
|
||||
Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = valueColor, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Bar(fraction: Float, color: Color, modifier: Modifier) {
|
||||
Box(modifier.clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line)) {
|
||||
Box(Modifier.fillMaxWidth(fraction.coerceIn(0f, 1f)).fillMaxHeight().background(color))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Tires(tires: List<Float>, modifier: Modifier) {
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
TireBox(tires[0], Modifier.weight(1f).fillMaxHeight())
|
||||
TireBox(tires[1], Modifier.weight(1f).fillMaxHeight())
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
TireBox(tires[2], Modifier.weight(1f).fillMaxHeight())
|
||||
TireBox(tires[3], Modifier.weight(1f).fillMaxHeight())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TireBox(c: Float, modifier: Modifier) {
|
||||
val bg = when {
|
||||
c > 100f -> Color(0xFF5A2A2C)
|
||||
c < 70f -> Color(0xFF1D3550)
|
||||
else -> Color(0xFF23352B)
|
||||
}
|
||||
Box(modifier.clip(RoundedCornerShape(6.dp)).background(bg), contentAlignment = Alignment.Center) {
|
||||
Text("%.0f".format(c), fontSize = 13.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TraceDash(t: Telemetry, trace: TraceData, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_trace), Modifier.fillMaxWidth().height(168.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
Legend(StatsColors.throttle, "${stringResource(R.string.stats_throttle)} ${t.throttle?.let { (it * 100).roundToInt() } ?: 0}%")
|
||||
Legend(StatsColors.brake, "${stringResource(R.string.stats_brake)} ${t.brake?.let { (it * 100).roundToInt() } ?: 0}%")
|
||||
}
|
||||
TraceChart(listOf(trace.throttle to StatsColors.throttle, trace.brake to StatsColors.brake), 1f, Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
val speeds = trace.speed.map { it * unit.perKmh }
|
||||
val top = max(if (unit == SpeedUnit.MPH) 125f else 200f, (speeds.maxOrNull() ?: 0f) * 1.1f)
|
||||
StatsCard(stringResource(R.string.stats_speed_chart, unit.label), Modifier.fillMaxWidth().height(114.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
Legend(StatsColors.speed, "${stringResource(R.string.stats_speed)} ${speedText(t, unit)}")
|
||||
Text("0 – %.0f".format(top), fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
TraceChart(listOf(speeds to StatsColors.speed), top, Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Legend(color: Color, text: String) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Box(Modifier.size(8.dp).clip(CircleShape).background(color))
|
||||
Text(text, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TraceChart(series: List<Pair<List<Float>, Color>>, max: Float, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
Canvas(modifier) {
|
||||
for (k in listOf(0f, 0.5f, 1f)) {
|
||||
val y = size.height - k * size.height
|
||||
drawLine(pal.line, Offset(0f, y), Offset(size.width, y), strokeWidth = 1.dp.toPx())
|
||||
}
|
||||
for ((values, color) in series) {
|
||||
if (values.size < 2) continue
|
||||
val path = Path()
|
||||
val offset = TRACE_N - values.size
|
||||
values.forEachIndexed { i, v ->
|
||||
val x = (i + offset) / (TRACE_N - 1f) * size.width
|
||||
val y = size.height - (v / max).coerceIn(0f, 1f) * size.height
|
||||
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
|
||||
}
|
||||
drawPath(path, color, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DialsDash(t: Telemetry, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val rpmMax = (rpmScale(t) / 1000f).let { kotlin.math.ceil(it) * 1000f }
|
||||
val hasExtras = t.lights != null || t.turboBar != null || t.engineTempC != null || t.oilTempC != null
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth().height(if (hasExtras) DASH_H - 56.dp else DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
|
||||
val speed = speedValue(t, unit)
|
||||
ArcDial(speed, speedScale(speed, unit), if (unit == SpeedUnit.MPH) 20f else 40f, { "%.0f".format(it) }, null,
|
||||
speedText(t, unit), unit.label, Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
|
||||
ArcDial(t.rpm ?: 0f, rpmMax, 1000f, { "%.0f".format(it / 1000f) }, t.maxRpm?.let { it * 0.9f },
|
||||
t.rpm?.let { "%,.0f".format(it) } ?: "–", "rpm × 1000 · ${t.gear ?: "–"}", Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
}
|
||||
if (hasExtras) StatsCard(stringResource(R.string.stats_lights), Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
t.lights?.let { on ->
|
||||
Lamp(stringResource(R.string.stats_lamp_shift), on and GameTelemetry.DL_SHIFT != 0, LocalPalette.current.primary)
|
||||
Lamp(stringResource(R.string.stats_lamp_handbrake), on and GameTelemetry.DL_HANDBRAKE != 0, StatsColors.brake)
|
||||
Lamp(stringResource(R.string.stats_lamp_pit), on and GameTelemetry.DL_PITSPEED != 0, StatsColors.warn)
|
||||
Lamp(stringResource(R.string.stats_lamp_tc), on and GameTelemetry.DL_TC != 0, StatsColors.warn)
|
||||
Lamp(stringResource(R.string.stats_lamp_abs), on and GameTelemetry.DL_ABS != 0, StatsColors.warn)
|
||||
}
|
||||
t.turboBar?.let { Lamp(stringResource(R.string.stats_turbo, "%.1f".format(it)), false, colors.onBackground) }
|
||||
t.engineTempC?.let { Lamp(stringResource(R.string.stats_engine_temp, "%.0f".format(it)), false, colors.onBackground) }
|
||||
t.oilTempC?.let { Lamp(stringResource(R.string.stats_oil_temp, "%.0f".format(it)), false, colors.onBackground) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ArcDial(value: Float, max: Float, major: Float, label: (Float) -> String, red: Float?, readout: String, unit: String, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val measurer = rememberTextMeasurer()
|
||||
val labelStyle = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
|
||||
Box(modifier) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val r = min(size.width * 0.46f, size.height * 0.5f)
|
||||
val cx = size.width / 2f
|
||||
val cy = r + 6.dp.toPx()
|
||||
dialFace(cx, cy, r, max, major, label, measurer, labelStyle, colors.onBackground, colors.onSurfaceVariant, pal.line, red, StatsColors.brake)
|
||||
needle(cx, cy, r - 18.dp.toPx(), dialAngle(value, max), colors.onBackground, pal.primary)
|
||||
}
|
||||
Column(Modifier.align(Alignment.BottomCenter), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(readout, fontSize = 22.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Text(unit, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Lamp(label: String, on: Boolean, color: Color) {
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
Text(label, fontSize = 12.sp, fontFamily = FontFamily.Monospace, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal,
|
||||
color = if (on) MaterialTheme.colorScheme.background else MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1,
|
||||
modifier = Modifier.clip(shape).background(if (on) color else Color.Transparent).border(1.dp, if (on) color else pal.line, shape)
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GlanceDash(t: Telemetry, unit: SpeedUnit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.primary
|
||||
val ratio = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
|
||||
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
EdgeBar(t.throttle, StatsColors.throttle)
|
||||
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
|
||||
Bar(ratio, if (ratio > 0.9f) StatsColors.brake else accent, Modifier.fillMaxWidth().height(14.dp))
|
||||
Column(Modifier.fillMaxWidth().weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Text(speedText(t, unit), fontSize = 110.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent, lineHeight = 112.sp)
|
||||
Text(unitAndGear(t, unit), fontSize = 34.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
}
|
||||
}
|
||||
EdgeBar(t.brake, StatsColors.brake)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EdgeBar(value: Float?, color: Color) {
|
||||
Box(Modifier.width(14.dp).fillMaxHeight().clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line)) {
|
||||
Box(Modifier.fillMaxWidth().fillMaxHeight((value ?: 0f).coerceIn(0f, 1f)).align(Alignment.BottomCenter).background(color))
|
||||
}
|
||||
}
|
||||
|
||||
internal object FlightLabels {
|
||||
const val IAS = "IAS, km/h"
|
||||
const val ALTITUDE = "H, m"
|
||||
const val G = "Ny"
|
||||
const val FUEL = "Mfuel, kg"
|
||||
const val THROTTLE = "throttle 1, %"
|
||||
|
||||
fun drawable(rows: List<Pair<String, String>>): Boolean = rows.any { it.first == IAS || it.first == ALTITUDE }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FlightDash(rows: List<Pair<String, String>>) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val v = rows.toMap()
|
||||
fun num(key: String) = v[key]?.toFloatOrNull()
|
||||
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(FlightLabels.IAS, Modifier.weight(1f).fillMaxHeight()) {
|
||||
num(FlightLabels.IAS)?.let { Tape(it, 10f, 50f, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
|
||||
}
|
||||
Column(Modifier.weight(1.3f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(FlightLabels.THROTTLE, Modifier.fillMaxWidth().weight(1f)) {
|
||||
val thr = num(FlightLabels.THROTTLE)
|
||||
Bar((thr ?: 0f) / 110f, StatsColors.throttle, Modifier.fillMaxWidth().height(16.dp))
|
||||
Text(thr?.let { "%.0f%%".format(it) } ?: "–", fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
StatsCard(FlightLabels.G, Modifier.fillMaxWidth().weight(1f)) {
|
||||
Text(num(FlightLabels.G)?.let { "%.1f".format(it) } ?: "–", fontSize = 34.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace,
|
||||
color = colors.onBackground)
|
||||
num(FlightLabels.FUEL)?.let { Text("${FlightLabels.FUEL} %.0f".format(it), fontSize = 12.sp, color = colors.onSurfaceVariant) }
|
||||
}
|
||||
}
|
||||
StatsCard(FlightLabels.ALTITUDE, Modifier.weight(1f).fillMaxHeight()) {
|
||||
num(FlightLabels.ALTITUDE)?.let { Tape(it, 100f, 500f, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Tape(value: Float, step: Float, every: Float, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val measurer = rememberTextMeasurer()
|
||||
val small = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
|
||||
val big = TextStyle(color = colors.onBackground, fontSize = 18.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace)
|
||||
Canvas(modifier) {
|
||||
val cy = size.height / 2f
|
||||
val px = (size.height / 2f) / (step * 4f)
|
||||
val boxH = 32.dp.toPx()
|
||||
var m = floor((value - step * 5f) / step) * step
|
||||
while (m < value + step * 6f) {
|
||||
val y = cy - (m - value) * px
|
||||
if (y in 0f..size.height) {
|
||||
val labelled = abs((m / every).roundToInt() * every - m) < 0.01f
|
||||
drawLine(colors.onSurfaceVariant, Offset(size.width * 0.74f, y), Offset(size.width, y), strokeWidth = (if (labelled) 2.5f else 1f).dp.toPx())
|
||||
if (labelled && abs(y - cy) > boxH * 0.75f) {
|
||||
val layout = measurer.measure("%.0f".format(m), small)
|
||||
drawText(layout, topLeft = Offset(size.width * 0.70f - layout.size.width, y - layout.size.height / 2f))
|
||||
}
|
||||
}
|
||||
m += step
|
||||
}
|
||||
drawRoundRect(pal.primary, topLeft = Offset(1.dp.toPx(), cy - boxH / 2f), size = Size(size.width - 2.dp.toPx(), boxH),
|
||||
cornerRadius = CornerRadius(8.dp.toPx()), style = Stroke(2.dp.toPx()))
|
||||
val layout = measurer.measure("%.0f".format(value), big)
|
||||
drawText(layout, topLeft = Offset(size.width / 2f - layout.size.width / 2f, cy - layout.size.height / 2f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ShipDash(e: GameStatusFiles.Elite) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(Modifier.fillMaxWidth().height(210.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_power), Modifier.weight(1.2f).fillMaxHeight()) {
|
||||
e.pips?.takeIf { it.size == 3 }?.let { Pips(it, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
|
||||
}
|
||||
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
StatsCard(stringResource(R.string.stats_fuel_t), Modifier.fillMaxWidth().weight(1f)) {
|
||||
e.fuelMain?.let { Text(stringResource(R.string.stats_fuel_main, "%.1f".format(it)), fontSize = 15.sp, fontWeight = FontWeight.Bold,
|
||||
fontFamily = FontFamily.Monospace, color = colors.onBackground) }
|
||||
e.fuelReserve?.let { Text(stringResource(R.string.stats_fuel_reserve, "%.2f".format(it)), fontSize = 12.sp, color = colors.onSurfaceVariant) }
|
||||
}
|
||||
StatsCard("", Modifier.fillMaxWidth().weight(1f)) {
|
||||
e.cargo?.let { KvRow(stringResource(R.string.bottom_telemetry_cargo), "%.0f t".format(it)) }
|
||||
e.legal?.let { KvRow(stringResource(R.string.bottom_telemetry_legal), it, if (it == "Clean") StatsColors.gpu else StatsColors.warn) }
|
||||
e.balance?.let { KvRow(stringResource(R.string.bottom_telemetry_balance), "%,d CR".format(it)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Pips(pips: List<Int>, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val measurer = rememberTextMeasurer()
|
||||
val style = TextStyle(color = colors.onSurfaceVariant, fontSize = 12.sp, fontWeight = FontWeight.Bold)
|
||||
val names = listOf("SYS", "ENG", "WEP")
|
||||
Canvas(modifier) {
|
||||
val colW = size.width / 3f
|
||||
val pipW = colW * 0.62f
|
||||
val labelH = 18.dp.toPx()
|
||||
val pipH = (size.height - labelH) / 4f - 4.dp.toPx()
|
||||
for (col in 0 until 3) {
|
||||
val x = col * colW + (colW - pipW) / 2f
|
||||
val value = pips[col] / 2f
|
||||
for (i in 0 until 4) {
|
||||
val y = size.height - labelH - (i + 1) * (pipH + 4.dp.toPx())
|
||||
drawRoundRect(pal.line, topLeft = Offset(x, y), size = Size(pipW, pipH), cornerRadius = CornerRadius(4.dp.toPx()))
|
||||
val fill = (value - i).coerceIn(0f, 1f)
|
||||
if (fill > 0f) drawRoundRect(pal.primary, topLeft = Offset(x, y), size = Size(pipW * fill, pipH), cornerRadius = CornerRadius(4.dp.toPx()))
|
||||
}
|
||||
val layout = measurer.measure(names[col], style)
|
||||
drawText(layout, topLeft = Offset(col * colW + colW / 2f - layout.size.width / 2f, size.height - layout.size.height))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,666 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.graphics.BlurMaskFilter
|
||||
import android.graphics.LinearGradient
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Shader
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawWithCache
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.PathEffect
|
||||
import androidx.compose.ui.graphics.Shadow
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.StrokeJoin
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.nativeCanvas
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.TextUnit
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.hud.FrameStats
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.session.StatsHud
|
||||
import java.io.File
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal class CoreGroup(val cores: List<Int>, val maxGhz: Double?)
|
||||
|
||||
internal class HudData(
|
||||
val fps: Float?,
|
||||
val avgFps: Float?,
|
||||
val lows: FrameStats.Lows,
|
||||
val graph: FloatArray,
|
||||
val slowPerMinute: Int?,
|
||||
val engine: String,
|
||||
val resolution: String,
|
||||
val refreshHz: Int,
|
||||
val proton: String?,
|
||||
val device: HudMetrics.Snapshot?,
|
||||
val gpuName: String,
|
||||
val fanRpm: Long?,
|
||||
val title: String?,
|
||||
val cover: File?,
|
||||
val played: String?,
|
||||
val clock: String,
|
||||
val fpsHistory: List<Float>,
|
||||
val cpuHistory: List<Float>,
|
||||
val gpuHistory: List<Float>,
|
||||
val coreGroups: List<CoreGroup>,
|
||||
val gameCores: Set<Int>,
|
||||
val fahrenheit: Boolean,
|
||||
val tempColor: (HudMetrics.TempSensor, Int) -> Color,
|
||||
val redC: (HudMetrics.TempSensor) -> Int?,
|
||||
val historySeconds: Int = 0,
|
||||
) {
|
||||
val frametimeMs: Float? get() = fps?.takeIf { it > 0f }?.let { 1000f / it }
|
||||
val hz: Int get() = if (refreshHz > 0) refreshHz else 60
|
||||
}
|
||||
|
||||
private object HudInk {
|
||||
val value = Color(0xFFF2F5F9)
|
||||
val dim = Color(0xFF9AA4B2)
|
||||
val low = Color(0xFFE4E8EE)
|
||||
val vram = Color(0xFFC98BFF)
|
||||
val sep = Color(0xFF5D6876)
|
||||
val header = Color(0xFFEAF4FF)
|
||||
val amber = Color(0xFFFFB74D)
|
||||
val tile = Color(0x0EFFFFFF)
|
||||
}
|
||||
|
||||
private val Mono = FontFamily.Monospace
|
||||
private val HEADER = 40.dp
|
||||
private const val UNIT = 0.62f
|
||||
|
||||
@Composable
|
||||
internal fun StatsHudView(style: StatsHud, d: HudData, modifier: Modifier, onTap: () -> Unit) {
|
||||
val accent = LocalPalette.current.primary
|
||||
val night = style == StatsHud.NIGHT
|
||||
Box(modifier.clickable(onClick = onTap)) {
|
||||
HudPanel(d.clock, if (style == StatsHud.GRAPHS) stringResource(R.string.stats_hud_last_seconds, d.historySeconds) else null, night, accent) {
|
||||
when (style) {
|
||||
StatsHud.BIG_FPS -> BigFps(d, accent)
|
||||
StatsHud.FULL -> Full(d, accent)
|
||||
StatsHud.TILES -> Tiles(d, accent)
|
||||
StatsHud.RINGS -> Rings(d, accent)
|
||||
StatsHud.GRAPHS -> Graphs(d, accent)
|
||||
StatsHud.CORES -> Cores(d, accent)
|
||||
StatsHud.HEAT -> Heat(d)
|
||||
StatsHud.GAME -> GameCard(d, accent)
|
||||
StatsHud.PACING -> Pacing(d, accent)
|
||||
StatsHud.NIGHT -> Night(d, night)
|
||||
StatsHud.MEGA -> Mega(d, accent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HudPanel(clock: String, right: String?, dim: Boolean, accent: Color, content: @Composable ColumnScope.() -> Unit) {
|
||||
val headerInk = if (dim) Color(0xFF7D8794) else HudInk.header
|
||||
Column(
|
||||
Modifier.fillMaxSize()
|
||||
.drawWithCache {
|
||||
val w = size.width
|
||||
val h = size.height
|
||||
val stroke = 2.dp.toPx()
|
||||
val corner = 7.dp.toPx()
|
||||
val radius = min(h / 2f, 64.dp.toPx())
|
||||
val headerPx = HEADER.toPx()
|
||||
val a = accent.toArgb()
|
||||
val body = dPath(0f, 0f, w, h, radius, corner)
|
||||
val half = stroke / 2f
|
||||
val outline = dPath(half, half, w - half, h - half, radius - half, corner)
|
||||
val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (dim) argb(245, 0xFF040507.toInt()) else argb(240, 0xFF0E1014.toInt()) }
|
||||
val band = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
shader = LinearGradient(0f, 0f, w, 0f, argb(if (dim) 20 else 56, a), argb(0, a), Shader.TileMode.CLAMP)
|
||||
}
|
||||
val divider = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = argb(if (dim) 38 else 90, a) }
|
||||
val blur = BlurMaskFilter(4.dp.toPx(), BlurMaskFilter.Blur.NORMAL)
|
||||
val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = stroke; color = argb(if (dim) 90 else 255, a) }
|
||||
onDrawBehind {
|
||||
drawIntoCanvas { canvas ->
|
||||
val c = canvas.nativeCanvas
|
||||
c.drawPath(body, fill)
|
||||
c.save()
|
||||
c.clipPath(body)
|
||||
c.drawRect(0f, 0f, w, headerPx + 1f, band)
|
||||
c.drawRect(0f, headerPx, w, headerPx + max(1f, density), divider)
|
||||
c.restore()
|
||||
for (pass in 0..2) {
|
||||
line.maskFilter = if (pass < 2) blur else null
|
||||
c.drawPath(outline, line)
|
||||
}
|
||||
line.maskFilter = null
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(start = 24.dp, end = 34.dp, bottom = 14.dp),
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth().height(HEADER), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Wordmark(14.dp, ink = headerInk, ball = if (dim) accent.copy(alpha = 0.5f) else accent)
|
||||
if (clock.isNotEmpty()) {
|
||||
Text("·", fontSize = 13.sp, fontFamily = Mono, color = HudInk.sep)
|
||||
Text(clock, fontSize = 13.sp, fontFamily = Mono, fontWeight = FontWeight.Bold, color = HudInk.dim, maxLines = 1)
|
||||
}
|
||||
if (right != null) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(right, fontSize = 13.sp, fontFamily = Mono, fontWeight = FontWeight.Bold, color = HudInk.dim, maxLines = 1)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
private fun argb(alpha: Int, rgb: Int): Int = (alpha shl 24) or (rgb and 0xFFFFFF)
|
||||
|
||||
private fun dPath(l: Float, t: Float, r: Float, b: Float, rad: Float, corner: Float) = android.graphics.Path().apply {
|
||||
moveTo(l, t + corner)
|
||||
lineTo(l, b - corner); quadTo(l, b, l + corner, b)
|
||||
lineTo(r - rad, b)
|
||||
arcTo(r - 2f * rad, b - 2f * rad, r, b, 90f, -90f, false)
|
||||
lineTo(r, t + rad)
|
||||
arcTo(r - 2f * rad, t, r, t + 2f * rad, 0f, -90f, false)
|
||||
lineTo(l + corner, t); quadTo(l, t, l, t + corner)
|
||||
close()
|
||||
}
|
||||
|
||||
private fun f1(v: Float?): String = v?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–"
|
||||
|
||||
private fun gib(bytes: Long?): String = bytes?.let { "%.1f".format(it / 1073741824.0) } ?: "–"
|
||||
|
||||
private fun AnnotatedString.Builder.num(value: String, unit: String, size: TextUnit, color: Color = HudInk.value, unitScale: Float = UNIT) {
|
||||
withStyle(SpanStyle(color = color)) { append(value) }
|
||||
if (unit.isNotEmpty()) withStyle(SpanStyle(color = HudInk.dim, fontSize = size * unitScale)) { append(unit) }
|
||||
}
|
||||
|
||||
private fun AnnotatedString.Builder.gap() = append(" ")
|
||||
|
||||
private fun tempLabel(d: HudData, c: Int): String = if (d.fahrenheit) "${c * 9 / 5 + 32}°F" else "$c°C"
|
||||
|
||||
private fun AnnotatedString.Builder.temp(d: HudData, sensor: HudMetrics.TempSensor, c: Int?, size: TextUnit) {
|
||||
if (c == null) { num("–", "", size); return }
|
||||
val shown = if (d.fahrenheit) (c * 9 / 5 + 32) else c
|
||||
num(shown.toString(), if (d.fahrenheit) "°F" else "°C", size, d.tempColor(sensor, c))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Big(value: String, unit: String, size: TextUnit, color: Color, glow: Boolean, unitScale: Float = 0.27f, modifier: Modifier = Modifier) {
|
||||
Text(
|
||||
buildAnnotatedString { num(value, unit, size, color, unitScale) },
|
||||
modifier = modifier, fontSize = size, fontFamily = Mono, fontWeight = FontWeight.Bold, maxLines = 1, softWrap = false,
|
||||
style = if (glow) TextStyle(shadow = Shadow(color.copy(alpha = 0.85f), Offset.Zero, 18f)) else TextStyle.Default,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Line(text: AnnotatedString, size: TextUnit, modifier: Modifier = Modifier, align: TextAlign = TextAlign.Start) {
|
||||
Text(text, modifier = modifier, fontSize = size, fontFamily = Mono, fontWeight = FontWeight.Bold, color = HudInk.value, maxLines = 1,
|
||||
softWrap = false, overflow = TextOverflow.Clip, textAlign = align)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Small(text: String, size: TextUnit = 12.sp, color: Color = HudInk.dim, modifier: Modifier = Modifier) {
|
||||
Text(text, modifier = modifier, fontSize = size, fontFamily = Mono, fontWeight = FontWeight.Bold, color = color, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
|
||||
private fun lowsText(d: HudData, size: TextUnit, accent: Color, deep: Boolean = true): AnnotatedString = buildAnnotatedString {
|
||||
fun part(label: String, v: Float) {
|
||||
withStyle(SpanStyle(color = HudInk.dim)) { append("$label ") }
|
||||
withStyle(SpanStyle(color = accent)) { append(f1(v)) }
|
||||
}
|
||||
part("1%", d.lows.low1Fps)
|
||||
withStyle(SpanStyle(color = HudInk.sep)) { append(" · ") }
|
||||
part("0.1%", d.lows.low01Fps)
|
||||
if (deep) {
|
||||
withStyle(SpanStyle(color = HudInk.sep)) { append(" · ") }
|
||||
part("0.01%", d.lows.low001Fps)
|
||||
}
|
||||
}
|
||||
|
||||
private val GRAPH_MIN_GAP = 3.dp
|
||||
|
||||
@Composable
|
||||
private fun Graph(values: List<Float>, lo: Float, hi: Float, color: Color, modifier: Modifier) {
|
||||
Canvas(modifier) {
|
||||
if (values.size < 2 || hi <= lo) return@Canvas
|
||||
val stride = ceil(GRAPH_MIN_GAP.toPx() * (values.size - 1) / size.width).toInt().coerceAtLeast(1)
|
||||
val points = if (stride == 1) values else values.chunked(stride) { it.average().toFloat() }
|
||||
if (points.size < 2) return@Canvas
|
||||
val path = Path()
|
||||
points.forEachIndexed { i, v ->
|
||||
val x = i / (points.size - 1f) * size.width
|
||||
val y = size.height - ((v - lo) / (hi - lo)).coerceIn(0f, 1f) * size.height
|
||||
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
|
||||
}
|
||||
drawPath(path, color.copy(alpha = 0.22f), style = Stroke(width = 6.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
|
||||
drawPath(path, color, style = Stroke(width = 2.2f.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FrameGraph(d: HudData, accent: Color, height: Dp) {
|
||||
Graph(d.graph.toList(), 0f, FrameStats.GRAPH_MAX_MS, lerp(accent, Color.White, 0.3f), Modifier.fillMaxWidth().height(height))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Rows(rows: List<Pair<Pair<String, Color>, AnnotatedString>>, size: TextUnit, labelWidth: Dp, gap: Dp) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(gap)) {
|
||||
for ((label, value) in rows) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label.first, modifier = Modifier.width(labelWidth), fontSize = size, fontFamily = Mono, fontWeight = FontWeight.Bold,
|
||||
color = label.second, maxLines = 1, softWrap = false)
|
||||
Line(value, size)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun row(label: String, color: Color, value: AnnotatedString) = (label to color) to value
|
||||
|
||||
@Composable
|
||||
private fun RowScope.Tile(key: String, keyColor: Color, value: AnnotatedString, sub: String, glow: Color? = null) {
|
||||
Column(
|
||||
Modifier.weight(1f).fillMaxHeight().clip(RoundedCornerShape(9.dp)).background(HudInk.tile).padding(horizontal = 11.dp, vertical = 6.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Small(key, 12.sp, keyColor)
|
||||
Text(value, fontSize = 28.sp, fontFamily = Mono, fontWeight = FontWeight.Bold, color = HudInk.value, maxLines = 1, softWrap = false,
|
||||
style = if (glow != null) TextStyle(shadow = Shadow(glow.copy(alpha = 0.85f), Offset.Zero, 16f)) else TextStyle.Default)
|
||||
Small(sub)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Ring(ringSize: Dp, fraction: Float?, color: Color, label: String, sub: String?, center: @Composable () -> Unit) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Box(Modifier.size(ringSize), contentAlignment = Alignment.Center) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val w = size.minDimension * 0.085f
|
||||
val tl = Offset(w, w)
|
||||
val sz = Size(size.width - 2 * w, size.height - 2 * w)
|
||||
drawArc(Color.White.copy(alpha = 0.08f), 0f, 360f, false, topLeft = tl, size = sz, style = Stroke(width = w))
|
||||
if (fraction != null) {
|
||||
val sweep = (fraction.coerceIn(0f, 1f) * 360f).coerceAtLeast(1f)
|
||||
drawArc(color.copy(alpha = 0.25f), -90f, sweep, false, topLeft = tl, size = sz, style = Stroke(width = w * 1.9f, cap = StrokeCap.Round))
|
||||
drawArc(color, -90f, sweep, false, topLeft = tl, size = sz, style = Stroke(width = w, cap = StrokeCap.Round))
|
||||
}
|
||||
}
|
||||
center()
|
||||
}
|
||||
Small(label, 13.sp, color)
|
||||
if (sub != null) Small(sub, 11.5.sp)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.BigFps(d: HudData, accent: Color) {
|
||||
Big(f1(d.fps), "fps", 104.sp, accent, glow = true, modifier = Modifier.offset(x = (-4).dp))
|
||||
Line(lowsText(d, 16.sp, accent), 16.sp, Modifier.padding(top = 10.dp))
|
||||
Spacer(Modifier.weight(1f))
|
||||
FrameGraph(d, accent, 72.dp)
|
||||
Small(listOfNotNull(d.engine.ifEmpty { null }, d.title, d.played).joinToString(" · "), modifier = Modifier.padding(top = 8.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Full(d: HudData, accent: Color) {
|
||||
val s = d.device
|
||||
val z = 16.sp
|
||||
val left = listOf(
|
||||
row("GPU", StatsColors.gpu, AnnotatedString(d.gpuName)),
|
||||
row("GPU", StatsColors.gpu, buildAnnotatedString { num(s?.gpuPercent?.toString() ?: "–", "%", z); gap(); temp(d, HudMetrics.TempSensor.GPU, s?.gpuTempC, z) }),
|
||||
row("", StatsColors.gpu, buildAnnotatedString { num(s?.gpuClockMhz?.toString() ?: "–", "MHz", z) }),
|
||||
row("CPU", StatsColors.cpu, buildAnnotatedString { num(s?.cpuPercent?.toString() ?: "–", "%", z); gap(); temp(d, HudMetrics.TempSensor.CPU, s?.cpuTempC, z) }),
|
||||
row("", StatsColors.cpu, buildAnnotatedString { num(s?.cpuClockMhz?.toString() ?: "–", "MHz", z) }),
|
||||
row("VRAM", HudInk.vram, buildAnnotatedString { num(gib(s?.vramUsedBytes), "GiB", z) }),
|
||||
row("RAM", StatsColors.ram, buildAnnotatedString { num(gib(s?.ramUsedBytes), "GiB", z); gap(); num(s?.ramPercent?.roundToInt()?.toString() ?: "–", "%", z) }),
|
||||
row("BAT", StatsColors.bat, buildAnnotatedString { num(s?.battery?.percent?.toString() ?: "–", "%", z); gap(); num(s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–", "W", z) }),
|
||||
)
|
||||
val right = listOf(
|
||||
row(d.engine.ifEmpty { "FPS" }, accent, buildAnnotatedString { num(f1(d.fps), "FPS", z, accent) }),
|
||||
row("", accent, buildAnnotatedString { num(f1(d.frametimeMs), "ms", z) }),
|
||||
row("AVG", HudInk.low, buildAnnotatedString { num(f1(d.avgFps), "FPS", z) }),
|
||||
row("1%", HudInk.low, buildAnnotatedString { num(f1(d.lows.low1Fps), "FPS", z) }),
|
||||
row("0.1%", HudInk.low, buildAnnotatedString { num(f1(d.lows.low01Fps), "FPS", z) }),
|
||||
row("0.01%", HudInk.low, buildAnnotatedString { num(f1(d.lows.low001Fps), "FPS", z) }),
|
||||
row("TEMP", StatsColors.bat, buildAnnotatedString { temp(d, HudMetrics.TempSensor.BATTERY, s?.battery?.tempC, z) }),
|
||||
row("FAN", HudInk.dim, buildAnnotatedString { num(d.fanRpm?.toString() ?: "–", "rpm", z) }),
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(28.dp)) {
|
||||
Rows(left, z, 52.dp, 6.dp)
|
||||
Rows(right, z, 62.dp, 6.dp)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
val frametime = stringResource(R.string.stats_hud_frametime)
|
||||
Line(buildAnnotatedString {
|
||||
withStyle(SpanStyle(color = accent)) { append(frametime) }
|
||||
withStyle(SpanStyle(color = HudInk.dim)) { append(" min %.1f · max %.1f ms".format(d.graph.filter { it > 0f }.minOrNull() ?: 0f, d.graph.maxOrNull() ?: 0f)) }
|
||||
}, 12.5.sp, Modifier.padding(bottom = 6.dp))
|
||||
FrameGraph(d, accent, 44.dp)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Tiles(d: HudData, accent: Color) {
|
||||
val s = d.device
|
||||
val z = 28.sp
|
||||
val u = 0.5f
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Tile("FPS", accent, buildAnnotatedString { num(f1(d.fps), "", z) }, "${f1(d.avgFps)} avg · ${f1(d.lows.low1Fps)} 1%", glow = accent)
|
||||
Tile("FRAME", HudInk.dim, buildAnnotatedString { num(f1(d.frametimeMs), "ms", z, unitScale = u) }, "max %.1f ms".format(d.graph.maxOrNull() ?: 0f))
|
||||
Tile("GPU", StatsColors.gpu, buildAnnotatedString { num(s?.gpuPercent?.toString() ?: "–", "%", z, unitScale = u) },
|
||||
listOfNotNull(s?.gpuTempC?.let { tempLabel(d, it) }, s?.gpuClockMhz?.let { "$it MHz" }).joinToString(" · "))
|
||||
}
|
||||
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Tile("CPU", StatsColors.cpu, buildAnnotatedString { num(s?.cpuPercent?.toString() ?: "–", "%", z, unitScale = u) },
|
||||
listOfNotNull(s?.cpuTempC?.let { tempLabel(d, it) }, s?.cpuClockMhz?.let { "$it MHz" }).joinToString(" · "))
|
||||
Tile("RAM", StatsColors.ram, buildAnnotatedString { num(s?.ramPercent?.roundToInt()?.toString() ?: "–", "%", z, unitScale = u) },
|
||||
"${gib(s?.ramUsedBytes)} / ${gib(s?.ramTotalBytes)} GiB")
|
||||
Tile("VRAM", HudInk.vram, buildAnnotatedString { num(gib(s?.vramUsedBytes), "GiB", z, unitScale = u) }, d.gpuName)
|
||||
}
|
||||
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Tile("BAT TEMP", StatsColors.bat, buildAnnotatedString { temp(d, HudMetrics.TempSensor.BATTERY, s?.battery?.tempC, z) }, stringResource(R.string.stats_hud_battery_temp))
|
||||
Tile("FAN", HudInk.dim, buildAnnotatedString { num(d.fanRpm?.toString() ?: "–", "", z) }, "rpm")
|
||||
Tile("BATTERY", StatsColors.bat, buildAnnotatedString { num(s?.battery?.percent?.toString() ?: "–", "%", z, unitScale = u) },
|
||||
listOfNotNull(s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f W".format(it) }, s?.battery?.runtimeText).joinToString(" · "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Rings(d: HudData, accent: Color) {
|
||||
val s = d.device
|
||||
Row(Modifier.weight(1f).fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(26.dp)) {
|
||||
Ring(200.dp, d.fps?.let { it / d.hz }, accent, stringResource(R.string.stats_hud_fps_of, d.hz), "1% ${f1(d.lows.low1Fps)} · 0.1% ${f1(d.lows.low01Fps)}") {
|
||||
Big(f1(d.fps), "fps", 40.sp, HudInk.value, glow = true, unitScale = 0.4f)
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(22.dp)) {
|
||||
Ring(96.dp, s?.gpuPercent?.let { it / 100f }, StatsColors.gpu, "GPU", s?.gpuTempC?.let { tempLabel(d, it) }) { Big(s?.gpuPercent?.toString() ?: "–", "%", 20.sp, HudInk.value, false, 0.6f) }
|
||||
Ring(96.dp, s?.cpuPercent?.let { it / 100f }, StatsColors.cpu, "CPU", s?.cpuTempC?.let { tempLabel(d, it) }) { Big(s?.cpuPercent?.toString() ?: "–", "%", 20.sp, HudInk.value, false, 0.6f) }
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(22.dp)) {
|
||||
Ring(96.dp, s?.ramPercent?.let { it / 100f }, StatsColors.ram, "RAM", s?.let { "${gib(it.ramUsedBytes)} GiB" }) {
|
||||
Big(s?.ramPercent?.roundToInt()?.toString() ?: "–", "%", 20.sp, HudInk.value, false, 0.6f)
|
||||
}
|
||||
Ring(96.dp, s?.battery?.percent?.let { it / 100f }, StatsColors.bat, "BAT", s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f W".format(it) }) {
|
||||
Big(s?.battery?.percent?.toString() ?: "–", "%", 20.sp, HudInk.value, false, 0.6f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Graphs(d: HudData, accent: Color) {
|
||||
val s = d.device
|
||||
val frameMs = d.fpsHistory.map { 1000f / max(it, 1f) }
|
||||
@Composable
|
||||
fun graphRow(label: String, color: Color, values: List<Float>, hi: Float, value: AnnotatedString) {
|
||||
Row(Modifier.fillMaxWidth().height(56.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Small(label, 14.sp, color, Modifier.width(62.dp))
|
||||
Graph(values, 0f, hi, color, Modifier.weight(1f).height(52.dp))
|
||||
Line(value, 24.sp, Modifier.width(128.dp), TextAlign.End)
|
||||
}
|
||||
}
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.SpaceEvenly) {
|
||||
graphRow("FPS", accent, d.fpsHistory, max(d.hz.toFloat(), d.fpsHistory.maxOrNull() ?: 0f) * 1.1f, buildAnnotatedString { num(f1(d.fps), "fps", 24.sp, accent, 0.5f) })
|
||||
graphRow("FRAME", lerp(accent, Color.White, 0.3f), frameMs, max(40f, (frameMs.maxOrNull() ?: 0f) * 1.2f), buildAnnotatedString { num(f1(d.frametimeMs), "ms", 24.sp, unitScale = 0.5f) })
|
||||
graphRow("CPU", StatsColors.cpu, d.cpuHistory, 100f, buildAnnotatedString { num(s?.cpuPercent?.toString() ?: "–", "%", 24.sp, unitScale = 0.5f) })
|
||||
graphRow("GPU", StatsColors.gpu, d.gpuHistory, 100f, buildAnnotatedString { num(s?.gpuPercent?.toString() ?: "–", "%", 24.sp, unitScale = 0.5f) })
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Cores(d: HudData, accent: Color) {
|
||||
val s = d.device
|
||||
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Big(f1(d.fps), "fps", 40.sp, accent, glow = true, unitScale = 0.38f)
|
||||
Small(listOfNotNull(d.engine.ifEmpty { null }, d.frametimeMs?.let { "%.1f ms".format(it) },
|
||||
s?.cpuPercent?.let { "CPU $it%" }, s?.cpuTempC?.let { tempLabel(d, it) }).joinToString(" · "), 15.sp, modifier = Modifier.padding(bottom = 6.dp))
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
val gameTag = stringResource(R.string.stats_hud_game_cores)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
for (group in d.coreGroups) {
|
||||
for (core in group.cores) {
|
||||
val p = s?.perCorePercent?.getOrNull(core)?.takeIf { it >= 0 }
|
||||
val mhz = s?.perCoreClockMhz?.getOrNull(core)?.takeIf { it > 0 }
|
||||
Row(Modifier.fillMaxWidth().height(20.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Small("C$core", 14.sp, StatsColors.cpu, Modifier.width(40.dp))
|
||||
Box(Modifier.weight(1f).height(14.dp).clip(RoundedCornerShape(7.dp)).background(Color.White.copy(alpha = 0.07f))) {
|
||||
if (p != null && p > 0) Box(
|
||||
Modifier.fillMaxHeight().fillMaxWidth(p / 100f).clip(RoundedCornerShape(7.dp))
|
||||
.background(Brush.horizontalGradient(listOf(Color(0xFF2B6FC9), if (p >= 80) HudInk.amber else StatsColors.cpu))),
|
||||
)
|
||||
}
|
||||
Line(buildAnnotatedString { num(p?.toString() ?: "–", "%", 14.sp); append(" "); num(mhz?.toString() ?: "–", "MHz", 14.sp) },
|
||||
14.sp, Modifier.width(118.dp), TextAlign.End)
|
||||
}
|
||||
}
|
||||
val label = group.maxGhz?.let { stringResource(R.string.stats_hud_core_group, group.cores.size, "%.2f".format(it)) }
|
||||
?: stringResource(R.string.stats_hud_core_group_unknown, group.cores.size)
|
||||
Row(Modifier.padding(start = 50.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Small(label, 11.5.sp)
|
||||
if (d.gameCores.isNotEmpty() && group.cores.any { it in d.gameCores }) {
|
||||
Text(gameTag.uppercase(), fontSize = 10.sp, fontFamily = Mono, fontWeight = FontWeight.Bold, color = Color(0xFF0A0B0D),
|
||||
modifier = Modifier.clip(RoundedCornerShape(4.dp)).background(StatsColors.cpu).padding(horizontal = 4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Heat(d: HudData) {
|
||||
val s = d.device
|
||||
@Composable
|
||||
fun bar(label: String, color: Color, sensor: HudMetrics.TempSensor, c: Int?) {
|
||||
val red = d.redC(sensor)
|
||||
Row(Modifier.fillMaxWidth().height(28.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Small(label, 15.sp, color, Modifier.width(48.dp))
|
||||
BoxWithConstraints(Modifier.weight(1f).height(20.dp).clip(RoundedCornerShape(10.dp)).background(Color.White.copy(alpha = 0.07f))) {
|
||||
if (c != null && c > 0) Box(Modifier.fillMaxHeight().fillMaxWidth((c / 100f).coerceIn(0f, 1f)).clip(RoundedCornerShape(10.dp))
|
||||
.background(Brush.horizontalGradient(listOf(color.copy(alpha = 0.55f), color))))
|
||||
if (red != null && red in 1..99) Box(Modifier.offset(x = maxWidth * (red / 100f)).width(2.dp).fillMaxHeight().background(Color(0xFFEF5350)))
|
||||
}
|
||||
Line(buildAnnotatedString { temp(d, sensor, c, 24.sp) }, 24.sp, Modifier.width(92.dp), TextAlign.End)
|
||||
}
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
bar("CPU", StatsColors.cpu, HudMetrics.TempSensor.CPU, s?.cpuTempC)
|
||||
bar("GPU", StatsColors.gpu, HudMetrics.TempSensor.GPU, s?.gpuTempC)
|
||||
bar("BAT", StatsColors.bat, HudMetrics.TempSensor.BATTERY, s?.battery?.tempC)
|
||||
}
|
||||
Small(stringResource(R.string.stats_hud_red_mark), 12.sp, modifier = Modifier.padding(top = 8.dp))
|
||||
Spacer(Modifier.weight(1f))
|
||||
Row(Modifier.fillMaxWidth().height(96.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Tile("FAN", HudInk.dim, buildAnnotatedString { num(d.fanRpm?.toString() ?: "–", "", 28.sp) }, "rpm")
|
||||
Tile("POWER", StatsColors.bat, buildAnnotatedString { num(s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–", "W", 28.sp, unitScale = 0.5f) },
|
||||
stringResource(R.string.stats_hud_whole_device))
|
||||
Tile("BATTERY", StatsColors.bat, buildAnnotatedString { num(s?.battery?.percent?.toString() ?: "–", "%", 28.sp, unitScale = 0.5f) }, s?.battery?.runtimeText ?: "")
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.GameCard(d: HudData, accent: Color) {
|
||||
Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
|
||||
Box(
|
||||
Modifier.width(150.dp).fillMaxHeight().clip(RoundedCornerShape(10.dp))
|
||||
.background(Brush.linearGradient(listOf(lerp(accent, Color.Black, 0.55f), Color(0xFF0B0D10)))),
|
||||
contentAlignment = Alignment.BottomStart,
|
||||
) {
|
||||
if (d.cover != null) AsyncImage(model = d.cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
else Text(d.title.orEmpty(), fontSize = 20.sp, fontWeight = FontWeight.Bold, color = Color.White.copy(alpha = 0.85f), maxLines = 3,
|
||||
modifier = Modifier.padding(12.dp))
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text(d.title.orEmpty(), fontSize = 26.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
d.played?.let { Small(stringResource(R.string.stats_hud_playing_for, it), 13.5.sp) }
|
||||
Line(buildAnnotatedString {
|
||||
withStyle(SpanStyle(color = accent)) { append(d.engine) }
|
||||
if (d.engine.isNotEmpty() && d.proton != null) withStyle(SpanStyle(color = HudInk.dim)) { append(" · ") }
|
||||
d.proton?.let { withStyle(SpanStyle(color = HudInk.vram)) { append(it) } }
|
||||
}, 13.5.sp)
|
||||
if (d.resolution.isNotEmpty()) Small(d.resolution, 13.5.sp)
|
||||
Big(f1(d.fps), "fps", 60.sp, accent, glow = true, unitScale = 0.3f, modifier = Modifier.padding(top = 6.dp))
|
||||
Line(lowsText(d, 14.sp, accent, deep = false), 14.sp)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FrameGraph(d, accent, 40.dp)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Pacing(d: HudData, accent: Color) {
|
||||
@Composable
|
||||
fun stat(label: String, value: String, color: Color = HudInk.value) {
|
||||
Column {
|
||||
Small(label, 13.sp)
|
||||
Text(value, fontSize = 22.sp, fontFamily = Mono, fontWeight = FontWeight.Bold, color = color, maxLines = 1)
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(24.dp)) {
|
||||
Big(f1(d.fps), "fps", 52.sp, accent, glow = true, unitScale = 0.3f)
|
||||
stat(stringResource(R.string.stats_hud_avg_frame), d.frametimeMs?.let { "%.1f ms".format(it) } ?: "–")
|
||||
stat(stringResource(R.string.stats_hud_low), f1(d.lows.low1Fps))
|
||||
val slow = d.slowPerMinute
|
||||
stat(stringResource(R.string.stats_hud_slow_frames), slow?.let { stringResource(R.string.stats_hud_per_minute, it) } ?: "–",
|
||||
if ((slow ?: 0) > 0) HudInk.amber else HudInk.value)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
val target = 1000f / d.hz
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val graphColor = lerp(accent, Color.White, 0.3f)
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val axis = Color.White.copy(alpha = 0.12f)
|
||||
drawLine(axis, Offset(0f, 0f), Offset(0f, size.height), 1.dp.toPx())
|
||||
drawLine(axis, Offset(0f, size.height), Offset(size.width, size.height), 1.dp.toPx())
|
||||
val dash = PathEffect.dashPathEffect(floatArrayOf(6.dp.toPx(), 5.dp.toPx()))
|
||||
for ((ms, color) in listOf(target to Color.White.copy(alpha = 0.25f), target * 2 to HudInk.amber.copy(alpha = 0.5f))) {
|
||||
val y = size.height * (1f - ms / FrameStats.GRAPH_MAX_MS)
|
||||
drawLine(color, Offset(0f, y), Offset(size.width, y), 1.dp.toPx(), pathEffect = dash)
|
||||
}
|
||||
}
|
||||
Graph(d.graph.toList(), 0f, FrameStats.GRAPH_MAX_MS, graphColor, Modifier.fillMaxSize())
|
||||
for ((ms, color) in listOf(target to HudInk.dim, target * 2 to HudInk.amber)) {
|
||||
Small("%.1f ms · %d fps".format(ms, (1000f / ms).roundToInt()), 11.sp, color,
|
||||
Modifier.align(Alignment.TopEnd).offset(y = maxHeight * (1f - ms / FrameStats.GRAPH_MAX_MS) - 17.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Night(d: HudData, dim: Boolean) {
|
||||
val clockInk = if (dim) Color(0xFF6F7A87) else HudInk.value
|
||||
val fpsInk = if (dim) Color(0xFF4D7FA8) else LocalPalette.current.primary
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.Center) {
|
||||
Text(d.clock, fontSize = 88.sp, fontWeight = FontWeight.Light, color = clockInk, maxLines = 1, softWrap = false)
|
||||
Line(buildAnnotatedString {
|
||||
num(f1(d.fps), "fps", 30.sp, fpsInk)
|
||||
d.device?.battery?.percent?.let {
|
||||
withStyle(SpanStyle(color = HudInk.sep)) { append(" · ") }
|
||||
num(it.toString(), "%", 30.sp, if (dim) Color(0xFF6B5A44) else StatsColors.bat)
|
||||
}
|
||||
}, 30.sp, Modifier.padding(top = 14.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ColumnScope.Mega(d: HudData, accent: Color) {
|
||||
val s = d.device
|
||||
val z = 13.5.sp
|
||||
val left = mutableListOf(
|
||||
row("GPU", StatsColors.gpu, AnnotatedString(d.gpuName)),
|
||||
row("GPU", StatsColors.gpu, buildAnnotatedString {
|
||||
num(s?.gpuPercent?.toString() ?: "–", "%", z); gap(); temp(d, HudMetrics.TempSensor.GPU, s?.gpuTempC, z); gap(); num(s?.gpuClockMhz?.toString() ?: "–", "MHz", z)
|
||||
}),
|
||||
row("CPU", StatsColors.cpu, buildAnnotatedString {
|
||||
num(s?.cpuPercent?.toString() ?: "–", "%", z); gap(); temp(d, HudMetrics.TempSensor.CPU, s?.cpuTempC, z); gap(); num(s?.cpuClockMhz?.toString() ?: "–", "MHz", z)
|
||||
}),
|
||||
)
|
||||
val cores = s?.perCorePercent?.size ?: 0
|
||||
for (i in 0 until cores) {
|
||||
left += row("C$i", StatsColors.cpu, buildAnnotatedString {
|
||||
num(s?.perCorePercent?.getOrNull(i)?.takeIf { it >= 0 }?.toString() ?: "–", "%", z); gap()
|
||||
num(s?.perCoreClockMhz?.getOrNull(i)?.takeIf { it > 0 }?.toString() ?: "–", "MHz", z)
|
||||
})
|
||||
}
|
||||
val right = listOf(
|
||||
row("VRAM", HudInk.vram, buildAnnotatedString { num(gib(s?.vramUsedBytes), "GiB", z) }),
|
||||
row("RAM", StatsColors.ram, buildAnnotatedString { num("${gib(s?.ramUsedBytes)}/${gib(s?.ramTotalBytes)}", "GiB", z); gap(); num(s?.ramPercent?.roundToInt()?.toString() ?: "–", "%", z) }),
|
||||
row("SWP", StatsColors.ram, buildAnnotatedString { num("${gib(s?.swapUsedBytes)}/${gib(s?.swapTotalBytes)}", "GiB", z) }),
|
||||
row("NET", accent, buildAnnotatedString {
|
||||
withStyle(SpanStyle(color = HudInk.dim)) { append("↓") }; num(s?.netDownBps?.let { (it / 1024).toString() } ?: "–", "", z)
|
||||
append(" "); withStyle(SpanStyle(color = HudInk.dim)) { append("↑") }; num(s?.netUpBps?.let { (it / 1024).toString() } ?: "–", "KB/s", z)
|
||||
}),
|
||||
row("BAT", StatsColors.bat, buildAnnotatedString {
|
||||
num(s?.battery?.percent?.toString() ?: "–", "%", z); gap(); temp(d, HudMetrics.TempSensor.BATTERY, s?.battery?.tempC, z); gap()
|
||||
num(s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–", "W", z)
|
||||
}),
|
||||
row("FAN", HudInk.dim, buildAnnotatedString { num(d.fanRpm?.toString() ?: "–", "rpm", z) }),
|
||||
row(d.engine.ifEmpty { "FPS" }, accent, buildAnnotatedString { num(f1(d.fps), "FPS", z, accent); gap(); num(f1(d.frametimeMs), "ms", z) }),
|
||||
row("AVG", HudInk.low, buildAnnotatedString { num(f1(d.avgFps), "FPS", z) }),
|
||||
row("1%", HudInk.low, buildAnnotatedString { num(f1(d.lows.low1Fps), "FPS", z) }),
|
||||
row("0.1%", HudInk.low, buildAnnotatedString { num(f1(d.lows.low01Fps), "FPS", z) }),
|
||||
row("0.01%", HudInk.low, buildAnnotatedString { num(f1(d.lows.low001Fps), "FPS", z) }),
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) {
|
||||
Rows(left, z, 44.dp, 3.dp)
|
||||
Rows(right, z, 58.dp, 3.dp)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
Line(buildAnnotatedString {
|
||||
withStyle(SpanStyle(color = HudInk.dim)) { append("RES ") }; append(d.resolution.ifEmpty { "–" })
|
||||
d.proton?.let { withStyle(SpanStyle(color = HudInk.dim)) { append(" · ") }; withStyle(SpanStyle(color = HudInk.vram)) { append(it) } }
|
||||
d.played?.let { withStyle(SpanStyle(color = HudInk.dim)) { append(" · ") }; append(it) }
|
||||
}, 12.5.sp, Modifier.padding(bottom = 6.dp))
|
||||
FrameGraph(d, accent, 30.dp)
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.StrokeJoin
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.nativeCanvas
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.layout.Layout
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Constraints
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.TextUnit
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.hud.DroidDeckMark
|
||||
import com.droiddeck.launcher.hud.FrameStats
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.session.StatsStrip
|
||||
import com.droiddeck.launcher.session.StripMetric
|
||||
import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal object StatsColors {
|
||||
val cpu = Color(0xFF58A6FF)
|
||||
val gpu = Color(0xFF5EE08A)
|
||||
val ram = Color(0xFFFF7BC0)
|
||||
val bat = Color(0xFFFFAB5E)
|
||||
val throttle = Color(0xFF14A39A)
|
||||
val brake = Color(0xFFE5484D)
|
||||
val speed = Color(0xFF2E8FD6)
|
||||
val warn = Color(0xFFF2C94C)
|
||||
val shiftGreen = Color(0xFF2FB36A)
|
||||
val badge = Color(0xFF0B0D10)
|
||||
}
|
||||
|
||||
internal class History(private val capacity: Int) {
|
||||
private val values = ArrayDeque<Float>(capacity)
|
||||
private val times = ArrayDeque<Long>(capacity)
|
||||
fun add(v: Float, atMs: Long = 0L) {
|
||||
if (values.size == capacity) {
|
||||
values.removeFirst()
|
||||
times.removeFirst()
|
||||
}
|
||||
values.addLast(v)
|
||||
times.addLast(atMs)
|
||||
}
|
||||
fun snapshot(): List<Float> = values.toList()
|
||||
fun spanSeconds(): Int {
|
||||
val first = times.firstOrNull()?.takeIf { it > 0L } ?: return 0
|
||||
val last = times.last()
|
||||
return ((last - first + 500L) / 1000L).toInt()
|
||||
}
|
||||
}
|
||||
|
||||
private val MARK_RATIO = DroidDeckMark.widthFor(1f)
|
||||
|
||||
@Composable
|
||||
internal fun DroidDeckLogo(height: Dp, modifier: Modifier = Modifier, body: Color = Color.White, orb: Color = LocalPalette.current.primary) {
|
||||
Canvas(modifier.size(height * MARK_RATIO, height)) {
|
||||
val b = body.toArgb()
|
||||
val o = orb.toArgb()
|
||||
drawIntoCanvas { DroidDeckMark.draw(it.nativeCanvas, 0f, 0f, size.height, b, o) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LogoBadge(size: Dp) {
|
||||
val shape = RoundedCornerShape(size * 0.22f)
|
||||
Box(Modifier.size(size).clip(shape).background(StatsColors.badge).border(2.dp, LocalPalette.current.primary, shape), contentAlignment = Alignment.Center) {
|
||||
DroidDeckLogo(size * 0.62f)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LogoHeader(clock: String, game: String?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Wordmark(14.dp, ink = colors.onBackground)
|
||||
Text(game.orEmpty(), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (clock.isNotEmpty()) Text(clock, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Sparkline(values: List<Float>, min: Float, max: Float, color: Color, modifier: Modifier) {
|
||||
Canvas(modifier) {
|
||||
if (values.size < 2 || max <= min) return@Canvas
|
||||
val path = Path()
|
||||
values.forEachIndexed { i, v ->
|
||||
val x = i / (values.size - 1f) * size.width
|
||||
val y = size.height - ((v - min) / (max - min)).coerceIn(0f, 1f) * (size.height - 2f) - 1f
|
||||
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
|
||||
}
|
||||
drawPath(path, color, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StatsCard(title: String?, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(14.dp)
|
||||
Column(
|
||||
modifier.clip(shape).background(pal.surface).border(1.dp, pal.primary.copy(alpha = 0.22f), shape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
if (title != null) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
DroidDeckLogo(12.dp, body = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
if (title.isNotEmpty()) Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = pal.primary, letterSpacing = 0.6.sp,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
internal class StripData(
|
||||
val fps: Float?,
|
||||
val device: HudMetrics.Snapshot?,
|
||||
val fpsHistory: List<Float>,
|
||||
val cpuHistory: List<Float>,
|
||||
val gpuHistory: List<Float>,
|
||||
val wattsHistory: List<Float>,
|
||||
val clock: String,
|
||||
val game: String? = null,
|
||||
val engine: String = "",
|
||||
val lows: FrameStats.Lows? = null,
|
||||
val graph: FloatArray? = null,
|
||||
val metrics: Set<StripMetric> = StripMetric.defaults,
|
||||
val fahrenheit: Boolean = false,
|
||||
val tempColor: ((HudMetrics.TempSensor, Int) -> Color)? = null,
|
||||
)
|
||||
|
||||
private fun percentTemp(percent: Int?, temp: Int?): String =
|
||||
listOfNotNull(percent?.let { "$it%" }, temp?.let { "$it°" }).joinToString(" · ").ifEmpty { "–" }
|
||||
|
||||
private fun batteryText(s: HudMetrics.Snapshot?): String =
|
||||
listOfNotNull(s?.battery?.percent?.let { "$it%" }, s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f W".format(it) }).joinToString(" · ").ifEmpty { "–" }
|
||||
|
||||
private fun fpsText(fps: Float?): String = fps?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–"
|
||||
|
||||
@Composable
|
||||
internal fun StatsStripView(style: StatsStrip, d: StripData, onTap: () -> Unit) {
|
||||
Box(Modifier.fillMaxWidth().clickable(onClick = onTap)) {
|
||||
when (style) {
|
||||
StatsStrip.LINE -> LineStrip(d)
|
||||
StatsStrip.PANEL -> PanelStrip(d)
|
||||
StatsStrip.TILES -> TilesStrip(d)
|
||||
StatsStrip.RINGS -> RingsStrip(d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private object LineInk {
|
||||
val value = Color(0xFFF2F5F9)
|
||||
val dim = Color(0xFF9AA4B2)
|
||||
val vram = Color(0xFFC98BFF)
|
||||
}
|
||||
|
||||
private class LineItem(val priority: Int, val content: @Composable () -> Unit)
|
||||
|
||||
@Composable
|
||||
internal fun LineStrip(d: StripData, modifier: Modifier = Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(12.dp)
|
||||
val m = d.metrics
|
||||
val s = d.device
|
||||
val items = ArrayList<LineItem>()
|
||||
items += LineItem(0) { DroidDeckLogo(16.dp) }
|
||||
if (StripMetric.ENGINE in m && d.engine.isNotEmpty()) items += LineItem(70) { LineText(d.engine, LineInk.dim, 12.sp) }
|
||||
items += LineItem(0) {
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
LineText(fpsText(d.fps), LineInk.value, 17.sp)
|
||||
LineText("fps", LineInk.dim, 10.sp, Modifier.padding(start = 2.dp, bottom = 2.dp))
|
||||
}
|
||||
}
|
||||
val graph = d.graph
|
||||
if (StripMetric.GRAPH in m && graph != null) items += LineItem(60) {
|
||||
Sparkline(graph.asList(), 0f, FrameStats.GRAPH_MAX_MS, lerp(pal.primary, Color.White, 0.3f), Modifier.width(56.dp).height(16.dp))
|
||||
}
|
||||
if (StripMetric.LOWS in m) {
|
||||
items += LineItem(10) { LinePair("1%", LineInk.dim, lowText(d.lows?.low1Fps), StatsColors.cpu) }
|
||||
items += LineItem(90) { LinePair("0.1%", LineInk.dim, lowText(d.lows?.low01Fps), StatsColors.cpu) }
|
||||
}
|
||||
if (StripMetric.LOW001 in m) items += LineItem(100) { LinePair("0.01%", LineInk.dim, lowText(d.lows?.low001Fps), StatsColors.cpu) }
|
||||
if (StripMetric.GPU in m || StripMetric.GPU_TEMP in m) items += LineItem(20) {
|
||||
LineMetric("GPU", StatsColors.gpu, if (StripMetric.GPU in m) s?.gpuPercent else null,
|
||||
if (StripMetric.GPU_TEMP in m) s?.gpuTempC else null, HudMetrics.TempSensor.GPU, d)
|
||||
}
|
||||
if (StripMetric.CPU in m || StripMetric.CPU_TEMP in m) items += LineItem(30) {
|
||||
LineMetric("CPU", StatsColors.cpu, if (StripMetric.CPU in m) s?.cpuPercent else null,
|
||||
if (StripMetric.CPU_TEMP in m) s?.cpuTempC else null, HudMetrics.TempSensor.CPU, d)
|
||||
}
|
||||
if (StripMetric.VRAM in m) items += LineItem(80) { LinePair("VRAM", LineInk.vram, gibText(s?.vramUsedBytes), LineInk.vram) }
|
||||
if (StripMetric.RAM in m) items += LineItem(40) { LinePair("RAM", StatsColors.ram, s?.let { "${it.ramPercent.roundToInt()}%" } ?: "–", StatsColors.ram) }
|
||||
val clock = StripMetric.CLOCK in m && d.clock.isNotEmpty()
|
||||
if (clock) items += LineItem(50) { LineText(d.clock, LineInk.dim, 12.sp) }
|
||||
PriorityRow(
|
||||
IntArray(items.size) { items[it].priority }, 10.dp, pinLast = clock,
|
||||
modifier = modifier.fillMaxWidth().clip(shape).background(pal.surface).border(1.dp, pal.primary.copy(alpha = 0.35f), shape)
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
) {
|
||||
items.forEach { it.content() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PriorityRow(priorities: IntArray, spacing: Dp, pinLast: Boolean, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
|
||||
Layout(content, modifier) { measurables, constraints ->
|
||||
val gap = spacing.roundToPx()
|
||||
val loose = Constraints(maxHeight = constraints.maxHeight)
|
||||
val placeables = measurables.map { it.measure(loose) }
|
||||
val max = if (constraints.hasBoundedWidth) constraints.maxWidth else Int.MAX_VALUE
|
||||
val keep = fitByPriority(IntArray(placeables.size) { placeables[it].width }, priorities.copyOf(placeables.size), gap, max)
|
||||
val height = maxOf(constraints.minHeight, placeables.filterIndexed { i, _ -> keep[i] }.maxOfOrNull { it.height } ?: 0)
|
||||
val used = placeables.filterIndexed { i, _ -> keep[i] }.sumOf { it.width } + gap * maxOf(0, keep.count { it } - 1)
|
||||
val width = if (constraints.hasBoundedWidth) constraints.maxWidth else used
|
||||
layout(width, height) {
|
||||
var x = 0
|
||||
val last = placeables.lastIndex
|
||||
placeables.forEachIndexed { i, p ->
|
||||
if (!keep[i]) return@forEachIndexed
|
||||
val px = if (pinLast && i == last) width - p.width else x
|
||||
p.placeRelative(px, (height - p.height) / 2)
|
||||
x += p.width + gap
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LineText(text: String, color: Color, size: TextUnit = 13.sp, modifier: Modifier = Modifier) {
|
||||
Text(text, fontSize = size, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = color, maxLines = 1, softWrap = false,
|
||||
modifier = modifier)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LinePair(label: String, labelColor: Color, value: String, valueColor: Color) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
LineText(label, labelColor, 11.sp)
|
||||
LineText(value, valueColor)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LineMetric(label: String, color: Color, percent: Int?, tempC: Int?, sensor: HudMetrics.TempSensor, d: StripData) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
LineText(label, color, 11.sp)
|
||||
if (percent == null && tempC == null) LineText("–", color)
|
||||
if (percent != null) LineText("$percent%", color)
|
||||
if (tempC != null) LineText(tempText(tempC, d.fahrenheit), d.tempColor?.invoke(sensor, tempC) ?: LineInk.value)
|
||||
}
|
||||
}
|
||||
|
||||
private fun lowText(fps: Float?): String = fps?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–"
|
||||
|
||||
private fun gibText(bytes: Long?): String = bytes?.let { "%.1fGiB".format(it / 1073741824.0) } ?: "–"
|
||||
|
||||
private fun tempText(c: Int, fahrenheit: Boolean): String = if (fahrenheit) "${(c * 9f / 5f + 32f).roundToInt()}°F" else "$c°C"
|
||||
|
||||
@Composable
|
||||
private fun PanelStrip(d: StripData) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = pal.primary
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clip(shape).background(pal.surface).border(2.dp, accent, shape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
LogoBadge(40.dp)
|
||||
Column(Modifier.widthIn(min = 84.dp)) {
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(fpsText(d.fps), fontSize = 30.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent, maxLines = 1)
|
||||
Text(" fps", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 4.dp))
|
||||
}
|
||||
Text(d.fps?.takeIf { it > 0f }?.let { "%.1f ms".format(1000f / it) } ?: stringResource(R.string.stats_fps_needs_hud),
|
||||
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
Sparkline(d.fpsHistory.map { 1000f / max(it, 1f) }, 8f, 34f, lerp(accent, Color.White, 0.3f), Modifier.weight(1f).height(44.dp))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
|
||||
MetricRow("CPU", percentTemp(d.device?.cpuPercent, d.device?.cpuTempC), StatsColors.cpu)
|
||||
MetricRow("GPU", percentTemp(d.device?.gpuPercent, d.device?.gpuTempC), StatsColors.gpu)
|
||||
MetricRow("RAM", d.device?.let { "${it.ramPercent.roundToInt()}%" } ?: "–", StatsColors.ram)
|
||||
MetricRow("BAT", batteryText(d.device), StatsColors.bat)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MetricRow(label: String, value: String, color: Color) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = color, modifier = Modifier.width(36.dp))
|
||||
Text(value, fontSize = 13.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TilesStrip(d: StripData) {
|
||||
val accent = LocalPalette.current.primary
|
||||
val s = d.device
|
||||
val gpuPercent: Int? = s?.gpuPercent
|
||||
val gpuTemp: Int? = s?.gpuTempC
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
LogoHeader(d.clock, d.game)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
HistoryTile("FPS", accent, fpsText(d.fps), "fps", d.fpsHistory, 75f)
|
||||
HistoryTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it°" } ?: "", d.cpuHistory, 100f)
|
||||
HistoryTile("GPU", StatsColors.gpu, gpuPercent?.let { "$it%" } ?: gpuTemp?.let { "$it°" } ?: "–",
|
||||
if (gpuPercent != null) gpuTemp?.let { "$it°" } ?: "" else "", d.gpuHistory, 100f)
|
||||
HistoryTile(stringResource(R.string.bottom_telemetry_battery).uppercase(), StatsColors.bat, s?.battery?.percent?.let { "$it%" } ?: "–",
|
||||
s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1fW".format(it) } ?: "", d.wattsHistory, 10f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowScope.HistoryTile(label: String, color: Color, value: String, unit: String, history: List<Float>, max: Float) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(
|
||||
Modifier.weight(1f).clip(RoundedCornerShape(12.dp)).background(pal.surface)
|
||||
.drawBehind { drawRect(color, topLeft = Offset.Zero, size = Size(size.width, 3.dp.toPx())) }
|
||||
.padding(start = 10.dp, end = 10.dp, top = 9.dp, bottom = 6.dp),
|
||||
) {
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = color, letterSpacing = 0.8.sp, maxLines = 1)
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(value, fontSize = 22.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground, maxLines = 1)
|
||||
if (unit.isNotEmpty()) Text(" $unit", fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.padding(bottom = 3.dp))
|
||||
}
|
||||
Sparkline(history, 0f, max, color, Modifier.fillMaxWidth().height(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RingsStrip(d: StripData) {
|
||||
val s = d.device
|
||||
val gpuPercent: Int? = s?.gpuPercent
|
||||
val gpuTemp: Int? = s?.gpuTempC
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
LogoHeader(d.clock, d.game)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
RingTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { it / 100f }, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it °C" } ?: "")
|
||||
RingTile("GPU", StatsColors.gpu, gpuPercent?.let { it / 100f }, gpuPercent?.let { "$it%" } ?: gpuTemp?.let { "$it°" } ?: "–",
|
||||
if (gpuPercent != null) gpuTemp?.let { "$it °C" } ?: "" else "")
|
||||
RingTile("RAM", StatsColors.ram, s?.ramPercent?.let { it / 100f }, s?.let { "${it.ramPercent.roundToInt()}%" } ?: "–",
|
||||
s?.let { "%.1f of %.1f GB".format(it.ramUsedBytes / 1e9, it.ramTotalBytes / 1e9) } ?: "")
|
||||
RingTile(stringResource(R.string.bottom_telemetry_battery).uppercase(), StatsColors.bat, s?.battery?.percent?.let { it / 100f },
|
||||
s?.battery?.percent?.let { "$it%" } ?: "–", s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f W".format(it) } ?: "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowScope.RingTile(label: String, color: Color, fraction: Float?, center: String, sub: String) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(
|
||||
Modifier.weight(1f).clip(RoundedCornerShape(12.dp)).background(pal.surface).padding(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Box(Modifier.size(52.dp), contentAlignment = Alignment.Center) {
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val w = 6.dp.toPx()
|
||||
val tl = Offset(w / 2, w / 2)
|
||||
val sz = Size(size.width - w, size.height - w)
|
||||
drawArc(pal.line, 0f, 360f, false, topLeft = tl, size = sz, style = Stroke(width = w))
|
||||
if (fraction != null) drawArc(color, -90f, (fraction.coerceIn(0f, 1f) * 360f).coerceAtLeast(1f), false, topLeft = tl, size = sz,
|
||||
style = Stroke(width = w, cap = StrokeCap.Round))
|
||||
}
|
||||
Text(center, fontSize = 12.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground, maxLines = 1)
|
||||
}
|
||||
Column {
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = color, letterSpacing = 0.8.sp, maxLines = 1)
|
||||
if (sub.isNotEmpty()) Text(sub, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,8 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.layout.boundsInParent
|
||||
import androidx.compose.ui.layout.layout
|
||||
import androidx.compose.ui.unit.Constraints
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -142,7 +144,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
|
||||
words = {
|
||||
val runtimeStatus: @Composable () -> Unit = {
|
||||
if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s)
|
||||
if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s)
|
||||
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
|
||||
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
||||
}
|
||||
@@ -166,11 +168,17 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
)
|
||||
}
|
||||
|
||||
internal fun Modifier.overhang(by: androidx.compose.ui.unit.Dp = 4.dp): Modifier = layout { measurable, constraints ->
|
||||
val e = by.roundToPx()
|
||||
val placeable = measurable.measure(Constraints.fixed(constraints.maxWidth + e * 2, constraints.maxHeight + e * 2))
|
||||
layout(constraints.maxWidth, constraints.maxHeight) { placeable.place(-e, -e) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun WallFade() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(
|
||||
Modifier.fillMaxSize().overhang().background(
|
||||
Brush.horizontalGradient(
|
||||
0f to colors.background.copy(alpha = 0.97f),
|
||||
0.34f to colors.background.copy(alpha = 0.86f),
|
||||
@@ -179,7 +187,7 @@ internal fun WallFade() {
|
||||
),
|
||||
),
|
||||
)
|
||||
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to colors.background.copy(alpha = 0.9f))))
|
||||
Box(Modifier.fillMaxSize().overhang().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to colors.background.copy(alpha = 0.9f))))
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -60,7 +60,7 @@ internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) {
|
||||
Feature.WIFI -> wifi && locationPermission && locationOn
|
||||
Feature.BRIGHTNESS -> brightness
|
||||
Feature.HOME -> home
|
||||
Feature.SHORTCUTS -> home && shortcuts
|
||||
Feature.SHORTCUTS -> shortcuts
|
||||
}
|
||||
|
||||
internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) }
|
||||
@@ -105,14 +105,12 @@ private fun IntegrationRow(
|
||||
val bg by animateColorAsState(if (flash) pal.signal.copy(alpha = 0.12f) else Color.Transparent, Motion.tw(400), label = "integrationFlash")
|
||||
val wifiLocationOff = feature == Feature.WIFI && state.wifi && state.locationPermission && !state.locationOn
|
||||
val wifiDenied = feature == Feature.WIFI && !state.locationPermission && state.locationBlocked
|
||||
val needsHome = feature == Feature.SHORTCUTS && !state.home
|
||||
val restricted = feature == Feature.SHORTCUTS && !needsHome && !state.shortcuts && state.shortcutsRestricted
|
||||
val maybeRestricted = feature == Feature.SHORTCUTS && !needsHome && !state.shortcuts && !restricted && state.shortcutsTried &&
|
||||
val restricted = feature == Feature.SHORTCUTS && !state.shortcuts && state.shortcutsRestricted
|
||||
val maybeRestricted = feature == Feature.SHORTCUTS && !state.shortcuts && !restricted && state.shortcutsTried &&
|
||||
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU
|
||||
val hint = stringResource(when {
|
||||
wifiLocationOff -> R.string.integration_wifi_location_off
|
||||
wifiDenied -> R.string.integration_wifi_denied
|
||||
needsHome -> R.string.integration_shortcuts_needs_home
|
||||
restricted -> R.string.integration_shortcuts_restricted
|
||||
maybeRestricted -> R.string.integration_shortcuts_maybe_restricted
|
||||
feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint
|
||||
@@ -141,7 +139,7 @@ private fun IntegrationRow(
|
||||
restricted || maybeRestricted -> SecondaryButton(stringResource(R.string.integration_app_info), compact = true, onClick = onAppInfo)
|
||||
}
|
||||
val checked = if (feature == Feature.WIFI) state.wifi && state.locationPermission else on
|
||||
ToggleSwitch(checked, enabled = !needsHome && !restricted, label = stringResource(featureTitle(feature)),
|
||||
ToggleSwitch(checked, enabled = !restricted, label = stringResource(featureTitle(feature)),
|
||||
modifier = Modifier.testTag("integration-action-${feature.name.lowercase()}")) { onFeature(feature) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +124,18 @@ internal enum class StepSide {
|
||||
Right,
|
||||
}
|
||||
|
||||
internal fun fitStepSide(preferred: StepSide, pill: Rect, hostWidth: Float, wanted: Float): StepSide {
|
||||
val leftRoom = pill.right
|
||||
val rightRoom = hostWidth - pill.left
|
||||
val room = if (preferred == StepSide.Left) leftRoom else rightRoom
|
||||
val other = if (preferred == StepSide.Left) rightRoom else leftRoom
|
||||
return if (room >= wanted || other <= room) preferred else if (preferred == StepSide.Left) StepSide.Right else StepSide.Left
|
||||
}
|
||||
|
||||
internal fun stepReach(side: StepSide, pill: Rect, hostWidth: Float, width: Int): Pair<Float, Float> =
|
||||
if (side == StepSide.Left) pill.left to (pill.right - width).coerceAtLeast(0f)
|
||||
else pill.right to (pill.left + width).coerceAtMost(hostWidth)
|
||||
|
||||
internal class StepOutScope(private val items: List<Animatable<Float, AnimationVector1D>>, val first: FocusRequester, val open: Boolean, val maxHeight: Dp) {
|
||||
fun Modifier.stepItem(i: Int): Modifier = graphicsLayer {
|
||||
val v = items[i.coerceIn(0, items.lastIndex)].value
|
||||
@@ -141,7 +153,7 @@ private val OutFillet = 10.dp
|
||||
internal fun StepOut(
|
||||
open: Boolean,
|
||||
pill: Rect,
|
||||
side: StepSide,
|
||||
preferredSide: StepSide,
|
||||
accent: Color,
|
||||
onDismiss: () -> Unit,
|
||||
onClosed: () -> Unit,
|
||||
@@ -166,6 +178,7 @@ internal fun StepOut(
|
||||
val opener = remember { arrayOfNulls<GlideSource>(1) }
|
||||
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
|
||||
var moving by remember { mutableStateOf(false) }
|
||||
val placed = remember { arrayOfNulls<Any>(3) }
|
||||
if (moving) VeilRing()
|
||||
val pull = with(density) { OutPull.toPx() }
|
||||
val corner = pillCorner?.let { with(density) { it.toPx() } } ?: minOf(pill.height, pill.width) / 2f
|
||||
@@ -177,13 +190,18 @@ internal fun StepOut(
|
||||
maxOf(hostHeight - pill.bottom - pull, pill.top - pull).coerceAtLeast(44.dp.toPx()).toDp()
|
||||
}
|
||||
val up = measured?.let { pill.bottom + pull + it.height > hostHeight && pill.top - pull - it.height >= 0f } ?: false
|
||||
val wantedW = with(density) { maxWidth.toPx() }
|
||||
val side = fitStepSide(preferredSide, pill, hostWidth, wantedW)
|
||||
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) {
|
||||
if (!open && !grown) { onClosed(); return@LaunchedEffect }
|
||||
val maxW = wantedW.coerceAtMost(room).coerceAtLeast(pill.width)
|
||||
LaunchedEffect(open, measured, side, pill, hostWidth) {
|
||||
val moved = placed[0] == open && placed[1] == measured
|
||||
val flipped = placed[2] != null && placed[2] != side
|
||||
placed[0] = open; placed[1] = measured; placed[2] = side
|
||||
if (!open && !grown) { if (!moved) onClosed(); return@LaunchedEffect }
|
||||
val c = measured ?: return@LaunchedEffect
|
||||
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)
|
||||
val (rest, out) = stepReach(side, pill, hostWidth, c.width)
|
||||
if (grown && flipped) edge.snapTo(if (open) out else rest)
|
||||
val boxBottom = pill.bottom + pull + c.height
|
||||
if (open) {
|
||||
if (!grown) {
|
||||
@@ -202,11 +220,6 @@ internal fun StepOut(
|
||||
pieces.forEachIndexed { i, a ->
|
||||
launch { delay(Motion.ms(260 + i * 55).toLong()); a.animateTo(1f, Motion.tw(220)) }
|
||||
}
|
||||
if (inputMode.inputMode == InputMode.Keyboard) launch {
|
||||
delay(Motion.ms(300).toLong())
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
opener[0]?.let { o -> if (inputMode.inputMode == InputMode.Keyboard) runCatching { o.requester.requestFocus() } }
|
||||
@@ -225,6 +238,13 @@ internal fun StepOut(
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(open, measured) {
|
||||
if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
delay(Motion.ms(300).toLong())
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
}
|
||||
|
||||
LaunchedEffect(open, grown, inputMode.inputMode) {
|
||||
if (open && grown && inputMode.inputMode == InputMode.Keyboard) { withFrameNanos { }; runCatching { first.requestFocus() } }
|
||||
}
|
||||
@@ -245,8 +265,7 @@ internal fun StepOut(
|
||||
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 })
|
||||
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)
|
||||
val (rest, out) = stepReach(side, pill, hostWidth, c.width)
|
||||
val down = pill.bottom + pull + c.height - pill.bottom
|
||||
val across = kotlin.math.abs(out - rest)
|
||||
val fd = if (down < 1f) 1f else (bottom.value - pill.bottom) / down
|
||||
|
||||
@@ -39,7 +39,7 @@ internal fun StepsLayer(origin: Offset) {
|
||||
androidx.activity.compose.BackHandler(enabled = Steps.open) { Steps.fold() }
|
||||
key(ask) {
|
||||
StepOut(
|
||||
open = Steps.open, pill = ask.anchor.translate(-origin), side = ask.side, accent = ask.accent,
|
||||
open = Steps.open, pill = ask.anchor.translate(-origin), preferredSide = ask.side, accent = ask.accent,
|
||||
onDismiss = { Steps.fold() }, onClosed = { Steps.closed(ask) },
|
||||
pillCorner = ask.pillCorner, maxWidth = ask.maxWidth, items = ask.items, handle = ask.handle, content = ask.content,
|
||||
)
|
||||
|
||||
@@ -621,7 +621,6 @@ private fun GamesView(report: StorageReport, sessionRunning: Boolean, a: FrontEn
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Note(stringResource(R.string.storage_games_note))
|
||||
confirm?.let { g ->
|
||||
// steam://uninstall reaches only the session's client, the selected one.
|
||||
val otherClient = g.x64 != (SessionPrefs.steamClientArch(LocalContext.current) == "x86_64")
|
||||
if (otherClient) AlertDialog(
|
||||
onDismissRequest = { confirm = null },
|
||||
|
||||
@@ -204,22 +204,6 @@ internal fun AchievementRow(a: Achievement, compact: Boolean, modifier: Modifier
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StoreAchievementsCard(game: StoreAchievements.Game, title: String, modifier: Modifier = Modifier) {
|
||||
val label = StoreAchievements.forSource(game.source)?.label ?: return
|
||||
val state = rememberAchievements(game) ?: return
|
||||
var open by remember { mutableStateOf(false) }
|
||||
StoreAchievementsCardContent(label, state, modifier) { open = true }
|
||||
if (open) {
|
||||
VeilRing()
|
||||
Dialog(onDismissRequest = { open = false }, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
|
||||
CompositionLocalProvider(LocalFrontFocus provides null) {
|
||||
SessionAchievementsPanel(label, state, title, veil = Color.Transparent, floating = true, onClose = { open = false })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StoreAchievementsCardContent(label: String, state: AchievementsState, modifier: Modifier = Modifier, onOpen: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
@@ -31,6 +31,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
||||
Store.AMAZON.id -> SourceColours(Color(0xFF3A2A0A), Color(0xFFFFC266), Color(0xFFFF9900))
|
||||
Store.XBOX.id -> SourceColours(Color(0xFF17381B), Color(0xFFC6EDC2), Color(0xFF70C850))
|
||||
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
|
||||
Store.GAMEJOLT.id -> SourceColours(Color(0xFF232E00), Color(0xFFE3FF66), Color(0xFFCCFF00))
|
||||
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
|
||||
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
||||
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
|
||||
@@ -45,6 +46,7 @@ internal fun sourceLabel(source: String): String = when (source) {
|
||||
Store.AMAZON.id -> Store.AMAZON.label
|
||||
Store.XBOX.id -> Store.XBOX.label
|
||||
Store.ITCH.id -> Store.ITCH.label
|
||||
Store.GAMEJOLT.id -> Store.GAMEJOLT.label
|
||||
Store.BATTLENET.id -> Store.BATTLENET.label
|
||||
else -> stringResource(R.string.source_added)
|
||||
}
|
||||
|
||||
@@ -177,7 +177,6 @@ internal fun StoreGameFacts(developer: String, publisher: String, releaseDate: S
|
||||
}
|
||||
}
|
||||
|
||||
/** The headline scores, small enough to sit inside the action capsule. */
|
||||
@Composable
|
||||
internal fun CapsuleScores(scores: GameScores, modifier: Modifier = Modifier) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp), modifier = modifier) {
|
||||
@@ -216,7 +215,6 @@ private fun CapsuleStat(label: String, link: String?, showLabel: Boolean = true,
|
||||
}
|
||||
}
|
||||
|
||||
/** Credits and times as label and value rows, for the details panel. */
|
||||
@Composable
|
||||
internal fun StoreDetailRows(developer: String, publisher: String, releaseDate: String, scores: GameScores) {
|
||||
val released = remember(releaseDate) { GameFacts.releaseLabel(releaseDate) }
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
// `split` is the size of a leading section that starts its own rows; 0 means one continuous grid.
|
||||
internal fun storeGridNeighbor(index: Int, count: Int, columns: Int, direction: Int, split: Int = 0): Int? {
|
||||
if (index !in 0 until count || columns < 1 || direction !in listOf(-1, 1)) return null
|
||||
if (split !in 1 until count) return (index + columns * direction).takeIf { it in 0 until count }
|
||||
|
||||
@@ -130,6 +130,7 @@ import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowseState
|
||||
import com.droiddeck.launcher.stores.itch.ItchBrowseState
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreTab
|
||||
@@ -389,13 +390,13 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
}
|
||||
}
|
||||
},
|
||||
) { key -> GameDetail(key, s, a, heroFocus, backLabel, hopRail = null, onBack = { closeGame() }) }
|
||||
) { key -> GameDetail(key, s, a, heroFocus, backLabel, hopRail = null, onBack = { closeGame() }, inStore = true) }
|
||||
}
|
||||
FlightLayer(hostAt)
|
||||
StoresMotion.step?.let { ask ->
|
||||
key(ask) {
|
||||
StepOut(
|
||||
open = StoresMotion.stepOpen, pill = ask.anchor.translate(-hostAt), side = ask.side, accent = ask.accent,
|
||||
open = StoresMotion.stepOpen, pill = ask.anchor.translate(-hostAt), preferredSide = ask.side, accent = ask.accent,
|
||||
onDismiss = { StoresMotion.fold() }, onClosed = { StoresMotion.closed(ask) },
|
||||
pillCorner = ask.pillCorner, maxWidth = ask.maxWidth, items = ask.items, handle = ask.handle, content = ask.content,
|
||||
)
|
||||
@@ -808,14 +809,6 @@ private fun SignInButton(store: Store, large: Boolean = false) {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StoreLogo(store: Store, size: Dp) {
|
||||
val c = sourceColours(store.id)
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(size).clip(Shape14).background(c.fill).border(1.dp, c.dot.copy(alpha = 0.5f), Shape14)) {
|
||||
Text(store.shortLabel, fontSize = (size.value / 4).sp, fontWeight = FontWeight.Black, color = c.ink, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun Storefront(
|
||||
@@ -835,8 +828,10 @@ private fun Storefront(
|
||||
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.accessible
|
||||
fun shelf(l: List<CatalogItem>?) = l?.filter(::shown)
|
||||
LaunchedEffect(store, q) { StoresState.search(ctx, store, q) }
|
||||
val browsing = store == Store.ITCH && q.isEmpty() && ItchBrowseState.active
|
||||
val browseItems = if (browsing) ItchBrowseState.items else emptyList()
|
||||
val gameJolt = store == Store.GAMEJOLT
|
||||
LaunchedEffect(gameJolt, s.storesShowMature) { if (gameJolt) GameJoltBrowseState.sync(ctx, s.storesShowMature) }
|
||||
val browsing = q.isEmpty() && ((store == Store.ITCH && ItchBrowseState.active) || gameJolt)
|
||||
val browseItems = if (!browsing) emptyList() else if (gameJolt) GameJoltBrowseState.items else ItchBrowseState.items
|
||||
val catalog = store == Store.BATTLENET && q.isEmpty()
|
||||
val visible = remember(found, library, shelves, q, s.storesShowMature, browsing, browseItems, catalog) {
|
||||
if (catalog) shelf(shelves?.trending) ?: emptyList()
|
||||
@@ -848,8 +843,10 @@ private fun Storefront(
|
||||
.filter { (it.title.lowercase().contains(q) || it.key in foundKeys) && shown(it) }
|
||||
}
|
||||
val nothing = stringResource(when {
|
||||
browsing && ItchBrowseState.loading -> R.string.stores_shelves_loading
|
||||
browsing && ItchBrowseState.failed -> R.string.stores_itch_browse_failed
|
||||
browsing && gameJolt && GameJoltBrowseState.loading -> R.string.stores_shelves_loading
|
||||
browsing && gameJolt && GameJoltBrowseState.failed -> R.string.stores_gamejolt_browse_failed
|
||||
browsing && !gameJolt && ItchBrowseState.loading -> R.string.stores_shelves_loading
|
||||
browsing && !gameJolt && ItchBrowseState.failed -> R.string.stores_itch_browse_failed
|
||||
catalog && shelves == null -> R.string.stores_shelves_loading
|
||||
else -> R.string.stores_nothing_matches
|
||||
})
|
||||
@@ -862,11 +859,11 @@ private fun Storefront(
|
||||
val focus = LocalFrontFocus.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val searching = q.isNotEmpty() || browsing || catalog
|
||||
// A bar only while there is nothing else to look at: no shelves yet and no search results.
|
||||
val bareTab = if (searching) visible.isEmpty() else shelves == null || shelves.isEmpty
|
||||
val barLine = StoresState.status[store]?.takeIf { bareTab && syncCount(it) != null }
|
||||
val itchBar = store == Store.ITCH && q.isEmpty()
|
||||
val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar) 1 else 0) + (if (catalog) 1 else 0)
|
||||
val gameJoltBar = gameJolt && q.isEmpty()
|
||||
val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar || gameJoltBar) 1 else 0) + (if (catalog) 1 else 0)
|
||||
val card: @Composable (CatalogItem) -> Unit = { item ->
|
||||
val first = if (searching) item.key == visible.firstOrNull()?.key else !firstPlaced
|
||||
firstPlaced = true
|
||||
@@ -915,12 +912,14 @@ private fun Storefront(
|
||||
barLine?.let { line -> item(key = "sync", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { SyncBar(line) } } }
|
||||
StoresState.problems[store]?.let { line -> item(key = "problem", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { Box(Modifier.padding(bottom = 8.dp)) { Note(line) } } } }
|
||||
if (itchBar) item(key = "itch-browse-bar", span = { GridItemSpan(maxLineSpan) }) { ItchBrowseBar() }
|
||||
if (gameJoltBar) item(key = "gamejolt-browse-bar", span = { GridItemSpan(maxLineSpan) }) { GameJoltBrowseBar(s.storesShowMature) }
|
||||
if (catalog) item(key = "catalog-label", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Box(Modifier.padding(top = 10.dp)) { SectionLabel(stringResource(R.string.bnet_store)) }
|
||||
}
|
||||
if (searching) {
|
||||
storeGrid(visible, nothing, card)
|
||||
if (browsing) item(key = "itch-more", span = { GridItemSpan(maxLineSpan) }) { ItchLoadMore() }
|
||||
if (browsing && gameJolt) item(key = "gamejolt-more", span = { GridItemSpan(maxLineSpan) }) { GameJoltLoadMore() }
|
||||
else if (browsing) item(key = "itch-more", span = { GridItemSpan(maxLineSpan) }) { ItchLoadMore() }
|
||||
} else item(key = "shelves", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column {
|
||||
Shelf(stringResource(R.string.stores_shelf_new), shelf(shelves?.whatsNew), card)
|
||||
@@ -1156,6 +1155,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
|
||||
Store.AMAZON -> Color(0xFFFF9900) to Color(0xFFE07800)
|
||||
Store.XBOX -> Color(0xFF70C850) to Color(0xFF107C10)
|
||||
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
|
||||
Store.GAMEJOLT -> Color(0xFFCCFF00) to Color(0xFFA3CC00)
|
||||
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
|
||||
null -> return base
|
||||
}
|
||||
@@ -1423,15 +1423,6 @@ internal fun ConfirmButton(label: String, confirm: String, compact: Boolean = fa
|
||||
SecondaryButton(if (armed) confirm else label, compact = compact) { if (!armed) armed = true else { armed = false; onConfirm() } }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun stageLabel(stage: DownloadStage): String = when (stage) {
|
||||
DownloadStage.MANIFEST -> stringResource(R.string.stores_stage_manifest)
|
||||
DownloadStage.DOWNLOAD -> stringResource(R.string.stores_stage_download)
|
||||
DownloadStage.VERIFY -> stringResource(R.string.stores_stage_verify)
|
||||
DownloadStage.INSTALL -> stringResource(R.string.stores_stage_install)
|
||||
DownloadStage.DONE -> stringResource(R.string.stores_stage_done)
|
||||
}
|
||||
|
||||
internal fun openStoreUrl(ctx: android.content.Context, item: CatalogItem) = openUrl(ctx, item.storeUrl)
|
||||
|
||||
internal fun openUrl(ctx: android.content.Context, url: String) {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
internal fun fitByPriority(widths: IntArray, priorities: IntArray, spacing: Int, maxWidth: Int): BooleanArray {
|
||||
val keep = BooleanArray(widths.size)
|
||||
var used = 0
|
||||
var count = 0
|
||||
for (i in widths.indices.sortedWith(compareBy({ priorities[it] }, { it }))) {
|
||||
val add = widths[i] + if (count > 0) spacing else 0
|
||||
if (used + add > maxWidth) break
|
||||
keep[i] = true
|
||||
used += add
|
||||
count++
|
||||
}
|
||||
return keep
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.sync.SyncPrefs
|
||||
import com.droiddeck.launcher.sync.Syncthing
|
||||
import java.io.File
|
||||
|
||||
@Composable
|
||||
internal fun SyncAdvancedPage(host: MenuHost, onBack: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
var runMode by remember { mutableStateOf(SyncPrefs.runMode(ctx)) }
|
||||
var wifiOnly by remember { mutableStateOf(SyncPrefs.wifiOnly(ctx)) }
|
||||
var pauseInGames by remember { mutableStateOf(SyncPrefs.pauseInGames(ctx)) }
|
||||
var confirmReset by rememberSaveable { mutableStateOf(false) }
|
||||
if (confirmReset) ResetDialog(onDismiss = { confirmReset = false }) { Syncthing.reset(ctx) }
|
||||
val ports = Syncthing.ports
|
||||
SettingsPage(host, stringResource(R.string.sync_advanced), onBack, eyebrow = stringResource(R.string.setup_tab_sync)) {
|
||||
PairedColumns(
|
||||
{
|
||||
SettingsGroup(stringResource(R.string.sync_ports)) {
|
||||
PortRow(stringResource(R.string.sync_port_sync), ports?.sync?.toString())
|
||||
PortRow(stringResource(R.string.sync_port_discovery), ports?.discovery?.toString())
|
||||
ActionRow(stringResource(R.string.sync_repick), stringResource(R.string.sync_repick_hint), stringResource(R.string.sync_repick_button), onClick = { Syncthing.restart() })
|
||||
}
|
||||
},
|
||||
{
|
||||
SettingsGroup(stringResource(R.string.sync_running_group)) {
|
||||
ChoiceRow(
|
||||
host, "sync-run", stringResource(R.string.sync_run), null,
|
||||
listOf(SyncPrefs.RUN_WHILE_OPEN to stringResource(R.string.sync_run_open), SyncPrefs.RUN_BACKGROUND to stringResource(R.string.sync_run_background)),
|
||||
runMode, stacked = true,
|
||||
) { SyncPrefs.setRunMode(ctx, it); runMode = it; Syncthing.settingsChanged() }
|
||||
ToggleRow(host, "sync-wifi", stringResource(R.string.sync_wifi_only), null, wifiOnly) {
|
||||
SyncPrefs.setWifiOnly(ctx, it); wifiOnly = it; Syncthing.settingsChanged()
|
||||
}
|
||||
ToggleRow(host, "sync-games", stringResource(R.string.sync_pause_games), null, pauseInGames) {
|
||||
SyncPrefs.setPauseInGames(ctx, it); pauseInGames = it; Syncthing.settingsChanged()
|
||||
}
|
||||
ActionRow(stringResource(R.string.sync_logs), stringResource(R.string.sync_logs_hint), stringResource(R.string.sync_logs_share), onClick = { shareLog(ctx) })
|
||||
}
|
||||
},
|
||||
)
|
||||
SettingsGroup(stringResource(R.string.sync_reset_group)) {
|
||||
SettingsRow(stringResource(R.string.sync_api_key), Syncthing.apiKeyTail?.let { "••••••••••••••••••••$it" }) {
|
||||
SecondaryButton(stringResource(R.string.sync_regenerate), enabled = Syncthing.phase == Syncthing.Phase.RUNNING, compact = true) { Syncthing.regenerateApiKey() }
|
||||
}
|
||||
ActionRow(stringResource(R.string.sync_reset), stringResource(R.string.sync_reset_hint), stringResource(R.string.sync_reset_button), onClick = { confirmReset = true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PortRow(label: String, value: String?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
SettingsRow(label, null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(value ?: "—", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Text(stringResource(R.string.common_auto).uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ResetDialog(onDismiss: () -> Unit, onReset: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
AppDialog(shown, close, "syncReset", wide = false, maxWidth = 480.dp) {
|
||||
DialogTitleRow(stringResource(R.string.sync_reset_confirm_title), onClose = close)
|
||||
Text(stringResource(R.string.sync_reset_hint), fontSize = 13.5.sp, color = colors.onSurfaceVariant)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = close)
|
||||
PrimaryButton(stringResource(R.string.sync_reset_button), compact = true) { onReset(); close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun shareLog(context: Context) {
|
||||
val log = Syncthing.logFile(context).takeIf { it.isFile } ?: return
|
||||
val out = File(File(context.cacheDir, "share").apply { mkdirs() }, "syncthing-log.txt")
|
||||
log.copyTo(out, overwrite = true)
|
||||
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", out)
|
||||
val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_STREAM, uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
send.clipData = ClipData.newRawUri(out.name, uri)
|
||||
context.startActivity(Intent.createChooser(send, context.getString(R.string.logshare_chooser)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.outlined.CreateNewFolder
|
||||
import androidx.compose.material.icons.outlined.Folder
|
||||
import androidx.compose.material.icons.outlined.FolderSpecial
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.SdCard
|
||||
import androidx.compose.material.icons.outlined.Smartphone
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.sync.Syncthing
|
||||
import java.io.File
|
||||
|
||||
internal class SyncLocation(val root: File, val label: String, val icon: ImageVector)
|
||||
|
||||
internal fun containerHome(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||
|
||||
internal fun syncLocations(context: Context): List<SyncLocation> {
|
||||
val volumes = pickVolumes(context)
|
||||
val roots = Syncthing.storageRoots(context)
|
||||
val shared = roots.drop(1).mapIndexed { i, root ->
|
||||
val volume = volumes.firstOrNull { root.path.startsWith(it.root.path + "/") }
|
||||
if (i == 0) SyncLocation(root, context.getString(R.string.sync_location_shared), Icons.Outlined.Smartphone)
|
||||
else SyncLocation(root, context.getString(R.string.sync_location_card, volume?.label ?: root.path), Icons.Outlined.SdCard)
|
||||
}
|
||||
val home = containerHome(context).takeIf { it.isDirectory }?.let { SyncLocation(it, context.getString(R.string.sync_location_home), Icons.Outlined.Home) }
|
||||
return listOfNotNull(home, SyncLocation(Syncthing.folderRoot(context), context.getString(R.string.sync_location_sync), Icons.Outlined.FolderSpecial)) +
|
||||
shared + SyncLocation(roots.first(), context.getString(R.string.sync_location_app), Icons.Outlined.Folder)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SyncFolderPicker(title: String, suggestedName: String?, onDismiss: () -> Unit, onPick: (File) -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val density = LocalDensity.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
val locations = remember { syncLocations(ctx) }
|
||||
val guard = remember { Syncthing.guard(ctx) }
|
||||
fun locationOf(d: File) = locations.filter { d.path == it.root.path || d.path.startsWith(it.root.path + "/") }.maxByOrNull { it.root.path.length }
|
||||
var dir by remember { mutableStateOf<File?>(containerHome(ctx).takeIf { it.isDirectory } ?: Syncthing.folderRoot(ctx).also { it.mkdirs() }) }
|
||||
var refresh by remember { mutableIntStateOf(0) }
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
val location = dir?.let { locationOf(it) }
|
||||
val up = { dir = dir?.let { d -> if (location == null || d.path == location.root.path) null else d.parentFile } }
|
||||
val back = { if (dir == null) close() else up() }
|
||||
val first = remember(dir) { FocusRequester() }
|
||||
LaunchedEffect(dir) { focusWithinFrames({ false }) { first } }
|
||||
val folders = remember(dir, refresh) {
|
||||
dir?.listFiles()?.filter { it.isDirectory && it.canRead() && guard.browsable(it) }
|
||||
?.sortedBy { it.name.lowercase() }.orEmpty()
|
||||
}
|
||||
var locked by remember { mutableStateOf<Dp?>(null) }
|
||||
if (naming) {
|
||||
TextEntryDialog(stringResource(R.string.sync_new_folder), suggestedName.orEmpty(), onDismiss = { naming = false }) { name ->
|
||||
val parent = dir
|
||||
if (parent != null && validName(name)) {
|
||||
val created = File(parent, name)
|
||||
if (created.isDirectory || created.mkdirs()) { dir = created; refresh++ }
|
||||
}
|
||||
}
|
||||
}
|
||||
AppDialog(
|
||||
shown, close, "syncFolderPicker", wide = false, maxWidth = 520.dp, width = locked, fitContent = locked == null, back = back,
|
||||
modifier = Modifier.onSizeChanged { if (locked == null && it.width > 0) locked = with(density) { it.width.toDp() } },
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
DialogTitleRow(title, onClose = close)
|
||||
if (dir != null && location != null) {
|
||||
val crumbs = listOf(location.label) + dir!!.path.removePrefix(location.root.path).split('/').filter { it.isNotEmpty() }
|
||||
Text(crumbs.joinToString(" › "), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
val maxHeight = (LocalConfiguration.current.screenHeightDp * 0.7f).dp
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()).padding(top = 4.dp),
|
||||
) {
|
||||
if (dir == null) {
|
||||
locations.forEachIndexed { i, l ->
|
||||
key(l.root.path) { PickerRow(l.icon, l.label, null, tall = true, focus = if (i == 0) first else null) { dir = l.root.also { it.mkdirs() } } }
|
||||
}
|
||||
} else {
|
||||
PickerRow(Icons.AutoMirrored.Outlined.ArrowBack, "..", null, focus = first, onClick = up)
|
||||
PickerRow(Icons.Filled.Check, stringResource(R.string.sync_use_folder), null, accent = true, enabled = guard.allows(dir!!.path)) {
|
||||
onPick(dir!!); close()
|
||||
}
|
||||
PickerRow(Icons.Outlined.CreateNewFolder, stringResource(R.string.sync_new_folder), null) { naming = true }
|
||||
for (f in folders) key(f.path) {
|
||||
PickerRow(Icons.Outlined.Folder, f.name, null) { dir = f }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun validName(name: String) = name.isNotBlank() && '/' !in name && name != "." && name != ".."
|
||||
@@ -0,0 +1,436 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.text.format.DateUtils
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Block
|
||||
import androidx.compose.material.icons.outlined.Sync
|
||||
import androidx.compose.material.icons.outlined.WarningAmber
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.FilterQuality
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.sync.SyncDevice
|
||||
import com.droiddeck.launcher.sync.SyncFolder
|
||||
import com.droiddeck.launcher.sync.SyncPendingFolder
|
||||
import com.droiddeck.launcher.sync.SyncSnapshot
|
||||
import com.droiddeck.launcher.sync.Syncthing
|
||||
import com.droiddeck.launcher.sync.SyncthingWebActivity
|
||||
import java.io.File
|
||||
|
||||
@Composable
|
||||
internal fun SyncPanel(host: MenuHost, runtimeReady: Boolean, onAdvanced: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
DisposableEffect(Unit) { val release = Syncthing.watch(); onDispose { release() } }
|
||||
var showId by rememberSaveable { mutableStateOf(false) }
|
||||
var confirmOff by rememberSaveable { mutableStateOf(false) }
|
||||
val snap = Syncthing.snapshot
|
||||
if (showId && snap != null) DeviceIdDialog(snap.myId) { showId = false }
|
||||
if (confirmOff) TurnOffDialog(onDismiss = { confirmOff = false }) { forget ->
|
||||
Syncthing.setEnabled(ctx, false, forget)
|
||||
}
|
||||
val phase = Syncthing.phase
|
||||
when {
|
||||
phase == Syncthing.Phase.FAILED -> SyncFailed(
|
||||
if (Syncthing.failure == Syncthing.FAILURE_MISSING) stringResource(R.string.sync_missing) else Syncthing.failure.orEmpty(),
|
||||
onRetry = { Syncthing.restart() }, onAdvanced = onAdvanced, onOff = { confirmOff = true })
|
||||
!Syncthing.enabled -> SyncOff(host, runtimeReady) { Syncthing.setEnabled(ctx, true) }
|
||||
phase != Syncthing.Phase.RUNNING || snap == null -> SyncStarting()
|
||||
else -> SyncRunning(snap, onShowId = { showId = true }, onAdvanced = onAdvanced, onOff = { confirmOff = true })
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncOff(host: MenuHost, runtimeReady: Boolean, onEnable: () -> Unit) {
|
||||
val missing = Syncthing.failure == Syncthing.FAILURE_MISSING
|
||||
val hint = when {
|
||||
missing -> R.string.sync_missing
|
||||
!runtimeReady -> R.string.sync_needs_runtime
|
||||
else -> R.string.sync_enable_hint
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.sync_group)) {
|
||||
ToggleRow(
|
||||
host, "sync-enable", stringResource(R.string.sync_enable), stringResource(hint), false, enabled = !missing && runtimeReady,
|
||||
) { if (it) onEnable() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncStarting() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 96.dp),
|
||||
) {
|
||||
CircularProgressIndicator(strokeWidth = 3.dp, color = LocalPalette.current.signal, modifier = Modifier.size(40.dp))
|
||||
Text(stringResource(R.string.sync_starting), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncFailed(reason: String, onRetry: () -> Unit, onAdvanced: () -> Unit, onOff: () -> Unit) {
|
||||
SettingsGroup(stringResource(R.string.sync_group)) {
|
||||
SettingsRow(stringResource(R.string.sync_status_failed), reason) {
|
||||
SecondaryButton(stringResource(R.string.sync_failed_retry), compact = true, onClick = onRetry)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.sync_advanced), stringResource(R.string.sync_advanced_hint)) {
|
||||
SecondaryButton(stringResource(R.string.sync_open), compact = true, onClick = onAdvanced)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.sync_running), stringResource(R.string.sync_running_hint)) {
|
||||
ToggleSwitch(true, label = stringResource(R.string.sync_running)) { if (!it) onOff() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncRunning(snap: SyncSnapshot, onShowId: () -> Unit, onAdvanced: () -> Unit, onOff: () -> Unit) {
|
||||
PairedColumns(
|
||||
{
|
||||
SettingsGroup(stringResource(R.string.sync_group)) {
|
||||
StatusCard(snap)
|
||||
SettingsRow(stringResource(R.string.sync_running), stringResource(R.string.sync_running_hint)) {
|
||||
ToggleSwitch(true, label = stringResource(R.string.sync_running)) { if (!it) onOff() }
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.sync_this_device)) {
|
||||
SettingsRow(stringResource(R.string.sync_device_id), shortId(snap.myId)) {
|
||||
SecondaryButton(stringResource(R.string.sync_show_qr), compact = true, onClick = onShowId)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.sync_advanced), stringResource(R.string.sync_advanced_hint)) {
|
||||
SecondaryButton(stringResource(R.string.sync_open), compact = true, onClick = onAdvanced)
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
Waiting(snap)
|
||||
SettingsGroup(stringResource(R.string.sync_folders)) {
|
||||
if (snap.folders.isEmpty()) SettingsRow(stringResource(R.string.sync_no_folders), null) {}
|
||||
snap.folders.sortedByDescending { it.blocked }.forEach { FolderRow(it) }
|
||||
AddFolderRow(snap.devices)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.sync_devices)) {
|
||||
if (snap.devices.isEmpty()) SettingsRow(stringResource(R.string.sync_no_devices), null) {}
|
||||
snap.devices.forEach { DeviceRow(it) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PairedColumns(left: @Composable ColumnScope.() -> Unit, right: @Composable ColumnScope.() -> Unit) {
|
||||
if (LocalNarrowPane.current) {
|
||||
Column { left(); right() }
|
||||
return
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(20.dp), verticalAlignment = Alignment.Top, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.weight(1f)) { left() }
|
||||
Column(Modifier.weight(1f)) { right() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusCard(snap: SyncSnapshot) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val paused = Syncthing.pauseRequested || Syncthing.devicesPaused
|
||||
val (headline, tint) = when {
|
||||
Syncthing.pauseRequested && Syncthing.devicesPaused -> stringResource(R.string.sync_status_paused) to colors.onSurfaceVariant
|
||||
Syncthing.pauseRequested -> stringResource(R.string.sync_status_pausing) to colors.onSurfaceVariant
|
||||
Syncthing.devicesPaused -> stringResource(R.string.sync_status_resuming) to colors.onSurfaceVariant
|
||||
snap.needsAttention -> stringResource(R.string.sync_status_attention) to AttentionAmber
|
||||
snap.syncing -> stringResource(R.string.sync_status_syncing) to pal.signal
|
||||
else -> stringResource(R.string.sync_status_up_to_date) to pal.good
|
||||
}
|
||||
val detail = when (Syncthing.autoPause) {
|
||||
Syncthing.AutoPause.WIFI -> stringResource(R.string.sync_paused_wifi)
|
||||
Syncthing.AutoPause.GAME -> stringResource(R.string.sync_paused_game)
|
||||
null -> if (snap.syncing && !paused) stringResource(R.string.sync_left, Formatter.formatShortFileSize(ctx, snap.needBytes))
|
||||
else stringResource(R.string.sync_summary, snap.folders.size, snap.devices.count { it.connected }, snap.devices.size)
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
when {
|
||||
snap.syncing && !paused -> Icon(Icons.Outlined.Sync, null, tint = tint, modifier = Modifier.size(22.dp))
|
||||
snap.needsAttention && !paused -> Icon(Icons.Outlined.WarningAmber, null, tint = tint, modifier = Modifier.size(22.dp))
|
||||
else -> Box(Modifier.size(12.dp).clip(CircleShape).background(tint))
|
||||
}
|
||||
Text(headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
if (snap.syncing && !paused) Text("${snap.percent}%", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = pal.signal)
|
||||
}
|
||||
if (snap.syncing && !paused) LinearProgressIndicator(
|
||||
progress = { snap.percent / 100f }, color = pal.signal, trackColor = pal.line, modifier = Modifier.fillMaxWidth().height(4.dp).clip(CircleShape),
|
||||
)
|
||||
Text(detail, fontSize = 12.5.sp, color = colors.onSurfaceVariant)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Text("↓ ${rate(ctx, snap.inBytesPerSecond)}", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Text("↑ ${rate(ctx, snap.outBytesPerSecond)}", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
PrimaryButton(stringResource(R.string.sync_open_web_ui), compact = true, modifier = Modifier.weight(1f)) { openWebUi(ctx) }
|
||||
SecondaryButton(stringResource(if (Syncthing.userPaused) R.string.sync_resume else R.string.sync_pause), compact = true) {
|
||||
Syncthing.setPaused(ctx, !Syncthing.userPaused)
|
||||
}
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Waiting(snap: SyncSnapshot) {
|
||||
if (snap.pendingFolders.isEmpty() && snap.pendingDevices.isEmpty()) return
|
||||
val ctx = LocalContext.current
|
||||
var accepting by remember { mutableStateOf<SyncPendingFolder?>(null) }
|
||||
accepting?.let { f ->
|
||||
SyncFolderPicker(stringResource(R.string.sync_accept_title, f.label), f.label, onDismiss = { accepting = null }) { dir ->
|
||||
Syncthing.addFolder(ctx, dir, f.label, listOf(f.deviceId), f.id) { ok -> if (!ok) addFailed(ctx) }
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.sync_waiting)) {
|
||||
snap.pendingDevices.forEach { name ->
|
||||
SettingsRow(stringResource(R.string.sync_pending_device, name), null, highlighted = true) {
|
||||
SecondaryButton(stringResource(R.string.sync_review), compact = true) { openWebUi(ctx) }
|
||||
}
|
||||
}
|
||||
snap.pendingFolders.forEach { f ->
|
||||
SettingsRow(stringResource(R.string.sync_pending_folder, f.offeredBy, f.label), stringResource(R.string.sync_pending_folder_hint), highlighted = true) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
SecondaryButton(stringResource(R.string.sync_review), compact = true) { openWebUi(ctx) }
|
||||
PrimaryButton(stringResource(R.string.sync_accept), compact = true) { accepting = f }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddFolderRow(devices: List<SyncDevice>) {
|
||||
val ctx = LocalContext.current
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
var picked by remember { mutableStateOf<File?>(null) }
|
||||
if (picking) SyncFolderPicker(stringResource(R.string.sync_add_folder), null, onDismiss = { picking = false }) { picked = it }
|
||||
picked?.let { dir ->
|
||||
ShareFolderDialog(dir, devices, onDismiss = { picked = null }) { chosen ->
|
||||
Syncthing.addFolder(ctx, dir, dir.name, chosen) { ok -> if (!ok) addFailed(ctx) }
|
||||
}
|
||||
}
|
||||
SettingsRow(stringResource(R.string.sync_add_folder), stringResource(R.string.sync_add_folder_hint)) {
|
||||
SecondaryButton(stringResource(R.string.sync_choose), compact = true) { picking = true }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ShareFolderDialog(folder: File, devices: List<SyncDevice>, onDismiss: () -> Unit, onAdd: (List<String>) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
val chosen = remember { mutableStateListOf<String>() }
|
||||
AppDialog(shown, close, "syncShareFolder", wide = false, maxWidth = 520.dp) {
|
||||
DialogTitleRow(folder.name, onClose = close)
|
||||
Text(folder.path, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
if (devices.isEmpty()) {
|
||||
Text(stringResource(R.string.sync_share_none), fontSize = 13.5.sp, color = colors.onSurfaceVariant)
|
||||
} else {
|
||||
Text(stringResource(R.string.sync_share_with), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
devices.forEach { d ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12).border(1.dp, pal.line, Shape12).background(colors.background).padding(end = 12.dp),
|
||||
) {
|
||||
Checkbox(d.id in chosen, { if (it) chosen.add(d.id) else chosen.remove(d.id) })
|
||||
Text(d.name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = close)
|
||||
PrimaryButton(stringResource(R.string.sync_add), compact = true) { onAdd(chosen.toList()); close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addFailed(context: Context) {
|
||||
android.widget.Toast.makeText(context, R.string.sync_add_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderRow(f: SyncFolder) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
if (f.blocked) {
|
||||
Column(Modifier.fillMaxWidth().background(colors.error.copy(alpha = 0.06f)).padding(horizontal = 14.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Icon(Icons.Outlined.Block, null, tint = colors.error, modifier = Modifier.size(18.dp))
|
||||
Text(f.label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
Text(stringResource(R.string.sync_folder_blocked), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.error)
|
||||
}
|
||||
Text(f.path, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(stringResource(R.string.sync_folder_blocked_hint), fontSize = 12.5.sp, color = colors.onSurfaceVariant)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 4.dp)) {
|
||||
SecondaryButton(stringResource(R.string.sync_remove_folder), compact = true) { Syncthing.removeFolder(f.id) }
|
||||
SecondaryButton(stringResource(R.string.sync_open_web_ui), compact = true) { openWebUi(ctx) }
|
||||
}
|
||||
Text(stringResource(R.string.sync_remove_folder_hint), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
return
|
||||
}
|
||||
val (state, tint) = when {
|
||||
f.paused -> stringResource(R.string.sync_folder_paused) to colors.onSurfaceVariant
|
||||
f.syncing -> stringResource(R.string.sync_folder_syncing, percent(f)) to pal.signal
|
||||
f.outOfSync -> stringResource(R.string.sync_folder_out_of_sync) to AttentionAmber
|
||||
f.state == "scanning" || f.state == "scan-waiting" -> stringResource(R.string.sync_folder_scanning) to colors.onSurfaceVariant
|
||||
else -> stringResource(R.string.sync_folder_up_to_date) to pal.good
|
||||
}
|
||||
val detail = when {
|
||||
f.errors > 0 -> stringResource(R.string.sync_folder_errors, f.errors)
|
||||
f.sharedWith.isEmpty() -> Formatter.formatShortFileSize(ctx, f.globalBytes)
|
||||
else -> stringResource(R.string.sync_folder_detail, Formatter.formatShortFileSize(ctx, f.globalBytes), f.sharedWith.joinToString(", "))
|
||||
}
|
||||
SettingsRow(f.label, detail) { StateLabel(state, tint) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeviceRow(d: SyncDevice) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val detail = when {
|
||||
d.connected -> d.address?.substringAfter("://")
|
||||
d.lastSeen != null -> stringResource(R.string.sync_last_seen, DateUtils.getRelativeTimeSpanString(d.lastSeen).toString())
|
||||
else -> null
|
||||
}
|
||||
SettingsRow(d.name, detail) {
|
||||
if (d.connected) StateLabel(stringResource(R.string.sync_connected), pal.good)
|
||||
else StateLabel(stringResource(R.string.sync_offline), colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StateLabel(text: String, tint: Color) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
Box(Modifier.size(9.dp).clip(CircleShape).background(tint))
|
||||
Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeviceIdDialog(id: String, onDismiss: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
val qr = remember(id) { qrBitmap(id) }
|
||||
AppDialog(shown, close, "syncDeviceId", wide = true, maxWidth = 640.dp) {
|
||||
DialogTitleRow(stringResource(R.string.sync_device_id_title), onClose = close)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(22.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Image(qr, stringResource(R.string.sync_device_id), filterQuality = FilterQuality.None,
|
||||
modifier = Modifier.size(208.dp).clip(Shape14).background(Color.White).padding(10.dp))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.weight(1f)) {
|
||||
Text(id.chunked(32).joinToString("\n"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, fontFamily = FontFamily.Monospace,
|
||||
color = colors.onBackground, lineHeight = 26.sp)
|
||||
Text(stringResource(R.string.sync_device_id_hint), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.sync_copy), compact = true) {
|
||||
ctx.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("Syncthing device ID", id))
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.sync_share), compact = true) {
|
||||
ctx.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, id), null))
|
||||
}
|
||||
PrimaryButton(stringResource(R.string.sync_done), compact = true, onClick = close)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TurnOffDialog(onDismiss: () -> Unit, onTurnOff: (Boolean) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
var forget by remember { mutableStateOf(false) }
|
||||
AppDialog(shown, close, "syncTurnOff", wide = false, maxWidth = 520.dp) {
|
||||
DialogTitleRow(stringResource(R.string.sync_off_title), onClose = close)
|
||||
Text(stringResource(R.string.sync_off_body), fontSize = 13.5.sp, color = colors.onSurfaceVariant)
|
||||
Row(
|
||||
verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12).border(1.dp, pal.line, Shape12).background(colors.background).padding(end = 12.dp, top = 2.dp, bottom = 8.dp),
|
||||
) {
|
||||
Checkbox(forget, { forget = it })
|
||||
Column(Modifier.padding(top = 12.dp)) {
|
||||
Text(stringResource(R.string.sync_off_forget), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.sync_off_forget_hint), fontSize = 12.5.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = close)
|
||||
PrimaryButton(stringResource(R.string.sync_turn_off), compact = true) { onTurnOff(forget); close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun openWebUi(context: Context) {
|
||||
context.startActivity(Intent(context, SyncthingWebActivity::class.java))
|
||||
}
|
||||
|
||||
private fun shortId(id: String) = if (id.length > 16) "${id.take(7)}-…-${id.takeLast(7)}" else id
|
||||
|
||||
private fun rate(context: Context, bytesPerSecond: Long) = Formatter.formatShortFileSize(context, bytesPerSecond) + "/s"
|
||||
|
||||
private fun percent(f: SyncFolder): Int =
|
||||
if (f.globalBytes <= 0) 0 else (((f.globalBytes - f.needBytes).coerceAtLeast(0) * 100) / f.globalBytes).toInt().coerceIn(0, 99)
|
||||
|
||||
private fun qrBitmap(text: String): ImageBitmap {
|
||||
val matrix = com.google.zxing.qrcode.QRCodeWriter().encode(text, com.google.zxing.BarcodeFormat.QR_CODE, 0, 0)
|
||||
val bitmap = android.graphics.Bitmap.createBitmap(matrix.width, matrix.height, android.graphics.Bitmap.Config.ARGB_8888)
|
||||
for (x in 0 until matrix.width) for (y in 0 until matrix.height) {
|
||||
bitmap.setPixel(x, y, if (matrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE)
|
||||
}
|
||||
return bitmap.asImageBitmap()
|
||||
}
|
||||
@@ -52,7 +52,6 @@ object Themes {
|
||||
const val DEFAULT_PRIMARY = 0xFF8B5CF6.toInt()
|
||||
const val DEFAULT_SECONDARY = 0xFF22D3EE.toInt()
|
||||
|
||||
/** The two colours of the custom Gradient theme: primary, then secondary. Changing them restyles the app at once. */
|
||||
var gradientColors by mutableStateOf(DEFAULT_PRIMARY to DEFAULT_SECONDARY)
|
||||
private set
|
||||
|
||||
@@ -60,11 +59,9 @@ object Themes {
|
||||
const val DEFAULT_RGB_SPEED = 3
|
||||
const val RGB_HUE_STEP = 3f
|
||||
|
||||
/** How fast Inner Gamer cycles, 1 (slow) to [RGB_SPEEDS] (fast). */
|
||||
var rgbSpeed by mutableStateOf(DEFAULT_RGB_SPEED)
|
||||
private set
|
||||
|
||||
/** Where Inner Gamer is on the colour wheel, in whole [RGB_HUE_STEP] steps so the app restyles only when the colour visibly moves. */
|
||||
var rgbHue by mutableStateOf(0f)
|
||||
private set
|
||||
|
||||
@@ -78,7 +75,6 @@ object Themes {
|
||||
rgbSpeed = value
|
||||
}
|
||||
|
||||
/** Milliseconds for one trip round the colour wheel. */
|
||||
fun rgbCycleMillis(speed: Int): Int = 30_000 / speed.coerceIn(1, RGB_SPEEDS)
|
||||
|
||||
fun loadGradient(context: Context) {
|
||||
@@ -86,7 +82,6 @@ object Themes {
|
||||
rgbSpeed = SessionPrefs.rgbSpeed(context)
|
||||
}
|
||||
|
||||
/** The Inner Gamer palette at one point on the colour wheel. */
|
||||
fun innerGamer(hue: Float): Palette = ThemeColors.palette(
|
||||
Color.hsv(hue % 360f, 0.9f, 1f).toArgb(), Color.hsv((hue + 60f) % 360f, 0.9f, 1f).toArgb(),
|
||||
R.string.theme_inner_gamer, R.string.theme_inner_gamer_detail, INNER_GAMER,
|
||||
@@ -97,7 +92,6 @@ object Themes {
|
||||
gradientColors = primary to secondary
|
||||
}
|
||||
|
||||
/** The theme the person chose, with the custom colours read first; for code that is not in a composition. */
|
||||
fun current(context: Context): Palette {
|
||||
val id = SessionPrefs.theme(context)
|
||||
if (id == GRADIENT || id == INNER_GAMER) loadGradient(context)
|
||||
@@ -186,14 +180,12 @@ private val ContentDirected = Typography().run {
|
||||
)
|
||||
}
|
||||
|
||||
/** Turns the colour wheel on the system's own animation clock; with animations off, in the app or in Android, the colour holds still. */
|
||||
@Composable
|
||||
private fun InnerGamerHue(speed: Int) {
|
||||
if (Motion.scale == 0f) return
|
||||
key(speed) { InnerGamerCycle(speed) }
|
||||
}
|
||||
|
||||
/** One run of the cycle at one speed, picking up from the colour on screen so a new speed takes over at once without a jump. */
|
||||
@Composable
|
||||
private fun InnerGamerCycle(speed: Int) {
|
||||
val start = remember { Themes.rgbHue }
|
||||
|
||||
@@ -7,9 +7,7 @@ import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Colour maths for the custom gradient theme: hue, saturation and brightness in, a readable palette out. */
|
||||
internal object ThemeColors {
|
||||
/** Hue 0..360, saturation and brightness 0..1. */
|
||||
class Hsv(val h: Float, val s: Float, val v: Float)
|
||||
|
||||
fun toHsv(argb: Int): Hsv {
|
||||
@@ -32,7 +30,6 @@ internal object ThemeColors {
|
||||
|
||||
fun hex(argb: Int): String = "#%06X".format(argb and 0xFFFFFF)
|
||||
|
||||
/** `#RRGGBB`, `RRGGBB` or `#RGB`; null for anything else. */
|
||||
fun parseHex(text: String): Int? {
|
||||
val digits = text.trim().removePrefix("#")
|
||||
if (!digits.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }) return null
|
||||
@@ -46,7 +43,6 @@ internal object ThemeColors {
|
||||
|
||||
private const val MIN_LUMINANCE = 0.10f
|
||||
|
||||
/** The colour, made brighter (then paler, for a deep blue that brightness alone cannot lift) when it is too dark to show on the dark background. */
|
||||
fun readable(argb: Int): Int {
|
||||
if (Color(argb).luminance() >= MIN_LUMINANCE) return argb or 0xFF000000.toInt()
|
||||
val hsv = toHsv(argb)
|
||||
@@ -64,7 +60,6 @@ internal object ThemeColors {
|
||||
return out
|
||||
}
|
||||
|
||||
/** A dark neutral tinted with the primary's hue; plain greys stay grey. */
|
||||
fun tint(primary: Int, saturation: Float, brightness: Float): Color {
|
||||
val hsv = toHsv(primary)
|
||||
val strength = (hsv.s / 0.35f).coerceIn(0f, 1f)
|
||||
@@ -79,7 +74,6 @@ internal object ThemeColors {
|
||||
return (max(x, y) + 0.05f) / (min(x, y) + 0.05f)
|
||||
}
|
||||
|
||||
/** Dark or white text, whichever reads better on the worse of the two gradient colours. */
|
||||
internal fun inkFor(first: Int, second: Int): Color {
|
||||
fun worst(ink: Color) = min(contrast(ink, Color(first)), contrast(ink, Color(second)))
|
||||
return if (worst(DARK_INK) >= worst(Color.White)) DARK_INK else Color.White
|
||||
@@ -87,7 +81,6 @@ internal object ThemeColors {
|
||||
|
||||
private const val MIN_CONTRAST = 4.5f
|
||||
|
||||
/** The colour nudged just enough, lighter for dark text and darker for white text, to give [ink] a readable contrast on it. */
|
||||
private fun fitTo(ink: Color, argb: Int): Int {
|
||||
fun short(color: Int) = contrast(ink, Color(color)) < MIN_CONTRAST
|
||||
if (!short(argb)) return argb
|
||||
|
||||
@@ -55,7 +55,6 @@ import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_DRAG_MOVE
|
||||
@Composable
|
||||
fun TouchGestureDialog(game: String?, onDismiss: () -> Unit, onSaved: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
// Keep an open editor attached to the game it was opened for.
|
||||
val targetGame = remember { game }
|
||||
val initialDefaults = remember { GesturePrefs.read(context) }
|
||||
val initialGame = remember { targetGame?.takeIf { GesturePrefs.hasOverride(context, it) }?.let { GesturePrefs.read(context, it) } }
|
||||
@@ -169,7 +168,6 @@ fun TouchGestureDialog(game: String?, onDismiss: () -> Unit, onSaved: () -> Unit
|
||||
private fun GestureDialogFrame(onDismiss: () -> Unit,
|
||||
footer: @Composable () -> Unit = {}, content: @Composable ColumnScope.() -> Unit) {
|
||||
val p = LocalPalette.current
|
||||
// The app window does not opt into RTL, so these dialogs follow their resource locale explicitly.
|
||||
val direction = if (LocalConfiguration.current.layoutDirection == android.view.View.LAYOUT_DIRECTION_RTL) LayoutDirection.Rtl else LayoutDirection.Ltr
|
||||
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
|
||||
CompositionLocalProvider(LocalLayoutDirection provides direction) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.drawscope.scale
|
||||
import androidx.compose.ui.graphics.drawscope.translate
|
||||
import androidx.compose.ui.graphics.vector.PathParser
|
||||
@@ -16,22 +17,21 @@ import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.hud.WordmarkArt
|
||||
|
||||
@Composable
|
||||
internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
|
||||
val ink = MaterialTheme.colorScheme.onBackground
|
||||
val ball = LocalPalette.current.signal
|
||||
internal fun Wordmark(height: Dp, modifier: Modifier = Modifier, ink: Color = MaterialTheme.colorScheme.onBackground, ball: Color = LocalPalette.current.signal) {
|
||||
val name = stringResource(R.string.app_name)
|
||||
val letters = remember { PathParser().parsePathString(LETTERS).toPath() }
|
||||
val leftHalf = remember { PathParser().parsePathString(LEFT_HALF).toPath() }
|
||||
val rightHalf = remember { PathParser().parsePathString(RIGHT_HALF).toPath() }
|
||||
Canvas(modifier.height(height).width(height * (BOX_W / BOX_H)).semantics { contentDescription = name }) {
|
||||
val k = size.height / BOX_H
|
||||
val letters = remember { PathParser().parsePathString(WordmarkArt.LETTERS).toPath() }
|
||||
val leftHalf = remember { PathParser().parsePathString(WordmarkArt.LEFT_HALF).toPath() }
|
||||
val rightHalf = remember { PathParser().parsePathString(WordmarkArt.RIGHT_HALF).toPath() }
|
||||
Canvas(modifier.height(height).width(height * (WordmarkArt.BOX_W / WordmarkArt.BOX_H)).semantics { contentDescription = name }) {
|
||||
val k = size.height / WordmarkArt.BOX_H
|
||||
scale(k, k, Offset.Zero) {
|
||||
translate(-BOX_X, -BOX_Y) {
|
||||
translate(-WordmarkArt.BOX_X, -WordmarkArt.BOX_Y) {
|
||||
drawPath(letters, ink)
|
||||
translate(239.135f, 123.36f) {
|
||||
scale(MARK_SCALE, MARK_SCALE, Offset.Zero) {
|
||||
scale(WordmarkArt.MARK_SCALE, WordmarkArt.MARK_SCALE, Offset.Zero) {
|
||||
translate(31.98f, 0f) {
|
||||
drawPath(leftHalf, ink)
|
||||
drawPath(rightHalf, ink)
|
||||
@@ -43,22 +43,3 @@ internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val BOX_X = 239.135f
|
||||
private const val BOX_Y = 120.02f
|
||||
private const val BOX_W = 1040.7f - 239.135f
|
||||
private const val BOX_H = 243.2f - 120.02f
|
||||
private const val MARK_SCALE = 0.527445f
|
||||
|
||||
private const val LEFT_HALF = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z"
|
||||
private const val RIGHT_HALF = "M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"
|
||||
private const val LETTERS =
|
||||
"M361.45 241.36V160.13H387.02V241.36ZM387.02 196.73 376.32 188.38Q379.5 174.17 387.02 166.31Q394.54 158.46 407.91 158.46Q413.76 158.46 418.19 160.21Q422.62 161.97 425.96 165.65L410.75 184.87Q409.08 183.03 406.57 182.03Q404.07 181.02 400.89 181.02Q394.54 181.02 390.78 184.95Q387.02 188.88 387.02 196.73" +
|
||||
"ZM467.91 243.2Q455.38 243.2 445.27 237.6Q435.15 232 429.3 222.31Q423.45 212.61 423.45 200.58Q423.45 188.54 429.3 179.02Q435.15 169.49 445.18 163.89Q455.21 158.29 467.91 158.29Q480.62 158.29 490.64 163.81Q500.67 169.32 506.52 178.93Q512.37 188.54 512.37 200.58Q512.37 212.61 506.52 222.31Q500.67 232 490.64 237.6Q480.62 243.2 467.91 243.2" +
|
||||
"ZM467.91 219.97Q473.43 219.97 477.61 217.54Q481.79 215.12 484.04 210.69Q486.3 206.26 486.3 200.58Q486.3 194.9 483.96 190.63Q481.62 186.37 477.52 183.95Q473.43 181.52 467.91 181.52Q462.56 181.52 458.39 183.95Q454.21 186.37 451.87 190.72Q449.53 195.06 449.53 200.75Q449.53 206.26 451.87 210.69Q454.21 215.12 458.39 217.54Q462.56 219.97 467.91 219.97" +
|
||||
"ZM523.4 241.36V160.13H548.98V241.36ZM536.27 148.93Q530.26 148.93 526.33 144.84Q522.4 140.74 522.4 134.89Q522.4 128.88 526.33 124.86Q530.26 120.85 536.27 120.85Q542.29 120.85 546.13 124.86Q549.98 128.88 549.98 134.89Q549.98 140.74 546.13 144.84Q542.29 148.93 536.27 148.93ZM599.95 243.03Q588.42 243.03 579.48 237.52Q570.54 232 565.44 222.47Q560.34 212.95 560.34 200.75Q560.34 188.54 565.44 179.02Q570.54 169.49 579.48 163.97Q588.42 158.46 599.95 158.46Q608.31 158.46 615.08 161.63Q621.85 164.81 626.28 170.41Q630.71 176.01 631.21 183.2V217.46Q630.71 224.65 626.36 230.41Q622.02 236.18 615.16 239.61Q608.31 243.03 599.95 243.03" +
|
||||
"ZM604.47 219.97Q609.98 219.97 613.99 217.54Q618 215.12 620.34 210.77Q622.68 206.43 622.68 200.75Q622.68 195.06 620.43 190.8Q618.17 186.54 614.08 184.03Q609.98 181.52 604.63 181.52Q599.28 181.52 595.19 184.03Q591.09 186.54 588.67 190.88Q586.25 195.23 586.25 200.75Q586.25 206.26 588.59 210.61Q590.93 214.95 595.11 217.46Q599.28 219.97 604.47 219.97" +
|
||||
"ZM646.75 241.36H621.68V219.46L625.53 199.74L621.18 180.02V120.02H646.75ZM683.19 241.36V218.29H712.44Q723.13 218.29 731.16 214.03Q739.18 209.77 743.53 201.58Q747.87 193.39 747.87 182.19Q747.87 170.99 743.44 162.97Q739.01 154.95 731.07 150.6Q723.13 146.26 712.44 146.26H682.35V123.36H712.77Q726.14 123.36 737.42 127.62Q748.71 131.88 757.15 139.82Q765.59 147.76 770.18 158.54Q774.78 169.32 774.78 182.36Q774.78 195.23 770.18 206.09Q765.59 216.96 757.23 224.81Q748.87 232.67 737.59 237.01Q726.31 241.36 713.11 241.36" +
|
||||
"ZM665.47 241.36V123.36H691.71V241.36ZM827.6 243.2Q814.39 243.2 804.11 237.77Q793.83 232.33 787.98 222.64Q782.13 212.95 782.13 200.75Q782.13 188.54 787.9 178.93Q793.67 169.32 803.53 163.81Q813.39 158.29 825.76 158.29Q837.79 158.29 846.98 163.47Q856.18 168.65 861.44 177.85Q866.71 187.04 866.71 198.91Q866.71 201.08 866.46 203.5Q866.21 205.93 865.54 209.1L795.51 209.27V191.72L854.67 191.55L843.64 198.91Q843.47 191.89 841.47 187.29Q839.46 182.69 835.54 180.27Q831.61 177.85 825.92 177.85Q819.91 177.85 815.48 180.61Q811.05 183.36 808.63 188.38Q806.2 193.39 806.2 200.58Q806.2 207.77 808.79 212.86Q811.38 217.96 816.15 220.72Q820.91 223.48 827.43 223.48Q833.45 223.48 838.29 221.39Q843.14 219.3 846.82 215.12L860.86 229.16Q854.84 236.18 846.32 239.69Q837.79 243.2 827.6 243.2" +
|
||||
"ZM916.68 243.2Q904.15 243.2 893.95 237.68Q883.75 232.17 877.9 222.47Q872.05 212.78 872.05 200.75Q872.05 188.54 877.99 178.93Q883.92 169.32 894.12 163.81Q904.31 158.29 917.02 158.29Q926.54 158.29 934.48 161.55Q942.42 164.81 948.6 171.33L932.22 187.71Q929.38 184.53 925.62 183.03Q921.86 181.52 917.02 181.52Q911.5 181.52 907.24 183.95Q902.98 186.37 900.55 190.63Q898.13 194.9 898.13 200.58Q898.13 206.26 900.55 210.61Q902.98 214.95 907.32 217.46Q911.67 219.97 917.02 219.97Q922.03 219.97 925.96 218.21Q929.88 216.46 932.73 213.28L948.94 229.66Q942.59 236.35 934.56 239.77Q926.54 243.2 916.68 243.2" +
|
||||
"ZM1010.61 241.36 982.2 199.24 1010.45 160.13H1039.03L1004.93 204.09L1005.77 193.56L1040.7 241.36ZM958.63 241.36V120.02H984.21V241.36Z"
|
||||
Reference in new issue
Block a user