mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 04:46:08 +00:00
Merge latest origin/main and resolve conflicts
This commit is contained in:
commit
8171bf20fd
581 files changed
+14773
-4227
No files matched your search
@@ -287,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
|
||||
@@ -300,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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -56,23 +56,14 @@ 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")
|
||||
|
||||
/** Steam chat stays on Steam's own sites; anything else is not opened on the bottom screen. */
|
||||
internal fun steamChatAllows(host: String?): Boolean =
|
||||
host != null && STEAM_HOSTS.any { host == it || host.endsWith(".$it") }
|
||||
|
||||
/** The desktop chat fits the bottom panel better than the phone site; keep WebView's Chrome version. */
|
||||
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"
|
||||
}
|
||||
|
||||
/**
|
||||
* At the panel's own scale Steam's desktop chat gets about 600x300 CSS pixels and its friends list collapses, so the
|
||||
* page is laid out [cssWidth] wide and drawn at [scale]. Steam's site header (the rows before .chat_main_flex; its
|
||||
* class name is generated) is hidden to leave the height to the friends list and the chat. The group chat list keeps
|
||||
* a fixed 114 px height and an empty-list note that cover the online friends, so it shrinks to its rows (at most a
|
||||
* quarter of the panel) and the note is hidden.
|
||||
*/
|
||||
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]');" +
|
||||
@@ -92,7 +83,6 @@ fun BottomChatPage() {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var chatOpen by remember { mutableStateOf(true) }
|
||||
// Set when Android ended the page's renderer; the chat opens again once DroidDeck is back in front.
|
||||
var stopped by remember { mutableStateOf(false) }
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
DisposableEffect(lifecycle) {
|
||||
@@ -105,7 +95,6 @@ fun BottomChatPage() {
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
// null while the Steam client's sign-in is being copied, then whether there was one.
|
||||
var fromSteam by remember { mutableStateOf<Boolean?>(null) }
|
||||
LaunchedEffect(chatOpen) {
|
||||
if (!chatOpen) {
|
||||
@@ -145,7 +134,6 @@ fun BottomChatPage() {
|
||||
}
|
||||
}
|
||||
|
||||
/** With [onClose] set the chat is open: the row also carries Close and leaves out the long mic hint. */
|
||||
@Composable
|
||||
private fun VoiceRow(context: Context, onClose: (() -> Unit)? = null, note: String = "") {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -153,7 +141,6 @@ private fun VoiceRow(context: Context, onClose: (() -> Unit)? = null, note: Stri
|
||||
val max = remember { audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1) }
|
||||
var volume by remember { mutableIntStateOf(audio.getStreamVolume(AudioManager.STREAM_MUSIC)) }
|
||||
fun step(direction: Int) {
|
||||
// No flags: Android's volume panel would cover the game on the main screen.
|
||||
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, 0)
|
||||
volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
|
||||
}
|
||||
@@ -178,8 +165,6 @@ private fun VoiceRow(context: Context, onClose: (() -> Unit)? = null, note: Stri
|
||||
private fun SteamChatView(onStopped: () -> Unit) {
|
||||
AndroidView(factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
// AndroidView's default WRAP_CONTENT height gives the page a 0 px tall viewport, which collapses Steam
|
||||
// chat's full-height layout (measured on the Retroid Pocket Duo: html and every container 0 px).
|
||||
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
|
||||
setBackgroundColor(0xFF0A0B0D.toInt())
|
||||
settings.javaScriptEnabled = true
|
||||
@@ -199,8 +184,6 @@ private fun SteamChatView(onStopped: () -> Unit) {
|
||||
if (view.width > 0) view.evaluateJavascript(steamChatFitScript((view.width / scale).roundToInt(), CHAT_PAGE_SCALE), null)
|
||||
}
|
||||
|
||||
// Android ends the page's renderer once DroidDeck goes to picture-in-picture ("isolated not needed"
|
||||
// on the Retroid Pocket Duo); the page cannot come back, so the chat closes and reopens on resume.
|
||||
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
||||
onStopped()
|
||||
return true
|
||||
|
||||
@@ -45,7 +45,6 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
/** A page the bottom screen can show while the game runs on the main screen. */
|
||||
class BottomPage(
|
||||
val id: String,
|
||||
@StringRes val label: Int,
|
||||
@@ -56,10 +55,6 @@ class BottomPage(
|
||||
internal fun pickBottomPage(remembered: String?, ids: List<String>): String? =
|
||||
ids.firstOrNull { it == remembered } ?: ids.firstOrNull { it == DEFAULT_PAGE } ?: ids.firstOrNull()
|
||||
|
||||
/**
|
||||
* The tab picked during one session. Each Steam session starts with no pick, so the dashboard opens on Chat; reopened
|
||||
* later in the same session it shows the tab picked last.
|
||||
*/
|
||||
internal object SessionBottomTab {
|
||||
private var session: String? = null
|
||||
private var tab: String? = null
|
||||
@@ -74,13 +69,11 @@ internal object SessionBottomTab {
|
||||
}
|
||||
}
|
||||
|
||||
/** The page a game start switches to; not remembered as the user's pick. */
|
||||
internal fun pageForGameStart(ids: List<String>): String? = GAME_PAGE.takeIf { it in ids }
|
||||
|
||||
private const val DEFAULT_PAGE = "chat"
|
||||
private const val GAME_PAGE = "telemetry"
|
||||
|
||||
/** Tabs show their names while every tab still fits at [TAB_WIDTH]; otherwise only the open tab keeps its name. */
|
||||
internal fun bottomTabsWithLabels(widthDp: Float, tabs: Int): Boolean = tabs * TAB_WIDTH + 2 * BAR_BUTTON <= widthDp
|
||||
|
||||
private const val TAB_WIDTH = 132f
|
||||
@@ -94,6 +87,7 @@ fun BottomDashboard(
|
||||
onClose: () -> Unit,
|
||||
onMenu: (() -> Unit)?,
|
||||
gameStarts: Int = 0,
|
||||
strip: (@Composable (String?) -> Unit)? = null,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var current by remember { mutableStateOf(pickBottomPage(remembered, pages.map { it.id })) }
|
||||
@@ -117,6 +111,7 @@ fun BottomDashboard(
|
||||
}
|
||||
if (onMenu != null) BarButton(Icons.Outlined.Menu, stringResource(R.string.touch_droiddeck_menu), "bottom-menu", onMenu)
|
||||
}
|
||||
strip?.invoke(page?.id)
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
if (page != null) page.content()
|
||||
else Text(stringResource(R.string.bottom_dashboard_empty), fontSize = 15.sp, color = colors.onSurfaceVariant,
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
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.SystemClock
|
||||
import android.graphics.Typeface
|
||||
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.graphics.RectF
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.ImageView
|
||||
import android.widget.TextView
|
||||
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>?,
|
||||
) : 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 lateinit var touchButton: ImageView
|
||||
private lateinit var title: TextView
|
||||
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), 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>?): View {
|
||||
val bar = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
setPadding(dp(8), dp(6), dp(8), dp(6))
|
||||
setBackgroundColor(Color.BLACK)
|
||||
}
|
||||
fun gap() = View(context).apply { layoutParams = LayoutParams(dp(6), 1) }
|
||||
bar.addView(DeckControlsPanel.roundButton(context, "×", context.getString(R.string.deck_close), onClose))
|
||||
title = TextView(context).apply {
|
||||
textSize = 14f
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
setTextColor(Color.rgb(0x7A, 0x80, 0x8A))
|
||||
setPadding(dp(12), 0, dp(6), 0)
|
||||
isSingleLine = true
|
||||
ellipsize = android.text.TextUtils.TruncateAt.END
|
||||
}
|
||||
bar.addView(title, LayoutParams(0, -2, 1f))
|
||||
touchButton = DeckControlsPanel.iconButton(context, R.drawable.ic_bottom_mouse, "") { setDirectTouch(!directTouch) }
|
||||
bar.addView(touchButton)
|
||||
bar.addView(gap())
|
||||
bar.addView(DeckControlsPanel.iconButton(context, R.drawable.ic_bottom_keyboard,
|
||||
context.getString(R.string.second_show_keyboard)) { keyboardHost.toggle() })
|
||||
onMenu?.let {
|
||||
bar.addView(gap())
|
||||
bar.addView(DeckControlsPanel.menuButton(context, it))
|
||||
}
|
||||
steamButtons?.let { (steam, qam) ->
|
||||
bar.addView(gap())
|
||||
bar.addView(DeckControlsPanel.roundButton(context, "STEAM", context.getString(R.string.deck_open_steam_menu), steam, wide = true))
|
||||
bar.addView(gap())
|
||||
bar.addView(DeckControlsPanel.roundButton(context, "•••", context.getString(R.string.drawer_open_qam), qam, wide = true))
|
||||
}
|
||||
return bar
|
||||
}
|
||||
|
||||
private fun setDirectTouch(on: Boolean) {
|
||||
trackpad.cancel()
|
||||
BottomDesktop.sendTouch(3, -1, 0, 0)
|
||||
directTouch = on
|
||||
SessionPrefs.setBottomDesktopDirectTouch(context, on)
|
||||
showTouchMode()
|
||||
}
|
||||
|
||||
private fun showTouchMode() {
|
||||
touchButton.setImageResource(if (directTouch) R.drawable.ic_bottom_touch else R.drawable.ic_bottom_mouse)
|
||||
touchButton.contentDescription = context.getString(
|
||||
if (directTouch) R.string.bottom_desktop_direct_touch else R.string.bottom_desktop_trackpad)
|
||||
title.text = context.getString(R.string.bottom_desktop_title,
|
||||
context.getString(if (directTouch) R.string.bottom_desktop_mode_touch else R.string.bottom_desktop_mode_trackpad))
|
||||
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) attach(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
|
||||
surfaceView.layoutParams = FrameLayout.LayoutParams(w, h)
|
||||
}
|
||||
pan()
|
||||
}
|
||||
|
||||
private fun pan() {
|
||||
val visible = area.height
|
||||
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) {
|
||||
if (!attached) attach(holder)
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
if (holder !== surfaceView.holder) return
|
||||
attached = false
|
||||
surfaceUsed = false
|
||||
BottomDesktop.detach()
|
||||
}
|
||||
|
||||
private fun attach(holder: SurfaceHolder) {
|
||||
val frame = holder.surfaceFrame
|
||||
val (width, height) = BottomDesktop.outputSizeFor(fullWidth.takeIf { it > 0 } ?: frame.width(),
|
||||
fullHeight.takeIf { it > 0 } ?: frame.height())
|
||||
if (width <= 0 || height <= 0) return
|
||||
if (frame.width() != width || frame.height() != height) {
|
||||
holder.setFixedSize(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.outputSizeFor(surfaceView.width, surfaceView.height)
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,6 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** Bytes per second between two reads of the same download; 0 when it did not move or restarted. */
|
||||
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)
|
||||
|
||||
|
||||
@@ -39,7 +39,6 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.BottomNotifications
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/** DroidDeck's own switch on Android 11 and later; the list of all apps before that. */
|
||||
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(
|
||||
|
||||
@@ -8,19 +8,17 @@ import androidx.compose.material.icons.outlined.Notifications
|
||||
import androidx.compose.material.icons.outlined.PhotoLibrary
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
/** What the bottom-screen pages can ask the running session to do. */
|
||||
class BottomPageActions(
|
||||
val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null,
|
||||
val fps: () -> Float? = { null },
|
||||
/** Opens an Android settings page on the bottom screen; the dashboard comes back once [done] is true. */
|
||||
val openSettings: ((intent: android.content.Intent, done: () -> Boolean) -> Unit)? = null,
|
||||
/** The focused game's Steam app id as text (or another key for non-Steam programs); null in the Steam menus. */
|
||||
val runningGame: () -> String? = { null },
|
||||
)
|
||||
|
||||
/** The pages the bottom-screen dashboard offers during a session, in tab order. */
|
||||
internal const val BOTTOM_PAGE_TELEMETRY = "telemetry"
|
||||
|
||||
fun sessionBottomPages(actions: BottomPageActions): List<BottomPage> = listOf(
|
||||
BottomPage("telemetry", R.string.bottom_page_telemetry, Icons.Outlined.Speed) { BottomTelemetryPage(actions.fps, actions.runningGame) },
|
||||
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) },
|
||||
|
||||
@@ -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 = 100L
|
||||
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)
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
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
|
||||
@@ -22,6 +26,7 @@ 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
|
||||
@@ -41,18 +46,30 @@ 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
|
||||
@@ -72,16 +89,17 @@ 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 = 1_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
|
||||
/** Top strip history: one reading a second for 30 s. */
|
||||
private const val PERF_N = 30
|
||||
private const val PERF_N = 60
|
||||
private const val FRAME_MS = 100L
|
||||
private const val MINUTE_NS = 60_000_000_000L
|
||||
private const val TEMP_PLAIN = 0xFFF2F5F9.toInt()
|
||||
|
||||
/** What arrives on one telemetry port; written only by that port's listener. */
|
||||
private class PortTraffic {
|
||||
@Volatile var packets = 0L
|
||||
@Volatile var length = 0
|
||||
@@ -126,6 +144,21 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
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) {
|
||||
@@ -169,22 +202,49 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
speedTrace.add(r.speedKmh ?: 0f)
|
||||
traceTick++
|
||||
}
|
||||
fpsNow = fps()
|
||||
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() }
|
||||
fps()?.takeIf { it > 0f }?.let { fpsHistory.add(it) }
|
||||
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()) }
|
||||
s.gpuPercent?.let { gpuHistory.add(it.toFloat()) }
|
||||
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)
|
||||
}
|
||||
@@ -208,7 +268,6 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
}
|
||||
}
|
||||
val f = file
|
||||
// Status.json changes while Elite runs; one older than a minute belongs to an earlier session.
|
||||
elite = if (f != null && now - f.lastModified() < 60_000L) {
|
||||
withContext(Dispatchers.IO) { runCatching { GameStatusFiles.elite(f.readText()) }.getOrNull() }
|
||||
} else null
|
||||
@@ -224,6 +283,7 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
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) {
|
||||
@@ -233,96 +293,167 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
perfTick.let {
|
||||
StatsStripView(strip, StripData(fpsNow, device, fpsHistory.snapshot(), cpuHistory.snapshot(), gpuHistory.snapshot(), wattsHistory.snapshot(), clock,
|
||||
if (running != null) gameName else steamClient?.let { stringResource(steamClientLabel(it)) })) {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 (race == null && thunder.isEmpty() && elite == null) {
|
||||
Text(stringResource(R.string.bottom_telemetry_help),
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
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) }
|
||||
} 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)
|
||||
}
|
||||
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 ->
|
||||
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 (race == null && thunder.isEmpty() && elite == null && running == null) {
|
||||
Text(stringResource(R.string.bottom_telemetry_help),
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
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 {
|
||||
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)
|
||||
withContext(Dispatchers.IO) {
|
||||
SessionPrefs.setTelemetryAuto(context, want)
|
||||
if (want) TelemetryOutput.applyAutomatic(context, running)
|
||||
else TelemetryOutput.restoreTargets(outputs, running).forEach { TelemetryOutput.set(it, false) }
|
||||
}
|
||||
outputFailed = if (ok) null else game.name
|
||||
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 (game in menuGames) {
|
||||
Text(stringResource(R.string.bottom_telemetry_send_menu, game.name, game.setting, game.port), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
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 (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) }
|
||||
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))
|
||||
}
|
||||
ChoiceRow(stringResource(R.string.stats_speed_units),
|
||||
if (speedUnit == SpeedUnit.AUTO) stringResource(R.string.stats_speed_units_auto, shownUnit.label) else speedUnit.label) {
|
||||
speedUnit = speedUnit.next()
|
||||
SessionPrefs.setStatsSpeedUnit(context, speedUnit.id)
|
||||
}
|
||||
Text(stringResource(R.string.stats_tap_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
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))
|
||||
}
|
||||
ChoiceRow(stringResource(R.string.stats_speed_units),
|
||||
if (speedUnit == SpeedUnit.AUTO) stringResource(R.string.stats_speed_units_auto, shownUnit.label) else speedUnit.label) {
|
||||
speedUnit = speedUnit.next()
|
||||
SessionPrefs.setStatsSpeedUnit(context, speedUnit.id)
|
||||
}
|
||||
Text(stringResource(R.string.stats_tap_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, 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
|
||||
@@ -335,7 +466,6 @@ private fun httpGet(url: String): String {
|
||||
}
|
||||
|
||||
|
||||
/** The Steam client the session runs, shown in the strip's top line while no game runs. */
|
||||
internal fun steamClientLabel(arch: String): Int = if (arch == "x86_64") R.string.stats_steam_client_x86 else R.string.stats_steam_client_arm
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -17,7 +17,6 @@ import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.QuestXrActivity
|
||||
|
||||
/** A faint bottom-right tag on every screen of a test or local build; stable and preview builds draw none. */
|
||||
object BuildWatermark {
|
||||
private const val TITLE_LIMIT = 80
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -254,11 +254,8 @@ 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
|
||||
@@ -715,10 +712,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)
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
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.DroidDeckHudSize
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.StripMetric
|
||||
|
||||
/** Bannerlator's DroidDeck HUD settings (DeckOverlaySettings): one row per key of the HUD's config string. */
|
||||
@Composable
|
||||
internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val cfg = a.hudConfig
|
||||
@@ -29,7 +35,10 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
||||
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)) {
|
||||
@@ -95,12 +104,51 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
||||
|
||||
private fun flag(on: Boolean) = if (on) "1" else "0"
|
||||
|
||||
// The Pill also draws the battery temperature and watts.
|
||||
@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), detail = stringResource(R.string.bottom_hud_group_detail)) {
|
||||
ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), stringResource(R.string.bottom_hud_hint), hudOn,
|
||||
chipModifier = track("bottom-hud")) { on ->
|
||||
hudOn = on
|
||||
SessionPrefs.setBottomHud(context, on)
|
||||
}
|
||||
ToggleRow(host, "bottom-strip-tabs", stringResource(R.string.bottom_strip_tabs), stringResource(R.string.bottom_strip_tabs_hint), 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)
|
||||
|
||||
// DroidDeckHudSize.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),
|
||||
@@ -125,8 +173,6 @@ private val METRICS = listOf(
|
||||
HudMetric("Clock", "showClock", R.string.hud_metric_clock),
|
||||
)
|
||||
|
||||
// Switches a size lists but never draws (DroidDeckHudView): the Pill and Minimal always show the FPS, the
|
||||
// Pill has no graph, Tiles has no graph and no 0.01% low, the Strip always shows the FPS.
|
||||
private val HIDDEN = mapOf(
|
||||
DroidDeckHudSize.PILL to setOf("FPS", "FPS graph"),
|
||||
DroidDeckHudSize.MINIMAL to setOf("FPS"),
|
||||
|
||||
@@ -128,8 +128,6 @@ object DualScreenPanel {
|
||||
val host = context as? ComponentActivity
|
||||
val target = host?.getSystemService(Context.DISPLAY_SERVICE)
|
||||
?.let { (it as android.hardware.display.DisplayManager).getDisplay(display) }
|
||||
// A second-display activity makes the system launcher treat its bottom home as lost and bring itself forward;
|
||||
// a presentation belongs to this task and leaves that home alone.
|
||||
if (host != null && target != null) {
|
||||
val shown = runCatching { DualScreenPresentation(host, target).also { it.show() } }
|
||||
if (shown.isSuccess) {
|
||||
@@ -170,7 +168,6 @@ object DualScreenPanel {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -298,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()
|
||||
@@ -319,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) }
|
||||
@@ -442,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
|
||||
}
|
||||
@@ -561,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)
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
@@ -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 { }
|
||||
@@ -524,7 +537,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(
|
||||
@@ -720,7 +734,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
|
||||
@@ -929,14 +942,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)) }
|
||||
}
|
||||
@@ -115,7 +115,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 }
|
||||
@@ -195,7 +194,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 { }
|
||||
@@ -319,7 +317,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(
|
||||
@@ -500,7 +497,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 +531,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 +567,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 +587,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 +925,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 +945,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
|
||||
|
||||
@@ -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)?,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -112,7 +112,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 +119,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> {
|
||||
@@ -159,7 +157,6 @@ internal fun librarySources(entries: List<LibraryEntry>, order: List<String>): L
|
||||
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED)
|
||||
.filter { source -> 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)
|
||||
@@ -797,7 +794,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
|
||||
|
||||
@@ -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,13 @@ 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 storageDiagnostics: Boolean = false,
|
||||
val fexPreset: String? = null,
|
||||
val forceSsbs: Boolean = false,
|
||||
@@ -80,9 +82,7 @@ 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,
|
||||
@@ -118,12 +118,16 @@ 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 onRenameSteamLibrary: (id: String, label: String) -> Unit = { _, _ -> },
|
||||
val onRemoveSteamLibrary: (id: String) -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit = {},
|
||||
val onForceSsbs: (Boolean) -> Unit = {},
|
||||
val onSyncBackend: (String) -> Unit = {},
|
||||
@@ -154,15 +158,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 +224,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 +297,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 +308,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()
|
||||
@@ -401,6 +406,34 @@ 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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
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 +698,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)
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
@@ -34,6 +34,7 @@ import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
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
|
||||
@@ -199,7 +200,8 @@ class SecondScreenPresentation(
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
val ownKeys = currentMode == SecondScreenMode.TERMINAL || currentMode == SecondScreenMode.DASHBOARD
|
||||
val ownKeys = currentMode == SecondScreenMode.TERMINAL || currentMode == SecondScreenMode.DASHBOARD ||
|
||||
currentMode == SecondScreenMode.DESKTOP
|
||||
val forward = menuShown || !ownKeys || PadBridge.isControllerKeyEvent(event)
|
||||
if (forward && sessionActivity.dispatchKeyEvent(event)) return true
|
||||
return super.dispatchKeyEvent(event)
|
||||
@@ -231,6 +233,7 @@ class SecondScreenPresentation(
|
||||
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
|
||||
@@ -240,6 +243,11 @@ class SecondScreenPresentation(
|
||||
SecondScreenMode.TERMINAL -> renderTerminal()
|
||||
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam, pad, onMenu = onMenu), weightParams())
|
||||
SecondScreenMode.DASHBOARD -> renderDashboard()
|
||||
SecondScreenMode.DESKTOP -> {
|
||||
ownComposeViews()
|
||||
root.addView(BottomDesktopPanel(context, onClose, onMenu,
|
||||
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }), weightParams())
|
||||
}
|
||||
SecondScreenMode.NONE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import androidx.compose.foundation.layout.heightIn
|
||||
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
|
||||
@@ -221,6 +222,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 = {},
|
||||
@@ -242,6 +245,7 @@ class DrawerActions(
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val dashboardAvailable: Boolean = false,
|
||||
val desktopAvailable: Boolean = false,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
@@ -641,6 +645,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)
|
||||
@@ -896,6 +903,7 @@ private fun BottomScreenModes(a: DrawerActions, modifier: Modifier, onPick: () -
|
||||
add(SecondScreenMode.KEYBOARD_TRACKPAD to Icons.Outlined.Keyboard)
|
||||
add(SecondScreenMode.TERMINAL to Icons.Outlined.Terminal)
|
||||
if (a.dashboardAvailable) add(SecondScreenMode.DASHBOARD to Icons.Outlined.Dashboard)
|
||||
if (a.desktopAvailable) add(SecondScreenMode.DESKTOP to Icons.Outlined.DesktopWindows)
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -1194,7 +1202,8 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
|
||||
val pal = LocalPalette.current
|
||||
val modes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
|
||||
(if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) +
|
||||
(if (a.dashboardAvailable) listOf(SecondScreenMode.DASHBOARD) else emptyList())
|
||||
(if (a.dashboardAvailable) listOf(SecondScreenMode.DASHBOARD) else emptyList()) +
|
||||
(if (a.desktopAvailable) listOf(SecondScreenMode.DESKTOP) else emptyList())
|
||||
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
|
||||
Column(Modifier.fillMaxWidth().selectableGroup()) {
|
||||
modes.forEach { mode ->
|
||||
@@ -1596,7 +1605,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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -489,10 +489,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 ->
|
||||
|
||||
@@ -58,12 +58,10 @@ import kotlin.math.roundToInt
|
||||
import kotlin.math.sin
|
||||
|
||||
private val DASH_H = 290.dp
|
||||
/** Pedal and speed trace length: 150 readings at the page's 66 ms draw rate, about 10 s. */
|
||||
internal const val TRACE_N = 150
|
||||
|
||||
internal class TraceData(val throttle: List<Float>, val brake: List<Float>, val speed: List<Float>)
|
||||
|
||||
/** The racing dash in [style] with speeds in [unit] (km/h or mph); a tap moves to the next one. */
|
||||
@Composable
|
||||
internal fun RaceDashView(style: StatsDash, t: Telemetry, trace: TraceData, unit: SpeedUnit, onTap: () -> Unit) {
|
||||
Box(Modifier.fillMaxWidth().clickable(onClick = onTap)) {
|
||||
@@ -87,7 +85,6 @@ private const val DIAL_SWEEP = 250f
|
||||
|
||||
private fun dialAngle(v: Float, max: Float) = DIAL_START + DIAL_SWEEP * (v / max).coerceIn(0f, 1f)
|
||||
|
||||
/** A 250° dial face: track, optional red zone from [red], ticks and numbers every [major]. */
|
||||
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,
|
||||
@@ -468,7 +465,6 @@ private fun EdgeBar(value: Float?, color: Color) {
|
||||
}
|
||||
}
|
||||
|
||||
/** War Thunder's own labels the Flight layout places; others stay in the list. */
|
||||
internal object FlightLabels {
|
||||
const val IAS = "IAS, km/h"
|
||||
const val ALTITUDE = "H, m"
|
||||
@@ -573,7 +569,6 @@ private fun Pips(pips: List<Int>, modifier: Modifier) {
|
||||
val pipH = (size.height - labelH) / 4f - 4.dp.toPx()
|
||||
for (col in 0 until 3) {
|
||||
val x = col * colW + (colW - pipW) / 2f
|
||||
// Status.json counts half pips: 0..8 per system.
|
||||
val value = pips[col] / 2f
|
||||
for (i in 0 until 4) {
|
||||
val y = size.height - labelH - (i + 1) * (pipH + 4.dp.toPx())
|
||||
|
||||
@@ -0,0 +1,667 @@
|
||||
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.DroidDeckMark
|
||||
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.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) }
|
||||
val markH = min(h, w) * 0.55f
|
||||
val markX = w - DroidDeckMark.widthFor(markH) - 16.dp.toPx()
|
||||
val markBody = android.graphics.Color.argb(if (dim) 9 else 20, 255, 255, 255)
|
||||
val markOrb = argb(if (dim) 9 else 20, 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)
|
||||
DroidDeckMark.draw(c, markX, (h - markH) / 2f, markH, markBody, markOrb)
|
||||
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)) {
|
||||
DroidDeckLogo(16.dp, body = headerInk, orb = if (dim) accent.copy(alpha = 0.5f) else accent)
|
||||
Text("DroidDeck", fontSize = 14.sp, fontWeight = FontWeight.Bold, color = headerInk, maxLines = 1)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@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 path = Path()
|
||||
values.forEachIndexed { i, v ->
|
||||
val x = i / (values.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)
|
||||
}
|
||||
@@ -36,28 +36,31 @@ 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
|
||||
|
||||
/** FusionHUD's metric colors, so the bottom screen reads like the HUD on the top screen. */
|
||||
internal object StatsColors {
|
||||
val cpu = Color(0xFF58A6FF)
|
||||
val gpu = Color(0xFF5EE08A)
|
||||
val ram = Color(0xFFFF7BC0)
|
||||
val bat = Color(0xFFFFAB5E)
|
||||
// Throttle and brake stay apart for red-green colour blindness (checked against the dark surface).
|
||||
val throttle = Color(0xFF14A39A)
|
||||
val brake = Color(0xFFE5484D)
|
||||
val speed = Color(0xFF2E8FD6)
|
||||
@@ -66,19 +69,27 @@ internal object StatsColors {
|
||||
val badge = Color(0xFF0B0D10)
|
||||
}
|
||||
|
||||
/** The last [capacity] readings, oldest first. */
|
||||
internal class History(private val capacity: Int) {
|
||||
private val values = ArrayDeque<Float>(capacity)
|
||||
fun add(v: Float) {
|
||||
if (values.size == capacity) values.removeFirst()
|
||||
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)
|
||||
|
||||
/** The DroidDeck mark (the split D with the blue orb), the same artwork the HUD draws. */
|
||||
@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)) {
|
||||
@@ -96,7 +107,6 @@ private fun LogoBadge(size: Dp) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The mark and "DroidDeck" on the left, the running game's name in the middle, the clock on the right. */
|
||||
@Composable
|
||||
private fun LogoHeader(clock: String, game: String?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -123,7 +133,6 @@ internal fun Sparkline(values: List<Float>, min: Float, max: Float, color: Color
|
||||
}
|
||||
}
|
||||
|
||||
/** A readout card: dark surface, a thin accent edge and the DroidDeck mark before the title ("" = mark only). */
|
||||
@Composable
|
||||
internal fun StatsCard(title: String?, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
@@ -141,7 +150,6 @@ internal fun StatsCard(title: String?, modifier: Modifier = Modifier, content: @
|
||||
}
|
||||
}
|
||||
|
||||
/** What the top strip shows; histories hold one reading a second, oldest first. */
|
||||
internal class StripData(
|
||||
val fps: Float?,
|
||||
val device: HudMetrics.Snapshot?,
|
||||
@@ -151,6 +159,12 @@ internal class StripData(
|
||||
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 =
|
||||
@@ -161,11 +175,11 @@ private fun batteryText(s: HudMetrics.Snapshot?): String =
|
||||
|
||||
private fun fpsText(fps: Float?): String = fps?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–"
|
||||
|
||||
/** The top strip; a tap moves to the next style. */
|
||||
@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)
|
||||
@@ -173,6 +187,113 @@ internal fun StatsStripView(style: StatsStrip, d: StripData, onTap: () -> Unit)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -808,14 +808,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(
|
||||
@@ -862,7 +854,6 @@ 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()
|
||||
@@ -1423,15 +1414,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) {
|
||||
|
||||
Reference in new issue
Block a user