mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
Merge Droid-Deck main into fix/proot-performance
This commit is contained in:
commit
531087be16
50 files changed
+3126
-428
No files matched your search
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.ActivityOptions
|
||||
import android.app.role.RoleManager
|
||||
import android.graphics.Bitmap
|
||||
import android.content.ComponentName
|
||||
@@ -21,6 +22,25 @@ object HomeApp {
|
||||
val icon: Bitmap?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Whether the app offers itself as a Home app at all. HomeActivity is declared disabled and
|
||||
* only enabled when the user turns on "Use as a Home screen": a player who does not want a
|
||||
* launcher never gets Android's "which Home app?" question, and it is one apk either way.
|
||||
* The setting is the component's own state, which Android keeps across updates.
|
||||
*/
|
||||
fun isHomeScreenEnabled(context: Context): Boolean =
|
||||
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
|
||||
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
|
||||
|
||||
/** Turned off while DroidDeck is the Home app, the phone goes back to its own launcher. */
|
||||
fun setHomeScreenEnabled(context: Context, enabled: Boolean) {
|
||||
context.packageManager.setComponentEnabledSetting(
|
||||
ComponentName(context, HomeActivity::class.java),
|
||||
if (enabled) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
|
||||
PackageManager.DONT_KILL_APP,
|
||||
)
|
||||
}
|
||||
|
||||
fun isDefault(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val roles = context.getSystemService(RoleManager::class.java)
|
||||
@@ -73,11 +93,19 @@ object HomeApp {
|
||||
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
|
||||
fun launch(context: Context, app: LaunchableApp) {
|
||||
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) {
|
||||
val intent = Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(ComponentName(app.packageName, app.className))
|
||||
context.startActivity(intent)
|
||||
if (displayId == null) {
|
||||
context.startActivity(intent)
|
||||
return
|
||||
}
|
||||
// Keep the target app's task separate from DroidDeck. Without this, Android can put the
|
||||
// app on top of the caller's task and move the entire task to the chosen display.
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
|
||||
context.startActivity(intent, options.toBundle())
|
||||
}
|
||||
|
||||
fun isActiveSteamSession(): Boolean =
|
||||
|
||||
@@ -4,12 +4,14 @@ import android.Manifest
|
||||
import android.content.Intent
|
||||
import java.io.File
|
||||
import android.content.pm.PackageManager
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -47,6 +49,7 @@ import com.droiddeck.launcher.ui.CreditsDialog
|
||||
import com.droiddeck.launcher.ui.FrontEndScreen
|
||||
import com.droiddeck.launcher.ui.FrontEndState
|
||||
import com.droiddeck.launcher.ui.FrontEndActions
|
||||
import com.droiddeck.launcher.frontend.CoverArt
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.RomsDialog
|
||||
@@ -54,6 +57,8 @@ import com.droiddeck.launcher.files.InAppFilePicker
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplays
|
||||
|
||||
/**
|
||||
* The whole app outside a session: is the runtime installed, is there a newer one, frame
|
||||
@@ -104,6 +109,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
private var directAudio by mutableStateOf(false)
|
||||
private var clientDirectAudio by mutableStateOf(false)
|
||||
private var forceFullscreen by mutableStateOf(true)
|
||||
private var mic by mutableStateOf(false)
|
||||
private var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
|
||||
@@ -169,6 +175,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var renderer by mutableStateOf("vulkan")
|
||||
private var gameStorage by mutableStateOf("")
|
||||
private var storageOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
|
||||
@@ -182,8 +189,16 @@ class MainActivity : ComponentActivity() {
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var showRoms by mutableStateOf(false)
|
||||
private var homeAppSelected by mutableStateOf(false)
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
private var defaultHomeLabel by mutableStateOf<String?>(null)
|
||||
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
refreshHomeAppState()
|
||||
@@ -209,7 +224,9 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
theme = SessionPrefs.theme(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
setContent {
|
||||
DroidDeckTheme(theme) {
|
||||
val sm = settingsMode
|
||||
@@ -232,14 +249,18 @@ class MainActivity : ComponentActivity() {
|
||||
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else null,
|
||||
theme = theme,
|
||||
isHomeApp = homeAppSelected,
|
||||
homeScreenEnabled = homeScreenEnabled,
|
||||
defaultHomeLabel = defaultHomeLabel,
|
||||
androidApps = androidApps,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
packages = packageRows,
|
||||
packageCatalogLoading = catalogLoading,
|
||||
packageBusyId = pkgId,
|
||||
packageStage = pkgStage,
|
||||
packagePercent = pkgPercent,
|
||||
sessionRunning = SessionState.running,
|
||||
backActionsInverted = backActionsInverted,
|
||||
buildLabel = BuildConfig.BUILD_LABEL,
|
||||
),
|
||||
FrontEndActions(
|
||||
onPlay = { startSession(Intent(this, SessionActivity::class.java)) },
|
||||
@@ -299,7 +320,18 @@ class MainActivity : ComponentActivity() {
|
||||
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false },
|
||||
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
||||
onHomeApp = { manageHomeApp() },
|
||||
onAndroidApp = { app -> launchAndroidApp(app) },
|
||||
onHomeScreen = { on ->
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
},
|
||||
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
onCheckLatestBuild = {
|
||||
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml")))
|
||||
},
|
||||
),
|
||||
page = page,
|
||||
)
|
||||
@@ -354,6 +386,7 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
refreshHomeAppState()
|
||||
refreshSecondScreenDisplays()
|
||||
refresh()
|
||||
// Added games' art (a store lookup for what the folders lack) starts here, not only when
|
||||
// the cog opens.
|
||||
@@ -362,17 +395,36 @@ class MainActivity : ComponentActivity() {
|
||||
if (!busy) Thread({ checkCatalog() }, "catalog").start()
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
private fun refreshHomeAppState() {
|
||||
homeAppSelected = HomeApp.isDefault(this)
|
||||
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
||||
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||
androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
|
||||
}
|
||||
|
||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp) {
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
if (!::displayManager.isInitialized) return
|
||||
secondScreenDisplays = SecondScreenDisplays.available(displayManager)
|
||||
}
|
||||
|
||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
|
||||
try {
|
||||
HomeApp.launch(this, app)
|
||||
HomeApp.launch(this, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
android.widget.Toast.makeText(this, "Could not open ${app.label}", android.widget.Toast.LENGTH_SHORT).show()
|
||||
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
|
||||
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
|
||||
android.widget.Toast.makeText(this, "Could not open ${app.label} on $target", android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -515,8 +567,10 @@ class MainActivity : ComponentActivity() {
|
||||
touchMode = touchMode,
|
||||
suspendPolicy = suspendPolicy,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||
clientDirectAudio = clientDirectAudio,
|
||||
forceFullscreen = if (mode == SessionService.MODE_STEAM) forceFullscreen else null,
|
||||
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
||||
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
@@ -546,8 +600,13 @@ class MainActivity : ComponentActivity() {
|
||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
|
||||
onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on },
|
||||
onForceFullscreen = { on -> SessionPrefs.setForceFullscreen(this, on); forceFullscreen = on },
|
||||
onMic = { on ->
|
||||
SessionPrefs.setMicEnabled(this, on)
|
||||
mic = on
|
||||
@@ -641,8 +700,10 @@ class MainActivity : ComponentActivity() {
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
directAudio = SessionPrefs.directAudio(this)
|
||||
clientDirectAudio = SessionPrefs.clientDirectAudio(this)
|
||||
forceFullscreen = SessionPrefs.forceFullscreen(this)
|
||||
mic = SessionPrefs.micEnabled(this)
|
||||
renderer = SessionPrefs.desktopRenderer(this)
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
@@ -885,6 +946,12 @@ class MainActivity : ComponentActivity() {
|
||||
} else emptyList()
|
||||
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
||||
ui.post { steamGames = games; emulatorList = emus }
|
||||
// Box art for the games that have none, fetched after the list is up; the list is
|
||||
// rebuilt once if any was found.
|
||||
if (!OfflineMode.enabled(this) && CoverArt.fetchMissing(this, emus.flatMap { it.games })) {
|
||||
val refreshed = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
||||
ui.post { emulatorList = refreshed }
|
||||
}
|
||||
}, "library").start()
|
||||
}
|
||||
|
||||
|
||||
@@ -8,9 +8,12 @@ import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.Display
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
@@ -21,6 +24,7 @@ import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -35,6 +39,7 @@ import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplays
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.input.TouchpadGestures
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
@@ -58,6 +63,7 @@ import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.wayland.CompositorHost
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* The session's screen: our Wayland compositor presenting onto this activity's Surface, and the
|
||||
@@ -72,25 +78,56 @@ import java.io.File
|
||||
*/
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private lateinit var sessionOverlay: ComposeView
|
||||
private lateinit var loading: LoadingState
|
||||
private lateinit var hud: PerfHud
|
||||
private var padBridge: PadBridge? = null
|
||||
private var onScreenControls: OnScreenControls? = null
|
||||
private var keyboard: KeyboardHost? = null
|
||||
private var watching = true
|
||||
private lateinit var gestures: PointerGestures
|
||||
private lateinit var touchpad: TouchpadGestures
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f))
|
||||
private var cursorVisible by mutableStateOf(false)
|
||||
private val cursorHide = Runnable { cursorVisible = false }
|
||||
private val uiHandler = Handler(Looper.getMainLooper())
|
||||
private var pendingBackAction: Runnable? = null
|
||||
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
private var drawerDirectionDownTime = 0L
|
||||
private var drawerDirectionDeviceId = -1
|
||||
private var drawerDirectionRepeatCount = 0
|
||||
private val drawerFirstRepeatDelayMs = ViewConfiguration.getKeyRepeatTimeout().toLong()
|
||||
private val drawerSlowRepeatIntervalMs = maxOf(
|
||||
ViewConfiguration.getKeyRepeatDelay().toLong(), DRAWER_SLOW_REPEAT_FLOOR_MS,
|
||||
)
|
||||
private val drawerDirectionRepeat = object : Runnable {
|
||||
override fun run() {
|
||||
if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) return
|
||||
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val heldMs = now - drawerDirectionDownTime
|
||||
val progress = ((heldMs - drawerFirstRepeatDelayMs).toFloat() / DRAWER_REPEAT_ACCELERATION_MS)
|
||||
.coerceIn(0f, 1f)
|
||||
val intervalMs = (
|
||||
drawerSlowRepeatIntervalMs +
|
||||
(DRAWER_FAST_REPEAT_INTERVAL_MS - drawerSlowRepeatIntervalMs) * progress
|
||||
).toLong()
|
||||
|
||||
dispatchDrawerKey(KeyEvent.ACTION_DOWN, ++drawerDirectionRepeatCount, now)
|
||||
uiHandler.postDelayed(this, intervalMs)
|
||||
}
|
||||
}
|
||||
private val resumeKeysDown = mutableSetOf<Pair<Int, Int>>()
|
||||
|
||||
// Compose reads these; the activity writes them.
|
||||
private var drawerOpen by mutableStateOf(false)
|
||||
private var drawerPage by mutableIntStateOf(0)
|
||||
private var drawerControllerActive by mutableStateOf(false)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
|
||||
private var pcKeyboardOpen by mutableStateOf(false)
|
||||
private var hudOn by mutableStateOf(true)
|
||||
private var fillScreen by mutableStateOf(true)
|
||||
private var frameGenLabel by mutableStateOf("Off")
|
||||
private var frameGenEngine by mutableStateOf(FrameGen.ENGINE_OFF)
|
||||
private var frameGenMultiplier by mutableStateOf(2)
|
||||
@@ -147,7 +184,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
padBridge = bridge
|
||||
onScreenControls = OnScreenControls(this, bridge).also { root.addView(it) }
|
||||
keyboard = KeyboardHost(this).also { root.addView(it) }
|
||||
gestures = PointerGestures(PointerGestures.slop(this), pointerListener)
|
||||
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
|
||||
// One arrow, ours: Android draws a system pointer for a mouse over any window, and the
|
||||
// session already draws the pointer it is sent.
|
||||
@@ -175,14 +211,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
// One Compose layer for every menu and overlay. Touches nothing in it consumes fall
|
||||
// through to the pad and the game underneath.
|
||||
root.addView(ComposeView(this).apply {
|
||||
sessionOverlay = ComposeView(this).apply {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density)
|
||||
if (hud.text.isNotEmpty()) HudText(hud.text)
|
||||
if (loading.visible) LoadingOverlay(loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended)
|
||||
// Opening the drawer takes the controller away from the game: release its pad.
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen) { if (drawerOpen) padBridge?.releaseAll() }
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
|
||||
if (drawerOpen) {
|
||||
padBridge?.releaseAll()
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
val requested = sessionOverlay.requestFocus()
|
||||
Log.i(TAG, "drawer root focus requested=$requested focused=${sessionOverlay.hasFocus()}")
|
||||
} else {
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
}
|
||||
// The PC keyboard takes it too, for moving over the keys; the drawer opens over it.
|
||||
androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) padBridge?.releaseAll() }
|
||||
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
|
||||
@@ -190,11 +237,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
|
||||
onClose = { pcKeyboardOpen = false },
|
||||
)
|
||||
SessionDrawer(drawerOpen, DrawerActions(
|
||||
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
|
||||
steam = SessionState.mode == SessionService.MODE_STEAM,
|
||||
title = if (SessionState.mode == SessionService.MODE_RUN)
|
||||
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null,
|
||||
isHomeApp = isHomeApp,
|
||||
androidApps = androidApps,
|
||||
hudOn = hudOn,
|
||||
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
|
||||
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
|
||||
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
|
||||
oscMode = oscMode, touchMode = touchMode,
|
||||
@@ -204,6 +254,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
|
||||
onFrameGenPick = { engine, multiplier ->
|
||||
FrameGen.set(this@SessionActivity, engine, multiplier)
|
||||
readPrefs()
|
||||
@@ -212,22 +263,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
|
||||
onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen },
|
||||
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({
|
||||
drawerOpen = false
|
||||
padBridge?.triggerQam()
|
||||
}) else null,
|
||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
|
||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
|
||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||
onSecondScreenMode = ::selectSecondScreenMode,
|
||||
onSecondScreenDisplay = ::selectSecondScreenDisplay,
|
||||
onLaunchAndroidApp = { app ->
|
||||
onLaunchAndroidApp = { app, displayId ->
|
||||
drawerOpen = false
|
||||
try {
|
||||
HomeApp.launch(this@SessionActivity, app)
|
||||
HomeApp.launch(this@SessionActivity, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
Toast.makeText(this@SessionActivity, "Could not open ${app.label}", Toast.LENGTH_SHORT).show()
|
||||
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
|
||||
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
|
||||
Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
},
|
||||
onBackground = { drawerOpen = false; moveTaskToBack(true) },
|
||||
@@ -239,7 +294,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
root.addView(sessionOverlay)
|
||||
setContentView(root)
|
||||
handleHomeGuideIntent(intent)
|
||||
|
||||
@@ -252,13 +308,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
SessionState.endListener = endListener
|
||||
// Back opens the drawer (and closes it again). Leaving the session running in the
|
||||
// background and ending it are both actions in there, so neither can happen by accident
|
||||
// from a button a game might also be reading.
|
||||
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
|
||||
// The single action waits out the double-press window so the two actions stay distinct.
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
// The PC keyboard closes first (B on a controller), then Back is the drawer again.
|
||||
if (pcKeyboardOpen && !drawerOpen) pcKeyboardOpen = false else drawerOpen = !drawerOpen
|
||||
when {
|
||||
drawerOpen -> drawerOpen = false
|
||||
pcKeyboardOpen -> pcKeyboardOpen = false
|
||||
else -> routeBackAction()
|
||||
}
|
||||
}
|
||||
})
|
||||
watchSession()
|
||||
@@ -277,6 +336,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}, 90)
|
||||
}
|
||||
|
||||
private fun triggerSteamQam() {
|
||||
drawerOpen = false
|
||||
padBridge?.triggerQam()
|
||||
}
|
||||
|
||||
private fun routeBackAction() {
|
||||
pendingBackAction?.let { pending ->
|
||||
uiHandler.removeCallbacks(pending)
|
||||
pendingBackAction = null
|
||||
performBackAction(double = true)
|
||||
return
|
||||
}
|
||||
val pending = Runnable {
|
||||
pendingBackAction = null
|
||||
performBackAction(double = false)
|
||||
}
|
||||
pendingBackAction = pending
|
||||
uiHandler.postDelayed(pending, BACK_DOUBLE_PRESS_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
private fun performBackAction(double: Boolean) {
|
||||
val isSteam = SessionState.mode == SessionService.MODE_STEAM
|
||||
val opensQam = isSteam && (double xor backActionsInverted)
|
||||
if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen
|
||||
}
|
||||
|
||||
private fun handleHomeGuideIntent(incoming: Intent?) {
|
||||
if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return
|
||||
incoming.action = null
|
||||
@@ -286,6 +371,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
private fun readPrefs() {
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
fillScreen = SessionPrefs.forceFullscreen(this)
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
frameGenEngine = FrameGen.engine(this)
|
||||
@@ -293,6 +379,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
shapeMode = SessionPrefs.shapeMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
}
|
||||
|
||||
// ── Compositor ──────────────────────────────────────────────────────────────────────────
|
||||
@@ -481,7 +568,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// Wider than 16:9 is fine - games and the client cope with a phone's 20:9 - so the
|
||||
// panel's aspect is kept above that, unless the user pinned 16:9 for a foldable, and the
|
||||
// compositor letterboxes onto a squarer panel.
|
||||
// "Exactly this panel" drops that floor, for a 4:3 or 3:2 handheld whose games should
|
||||
// "Match screen" drops that floor, for a 4:3 or 3:2 handheld whose games should
|
||||
// fill it.
|
||||
val aspect = when (SessionPrefs.shapeMode(this)) {
|
||||
SessionPrefs.SHAPE_WIDE -> 16f / 9f
|
||||
@@ -620,10 +707,41 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
// With the drawer open the controller drives the drawer, not the game: Android's own
|
||||
// handling moves focus with the d-pad and stick, and its fallbacks make A select and B Back
|
||||
// (which closes the drawer) - the same as on the app's main screen.
|
||||
if ((drawerOpen || pcKeyboardOpen) && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event)
|
||||
val fromController = event.device != null && PadBridge.isFromController(event.device)
|
||||
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
|
||||
if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus()
|
||||
drawerControllerActive = true
|
||||
}
|
||||
if (drawerOpen) {
|
||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else 2) % 3
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
return true
|
||||
}
|
||||
val handled = super.dispatchKeyEvent(event)
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
Log.i(TAG, "drawer key=${KeyEvent.keyCodeToString(event.keyCode)} handled=$handled viewFocused=${sessionOverlay.hasFocus()}")
|
||||
}
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK) {
|
||||
if (!handled && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) drawerOpen = false
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
return true
|
||||
}
|
||||
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START
|
||||
val resumeKeyId = event.deviceId to event.keyCode
|
||||
if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
resumeKeysDown.add(resumeKeyId)
|
||||
if (event.repeatCount == 0 && SessionState.suspended) SessionService.resume(this)
|
||||
} else if (event.action == KeyEvent.ACTION_UP) {
|
||||
resumeKeysDown.remove(resumeKeyId)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event)
|
||||
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
|
||||
// A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the
|
||||
// activity, which opens the drawer.
|
||||
@@ -665,18 +783,102 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if ((drawerOpen || pcKeyboardOpen) && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event)
|
||||
if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) {
|
||||
if (!drawerControllerActive) sessionOverlay.requestFocus()
|
||||
drawerControllerActive = true
|
||||
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
|
||||
event.isFromSource(InputDevice.SOURCE_JOYSTICK)
|
||||
) {
|
||||
dispatchDrawerDirection(event)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection()
|
||||
if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event)
|
||||
if (padBridge?.onMotionEvent(event) == true) return true
|
||||
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
/**
|
||||
* The pointer. Touch goes through [PointerGestures] (tap, hold, drag, two-finger scroll); a
|
||||
* mouse arrives with real buttons and a wheel and is forwarded as it is. Every position is
|
||||
* mapped through the letterboxed rectangle into the compositor's fixed 1920x1080 pointer
|
||||
* space, and the arrow is drawn where the app last sent the pointer.
|
||||
*/
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
drawerControllerActive = false
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
private fun dispatchDrawerDirection(event: MotionEvent) {
|
||||
val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
|
||||
val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
|
||||
val hatActive = maxOf(abs(hatX), abs(hatY)) >= DRAWER_HAT_THRESHOLD
|
||||
val x = if (hatActive) hatX else centeredStickAxis(event, MotionEvent.AXIS_X)
|
||||
val y = if (hatActive) hatY else centeredStickAxis(event, MotionEvent.AXIS_Y)
|
||||
val directionThreshold = if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) {
|
||||
DRAWER_STICK_ENTER_THRESHOLD
|
||||
} else {
|
||||
DRAWER_STICK_EXIT_THRESHOLD
|
||||
}
|
||||
val previousWasHorizontal = drawerDirectionKey == KeyEvent.KEYCODE_DPAD_LEFT ||
|
||||
drawerDirectionKey == KeyEvent.KEYCODE_DPAD_RIGHT
|
||||
val horizontalWins = if (previousWasHorizontal) {
|
||||
abs(x) >= abs(y) * DRAWER_ACTIVE_DIRECTION_MARGIN
|
||||
} else {
|
||||
abs(x) > abs(y) * DRAWER_DIRECTION_MARGIN
|
||||
}
|
||||
val keyCode = when {
|
||||
maxOf(abs(x), abs(y)) < directionThreshold -> KeyEvent.KEYCODE_UNKNOWN
|
||||
horizontalWins && x < 0f -> KeyEvent.KEYCODE_DPAD_LEFT
|
||||
horizontalWins -> KeyEvent.KEYCODE_DPAD_RIGHT
|
||||
y < 0f -> KeyEvent.KEYCODE_DPAD_UP
|
||||
else -> KeyEvent.KEYCODE_DPAD_DOWN
|
||||
}
|
||||
val now = SystemClock.uptimeMillis()
|
||||
if (keyCode == drawerDirectionKey) return
|
||||
|
||||
Log.i(TAG, "drawer axis source=${event.source} x=$x y=$y direction=$keyCode")
|
||||
releaseDrawerDirection()
|
||||
if (keyCode == KeyEvent.KEYCODE_UNKNOWN) return
|
||||
|
||||
drawerDirectionKey = keyCode
|
||||
drawerDirectionDeviceId = event.deviceId
|
||||
drawerDirectionDownTime = now
|
||||
drawerDirectionRepeatCount = 0
|
||||
dispatchDrawerKey(KeyEvent.ACTION_DOWN, 0, now)
|
||||
uiHandler.postDelayed(drawerDirectionRepeat, drawerFirstRepeatDelayMs)
|
||||
}
|
||||
|
||||
/** Use Android's per-device flat region, then rescale the remaining stick travel to 0..1. */
|
||||
private fun centeredStickAxis(event: MotionEvent, axis: Int): Float {
|
||||
val value = event.getAxisValue(axis)
|
||||
val flat = (event.device?.getMotionRange(axis, event.source)?.flat ?: 0f)
|
||||
.coerceIn(0f, 0.95f)
|
||||
val magnitude = abs(value)
|
||||
if (magnitude <= flat) return 0f
|
||||
|
||||
val centered = ((magnitude - flat) / (1f - flat)).coerceIn(0f, 1f)
|
||||
return if (value < 0f) -centered else centered
|
||||
}
|
||||
|
||||
private fun releaseDrawerDirection() {
|
||||
uiHandler.removeCallbacks(drawerDirectionRepeat)
|
||||
if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) return
|
||||
dispatchDrawerKey(KeyEvent.ACTION_UP, 0, SystemClock.uptimeMillis())
|
||||
drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
drawerDirectionDeviceId = -1
|
||||
drawerDirectionRepeatCount = 0
|
||||
}
|
||||
|
||||
private fun dispatchDrawerKey(action: Int, repeatCount: Int, eventTime: Long) {
|
||||
val event = KeyEvent(
|
||||
drawerDirectionDownTime, eventTime, action, drawerDirectionKey,
|
||||
repeatCount, 0, drawerDirectionDeviceId, 0, 0, InputDevice.SOURCE_DPAD,
|
||||
)
|
||||
if (action == KeyEvent.ACTION_DOWN && repeatCount == 0) {
|
||||
Log.i(TAG, "drawer synthetic key=${KeyEvent.keyCodeToString(drawerDirectionKey)} viewFocused=${sessionOverlay.hasFocus()}")
|
||||
}
|
||||
super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
private val pointerListener = object : PointerGestures.Listener {
|
||||
override fun onMove(x: Float, y: Float) = movePointer(x, y)
|
||||
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
|
||||
@@ -716,14 +918,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
if (!::displayManager.isInitialized) return
|
||||
val primaryId = display?.displayId ?: windowManager.defaultDisplay.displayId
|
||||
val candidates = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
|
||||
.asSequence()
|
||||
.filter { it.isValid && it.displayId != primaryId && (it.flags and Display.FLAG_PRESENTATION) != 0 }
|
||||
.map { target ->
|
||||
val mode = target.mode
|
||||
SecondScreenDisplay(target.displayId, "${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}")
|
||||
}
|
||||
.toList()
|
||||
val candidates = SecondScreenDisplays.available(displayManager, primaryId)
|
||||
val oldIds = secondScreenDisplays.map { it.id }.toSet()
|
||||
secondScreenDisplays = candidates
|
||||
val newIds = candidates.map { it.id }.toSet()
|
||||
@@ -784,6 +979,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onQam = {
|
||||
if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
|
||||
},
|
||||
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
|
||||
)
|
||||
secondScreenPresentation = presentation
|
||||
}
|
||||
@@ -844,7 +1040,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
return touchpad.onTouch(event)
|
||||
}
|
||||
return gestures.onTouch(event)
|
||||
val rect = drawnRect() ?: return false
|
||||
fun sendTouch(action: Int, index: Int) {
|
||||
val x = ((event.getX(index) - rect.left) / rect.width()).coerceIn(0f, 1f)
|
||||
val y = ((event.getY(index) - rect.top) / rect.height()).coerceIn(0f, 1f)
|
||||
WaylandCompositor.nativeSendTouch(action, event.getPointerId(index), (x * 1919f).toInt(), (y * 1079f).toInt())
|
||||
}
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> sendTouch(0, event.actionIndex)
|
||||
MotionEvent.ACTION_MOVE -> for (index in 0 until event.pointerCount) sendTouch(1, index)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> sendTouch(2, event.actionIndex)
|
||||
MotionEvent.ACTION_CANCEL -> WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
else -> return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** A mouse: hover moves, buttons press, the wheel scrolls. Android sends buttons as touch
|
||||
@@ -885,7 +1094,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionPrefs.OSC_ALWAYS -> true
|
||||
SessionPrefs.OSC_STEAM_QAM -> true
|
||||
SessionPrefs.OSC_NEVER -> false
|
||||
else -> !PadBridge.anyControllerConnected()
|
||||
// Auto: the touch pad when there is no controller - except on the desktop, where the
|
||||
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
|
||||
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
|
||||
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
|
||||
}
|
||||
if (show == (controls.visibility == View.VISIBLE)) return
|
||||
if (!show) controls.releaseAll()
|
||||
@@ -941,6 +1153,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onPause() {
|
||||
(getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener)
|
||||
releaseDrawerDirection()
|
||||
// A button held when the app goes away would stay held in the ring for the whole session.
|
||||
onScreenControls?.releaseAll()
|
||||
keyboard?.takeIf { it.shown }?.hide()
|
||||
@@ -975,6 +1188,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// Deliberately does NOT end the session: this activity can be destroyed while the user is
|
||||
// in another app, and the whole point of the service is that Steam survives that.
|
||||
watching = false
|
||||
releaseDrawerDirection()
|
||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||
pendingBackAction = null
|
||||
closeSecondScreen(reset = true)
|
||||
if (::hud.isInitialized) hud.stop()
|
||||
padBridge?.stop()
|
||||
@@ -991,6 +1207,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionActivity"
|
||||
private const val BACK_DOUBLE_PRESS_TIMEOUT_MS = 500L
|
||||
private const val DRAWER_HAT_THRESHOLD = 0.5f
|
||||
private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f
|
||||
private const val DRAWER_STICK_EXIT_THRESHOLD = 0.35f
|
||||
private const val DRAWER_DIRECTION_MARGIN = 1.15f
|
||||
private const val DRAWER_ACTIVE_DIRECTION_MARGIN = 0.85f
|
||||
private const val DRAWER_SLOW_REPEAT_FLOOR_MS = 240L
|
||||
private const val DRAWER_FAST_REPEAT_INTERVAL_MS = 90L
|
||||
private const val DRAWER_REPEAT_ACCELERATION_MS = 1_400L
|
||||
/** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */
|
||||
private const val SCALE_FIT = 1
|
||||
private const val ALIGN_CENTER = 0
|
||||
|
||||
@@ -149,6 +149,7 @@ object DeviceReport {
|
||||
k("Skip xalia", SessionPrefs.noXalia(context))
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch games to fill", SessionPrefs.forceFullscreen(context))
|
||||
k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic")
|
||||
k("Microphone", SessionPrefs.micEnabled(context))
|
||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ProviderInfo
|
||||
import android.content.res.AssetFileDescriptor
|
||||
import android.database.Cursor
|
||||
import android.database.MatrixCursor
|
||||
import android.graphics.Point
|
||||
import android.os.CancellationSignal
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.provider.DocumentsContract.Document
|
||||
import android.provider.DocumentsContract.Root
|
||||
import android.provider.DocumentsProvider
|
||||
import android.webkit.MimeTypeMap
|
||||
import com.droiddeck.launcher.R
|
||||
import java.io.File
|
||||
import java.io.FileNotFoundException
|
||||
import java.io.IOException
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
|
||||
/**
|
||||
* The app's own data folder (the Linux runtime, settings, logs) in Android's file picker, under the
|
||||
* app's name beside the phone's storage - what MT Manager's "documents provider" injection does, as
|
||||
* part of the app. Only the system's documents UI can bind it (MANAGE_DOCUMENTS); another app sees
|
||||
* a file only when the user picks it there.
|
||||
*
|
||||
* A document id is the file's absolute path, and nothing outside the data folder is ever handed out
|
||||
* or accepted: every id is resolved and checked to lie inside it.
|
||||
*/
|
||||
class AppFilesProvider : DocumentsProvider() {
|
||||
private lateinit var base: File
|
||||
private lateinit var baseCanonical: String
|
||||
|
||||
override fun attachInfo(context: Context, info: ProviderInfo) {
|
||||
super.attachInfo(context, info)
|
||||
base = context.dataDir
|
||||
baseCanonical = base.canonicalPath
|
||||
}
|
||||
|
||||
override fun onCreate() = true
|
||||
|
||||
override fun queryRoots(projection: Array<String>?): Cursor {
|
||||
val ctx = context!!
|
||||
val result = MatrixCursor(projection ?: ROOT_COLUMNS)
|
||||
result.newRow().apply {
|
||||
add(Root.COLUMN_ROOT_ID, ROOT_ID)
|
||||
add(Root.COLUMN_DOCUMENT_ID, base.absolutePath)
|
||||
add(Root.COLUMN_TITLE, titleFor(ctx))
|
||||
add(Root.COLUMN_SUMMARY, null)
|
||||
add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE or Root.FLAG_SUPPORTS_SEARCH or Root.FLAG_SUPPORTS_IS_CHILD)
|
||||
add(Root.COLUMN_MIME_TYPES, "*/*")
|
||||
add(Root.COLUMN_AVAILABLE_BYTES, base.freeSpace)
|
||||
add(Root.COLUMN_ICON, R.mipmap.ic_launcher)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
override fun queryDocument(documentId: String, projection: Array<String>?): Cursor =
|
||||
MatrixCursor(projection ?: DOCUMENT_COLUMNS).also { addRow(it, fileFor(documentId)) }
|
||||
|
||||
override fun queryChildDocuments(parentDocumentId: String, projection: Array<String>?, sortOrder: String?): Cursor {
|
||||
val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS)
|
||||
// A link in the runtime that leads out of the data folder (/etc/localtime and the like) is
|
||||
// left out rather than listed as something that cannot be opened.
|
||||
fileFor(parentDocumentId).listFiles()?.filter { inside(it) }?.forEach { addRow(result, it) }
|
||||
return result
|
||||
}
|
||||
|
||||
override fun openDocument(documentId: String, mode: String, signal: CancellationSignal?): ParcelFileDescriptor =
|
||||
ParcelFileDescriptor.open(fileFor(documentId), ParcelFileDescriptor.parseMode(mode))
|
||||
|
||||
override fun openDocumentThumbnail(documentId: String, sizeHint: Point?, signal: CancellationSignal?): AssetFileDescriptor {
|
||||
val file = fileFor(documentId)
|
||||
return AssetFileDescriptor(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY), 0, file.length())
|
||||
}
|
||||
|
||||
override fun createDocument(parentDocumentId: String, mimeType: String, displayName: String): String {
|
||||
val parent = fileFor(parentDocumentId)
|
||||
val name = displayName.substringAfterLast('/')
|
||||
var file = File(parent, name)
|
||||
var n = 2
|
||||
while (file.exists()) file = File(parent, "$name (${n++})")
|
||||
val made = try {
|
||||
if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile()
|
||||
} catch (e: IOException) {
|
||||
false
|
||||
}
|
||||
if (!made) throw FileNotFoundException("could not create ${file.path}")
|
||||
return file.absolutePath
|
||||
}
|
||||
|
||||
override fun deleteDocument(documentId: String) {
|
||||
val file = fileFor(documentId)
|
||||
if (file.absolutePath == base.absolutePath) throw FileNotFoundException("the app folder itself is not deleted")
|
||||
try {
|
||||
deleteTree(file.toPath())
|
||||
} catch (e: IOException) {
|
||||
throw FileNotFoundException("could not delete $documentId: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a file or a folder and what is in it without ever following a link: the runtime holds
|
||||
* links to places outside it, and deleting a folder must remove the link, not what it points at.
|
||||
*/
|
||||
private fun deleteTree(root: Path) {
|
||||
if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
|
||||
Files.delete(root)
|
||||
return
|
||||
}
|
||||
Files.walkFileTree(root, object : SimpleFileVisitor<Path>() {
|
||||
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||
Files.delete(file)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
|
||||
if (exc != null) throw exc
|
||||
Files.delete(dir)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
override fun removeDocument(documentId: String, parentDocumentId: String) = deleteDocument(documentId)
|
||||
|
||||
override fun renameDocument(documentId: String, displayName: String): String {
|
||||
val file = fileFor(documentId)
|
||||
val target = File(file.parentFile, displayName.substringAfterLast('/'))
|
||||
if (target.exists() || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId")
|
||||
return target.absolutePath
|
||||
}
|
||||
|
||||
override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String {
|
||||
val source = fileFor(sourceDocumentId)
|
||||
val targetParent = fileFor(targetParentDocumentId)
|
||||
if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder")
|
||||
val target = File(targetParent, source.name)
|
||||
if (target.exists() || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId")
|
||||
return target.absolutePath
|
||||
}
|
||||
|
||||
override fun getDocumentType(documentId: String): String = mimeOf(fileFor(documentId))
|
||||
|
||||
override fun isChildDocument(parentDocumentId: String, documentId: String): Boolean {
|
||||
val parent = runCatching { fileFor(parentDocumentId).absolutePath }.getOrNull() ?: return false
|
||||
val child = runCatching { fileFor(documentId).absolutePath }.getOrNull() ?: return false
|
||||
return child == parent || child.startsWith("$parent/")
|
||||
}
|
||||
|
||||
override fun querySearchDocuments(rootId: String, query: String, projection: Array<String>?): Cursor {
|
||||
val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS)
|
||||
val needle = query.lowercase()
|
||||
val pending = ArrayDeque(listOf(base))
|
||||
var visited = 0
|
||||
// The runtime is tens of thousands of files: a bounded walk, not the whole tree.
|
||||
while (pending.isNotEmpty() && result.count < 50 && visited++ < 20000) {
|
||||
val f = pending.removeFirst()
|
||||
if (!inside(f)) continue
|
||||
if (f.isDirectory) f.listFiles()?.let { pending.addAll(it) }
|
||||
else if (f.name.lowercase().contains(needle)) addRow(result, f)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** The file an id names, when it exists and lies inside the data folder (links followed). */
|
||||
private fun fileFor(documentId: String): File {
|
||||
val f = File(documentId)
|
||||
if (!f.isAbsolute || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files")
|
||||
if (!f.exists()) throw FileNotFoundException("$documentId not found")
|
||||
return f
|
||||
}
|
||||
|
||||
private fun inside(f: File): Boolean {
|
||||
// The folder's own entries are listed as they are; a link is judged by where it leads.
|
||||
val abs = f.absoluteFile.normalize().path
|
||||
if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false
|
||||
val real = runCatching { f.canonicalPath }.getOrNull() ?: return false
|
||||
return real == baseCanonical || real.startsWith("$baseCanonical/")
|
||||
}
|
||||
|
||||
private fun addRow(result: MatrixCursor, file: File) {
|
||||
var flags = 0
|
||||
if (file.isDirectory) {
|
||||
if (file.canWrite()) flags = flags or Document.FLAG_DIR_SUPPORTS_CREATE
|
||||
} else if (file.canWrite()) {
|
||||
flags = flags or Document.FLAG_SUPPORTS_WRITE
|
||||
}
|
||||
if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true) {
|
||||
flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or
|
||||
Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE
|
||||
}
|
||||
val mime = mimeOf(file)
|
||||
if (mime.startsWith("image/")) flags = flags or Document.FLAG_SUPPORTS_THUMBNAIL
|
||||
result.newRow().apply {
|
||||
add(Document.COLUMN_DOCUMENT_ID, file.absolutePath)
|
||||
add(Document.COLUMN_DISPLAY_NAME, if (file.absolutePath == base.absolutePath) titleFor(context!!) else file.name)
|
||||
add(Document.COLUMN_SIZE, if (file.isDirectory) null else file.length())
|
||||
add(Document.COLUMN_MIME_TYPE, mime)
|
||||
add(Document.COLUMN_LAST_MODIFIED, file.lastModified())
|
||||
add(Document.COLUMN_FLAGS, flags)
|
||||
}
|
||||
}
|
||||
|
||||
private fun mimeOf(file: File): String {
|
||||
if (file.isDirectory) return Document.MIME_TYPE_DIR
|
||||
val ext = file.extension.lowercase()
|
||||
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) ?: "application/octet-stream"
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val ROOT_ID = "app"
|
||||
|
||||
private val ROOT_COLUMNS = arrayOf(
|
||||
Root.COLUMN_ROOT_ID, Root.COLUMN_MIME_TYPES, Root.COLUMN_FLAGS, Root.COLUMN_ICON,
|
||||
Root.COLUMN_TITLE, Root.COLUMN_SUMMARY, Root.COLUMN_DOCUMENT_ID, Root.COLUMN_AVAILABLE_BYTES,
|
||||
)
|
||||
private val DOCUMENT_COLUMNS = arrayOf(
|
||||
Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME,
|
||||
Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
|
||||
)
|
||||
|
||||
/**
|
||||
* The name in the picker. The same app ships under other package names (for the performance
|
||||
* modes some phones give only named apps); each says which it is, so four installs are not
|
||||
* four identical "DroidDeck" entries.
|
||||
*/
|
||||
fun titleFor(context: Context): String {
|
||||
val name = context.getString(R.string.app_name)
|
||||
return when (context.packageName) {
|
||||
"com.tencent.ig" -> "$name PUBG"
|
||||
"com.antutu.benchmark.full" -> "$name AnTuTu"
|
||||
"com.ludashi.benchmark" -> "$name Ludashi"
|
||||
else -> name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
/**
|
||||
* Box art for the emulators' games, found and kept on the device: the front end shows a disc image
|
||||
* with nothing but its emulator's logo otherwise.
|
||||
*
|
||||
* In order: the name of the file against RetroArch's thumbnail collection for the system
|
||||
* (libretro-thumbnails, named after the standard disc-dump names - "Need for Speed - Underground 2
|
||||
* (USA)"), first exactly and then loosely (tags dropped, the same region preferred) against the
|
||||
* collection's list of names; then the disc's own ID, read from the image - PS2 serials against
|
||||
* xlenore/ps2-covers (what PCSX2 and ARMSX2 download from), GameCube/Wii IDs against GameTDB (what
|
||||
* Dolphin uses). A PS3 disc image gives its own PS3_GAME/ICON0.PNG first: the libretro PS3
|
||||
* collection is small. A cover is downloaded once into files/covers; a game none of them has is not
|
||||
* asked about again for a few days.
|
||||
*/
|
||||
object CoverArt {
|
||||
private const val TAG = "CoverArt"
|
||||
private const val MISS_RETRY_MS = 3L * 24 * 3600 * 1000
|
||||
private const val INDEX_TTL_MS = 14L * 24 * 3600 * 1000
|
||||
/** Downloads in one pass, so a first visit to a big library does not hold the network for long. */
|
||||
private const val MAX_PER_PASS = 40
|
||||
|
||||
/** The emulator's systems in libretro-thumbnails, in the order they are tried. */
|
||||
private val collections = mapOf(
|
||||
"rpcs3" to listOf("Sony_-_PlayStation_3"),
|
||||
"armsx2" to listOf("Sony_-_PlayStation_2"),
|
||||
"duckstation" to listOf("Sony_-_PlayStation"),
|
||||
"ppsspp" to listOf("Sony_-_PlayStation_Portable"),
|
||||
"dolphin" to listOf("Nintendo_-_GameCube", "Nintendo_-_Wii"),
|
||||
"melonds" to listOf("Nintendo_-_Nintendo_DS"),
|
||||
"cemu" to listOf("Nintendo_-_Wii_U"),
|
||||
)
|
||||
|
||||
private fun root(context: Context) = File(context.filesDir, "covers")
|
||||
|
||||
/** The file name, as the cover is kept under: a game keeps its art when its folder moves. */
|
||||
private fun keyOf(rom: Library.Rom): String =
|
||||
rom.hostPath.name.replace(Regex("[^A-Za-z0-9._() -]"), "_").take(150)
|
||||
|
||||
private fun coverFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.img")
|
||||
private fun missFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.miss")
|
||||
|
||||
/** A cover already on the device for this game, or null. */
|
||||
fun cached(context: Context, rom: Library.Rom): File? = coverFile(context, rom).takeIf { it.isFile && it.length() > 0 }
|
||||
|
||||
private fun wanted(context: Context, rom: Library.Rom): Boolean {
|
||||
if (rom.art != null || cached(context, rom) != null || rom.emulatorId !in collections) return false
|
||||
val miss = missFile(context, rom)
|
||||
return !(miss.isFile && System.currentTimeMillis() - miss.lastModified() < MISS_RETRY_MS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for covers for the games that have none, on the calling (background) thread. True when
|
||||
* at least one was found, so the caller rebuilds the list to show it.
|
||||
*/
|
||||
fun fetchMissing(context: Context, roms: List<Library.Rom>): Boolean {
|
||||
var found = false
|
||||
var tries = 0
|
||||
for (rom in roms) {
|
||||
if (!wanted(context, rom)) continue
|
||||
if (++tries > MAX_PER_PASS) break
|
||||
val target = coverFile(context, rom)
|
||||
// A PS3 disc carries its own cover (PS3_GAME/ICON0.PNG, not encrypted): no download.
|
||||
if (rom.emulatorId == "rpcs3" && try { copyPs3Icon(rom.hostPath, target) } catch (e: Exception) { false }) {
|
||||
Log.i(TAG, "${rom.name}: ICON0.PNG from the disc")
|
||||
missFile(context, rom).delete()
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
val url = try { findUrl(context, rom) } catch (e: Exception) { Log.w(TAG, "${rom.name}: $e"); null }
|
||||
if (url != null && download(url, target)) {
|
||||
Log.i(TAG, "${rom.name}: $url")
|
||||
missFile(context, rom).delete()
|
||||
found = true
|
||||
} else {
|
||||
missFile(context, rom).apply { parentFile?.mkdirs(); writeText(url ?: "") }
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private fun findUrl(context: Context, rom: Library.Rom): String? {
|
||||
val name = rom.hostPath.nameWithoutExtension.removeSuffix(".dec")
|
||||
for (collection in collections.getValue(rom.emulatorId)) {
|
||||
// Exactly the dump name first: no listing needed.
|
||||
val exact = thumbnailUrl(collection, name)
|
||||
if (exists(exact)) return exact
|
||||
// Then loosely, against the collection's names.
|
||||
nearest(name, names(context, collection))?.let { return thumbnailUrl(collection, it) }
|
||||
}
|
||||
// The disc's own ID.
|
||||
return when (rom.emulatorId) {
|
||||
"armsx2" -> ps2Serial(rom.hostPath)?.let { "https://raw.githubusercontent.com/xlenore/ps2-covers/main/covers/default/$it.jpg" }
|
||||
"dolphin" -> nintendoDiscId(rom.hostPath)?.let { id ->
|
||||
val region = when (id.getOrNull(3)) { 'P' -> "EN"; 'J' -> "JA"; 'K' -> "KO"; else -> "US" }
|
||||
"https://art.gametdb.com/wii/cover/$region/$id.png"
|
||||
}
|
||||
else -> null
|
||||
}?.takeIf { exists(it) }
|
||||
}
|
||||
|
||||
/** libretro-thumbnails replaces these in a title's file name. */
|
||||
private fun thumbName(title: String) = title.replace(Regex("[&*/:`<>?\\\\|\"]"), "_")
|
||||
|
||||
private fun thumbnailUrl(collection: String, title: String) =
|
||||
"https://raw.githubusercontent.com/libretro-thumbnails/$collection/master/Named_Boxarts/" +
|
||||
URLEncoder.encode("${thumbName(title)}.png", "UTF-8").replace("+", "%20")
|
||||
|
||||
// ---- loose matching ------------------------------------------------------------------------
|
||||
|
||||
private fun tags(name: String): List<String> = Regex("[(\\[]([^)\\]]*)[)\\]]").findAll(name).map { it.groupValues[1].lowercase() }.toList()
|
||||
|
||||
/** A title without its tags, articles and punctuation: "Legend of Zelda, The (USA)" = "legend of zelda". */
|
||||
private fun base(name: String): String = name
|
||||
.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), " ")
|
||||
.lowercase()
|
||||
.replace(Regex("[^a-z0-9]+"), " ")
|
||||
.split(' ').filter { it.isNotEmpty() && it != "the" && it != "a" }
|
||||
.joinToString(" ")
|
||||
|
||||
private fun nearest(name: String, candidates: List<String>): String? {
|
||||
if (candidates.isEmpty()) return null
|
||||
val want = base(name)
|
||||
if (want.isEmpty()) return null
|
||||
val same = candidates.filter { base(it) == want }
|
||||
if (same.isEmpty()) return null
|
||||
val region = tags(name).firstOrNull { it in setOf("usa", "europe", "japan", "world", "korea") } ?: "usa"
|
||||
return same.firstOrNull { region in tags(it) } ?: same.firstOrNull { "usa" in tags(it) } ?: same.first()
|
||||
}
|
||||
|
||||
/** The titles in a collection's Named_Boxarts (no extension), kept for a fortnight. */
|
||||
private fun names(context: Context, collection: String): List<String> {
|
||||
val cache = File(root(context), "index-$collection.txt")
|
||||
if (cache.isFile && System.currentTimeMillis() - cache.lastModified() < INDEX_TTL_MS) return cache.readLines()
|
||||
val list = try {
|
||||
val top = JSONArray(get("https://api.github.com/repos/libretro-thumbnails/$collection/contents/") ?: return cachedOr(cache))
|
||||
val sha = (0 until top.length()).map { top.getJSONObject(it) }.firstOrNull { it.optString("name") == "Named_Boxarts" }
|
||||
?.optString("sha") ?: return cachedOr(cache)
|
||||
val tree = JSONObject(get("https://api.github.com/repos/libretro-thumbnails/$collection/git/trees/$sha") ?: return cachedOr(cache))
|
||||
.getJSONArray("tree")
|
||||
(0 until tree.length()).map { tree.getJSONObject(it).optString("path") }
|
||||
.filter { it.endsWith(".png") }.map { it.removeSuffix(".png") }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "index $collection: $e"); return cachedOr(cache)
|
||||
}
|
||||
cache.parentFile?.mkdirs()
|
||||
cache.writeText(list.joinToString("\n"))
|
||||
return list
|
||||
}
|
||||
|
||||
private fun cachedOr(cache: File): List<String> = if (cache.isFile) cache.readLines() else emptyList()
|
||||
|
||||
// ---- disc IDs ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A file's bytes from an ISO 9660 image by path ("PS3_GAME/ICON0.PNG"), or null. Primary volume
|
||||
* names only (upper case, ";1" suffix), which is what PS2 and PS3 discs use.
|
||||
*/
|
||||
private fun isoFile(file: File, path: String, maxSize: Int): ByteArray? {
|
||||
if (!file.name.endsWith(".iso", ignoreCase = true)) return null
|
||||
RandomAccessFile(file, "r").use { f ->
|
||||
fun read(lba: Long, length: Int): ByteArray = ByteArray(length).also { f.seek(lba * 2048); f.readFully(it) }
|
||||
fun le32(b: ByteArray, at: Int) = (b[at].toLong() and 0xff) or ((b[at + 1].toLong() and 0xff) shl 8) or
|
||||
((b[at + 2].toLong() and 0xff) shl 16) or ((b[at + 3].toLong() and 0xff) shl 24)
|
||||
val pvd = read(16, 2048)
|
||||
if (String(pvd, 1, 5, Charsets.US_ASCII) != "CD001") return null
|
||||
var lba = le32(pvd, 156 + 2)
|
||||
var size = le32(pvd, 156 + 10)
|
||||
val parts = path.split('/')
|
||||
for ((i, part) in parts.withIndex()) {
|
||||
val dir = read(lba, size.toInt().coerceAtMost(256 * 1024))
|
||||
var at = 0
|
||||
var hit = false
|
||||
while (at < dir.size) {
|
||||
val len = dir[at].toInt() and 0xff
|
||||
if (len == 0) { at = (at / 2048 + 1) * 2048; continue }
|
||||
val name = String(dir, at + 33, dir[at + 32].toInt() and 0xff, Charsets.US_ASCII).substringBefore(';')
|
||||
if (name.equals(part, ignoreCase = true)) {
|
||||
lba = le32(dir, at + 2); size = le32(dir, at + 10); hit = true; break
|
||||
}
|
||||
at += len
|
||||
}
|
||||
if (!hit) return null
|
||||
if (i == parts.lastIndex) return if (size in 1..maxSize) read(lba, size.toInt()) else null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun copyPs3Icon(file: File, target: File): Boolean {
|
||||
val png = isoFile(file, "PS3_GAME/ICON0.PNG", 4 * 1024 * 1024) ?: return false
|
||||
target.parentFile?.mkdirs()
|
||||
val tmp = File(target.path + ".part")
|
||||
tmp.writeBytes(png)
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(tmp.path, bounds)
|
||||
return if (bounds.outWidth > 0 && tmp.renameTo(target)) true else { tmp.delete(); false }
|
||||
}
|
||||
|
||||
/** "SLUS-21065" from a PS2 .iso's SYSTEM.CNF (BOOT2 = cdrom0:\SLUS_210.65;1), or null. */
|
||||
private fun ps2Serial(file: File): String? {
|
||||
val cnf = String(isoFile(file, "SYSTEM.CNF", 4096) ?: return null, Charsets.US_ASCII)
|
||||
val m = Regex("BOOT2\\s*=\\s*cdrom0:\\\\?([A-Z]{4})_(\\d{3})\\.(\\d{2})").find(cnf) ?: return null
|
||||
return "${m.groupValues[1]}-${m.groupValues[2]}${m.groupValues[3]}"
|
||||
}
|
||||
|
||||
/** The six-character ID of a GameCube/Wii disc image (.iso/.gcm, or .wbfs), or null. */
|
||||
private fun nintendoDiscId(file: File): String? {
|
||||
val offset = when (file.extension.lowercase()) { "iso", "gcm" -> 0L; "wbfs" -> 0x200L; else -> return null }
|
||||
RandomAccessFile(file, "r").use { f ->
|
||||
val b = ByteArray(6); f.seek(offset); f.readFully(b)
|
||||
val id = String(b, Charsets.US_ASCII)
|
||||
return id.takeIf { it.all { c -> c.isLetterOrDigit() } }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- network -------------------------------------------------------------------------------
|
||||
|
||||
private fun open(url: String, method: String = "GET"): HttpURLConnection =
|
||||
(URL(url).openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = method
|
||||
connectTimeout = 10_000
|
||||
readTimeout = 20_000
|
||||
instanceFollowRedirects = true
|
||||
setRequestProperty("User-Agent", "DroidDeck")
|
||||
}
|
||||
|
||||
private fun exists(url: String): Boolean = try {
|
||||
val c = open(url, "HEAD"); val ok = c.responseCode == 200; c.disconnect(); ok
|
||||
} catch (e: Exception) { false }
|
||||
|
||||
private fun get(url: String): String? = try {
|
||||
val c = open(url)
|
||||
if (c.responseCode != 200) { c.disconnect(); null } else c.inputStream.bufferedReader().use { it.readText() }
|
||||
} catch (e: Exception) { Log.w(TAG, "$url: $e"); null }
|
||||
|
||||
/** Saves the image at [url] to [target] if it really is an image. */
|
||||
private fun download(url: String, target: File): Boolean = try {
|
||||
val c = open(url)
|
||||
if (c.responseCode != 200) { c.disconnect(); false } else {
|
||||
target.parentFile?.mkdirs()
|
||||
val tmp = File(target.path + ".part")
|
||||
c.inputStream.use { input -> tmp.outputStream().use { input.copyTo(it) } }
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(tmp.path, bounds)
|
||||
if (bounds.outWidth > 0 && tmp.renameTo(target)) true else { tmp.delete(); false }
|
||||
}
|
||||
} catch (e: Exception) { Log.w(TAG, "$url: $e"); false }
|
||||
}
|
||||
@@ -71,11 +71,24 @@ object Library {
|
||||
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
|
||||
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
|
||||
)
|
||||
/**
|
||||
* A dump's file name as a title: its tags - (USA), (En,Fr,Es,Pt), [!], (v1.01) - identify the
|
||||
* file and are dropped for reading ("Tomb Raider (USA) (En,Fr,Es,Pt)" -> "Tomb Raider"). The
|
||||
* file keeps them, and the cover lookup still uses them.
|
||||
*/
|
||||
private fun displayTitle(name: String): String =
|
||||
name.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), "").trim().ifEmpty { name }
|
||||
|
||||
/** Every system folder name the specs claim, so a loose-file scan of the root skips them. */
|
||||
private val systemFolders: Set<String> by lazy { specs.flatMap { it.folders }.toSet() }
|
||||
private val installedIds = mapOf(
|
||||
"rpcs3" to "rpcs3", "armsx2" to "armsx2", "dolphin" to "dolphin", "duckstation" to "duckstation",
|
||||
"melonds" to "melonds", "cemu" to "cemu", "ppsspp" to "emulators", "retroarch" to "emulators",
|
||||
)
|
||||
|
||||
/** The emulator's name for a program path from the rail ("ARMSX2"), or null. */
|
||||
fun nameForProgram(program: String?): String? = specs.firstOrNull { it.program == program }?.name
|
||||
|
||||
/** Desktop catalog package that supplies this emulator. */
|
||||
fun packageId(emulatorId: String): String? = installedIds[emulatorId]
|
||||
|
||||
@@ -85,37 +98,68 @@ object Library {
|
||||
return specs.map { spec ->
|
||||
val games = ArrayList<Rom>()
|
||||
if (romsRoot != null && spec.exts.isNotEmpty()) {
|
||||
// The system's folder(s), matched without regard to case, then the root itself for
|
||||
// a file left loose there - and one folder deeper, since a dump usually comes as a
|
||||
// folder named for the game with the image inside it.
|
||||
// The system's folder(s), matched without regard to case, and up to three folders
|
||||
// inside them - a dump usually comes as a folder named for the game with the image
|
||||
// inside it, and people sort those into folders of their own (ps2/games/<game>/).
|
||||
// The root itself only one deep, for a file left loose there.
|
||||
val systemDirs = romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() in spec.folders }.orEmpty().toList()
|
||||
val dirs = LinkedHashSet<File>()
|
||||
for (top in systemDirs + romsRoot) {
|
||||
dirs.add(top)
|
||||
top.listFiles { f -> f.isDirectory }?.forEach { dirs.add(it) }
|
||||
}
|
||||
// A BIOS folder holds the console's firmware, not games (psx/bios/SCPH1001.BIN).
|
||||
for (top in systemDirs) top.walkTopDown().maxDepth(3).onEnter { it.name.lowercase() !in firmwareFolders }
|
||||
.filter { it.isDirectory }.forEach { dirs.add(it) }
|
||||
dirs.add(romsRoot)
|
||||
// ...and not into another system's folder: a PS3 .iso in ps3/ is not a PS2 game.
|
||||
romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() !in systemFolders }?.forEach { dirs.add(it) }
|
||||
for (dir in dirs) {
|
||||
// A PS3 disc dump is a folder with PS3_GAME in it; RPCS3 boots the folder.
|
||||
if (spec.id == "rpcs3" && File(dir, "PS3_GAME").isDirectory) {
|
||||
val rel = dir.relativeTo(romsRoot).path
|
||||
games.add(Rom(dir.name, dir, "/root/ROMs/$rel", spec.id))
|
||||
games.add(Rom(displayTitle(dir.name), dir, "/root/ROMs/$rel", spec.id,
|
||||
// The dump carries its own art, as an installed package does.
|
||||
art = File(dir, "PS3_GAME/ICON0.PNG").takeIf { it.isFile }))
|
||||
continue
|
||||
}
|
||||
dir.listFiles()?.sortedBy { it.name.lowercase() }?.forEach { f ->
|
||||
val files = dir.listFiles()?.sortedBy { it.name.lowercase() }.orEmpty()
|
||||
// A disc sheet (.cue, .gdi) names its track files and a playlist (.m3u) its
|
||||
// discs: the sheet is the game, what it names is part of it. A .bin beside a
|
||||
// .cue of the same name is a track even when the sheet can't be read.
|
||||
val parts = files.filter { it.isFile && it.extension.lowercase() in sheetExts }.flatMap(::sheetParts).toSet()
|
||||
files.forEach { f ->
|
||||
val ext = f.extension.lowercase()
|
||||
// A .bin beside a .cue is a track, not a game.
|
||||
if (f.isFile && ext in spec.exts && !(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) {
|
||||
if (f.isFile && ext in spec.exts && f.name.lowercase() !in parts &&
|
||||
!(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) {
|
||||
val rel = f.relativeTo(romsRoot).path
|
||||
games.add(Rom(f.nameWithoutExtension.removeSuffix(".dec"), f, "/root/ROMs/$rel", spec.id))
|
||||
games.add(Rom(displayTitle(f.nameWithoutExtension.removeSuffix(".dec")), f, "/root/ROMs/$rel", spec.id))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (spec.id == "rpcs3") games.addAll(rpcs3Installed(context))
|
||||
Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), games)
|
||||
// A cover found for the game before (CoverArt) where it has no art of its own.
|
||||
val withArt = games.map { g -> if (g.art != null) g else CoverArt.cached(context, g)?.let { Rom(g.name, g.hostPath, g.guestPath, g.emulatorId, it) } ?: g }
|
||||
Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), withArt)
|
||||
}
|
||||
}
|
||||
|
||||
private val firmwareFolders = setOf("bios", "firmware")
|
||||
private val sheetExts = setOf("cue", "gdi", "m3u")
|
||||
|
||||
/** The file names (lower case) a .cue, .gdi or .m3u refers to, from its own folder. */
|
||||
private fun sheetParts(sheet: File): List<String> = runCatching {
|
||||
if (sheet.length() > 64 * 1024) return emptyList()
|
||||
sheet.readLines().mapNotNull { line ->
|
||||
val t = line.trim()
|
||||
when (sheet.extension.lowercase()) {
|
||||
// FILE "Tekken 3 (USA) (Track 1).bin" BINARY
|
||||
"cue" -> Regex("^FILE\\s+\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1)
|
||||
?: Regex("^FILE\\s+(\\S+)", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1)
|
||||
// 1 0 4 2352 "track01.bin" 0 / 1 0 4 2352 track01.bin 0
|
||||
"gdi" -> Regex("\"([^\"]+)\"").find(t)?.groupValues?.get(1) ?: t.split(Regex("\\s+")).getOrNull(4)
|
||||
else -> t.takeIf { it.isNotEmpty() && !it.startsWith("#") }
|
||||
}
|
||||
}.map { File(it.replace('\\', '/')).name.lowercase() }
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
/**
|
||||
* What RPCS3 has installed on its own HDD - packages (PSN games) land in dev_hdd0/game/<ID>
|
||||
* with a PARAM.SFO for the title and an EBOOT to boot - as RPCS3's own file list would show
|
||||
@@ -170,6 +214,11 @@ object Library {
|
||||
/** How the emulator is told which game to boot, on its command line. */
|
||||
fun launchArgs(emulatorId: String, guestPath: String): List<String> = when (emulatorId) {
|
||||
"rpcs3" -> listOf("--no-gui", guestPath)
|
||||
// Straight into the game in its controller-driven full-screen UI (first-time setup there
|
||||
// too), and gone when the game is quit from its pause menu (guide button): -batch.
|
||||
"armsx2" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath)
|
||||
// DuckStation shares PCSX2's flags (src/duckstation-qt/qthost.cpp): the same launch and exit.
|
||||
"duckstation" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath)
|
||||
"dolphin" -> listOf("-e", guestPath)
|
||||
"cemu" -> listOf("-g", guestPath)
|
||||
else -> listOf(guestPath)
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.view.Display
|
||||
|
||||
/** The control surface shown on a secondary Android display during a Linux session. */
|
||||
enum class SecondScreenMode(val id: String, val label: String) {
|
||||
NONE("none", "None"),
|
||||
@@ -8,3 +11,19 @@ enum class SecondScreenMode(val id: String, val label: String) {
|
||||
}
|
||||
|
||||
data class SecondScreenDisplay(val id: Int, val label: String)
|
||||
|
||||
/** The presentation-capable displays shared by the session controls and Android app launcher. */
|
||||
object SecondScreenDisplays {
|
||||
fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List<SecondScreenDisplay> =
|
||||
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
|
||||
.asSequence()
|
||||
.filter { it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 }
|
||||
.map { target ->
|
||||
val mode = target.mode
|
||||
SecondScreenDisplay(
|
||||
target.displayId,
|
||||
"${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}",
|
||||
)
|
||||
}
|
||||
.toList()
|
||||
}
|
||||
@@ -31,12 +31,18 @@ object DesktopCatalog {
|
||||
return try {
|
||||
val json = JSONObject(body)
|
||||
val arr = json.getJSONArray("packages")
|
||||
// A package built per memory page size (ARMSX2: 4K and 16K kernels) names the others
|
||||
// under "pages"; the device's own size picks one, and the top-level file is the 4K one.
|
||||
val pageSize = try {
|
||||
android.system.Os.sysconf(android.system.OsConstants._SC_PAGESIZE).toString()
|
||||
} catch (e: Exception) { "4096" }
|
||||
(0 until arr.length()).map { i ->
|
||||
val o = arr.getJSONObject(i)
|
||||
val file = o.optJSONObject("pages")?.optJSONObject(pageSize) ?: o
|
||||
Entry(
|
||||
o.getString("id"), o.getString("name"), o.optInt("tier", 1), o.optString("version", ""),
|
||||
o.optString("kind", "tar"), o.getString("url"), o.optString("sha256", ""),
|
||||
o.optLong("size", 0L), o.optString("notes", ""),
|
||||
o.optString("kind", "tar"), file.getString("url"), file.optString("sha256", ""),
|
||||
file.optLong("size", 0L), o.optString("notes", ""),
|
||||
o.optString("icon", "applications-games"), o.optString("category", "Game"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,12 @@ object SessionPrefs {
|
||||
const val OSC_STEAM_QAM = "steam-qam"
|
||||
const val OSC_NEVER = "never"
|
||||
|
||||
const val BACK_MENU_THEN_QAM = "1: menu 2: QAM"
|
||||
const val BACK_QAM_THEN_MENU = "1: QAM 2: menu"
|
||||
|
||||
fun backActionsOrder(inverted: Boolean): String =
|
||||
if (inverted) BACK_QAM_THEN_MENU else BACK_MENU_THEN_QAM
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true)
|
||||
@@ -21,6 +27,13 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("hud", on).apply()
|
||||
}
|
||||
|
||||
/** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */
|
||||
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
|
||||
|
||||
fun setBackActionsInverted(context: Context, inverted: Boolean) {
|
||||
prefs(context).edit().putBoolean("backActionsInverted", inverted).apply()
|
||||
}
|
||||
|
||||
const val TOUCH_AUTO = "auto"
|
||||
const val TOUCH_PAD = "touchpad"
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
@@ -39,9 +52,9 @@ object SessionPrefs {
|
||||
|
||||
/** The choices the settings offer, in order. */
|
||||
val shapeChoices = listOf(
|
||||
SHAPE_AUTO to "The panel's shape (16:9 or wider)",
|
||||
SHAPE_EXACT to "Exactly this panel (4:3, 3:2…)",
|
||||
SHAPE_WIDE to "16:9 with bars",
|
||||
SHAPE_AUTO to "Auto (16:9+)",
|
||||
SHAPE_EXACT to "Match screen",
|
||||
SHAPE_WIDE to "Always 16:9",
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -87,6 +100,32 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("clientDirectAudio", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Steam only: gamescope makes every game window the size of the screen. A game that resizes
|
||||
* its own window when it loses focus (FlatOut) otherwise comes back smaller, drawn in a
|
||||
* corner; a game that sets its own resolution and never looks at its window again (Quake 3)
|
||||
* instead draws small in the bottom-left of the stretched one. On unless turned off.
|
||||
*/
|
||||
fun forceFullscreen(context: Context): Boolean = prefs(context).getBoolean("forceFullscreen", true)
|
||||
|
||||
fun setForceFullscreen(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("forceFullscreen", on).apply()
|
||||
writeForceFullscreenFlag(context)
|
||||
}
|
||||
|
||||
/**
|
||||
* The same choice as a file the running session watches, so the drawer can change it live:
|
||||
* the session hands every change to gamescope, which reads GAMESCOPE_FORCE_WINDOWS_FULLSCREEN
|
||||
* off its root window whenever it changes. Written again at every session start so a file left
|
||||
* by an earlier session never disagrees with the setting.
|
||||
*/
|
||||
fun writeForceFullscreenFlag(context: Context) {
|
||||
runCatching {
|
||||
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-fill")
|
||||
.writeText(if (forceFullscreen(context)) "1\n" else "0\n")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DirectAudio for games: their Wine audio driver talks to the relay helper on this side. On
|
||||
* unless the user turned it off.
|
||||
|
||||
@@ -304,6 +304,10 @@ class SessionService : Service() {
|
||||
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
|
||||
SessionPrefs.writeForceFullscreenFlag(this)
|
||||
}
|
||||
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
|
||||
// XALIA_SUPPORTED_ONLY itself otherwise). Off by default: xalia is Valve's, and on a device
|
||||
// whose seccomp answers its syscalls normally there is no reason to take it away.
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.view.Display
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
@@ -54,6 +64,7 @@ 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.heightIn
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
@@ -64,6 +75,7 @@ import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
@@ -76,6 +88,8 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -97,7 +111,14 @@ import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalWindowInfo
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
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.IntOffset
|
||||
@@ -106,8 +127,11 @@ import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.zIndex
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@@ -133,14 +157,18 @@ class FrontEndState(
|
||||
val pageKey: String? = null,
|
||||
val theme: String = Themes.PAPER,
|
||||
val isHomeApp: Boolean = false,
|
||||
val homeScreenEnabled: Boolean = false,
|
||||
val defaultHomeLabel: String? = null,
|
||||
val androidApps: List<com.droiddeck.launcher.HomeApp.LaunchableApp> = emptyList(),
|
||||
val androidApps: List<HomeApp.LaunchableApp> = emptyList(),
|
||||
val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(),
|
||||
val packages: List<PackageRow>? = null,
|
||||
val packageCatalogLoading: Boolean = false,
|
||||
val packageBusyId: String? = null,
|
||||
val packageStage: String? = null,
|
||||
val packagePercent: Int = -1,
|
||||
val sessionRunning: Boolean = false,
|
||||
val backActionsInverted: Boolean = false,
|
||||
val buildLabel: String = "local",
|
||||
)
|
||||
|
||||
class FrontEndActions(
|
||||
@@ -168,7 +196,10 @@ class FrontEndActions(
|
||||
val onPageBack: () -> Unit = {},
|
||||
val onTheme: (String) -> Unit = {},
|
||||
val onHomeApp: () -> Unit = {},
|
||||
val onAndroidApp: (com.droiddeck.launcher.HomeApp.LaunchableApp) -> Unit = {},
|
||||
val onHomeScreen: (Boolean) -> Unit = {},
|
||||
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onCheckLatestBuild: () -> Unit = {},
|
||||
)
|
||||
|
||||
|
||||
@@ -227,16 +258,102 @@ private fun Modifier.shine(trigger: Boolean, strength: Float = 0.22f): Modifier
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Controller focus on the front end: each rail item's requester and the page's main button (Play,
|
||||
* Open desktop, Open <emulator>, Launch...). The pane leaves, to the left, for the selected rail
|
||||
* item - whatever tile or button it leaves from - and remembers that control, so coming back in
|
||||
* lands on it again; a page not yet visited enters on its main button.
|
||||
*/
|
||||
private class FrontFocus {
|
||||
val rail = HashMap<String, FocusRequester>()
|
||||
val primary = FocusRequester()
|
||||
var primaryAttached by mutableStateOf(0)
|
||||
var railFocused by mutableStateOf(false)
|
||||
fun railFor(key: String): FocusRequester = rail.getOrPut(key) { FocusRequester() }
|
||||
// The pane's controls by id (a tile's key, a button's label), how many of each are on screen,
|
||||
// and the last one focused.
|
||||
val items = HashMap<String, FocusRequester>()
|
||||
val attached = HashMap<String, Int>()
|
||||
var last: String? = null
|
||||
// The first tile of the page's grid: Down from the page's buttons goes to it, not to whichever
|
||||
// tile happens to sit under the button.
|
||||
val firstTile = FocusRequester()
|
||||
var firstTileAttached = 0
|
||||
fun paneEntry(): FocusRequester {
|
||||
val id = last
|
||||
return when {
|
||||
id == PRIMARY && primaryAttached > 0 -> primary
|
||||
id != null && id != PRIMARY && (attached[id] ?: 0) > 0 -> items.getValue(id)
|
||||
primaryAttached > 0 -> primary
|
||||
else -> FocusRequester.Default
|
||||
}
|
||||
}
|
||||
companion object { const val PRIMARY = "\u0000primary" }
|
||||
}
|
||||
|
||||
/** Down from this button goes to the first tile of the page's grid, when there is one. */
|
||||
@Composable
|
||||
private fun Modifier.downToFirstTile(): Modifier {
|
||||
val ff = LocalFrontFocus.current ?: return this
|
||||
return this.focusProperties { down = if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
|
||||
}
|
||||
|
||||
/** Marks the first tile of the page's grid. */
|
||||
@Composable
|
||||
private fun Modifier.firstTile(): Modifier {
|
||||
val ff = LocalFrontFocus.current ?: return this
|
||||
DisposableEffect(Unit) {
|
||||
ff.firstTileAttached++
|
||||
onDispose { ff.firstTileAttached-- }
|
||||
}
|
||||
return this.focusRequester(ff.firstTile)
|
||||
}
|
||||
|
||||
/** Lets the pane come back to this control: it is remembered when focused. */
|
||||
@Composable
|
||||
private fun Modifier.paneItem(id: String): Modifier {
|
||||
val ff = LocalFrontFocus.current ?: return this
|
||||
val req = remember(id) { ff.items.getOrPut(id) { FocusRequester() } }
|
||||
DisposableEffect(id) {
|
||||
ff.attached[id] = (ff.attached[id] ?: 0) + 1
|
||||
onDispose { ff.attached[id] = (ff.attached[id] ?: 1) - 1 }
|
||||
}
|
||||
return this.focusRequester(req).onFocusChanged { if (it.isFocused) ff.last = id }
|
||||
}
|
||||
|
||||
private val LocalFrontFocus = staticCompositionLocalOf<FrontFocus?> { null }
|
||||
|
||||
@Composable
|
||||
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
|
||||
val frontFocus = remember { FrontFocus() }
|
||||
CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) }
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
|
||||
var selected by rememberSaveable { mutableStateOf("steam") }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val ctx = LocalContext.current
|
||||
BackHandler(enabled = s.pageKey != null && page != null) { a.onPageBack() }
|
||||
// Back (and B) from a game or an emulator steps out one level, as its "‹" link does, instead
|
||||
// of leaving the app: a game -> its emulator (or Steam), an emulator -> Desktop.
|
||||
BackHandler(
|
||||
enabled = (s.pageKey == null || page == null) &&
|
||||
(selected.startsWith("app:") || selected.startsWith("emu:") || selected.startsWith("rom:")),
|
||||
) {
|
||||
selected = when {
|
||||
selected.startsWith("app:") -> "steam"
|
||||
selected.startsWith("emu:") -> "desktop"
|
||||
else -> "emu:" + selected.removePrefix("rom:").substringBefore(':')
|
||||
}
|
||||
}
|
||||
LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" }
|
||||
remember { Motion.scale = Settings.Global.getFloat(ctx.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f); true }
|
||||
|
||||
BoxWithConstraints(modifier = Modifier.fillMaxSize().background(colors.background).systemBarsPadding()) {
|
||||
var anyFocused by remember { mutableStateOf(false) }
|
||||
BoxWithConstraints(modifier = Modifier.fillMaxSize().background(colors.background).systemBarsPadding().onFocusChanged { anyFocused = it.hasFocus }) {
|
||||
val wide = maxWidth >= 640.dp
|
||||
val railSelection = when {
|
||||
s.pageKey == "performance" || s.pageKey == "protons" -> "setup"
|
||||
@@ -257,9 +374,66 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -
|
||||
modifier = if (wide) Modifier.width(236.dp).fillMaxHeight() else Modifier.fillMaxWidth().height(maxHeight * 0.42f),
|
||||
)
|
||||
}
|
||||
val content: @Composable (Modifier) -> Unit = { m -> Pane(s, selected, a, page, m) { selected = it } }
|
||||
// The app opens with the selected rail item focused, so a controller sees where it is. An
|
||||
// app starts in touch mode, where clickables refuse focus, so leave it first (a touch goes
|
||||
// straight back to it); a request before the window has focus is dropped, so wait for
|
||||
// that and retry until it sticks.
|
||||
val window = LocalWindowInfo.current
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(Unit) {
|
||||
snapshotFlow { window.isWindowFocused }.first { it }
|
||||
repeat(20) {
|
||||
if (frontFocus.railFocused) return@LaunchedEffect
|
||||
if (inputMode.inputMode != InputMode.Keyboard) inputMode.requestInputMode(InputMode.Keyboard)
|
||||
runCatching { frontFocus.railFor(railSelection).requestFocus() }
|
||||
kotlinx.coroutines.delay(100)
|
||||
}
|
||||
}
|
||||
// A tile or button that opens a page goes away with the page it was on, and focus with it;
|
||||
// the pad then had nothing to move from (a press landed back on the rail's first item). So
|
||||
// once the new page is in, a controller lands on its main button.
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
LaunchedEffect(selected, s.pageKey) {
|
||||
kotlinx.coroutines.delay(450)
|
||||
if (!anyFocused && inputModeManager.inputMode == InputMode.Keyboard) runCatching {
|
||||
if (frontFocus.primaryAttached > 0) frontFocus.primary.requestFocus()
|
||||
else frontFocus.railFor(railSelection).requestFocus()
|
||||
}
|
||||
}
|
||||
val back = if (wide) FocusDirection.Left else FocusDirection.Up
|
||||
val paneFocus = Modifier
|
||||
.focusProperties {
|
||||
enter = { frontFocus.paneEntry() }
|
||||
exit = { dir ->
|
||||
if (dir == back) frontFocus.rail[railSelection] ?: FocusRequester.Default else FocusRequester.Default
|
||||
}
|
||||
}
|
||||
.focusGroup()
|
||||
val content: @Composable (Modifier) -> Unit = { m ->
|
||||
Pane(s, selected, a, page, m.then(paneFocus), { selected = it }) { app ->
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
}
|
||||
}
|
||||
if (wide) Row(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxHeight()) }
|
||||
else Column(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxWidth()) }
|
||||
|
||||
appToChooseDisplay?.let { app ->
|
||||
val secondaryDisplay = s.secondScreenDisplays.firstOrNull()
|
||||
ChooseAppDisplayDialog(
|
||||
app = app,
|
||||
secondaryDisplay = secondaryDisplay,
|
||||
onPrimary = {
|
||||
appToChooseDisplay = null
|
||||
a.onAndroidApp(app, Display.DEFAULT_DISPLAY)
|
||||
},
|
||||
onSecondary = {
|
||||
appToChooseDisplay = null
|
||||
secondaryDisplay?.let { a.onAndroidApp(app, it.id) }
|
||||
},
|
||||
onDismiss = { appToChooseDisplay = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,82 +445,89 @@ private fun Rail(
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(
|
||||
modifier = modifier.background(colors.surface).verticalScroll(rememberScrollState()).padding(horizontal = 10.dp, vertical = 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
modifier = modifier.background(colors.surface).padding(horizontal = 10.dp, vertical = 12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 8.dp, bottom = 10.dp)) {
|
||||
Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(30.dp))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column {
|
||||
Text("DroidDeck", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
val status = when {
|
||||
s.busy -> if (s.percent >= 0) "${s.stage} ${s.percent}%" else s.stage
|
||||
!s.ready -> "runtime not installed"
|
||||
s.available != null && s.available != s.installed -> "runtime update available"
|
||||
else -> null
|
||||
Column(
|
||||
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 8.dp, bottom = 10.dp)) {
|
||||
Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(30.dp))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column {
|
||||
Text("DroidDeck", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
val status = when {
|
||||
s.busy -> if (s.percent >= 0) "${s.stage} ${s.percent}%" else s.stage
|
||||
!s.ready -> "runtime not installed"
|
||||
s.available != null && s.available != s.installed -> "runtime update available"
|
||||
else -> null
|
||||
}
|
||||
if (status != null) Text(status, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (status != null) Text(status, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp))
|
||||
}
|
||||
AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp))
|
||||
}
|
||||
|
||||
var lastRunning by remember { mutableStateOf("") }
|
||||
if (s.running != null) lastRunning = s.running
|
||||
AnimatedVisibility(
|
||||
s.running != null,
|
||||
enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)) + slideInVertically(Motion.sp(0.6f)) { -it / 2 },
|
||||
exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)),
|
||||
) { RunningTile(lastRunning, a.onResume) }
|
||||
var lastRunning by remember { mutableStateOf("") }
|
||||
if (s.running != null) lastRunning = s.running
|
||||
AnimatedVisibility(
|
||||
s.running != null,
|
||||
enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)) + slideInVertically(Motion.sp(0.6f)) { -it / 2 },
|
||||
exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)),
|
||||
) { RunningTile(lastRunning, a.onResume) }
|
||||
|
||||
val pal = LocalPalette.current
|
||||
var navOrigin by remember { mutableStateOf(Offset.Zero) }
|
||||
val positions = remember { mutableStateMapOf<String, Rect>() }
|
||||
Box(modifier = Modifier.fillMaxWidth().onGloballyPositioned { val o = it.positionInRoot(); if (o != navOrigin) navOrigin = o }) {
|
||||
val target = positions[selected]?.translate(-navOrigin)
|
||||
val y by animateFloatAsState(target?.top ?: 0f, Motion.sp(0.72f, Spring.StiffnessLow), label = "indY")
|
||||
val x by animateFloatAsState(target?.left ?: 0f, Motion.sp(0.9f), label = "indX")
|
||||
val h by animateFloatAsState(target?.height ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indH")
|
||||
val w by animateFloatAsState(target?.width ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indW")
|
||||
val alpha by animateFloatAsState(if (target != null) 1f else 0f, Motion.tw(250), label = "indA")
|
||||
val density = LocalDensity.current
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.offset { IntOffset(x.roundToInt(), y.roundToInt()) }
|
||||
.width(with(density) { w.toDp() }).height(with(density) { h.toDp() })
|
||||
.alpha(alpha)
|
||||
.graphicsLayer { shadowElevation = 6.dp.toPx(); shape = Shape10; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
|
||||
.clip(Shape10)
|
||||
.background(Brush.linearGradient(listOf(colors.primary, pal.primary2))),
|
||||
val pal = LocalPalette.current
|
||||
var navOrigin by remember { mutableStateOf(Offset.Zero) }
|
||||
val positions = remember { mutableStateMapOf<String, Rect>() }
|
||||
Box(modifier = Modifier.fillMaxWidth().onGloballyPositioned { val o = it.positionInRoot(); if (o != navOrigin) navOrigin = o }) {
|
||||
val target = positions[selected]?.translate(-navOrigin)
|
||||
val y by animateFloatAsState(target?.top ?: 0f, Motion.sp(0.72f, Spring.StiffnessLow), label = "indY")
|
||||
val x by animateFloatAsState(target?.left ?: 0f, Motion.sp(0.9f), label = "indX")
|
||||
val h by animateFloatAsState(target?.height ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indH")
|
||||
val w by animateFloatAsState(target?.width ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indW")
|
||||
val alpha by animateFloatAsState(if (target != null) 1f else 0f, Motion.tw(250), label = "indA")
|
||||
val density = LocalDensity.current
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.offset { IntOffset(x.roundToInt(), y.roundToInt()) }
|
||||
.width(with(density) { w.toDp() }).height(with(density) { h.toDp() })
|
||||
.alpha(alpha)
|
||||
.graphicsLayer { shadowElevation = 6.dp.toPx(); shape = Shape10; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
|
||||
.clip(Shape10)
|
||||
.background(Brush.linearGradient(listOf(colors.primary, pal.primary2))),
|
||||
)
|
||||
val register: (String, LayoutCoordinates) -> Unit = { key, c ->
|
||||
val o = c.positionInRoot(); val r = Rect(o.x, o.y, o.x + c.size.width, o.y + c.size.height)
|
||||
if (positions[key] != r) positions[key] = r
|
||||
}
|
||||
val unregister: (String) -> Unit = { positions.remove(it) }
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
if (s.isHomeApp) {
|
||||
NavItem("Android apps", "android-apps", selected == "android-apps", count = s.androidApps.size,
|
||||
register = register, unregister = unregister) { onSelect("android-apps") }
|
||||
}
|
||||
NavItem("Steam", "steam", selected == "steam", count = s.steamGames.size, register = register, unregister = unregister) { onSelect("steam") }
|
||||
NavItem("Desktop", "desktop", selected == "desktop", count = s.emulators.count { it.installed }, register = register, unregister = unregister) { onSelect("desktop") }
|
||||
NavItem("Setup", "setup", selected == "setup", register = register, unregister = unregister) { onSelect("setup") }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
|
||||
val creditsSrc = remember { MutableInteractionSource() }
|
||||
val creditsHot = rememberHot(creditsSrc)
|
||||
Text(
|
||||
"credits", fontSize = 11.sp, color = if (creditsHot) LocalPalette.current.signal else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(Shape10)
|
||||
.border(2.dp, if (creditsHot) LocalPalette.current.signal else Color.Transparent, Shape10)
|
||||
.hoverable(creditsSrc).clickable(interactionSource = creditsSrc, indication = null, onClick = a.onCredits)
|
||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
)
|
||||
val register: (String, LayoutCoordinates) -> Unit = { key, c ->
|
||||
val o = c.positionInRoot(); val r = Rect(o.x, o.y, o.x + c.size.width, o.y + c.size.height)
|
||||
if (positions[key] != r) positions[key] = r
|
||||
}
|
||||
val unregister: (String) -> Unit = { positions.remove(it) }
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
if (s.isHomeApp) {
|
||||
NavItem("Android apps", "android-apps", selected == "android-apps", count = s.androidApps.size,
|
||||
register = register, unregister = unregister) { onSelect("android-apps") }
|
||||
}
|
||||
NavItem("Steam", "steam", selected == "steam", count = s.steamGames.size, register = register, unregister = unregister) { onSelect("steam") }
|
||||
NavItem("Desktop", "desktop", selected == "desktop", count = s.emulators.count { it.installed }, register = register, unregister = unregister) { onSelect("desktop") }
|
||||
NavItem("Setup", "setup", selected == "setup", register = register, unregister = unregister) { onSelect("setup") }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// Outlined when a controller is on it, like every other control; the ripple alone was
|
||||
// a faint box on the dark rail.
|
||||
val creditsSrc = remember { MutableInteractionSource() }
|
||||
val creditsHot = rememberHot(creditsSrc)
|
||||
Text(
|
||||
"credits", fontSize = 11.sp, color = if (creditsHot) LocalPalette.current.signal else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(Shape10)
|
||||
.border(2.dp, if (creditsHot) LocalPalette.current.signal else Color.Transparent, Shape10)
|
||||
.hoverable(creditsSrc).clickable(interactionSource = creditsSrc, indication = null, onClick = a.onCredits)
|
||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
BuildStatus(
|
||||
label = s.buildLabel,
|
||||
onCheckLatest = a.onCheckLatestBuild,
|
||||
modifier = Modifier.align(Alignment.Start).padding(start = 8.dp, top = 4.dp, bottom = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -391,6 +572,9 @@ private fun NavItem(
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val focused by src.collectIsFocusedAsState()
|
||||
val frontFocus = if (register != null && key != "x") LocalFrontFocus.current else null
|
||||
val railRequester = frontFocus?.railFor(key)
|
||||
if (frontFocus != null) LaunchedEffect(focused) { if (focused) frontFocus.railFocused = true }
|
||||
val hovered by src.collectIsHoveredAsState()
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val fg by animateColorAsState(if (current) colors.onPrimary else if (muted) colors.onSurfaceVariant else colors.onBackground, Motion.tw(280), label = "navFg")
|
||||
@@ -403,6 +587,7 @@ private fun NavItem(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.then(if (register != null && key != "x") Modifier.onGloballyPositioned { register(key, it) } else Modifier)
|
||||
.then(if (railRequester != null) Modifier.focusRequester(railRequester) else Modifier)
|
||||
.then(if (small && i >= 0 && register != null) Modifier.staggerIn(i) else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(Shape10)
|
||||
@@ -429,7 +614,10 @@ private fun NavItem(
|
||||
|
||||
|
||||
@Composable
|
||||
private fun Pane(s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier, onSelect: (String) -> Unit) {
|
||||
private fun Pane(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
) {
|
||||
Box(modifier = modifier) {
|
||||
val wash: Pair<File?, Float> = when {
|
||||
s.pageKey != null && page != null -> null to 250f
|
||||
@@ -450,7 +638,48 @@ private fun Pane(s: FrontEndState, selected: String, a: FrontEndActions, page: (
|
||||
.apply { targetContentZIndex = 1f }
|
||||
},
|
||||
label = "pane",
|
||||
) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect) }
|
||||
) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BuildStatus(label: String, onCheckLatest: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(interaction)
|
||||
val contextDivider = label.indexOf(" · ")
|
||||
val context = if (contextDivider >= 0) label.substring(0, contextDivider) else ""
|
||||
val identity = if (contextDivider >= 0) label.substring(contextDivider + 3) else label
|
||||
val identityDivider = identity.lastIndexOf(" at ")
|
||||
val branch = (if (identityDivider >= 0) identity.substring(0, identityDivider) else identity).substringAfterLast('/')
|
||||
val commit = if (identityDivider >= 0) identity.substring(identityDivider + 4) else ""
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(1.dp),
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.semantics { contentDescription = "Build $label. Check for newest build." }
|
||||
.hoverable(interaction)
|
||||
.clickable(
|
||||
interactionSource = interaction,
|
||||
indication = LocalIndication.current,
|
||||
role = Role.Button,
|
||||
onClick = onCheckLatest,
|
||||
)
|
||||
.heightIn(min = 44.dp)
|
||||
.padding(horizontal = 4.dp, vertical = 3.dp),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(branch, modifier = Modifier.weight(1f), fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = if (hot) colors.onSurfaceVariant else colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (commit.isNotEmpty()) Text("@$commit", fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1)
|
||||
Icon(Icons.Filled.Refresh, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.82f), modifier = Modifier.size(12.dp))
|
||||
}
|
||||
if (context.isNotEmpty()) Text(context, fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,7 +708,10 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier, onSelect: (String) -> Unit) {
|
||||
private fun Content(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(modifier = modifier.padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
when {
|
||||
@@ -495,7 +727,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi
|
||||
null,
|
||||
null,
|
||||
"android:${app.packageName}",
|
||||
onClick = { a.onAndroidApp(app) },
|
||||
onClick = { onAndroidAppClick(app) },
|
||||
iconBitmap = app.icon,
|
||||
)
|
||||
})
|
||||
@@ -506,7 +738,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi
|
||||
Rise(3) {
|
||||
Actions {
|
||||
// Enabled without a runtime: the session's loading screen installs it first.
|
||||
PrimaryButton("Play", enabled = !s.busy, onClick = a.onPlay)
|
||||
PrimaryButton("Play", enabled = !s.busy, main = true, onClick = a.onPlay)
|
||||
SecondaryButton("Steam Desktop UI", enabled = !s.busy, onClick = a.onPlayDesktopUi)
|
||||
Cog(a.onSteamSettings)
|
||||
}
|
||||
@@ -532,7 +764,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi
|
||||
Row {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Actions {
|
||||
PrimaryButton("Launch", enabled = s.ready && !s.busy) { a.onSteamGame(g) }
|
||||
PrimaryButton("Launch", enabled = s.ready && !s.busy, main = true) { a.onSteamGame(g) }
|
||||
Cog(a.onSteamSettings)
|
||||
Chip(if (s.ready) "● ready" else "runtime missing", ok = s.ready)
|
||||
}
|
||||
@@ -552,7 +784,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi
|
||||
Rise(3) {
|
||||
Actions {
|
||||
// Enabled without a runtime or the desktop: the session's loading screen installs them first.
|
||||
PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, onClick = a.onDesktop)
|
||||
PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, main = true, onClick = a.onDesktop)
|
||||
Cog(a.onDesktopSettings)
|
||||
}
|
||||
}
|
||||
@@ -578,7 +810,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi
|
||||
Rise(3) {
|
||||
Actions {
|
||||
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
|
||||
PrimaryButton("Open ${e.name}", enabled = s.ready && !s.busy) { a.onEmulator(e) }
|
||||
PrimaryButton("Open ${e.name}", enabled = s.ready && !s.busy, main = true) { a.onEmulator(e) }
|
||||
SecondaryButton("ROMs folder", onClick = a.onRoms)
|
||||
if (pkg != null) SecondaryButton(
|
||||
if (pkg.kind == "appimage") "Remove" else "Forget",
|
||||
@@ -655,7 +887,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Actions {
|
||||
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
|
||||
PrimaryButton("Launch in ${e.name}", enabled = s.ready && !s.busy) { a.onRom(g) }
|
||||
PrimaryButton("Launch in ${e.name}", enabled = s.ready && !s.busy, main = true) { a.onRom(g) }
|
||||
Chip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false)
|
||||
}
|
||||
}
|
||||
@@ -699,12 +931,19 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
|
||||
ActionRow("ROMs folder", s.romsDir ?: "Choose where emulator games are stored", "Choose", a.onRoms)
|
||||
}
|
||||
SettingsGroup("Session") {
|
||||
ChoiceRow(
|
||||
host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted),
|
||||
listOf(
|
||||
false to SessionPrefs.BACK_MENU_THEN_QAM,
|
||||
true to SessionPrefs.BACK_QAM_THEN_MENU,
|
||||
), s.backActionsInverted, onPick = a.onBackActionsInverted,
|
||||
)
|
||||
SettingsRow("Frame generation", "Select the frame generation mode") {
|
||||
Box {
|
||||
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
|
||||
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") {
|
||||
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
|
||||
val need = if (s.lsfgReady) null else "Install Lossless Scaling in Steam"
|
||||
MenuItem("Off", checked = s.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
||||
MenuItem("Off", checked = s.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
||||
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_WINFG && s.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
|
||||
for (m in 2..4) MenuItem("LSFG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_LSFG && s.frameGenMultiplier == m, enabled = s.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
|
||||
}
|
||||
@@ -725,12 +964,24 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
|
||||
SettingsRow("Theme", "Choose the launcher appearance") {
|
||||
Box {
|
||||
ValueChip(Themes.byId(s.theme).label, host.open == "theme") { host.open = if (host.open == "theme") null else "theme" }
|
||||
AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = "Theme") {
|
||||
for (t in Themes.all) MenuItem(t.label, checked = s.theme == t.id) { a.onTheme(t.id); host.open = null }
|
||||
AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = "Theme") { firstItemFocus ->
|
||||
Themes.all.forEachIndexed { index, theme ->
|
||||
MenuItem(theme.label, checked = s.theme == theme.id, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
a.onTheme(theme.id)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ActionRow("Default Home app", s.defaultHomeLabel ?: "Choose a Home app", "Choose", a.onHomeApp)
|
||||
ToggleRow(
|
||||
host, "home-screen", "Use as a Home screen",
|
||||
if (s.homeScreenEnabled) "DroidDeck can be the phone's Home app" else "Off: DroidDeck is never offered as a Home app",
|
||||
s.homeScreenEnabled,
|
||||
) { a.onHomeScreen(it) }
|
||||
if (s.homeScreenEnabled) {
|
||||
ActionRow("Default Home app", s.defaultHomeLabel ?: "Choose a Home app", "Choose", a.onHomeApp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -781,9 +1032,16 @@ private fun Chip(t: String, ok: Boolean) {
|
||||
private fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
|
||||
@Composable
|
||||
private fun PrimaryButton(text: String, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
private fun PrimaryButton(text: String, enabled: Boolean = true, main: Boolean = false, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
// The page's main button is where the pane is entered from the rail.
|
||||
val frontFocus = if (main) LocalFrontFocus.current else null
|
||||
if (frontFocus != null) DisposableEffect(Unit) {
|
||||
frontFocus.primaryAttached++
|
||||
onDispose { frontFocus.primaryAttached-- }
|
||||
}
|
||||
val track = (if (frontFocus == null) Modifier.paneItem("btn:$text") else Modifier).downToFirstTile()
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src) && enabled
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
@@ -791,7 +1049,8 @@ private fun PrimaryButton(text: String, enabled: Boolean = true, onClick: () ->
|
||||
val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift")
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier
|
||||
modifier = track
|
||||
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.primary).onFocusChanged { if (it.isFocused) frontFocus.last = FrontFocus.PRIMARY } else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
|
||||
.clip(Shape12)
|
||||
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
|
||||
@@ -817,9 +1076,10 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, onClick: ()
|
||||
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "secEdge")
|
||||
val fill by animateColorAsState(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f), Motion.tw(250), label = "secFill")
|
||||
Box(
|
||||
modifier = Modifier.graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12)
|
||||
modifier = Modifier.paneItem("btn:$text").downToFirstTile().graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12)
|
||||
.alpha(if (enabled) 1f else 0.5f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 11.dp),
|
||||
) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
|
||||
}
|
||||
@@ -834,7 +1094,7 @@ private fun Cog(onClick: () -> Unit) {
|
||||
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "cogEdge")
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(42.dp).clip(Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, Shape12)
|
||||
modifier = Modifier.paneItem("cog").downToFirstTile().size(42.dp).clip(Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, Shape12)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick),
|
||||
) { Icon(Icons.Filled.Settings, "Settings", tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(18.dp).rotate(rot)) }
|
||||
}
|
||||
@@ -849,7 +1109,7 @@ private fun Poster(art: File?, name: String, modifier: Modifier) {
|
||||
.graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 16.dp.toPx(); rotationZ = (1f - t.value) * 2f; scaleX = 0.94f + 0.06f * t.value; scaleY = scaleX; shadowElevation = 22.dp.toPx(); shape = Shape12; clip = false }
|
||||
.clip(Shape12).background(artBrush(hueOf(name))),
|
||||
) {
|
||||
if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
if (art != null) CoverImage(art, Modifier.fillMaxSize())
|
||||
else Text(name, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.align(Alignment.BottomStart).padding(8.dp), maxLines = 3, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
@@ -875,7 +1135,8 @@ private fun ArtGrid(tiles: List<Tile>, wide: Boolean = false) {
|
||||
for (t in row) key(t.key) {
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot) }
|
||||
val track = Modifier.paneItem("tile:" + t.key).then(if (t === tiles.first()) Modifier.firstTile() else Modifier)
|
||||
Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot, track) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -884,7 +1145,7 @@ private fun ArtGrid(tiles: List<Tile>, wide: Boolean = false) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean) {
|
||||
private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean, track: Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.97f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "tileScale")
|
||||
@@ -893,7 +1154,7 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera
|
||||
val pal = LocalPalette.current
|
||||
val ring by animateColorAsState(if (hot) pal.signal else Color.Transparent, Motion.tw(220), label = "tileRing")
|
||||
Column(
|
||||
modifier = Modifier
|
||||
modifier = track
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale; translationY = lift.dp.toPx(); shadowElevation = elev.dp.toPx(); shape = Shape12; clip = false; ambientShadowColor = if (hot) pal.signal else Color.Black; spotShadowColor = if (hot) pal.signal else Color.Black; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, 0.9f) }
|
||||
.clip(Shape12)
|
||||
.background(colors.surface)
|
||||
@@ -921,13 +1182,41 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Art for a portrait (2:3) tile. Box art fills it; wide art - a PS3 disc's ICON0, a game's header -
|
||||
* is shown whole over a blurred, darkened copy of itself instead of losing its sides to the crop.
|
||||
*/
|
||||
@Composable
|
||||
private fun CoverImage(art: File, modifier: Modifier) {
|
||||
var wideArt by remember(art) { mutableStateOf(false) }
|
||||
Box(modifier) {
|
||||
if (wideArt) {
|
||||
AsyncImage(
|
||||
model = art, contentDescription = null, contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.2f; scaleY = 1.2f }.blur(14.dp),
|
||||
)
|
||||
Spacer(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.45f)))
|
||||
}
|
||||
AsyncImage(
|
||||
model = art, contentDescription = null,
|
||||
contentScale = if (wideArt) ContentScale.Fit else ContentScale.Crop,
|
||||
onSuccess = { state ->
|
||||
val size = state.painter.intrinsicSize
|
||||
if (size.width > size.height * 1.1f) wideArt = true
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Art(art: File?, iconRes: Int?, label: String, modifier: Modifier, wide: Boolean = false, iconBitmap: Bitmap? = null) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val ratio = if (art == null && (iconRes != null || iconBitmap != null)) 1f else if (wide) 16f / 9f else 2f / 3f
|
||||
Box(modifier = modifier.aspectRatio(ratio).background(if (art == null && iconRes == null && iconBitmap == null) artBrush(hueOf(label)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surface)))) {
|
||||
when {
|
||||
art != null -> AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
art != null -> if (wide) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
else CoverImage(art, Modifier.fillMaxSize())
|
||||
iconRes != null -> Image(painterResource(iconRes), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(if (wide) 10.dp else 8.dp))
|
||||
iconBitmap != null -> Image(bitmap = iconBitmap.asImageBitmap(), contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(8.dp))
|
||||
else -> {
|
||||
|
||||
@@ -12,6 +12,34 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
|
||||
@Composable
|
||||
fun ChooseAppDisplayDialog(
|
||||
app: HomeApp.LaunchableApp,
|
||||
secondaryDisplay: SecondScreenDisplay?,
|
||||
onPrimary: () -> Unit,
|
||||
onSecondary: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Launch ${app.label}") },
|
||||
text = {
|
||||
Text(
|
||||
secondaryDisplay?.let { "Choose a screen. Secondary: ${it.label}." }
|
||||
?: "The secondary display is no longer available.",
|
||||
)
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onPrimary) { Text("Primary screen") } },
|
||||
dismissButton = {
|
||||
TextButton(onClick = onSecondary, enabled = secondaryDisplay != null) {
|
||||
Text("Secondary screen")
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
|
||||
@@ -46,6 +46,8 @@ class ModeSettings(
|
||||
val suspendPolicy: String,
|
||||
/** Steam only. */
|
||||
val oscMode: String?,
|
||||
/** Steam only: whether single and double Back actions are swapped. */
|
||||
val backActionsInverted: Boolean = false,
|
||||
val directAudio: Boolean?,
|
||||
val clientDirectAudio: Boolean = false,
|
||||
val mic: Boolean?,
|
||||
@@ -53,6 +55,8 @@ class ModeSettings(
|
||||
val gameStorage: String? = null,
|
||||
val storageOptions: List<Pair<String, String>> = emptyList(),
|
||||
val fexPreset: String? = null,
|
||||
/** Steam only: games are stretched to fill the screen (null = not a Steam page). */
|
||||
val forceFullscreen: Boolean? = null,
|
||||
/** Steam only: the client branch forced on the command line. */
|
||||
val steamChannel: String? = null,
|
||||
/** Steam only: the user's own games folder and what was found in it. */
|
||||
@@ -91,6 +95,7 @@ class ModeSettingsActions(
|
||||
val onTouch: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onOsc: (String) -> Unit,
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onDirectAudio: (Boolean) -> Unit,
|
||||
val onClientDirectAudio: (Boolean) -> Unit = {},
|
||||
val onMic: (Boolean) -> Unit,
|
||||
@@ -98,6 +103,7 @@ class ModeSettingsActions(
|
||||
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
|
||||
val onPickGameStorageFolder: () -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit = {},
|
||||
val onForceFullscreen: (Boolean) -> Unit = {},
|
||||
val onSteamChannel: (String) -> Unit = {},
|
||||
val onPickAddedGamesDir: () -> Unit = {},
|
||||
val onForgetAddedGamesDir: (path: String) -> Unit = {},
|
||||
@@ -177,8 +183,8 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
onPick = { v -> if (v == CUSTOM) editCustom = true else { a.onCustomResolution(null); a.onResolution(v) } },
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "shape", "Shape",
|
||||
if (custom != null) "Set by the custom resolution." else "The panel's shape stays at 16:9 or wider; pick Exactly this panel for a 4:3 or 3:2 screen.",
|
||||
host, "shape", "Screen ratio",
|
||||
if (custom != null) "Set by the custom resolution." else "Auto uses at least 16:9.",
|
||||
com.droiddeck.launcher.session.SessionPrefs.shapeChoices, s.shapeMode, enabled = custom == null, onPick = a.onShape,
|
||||
)
|
||||
if (editCustom) CustomResolutionDialog(
|
||||
@@ -226,6 +232,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
), s.oscMode,
|
||||
note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
|
||||
)
|
||||
if (steam) ChoiceRow(
|
||||
host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted),
|
||||
listOf(
|
||||
false to SessionPrefs.BACK_MENU_THEN_QAM,
|
||||
true to SessionPrefs.BACK_QAM_THEN_MENU,
|
||||
), s.backActionsInverted, onPick = a.onBackActionsInverted,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Session") {
|
||||
ChoiceRow(
|
||||
@@ -280,6 +293,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
FexPreset.all.map { it.id to it.label }, s.fexPreset,
|
||||
note = FexPreset.byId(s.fexPreset).detail, onPick = a.onFexPreset,
|
||||
)
|
||||
if (s.forceFullscreen != null) ToggleRow(
|
||||
host, "fill", "Stretch games to fill the screen",
|
||||
"Keeps games that resize their own window (FlatOut) full screen. Turn it off if a game shows up small in a corner (Quake 3). Applies next session.",
|
||||
s.forceFullscreen, onChange = a.onForceFullscreen,
|
||||
)
|
||||
}
|
||||
if (steam && s.directAudio != null && s.mic != null) SettingsGroup("Audio") {
|
||||
ToggleRow(host, "da", "DirectAudio for games", "Bypasses PulseAudio for lower latency in games.", s.directAudio, onChange = a.onDirectAudio)
|
||||
@@ -309,10 +327,12 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
AnchoredMenu(
|
||||
open, onDismiss = { if (host.open == "storage") host.open = null }, title = "Second library",
|
||||
note = "Games that stream assets from SD or shared storage may stutter. Keep them internal.",
|
||||
) {
|
||||
for ((path, label) in options) MenuItem(label, checked = path == s.gameStorage) {
|
||||
a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·"))
|
||||
host.open = null
|
||||
) { firstItemFocus ->
|
||||
options.forEachIndexed { index, (path, label) ->
|
||||
MenuItem(label, checked = path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·"))
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
MenuItem("Choose a folder…", checked = false) { host.open = null; a.onPickGameStorageFolder() }
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ class SecondScreenPresentation(
|
||||
private val sendWheel: (steps: Int) -> Unit,
|
||||
private val onSteamMenu: () -> Unit,
|
||||
private val onQam: () -> Unit,
|
||||
private val onClose: () -> Unit,
|
||||
) : Presentation(sessionActivity, display) {
|
||||
private val root = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
@@ -124,6 +125,12 @@ class SecondScreenPresentation(
|
||||
setPadding(dp(12), dp(8), dp(12), dp(8))
|
||||
setBackgroundColor(0xE6191E24.toInt())
|
||||
}
|
||||
controls.addView(Button(context).apply {
|
||||
text = "×"
|
||||
contentDescription = "Close second-screen controls"
|
||||
minWidth = dp(48)
|
||||
setOnClickListener { onClose() }
|
||||
})
|
||||
controls.addView(TextView(context).apply {
|
||||
text = "Trackpad"
|
||||
textSize = 14f
|
||||
@@ -169,6 +176,12 @@ class SecondScreenPresentation(
|
||||
setPadding(dp(8), dp(4), dp(8), dp(4))
|
||||
setBackgroundColor(Color.rgb(27, 32, 38))
|
||||
}
|
||||
bar.addView(Button(context).apply {
|
||||
text = "×"
|
||||
contentDescription = "Close second-screen controls"
|
||||
minWidth = dp(48)
|
||||
setOnClickListener { onClose() }
|
||||
})
|
||||
bar.addView(TextView(context).apply {
|
||||
text = "Linux terminal"
|
||||
textSize = 14f
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.view.Display
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.interaction.PressInteraction
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
@@ -20,16 +23,18 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
@@ -62,11 +67,18 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
@@ -74,6 +86,29 @@ import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import kotlinx.coroutines.flow.collect
|
||||
|
||||
private val drawerPageTitles = listOf("Now", "Controls", "Session")
|
||||
private val drawerPageEntries = listOf("hud", "touch", "shape")
|
||||
|
||||
private class DrawerFocus {
|
||||
private val requesters = HashMap<String, FocusRequester>()
|
||||
private val last = arrayOfNulls<String>(3)
|
||||
var focused by mutableStateOf<String?>(null)
|
||||
private set
|
||||
|
||||
private fun requester(key: String) = requesters.getOrPut(key) { FocusRequester() }
|
||||
|
||||
fun track(page: Int, key: String): Modifier = Modifier.focusRequester(requester(key)).onFocusChanged {
|
||||
if (it.isFocused) {
|
||||
last[page] = key
|
||||
focused = key
|
||||
} else if (focused == key) focused = null
|
||||
}
|
||||
|
||||
fun target(page: Int) = last[page] ?: drawerPageEntries[page]
|
||||
fun request(key: String) = runCatching { requester(key).requestFocus() }
|
||||
fun forget(page: Int) { last[page] = null }
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun HudText(text: String) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) {
|
||||
@@ -121,6 +156,11 @@ fun LoadingOverlay(step: String, percent: Int, elapsed: String, hint: String, en
|
||||
@Composable
|
||||
fun SessionPausedOverlay(onResume: () -> Unit) {
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val resumeFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
runCatching { resumeFocus.requestFocus() }
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
@@ -132,7 +172,10 @@ fun SessionPausedOverlay(onResume: () -> Unit) {
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
) {
|
||||
OutlinedButton(onClick = onResume) {
|
||||
OutlinedButton(
|
||||
onClick = onResume,
|
||||
modifier = Modifier.focusRequester(resumeFocus).controllerConfirm(onClick = onResume),
|
||||
) {
|
||||
Text("Resume session")
|
||||
}
|
||||
}
|
||||
@@ -142,6 +185,8 @@ fun SessionPausedOverlay(onResume: () -> Unit) {
|
||||
/** Everything the drawer shows and does. */
|
||||
class DrawerActions(
|
||||
val steam: Boolean,
|
||||
/** The drawer's heading: the emulator for a program from the rail, else Steam or Desktop. */
|
||||
val title: String? = null,
|
||||
val isHomeApp: Boolean,
|
||||
val androidApps: List<HomeApp.LaunchableApp>,
|
||||
val hudOn: Boolean,
|
||||
@@ -149,10 +194,13 @@ class DrawerActions(
|
||||
val frameGenMultiplier: Int,
|
||||
val lsfgReady: Boolean,
|
||||
val oscMode: String,
|
||||
val backActionsInverted: Boolean,
|
||||
val touchMode: String,
|
||||
val touchAuto: String,
|
||||
val shapeMode: String,
|
||||
val fexPreset: String,
|
||||
/** Steam only: games stretched to the screen's size, changed live (null = not Steam). */
|
||||
val fillScreen: Boolean? = null,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
@@ -165,32 +213,56 @@ class DrawerActions(
|
||||
val onSteamMenu: (() -> Unit)?,
|
||||
val onQam: (() -> Unit)?,
|
||||
val onOsc: (String) -> Unit,
|
||||
val onBackActionsInverted: (Boolean) -> Unit,
|
||||
val onTouch: (String) -> Unit,
|
||||
val onShape: (String) -> Unit,
|
||||
val onFexPreset: (String) -> Unit,
|
||||
val onFillScreen: (Boolean) -> Unit = {},
|
||||
val onSecondScreenMode: (SecondScreenMode) -> Unit,
|
||||
val onSecondScreenDisplay: (Int) -> Unit,
|
||||
val onLaunchAndroidApp: (HomeApp.LaunchableApp) -> Unit,
|
||||
val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit,
|
||||
val onBackground: () -> Unit,
|
||||
val onStop: () -> Unit,
|
||||
val onClose: () -> Unit,
|
||||
)
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageChange: (Int) -> Unit, a: DrawerActions) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val host = rememberMenuHost()
|
||||
var androidAppsExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
var confirmStop by remember { mutableStateOf(false) }
|
||||
val pageScroll = remember { List(3) { ScrollState(0) } }
|
||||
val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil")
|
||||
// A controller starts on the drawer's first control, highlighted, as on the app's main screen:
|
||||
// the STEAM button, or in a desktop session the first setting.
|
||||
val firstFocus = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
val steamButtons = a.onSteamMenu != null && a.onQam != null
|
||||
LaunchedEffect(open) {
|
||||
if (open) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
runCatching { firstFocus.requestFocus() }
|
||||
val focus = remember { DrawerFocus() }
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
BackHandler(enabled = open) {
|
||||
if (host.open != null) host.open = null else a.onClose()
|
||||
}
|
||||
BackHandler(enabled = open && confirmStop) { confirmStop = false }
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
|
||||
LaunchedEffect(open, controllerActive) {
|
||||
if (open && !controllerActive) focusManager.clearFocus(force = true)
|
||||
}
|
||||
LaunchedEffect(open, page, controllerActive, host.open, appToChooseDisplay, confirmStop) {
|
||||
if (!open) {
|
||||
host.open = null
|
||||
confirmStop = false
|
||||
} else if (controllerActive) {
|
||||
inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
if (host.open != null || appToChooseDisplay != null || confirmStop) return@LaunchedEffect
|
||||
val target = focus.target(page)
|
||||
repeat(24) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
focus.request(target)
|
||||
if (focus.focused == target) return@LaunchedEffect
|
||||
}
|
||||
focus.forget(page)
|
||||
focus.request(drawerPageEntries[page])
|
||||
}
|
||||
}
|
||||
if (open || veil > 0.01f) Box(
|
||||
@@ -209,13 +281,18 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
.width(340.dp)
|
||||
.background(pal.background.copy(alpha = 0.97f))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
|
||||
.verticalScroll(rememberScrollState())
|
||||
.focusGroup()
|
||||
.controllerBack {
|
||||
if (host.open != null) host.open = null else a.onClose()
|
||||
}
|
||||
.padding(horizontal = 14.dp, vertical = 16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 4.dp, bottom = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 4.dp, bottom = 6.dp)) {
|
||||
Box(modifier = Modifier.size(10.dp).clip(CircleShape).background(Brush.linearGradient(listOf(colors.primary, pal.primary2))))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(if (a.steam) "Steam" else "Desktop", fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(a.title ?: if (a.steam) "Steam" else "Desktop", fontSize = 17.sp, fontWeight = FontWeight.Bold,
|
||||
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
StopSessionButton(modifier = focus.track(page, "stop")) { host.open = null; confirmStop = true }
|
||||
}
|
||||
if (a.onSteamMenu != null && a.onQam != null) {
|
||||
val qamInteraction = remember { MutableInteractionSource() }
|
||||
@@ -239,7 +316,10 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
OutlinedButton(
|
||||
onClick = { host.open = null; a.onSteamMenu.invoke() },
|
||||
interactionSource = steamSrc,
|
||||
modifier = Modifier.weight(1f).height(48.dp).focusRequester(firstFocus),
|
||||
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "steam")).controllerConfirm {
|
||||
host.open = null
|
||||
a.onSteamMenu.invoke()
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
border = BorderStroke(if (steamHot) 2.dp else 1.dp, if (steamHot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (steamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
@@ -253,133 +333,241 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) {
|
||||
qamStartedOnPress = false
|
||||
},
|
||||
interactionSource = qamInteraction,
|
||||
modifier = Modifier.weight(1f).height(48.dp).semantics { contentDescription = "Open Quick Access Menu" },
|
||||
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "qam"))
|
||||
.semantics { contentDescription = "Open Quick Access Menu" }.controllerConfirm {
|
||||
host.open = null
|
||||
a.onQam.invoke()
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
border = BorderStroke(if (qamHot) 2.dp else 1.dp, if (qamHot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (qamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
) {
|
||||
Text("…", fontSize = 22.sp, fontWeight = FontWeight.SemiBold)
|
||||
Text("QAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (a.isHomeApp) SettingsGroup("Android apps") {
|
||||
ActionRow("Launch an app", null, if (androidAppsExpanded) "Hide" else "Show") {
|
||||
androidAppsExpanded = !androidAppsExpanded
|
||||
}
|
||||
if (androidAppsExpanded) {
|
||||
if (a.androidApps.isEmpty()) {
|
||||
Text("No launchable apps found", fontSize = 12.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
|
||||
} else {
|
||||
for (app in a.androidApps) {
|
||||
MenuItem(
|
||||
app.label,
|
||||
checked = false,
|
||||
leading = {
|
||||
app.icon?.let { icon ->
|
||||
Image(
|
||||
bitmap = icon.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(26.dp).clip(RoundedCornerShape(6.dp)),
|
||||
)
|
||||
}
|
||||
},
|
||||
) { a.onLaunchAndroidApp(app) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SettingsGroup("Now") {
|
||||
ToggleRow(
|
||||
host, "hud", "Performance HUD", null, a.hudOn,
|
||||
chipModifier = if (steamButtons) Modifier else Modifier.focusRequester(firstFocus), onChange = a.onHud,
|
||||
)
|
||||
val fgOpen = host.open == "fg"
|
||||
val fgLabel = when (a.frameGenEngine) {
|
||||
FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×"
|
||||
FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×"
|
||||
else -> "Off"
|
||||
}
|
||||
SettingsRow("Frame generation", null, highlighted = fgOpen) {
|
||||
Box {
|
||||
ValueChip(fgLabel, fgOpen) { host.open = if (fgOpen) null else "fg" }
|
||||
AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") {
|
||||
val need = if (a.lsfgReady) null else "install Lossless Scaling in Steam"
|
||||
MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
||||
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
|
||||
for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
ChoiceRow(
|
||||
host, "touch", "Touch", null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"), a.touchMode,
|
||||
onPick = a.onTouch,
|
||||
)
|
||||
if (a.steam) ChoiceRow(
|
||||
host, "osc", "On-screen controls", null,
|
||||
listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never"), a.oscMode,
|
||||
onPick = a.onOsc,
|
||||
)
|
||||
SettingsRow("Keyboard", null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
SecondaryButton("Hardware") { host.open = null; a.onHardwareKeyboard() }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
SecondaryButton("Android") { host.open = null; a.onKeyboard() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
||||
ChoiceRow(
|
||||
host, "second-screen-mode", "Controls", null,
|
||||
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL)
|
||||
.map { it to it.label }, a.secondScreenMode,
|
||||
onPick = a.onSecondScreenMode,
|
||||
)
|
||||
if (a.secondScreenDisplays.size > 1) ChoiceRow(
|
||||
host, "second-screen-display", "Display", null,
|
||||
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
|
||||
onPick = a.onSecondScreenDisplay,
|
||||
)
|
||||
}
|
||||
|
||||
SettingsGroup("Next session") {
|
||||
ChoiceRow(
|
||||
host, "shape", "Display shape", null,
|
||||
SessionPrefs.shapeChoices, a.shapeMode, onPick = a.onShape,
|
||||
)
|
||||
if (a.steam) ChoiceRow(
|
||||
host, "fex", "FEX preset", null,
|
||||
FexPreset.all.map { it.id to it.label }, a.fexPreset, note = FexPreset.byId(a.fexPreset).detail, onPick = a.onFexPreset,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Row(
|
||||
horizontalArrangement = if (a.isHomeApp) Arrangement.End else Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
) {
|
||||
if (!a.isHomeApp) SecondaryButton("Send to background") { host.open = null; a.onBackground() }
|
||||
DangerButton("Stop session") { host.open = null; a.onStop() }
|
||||
DrawerOutlineButton("LB ‹", modifier = Modifier.height(48.dp).then(focus.track(page, "prev"))) {
|
||||
host.open = null; onPageChange((page + 2) % 3)
|
||||
}
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
drawerPageTitles.forEachIndexed { index, title ->
|
||||
val dotSource = remember { MutableInteractionSource() }
|
||||
val dotFocused = dotSource.collectIsFocusedAsState().value
|
||||
val select = { host.open = null; onPageChange(index) }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(38.dp)
|
||||
.semantics { contentDescription = "$title page" }
|
||||
.hoverable(dotSource)
|
||||
.clickable(interactionSource = dotSource, indication = LocalIndication.current, onClick = select)
|
||||
.controllerConfirm(onClick = select),
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(if (index == page) 16.dp else 10.dp)
|
||||
.clip(CircleShape)
|
||||
.background(if (index == page) pal.signal else colors.onSurfaceVariant)
|
||||
.border(if (dotFocused) 2.dp else 0.dp, colors.onBackground, CircleShape),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
DrawerOutlineButton("› RB", modifier = Modifier.height(48.dp).then(focus.track(page, "next"))) {
|
||||
host.open = null; onPageChange((page + 1) % 3)
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll[page]),
|
||||
) {
|
||||
when (page) {
|
||||
0 -> SettingsGroup("Now") {
|
||||
ToggleRow(host, "hud", "Performance HUD", null, a.hudOn,
|
||||
chipModifier = focus.track(page, "hud"), onChange = a.onHud)
|
||||
if (a.fillScreen != null) ToggleRow(
|
||||
host, "fill", "Stretch games to fill", null, a.fillScreen,
|
||||
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen,
|
||||
)
|
||||
val fgOpen = host.open == "fg"
|
||||
val fgLabel = when (a.frameGenEngine) {
|
||||
FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×"
|
||||
FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×"
|
||||
else -> "Off"
|
||||
}
|
||||
SettingsRow("Frame generation", null, highlighted = fgOpen) {
|
||||
Box {
|
||||
ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" }
|
||||
AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
|
||||
val need = if (a.lsfgReady) null else "Requires Lossless Scaling"
|
||||
MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
||||
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
|
||||
for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
1 -> {
|
||||
SettingsGroup("Controls") {
|
||||
ChoiceRow(host, "touch", "Touch", null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"),
|
||||
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
|
||||
ChoiceRow(host, "osc", "On-screen controls", null,
|
||||
if (a.steam) listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never")
|
||||
else listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_NEVER to "Never"),
|
||||
a.oscMode, chipModifier = focus.track(page, "osc"), onPick = a.onOsc)
|
||||
if (a.steam) ChoiceRow(host, "back-actions", "Back", null,
|
||||
listOf(false to SessionPrefs.BACK_MENU_THEN_QAM, true to SessionPrefs.BACK_QAM_THEN_MENU),
|
||||
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
|
||||
}
|
||||
SettingsGroup("Keyboard") {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
|
||||
DrawerOutlineButton("Hardware", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "hardware"))) {
|
||||
host.open = null; a.onHardwareKeyboard()
|
||||
}
|
||||
DrawerOutlineButton("Android", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "android"))) {
|
||||
host.open = null; a.onKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
||||
ChoiceRow(host, "second-screen-mode", "Controls", null,
|
||||
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL).map { it to it.label },
|
||||
a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
|
||||
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", "Display", null,
|
||||
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
|
||||
chipModifier = focus.track(page, "second-screen-display"), onPick = a.onSecondScreenDisplay)
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
if (a.isHomeApp) SettingsGroup("Android apps") {
|
||||
SettingsRow("Launch an app", null) {
|
||||
DrawerOutlineButton(if (androidAppsExpanded) "Hide" else "Show", modifier = focus.track(page, "apps")) {
|
||||
androidAppsExpanded = !androidAppsExpanded
|
||||
}
|
||||
}
|
||||
if (androidAppsExpanded) {
|
||||
if (a.androidApps.isEmpty()) {
|
||||
Text("No launchable apps", fontSize = 12.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
|
||||
} else for (app in a.androidApps) {
|
||||
MenuItem(
|
||||
app.label, checked = false,
|
||||
modifier = focus.track(page, "app:${app.packageName}/${app.className}"),
|
||||
leading = {
|
||||
app.icon?.let { icon ->
|
||||
Image(bitmap = icon.asImageBitmap(), contentDescription = null,
|
||||
modifier = Modifier.size(26.dp).clip(RoundedCornerShape(6.dp)))
|
||||
}
|
||||
},
|
||||
) {
|
||||
host.open = null
|
||||
if (a.secondScreenDisplays.isEmpty()) a.onLaunchAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsGroup("Next session") {
|
||||
ChoiceRow(host, "shape", "Screen ratio", null,
|
||||
SessionPrefs.shapeChoices, a.shapeMode,
|
||||
chipModifier = focus.track(page, "shape"), onPick = a.onShape)
|
||||
if (a.steam) ChoiceRow(host, "fex", "FEX preset", null,
|
||||
FexPreset.all.map { it.id to it.label }, a.fexPreset,
|
||||
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
|
||||
}
|
||||
Spacer(Modifier.height(18.dp))
|
||||
if (!a.isHomeApp) DrawerOutlineButton("Background", modifier = focus.track(page, "background")) {
|
||||
host.open = null; a.onBackground()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
appToChooseDisplay?.let { app ->
|
||||
val secondaryDisplay = a.secondScreenDisplays.firstOrNull { it.id == a.selectedSecondScreenDisplay }
|
||||
?: a.secondScreenDisplays.firstOrNull()
|
||||
ChooseAppDisplayDialog(
|
||||
app = app,
|
||||
secondaryDisplay = secondaryDisplay,
|
||||
onPrimary = {
|
||||
appToChooseDisplay = null
|
||||
a.onLaunchAndroidApp(app, Display.DEFAULT_DISPLAY)
|
||||
},
|
||||
onSecondary = {
|
||||
appToChooseDisplay = null
|
||||
secondaryDisplay?.let { a.onLaunchAndroidApp(app, it.id) }
|
||||
},
|
||||
onDismiss = { appToChooseDisplay = null },
|
||||
)
|
||||
}
|
||||
if (confirmStop) {
|
||||
val cancelFocus = remember { FocusRequester() }
|
||||
val cancel = { confirmStop = false }
|
||||
val stop = { confirmStop = false; a.onStop() }
|
||||
LaunchedEffect(controllerActive) {
|
||||
if (controllerActive) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
runCatching { cancelFocus.requestFocus() }
|
||||
}
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = cancel,
|
||||
modifier = Modifier.controllerBack(onBack = cancel),
|
||||
title = { Text("Stop session?") },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = stop,
|
||||
modifier = Modifier.controllerConfirm(onClick = stop),
|
||||
colors = ButtonDefaults.textButtonColors(contentColor = colors.error),
|
||||
) { Text("Stop") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = cancel, modifier = Modifier.focusRequester(cancelFocus)
|
||||
.controllerConfirm(onClick = cancel)) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DangerButton(text: String, onClick: () -> Unit) {
|
||||
private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
OutlinedButton(
|
||||
onClick = onClick,
|
||||
interactionSource = source,
|
||||
modifier = modifier.controllerConfirm(onClick = onClick),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp),
|
||||
border = BorderStroke(if (hot) 2.dp else 1.dp, if (hot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
) { Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
|
||||
Box(
|
||||
modifier = Modifier.clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp))
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.size(42.dp).semantics { contentDescription = "Stop session" }
|
||||
.clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp))
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 11.dp),
|
||||
) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.error, maxLines = 1) }
|
||||
.controllerConfirm(onClick = onClick),
|
||||
) { Text("×", fontSize = 25.sp, fontWeight = FontWeight.Medium, color = colors.error) }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
@@ -39,6 +40,7 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -49,10 +51,15 @@ import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.TransformOrigin
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
@@ -69,6 +76,26 @@ import androidx.compose.ui.window.PopupProperties
|
||||
private val RowShape = RoundedCornerShape(12.dp)
|
||||
private val GroupShape = RoundedCornerShape(14.dp)
|
||||
|
||||
internal fun Modifier.controllerConfirm(enabled: Boolean = true, onClick: () -> Unit): Modifier = onPreviewKeyEvent { event ->
|
||||
val keyEvent = event.nativeKeyEvent
|
||||
if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_A) {
|
||||
false
|
||||
} else {
|
||||
if (enabled && keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) onClick()
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
internal fun Modifier.controllerBack(onBack: () -> Unit): Modifier = onPreviewKeyEvent { event ->
|
||||
val keyEvent = event.nativeKeyEvent
|
||||
if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_B && keyEvent.keyCode != KeyEvent.KEYCODE_BACK) {
|
||||
false
|
||||
} else {
|
||||
if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) onBack()
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
class MenuHost {
|
||||
var open by mutableStateOf<String?>(null)
|
||||
}
|
||||
@@ -88,10 +115,19 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.() -> Unit) {
|
||||
fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.(FocusRequester) -> Unit) {
|
||||
val state = remember { MutableTransitionState(false) }
|
||||
state.targetState = open
|
||||
if (!state.currentState && !state.targetState && state.isIdle) return
|
||||
val firstItemFocus = remember { FocusRequester() }
|
||||
val inputMode = LocalInputModeManager.current.inputMode
|
||||
LaunchedEffect(open, inputMode) {
|
||||
if (open && inputMode == InputMode.Keyboard) {
|
||||
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
|
||||
runCatching { firstItemFocus.requestFocus() }
|
||||
android.util.Log.i("AnchoredMenu", "requested first option focus")
|
||||
}
|
||||
}
|
||||
val gap = with(LocalDensity.current) { 6.dp.roundToPx() }
|
||||
val provider = remember(gap) { BelowEndProvider(gap) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -114,13 +150,14 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no
|
||||
.clip(RowShape)
|
||||
.background(pal.surfaceVariant.copy(alpha = 0.95f))
|
||||
.border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape)
|
||||
.controllerBack(onDismiss)
|
||||
.padding(6.dp),
|
||||
) {
|
||||
if (title != null) Text(
|
||||
title.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 6.dp),
|
||||
)
|
||||
Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content() }
|
||||
Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content(firstItemFocus) }
|
||||
if (note != null) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
@@ -134,7 +171,8 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no
|
||||
@Composable
|
||||
fun MenuItem(
|
||||
label: String, checked: Boolean, enabled: Boolean = true, detail: String? = null,
|
||||
trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit,
|
||||
trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null,
|
||||
focusRequester: FocusRequester? = null, modifier: Modifier = Modifier, onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
@@ -143,12 +181,14 @@ fun MenuItem(
|
||||
val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift")
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
modifier = modifier.fillMaxWidth()
|
||||
.graphicsLayer { translationX = shift.dp.toPx() }
|
||||
.then(focusRequester?.let { Modifier.focusRequester(it) } ?: Modifier)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent)
|
||||
.alpha(if (enabled) 1f else 0.4f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 9.dp),
|
||||
) {
|
||||
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f))
|
||||
@@ -181,6 +221,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
|
||||
.border(1.dp, edge, RoundedCornerShape(10.dp))
|
||||
.alpha(if (enabled) 1f else 0.5f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
AnimatedContent(
|
||||
@@ -234,8 +275,13 @@ fun <T> ChoiceRow(
|
||||
SettingsRow(label, hint, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) {
|
||||
for ((value, text) in options) MenuItem(text, checked = value == selected) { onPick(value); host.open = null }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
options.forEachIndexed { index, (value, text) ->
|
||||
MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
onPick(value)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,10 +306,10 @@ fun MultiRow(
|
||||
SettingsRow(label, hint, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(summary, open, enabled) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) {
|
||||
for ((value, text) in items) {
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
items.forEachIndexed { index, (value, text) ->
|
||||
val on = value in selected
|
||||
MenuItem(text, checked = on) { onToggle(value, !on) }
|
||||
MenuItem(text, checked = on, focusRequester = if (index == 0) firstItemFocus else null) { onToggle(value, !on) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +169,8 @@ public final class WaylandCompositor {
|
||||
* action: 0=down, 1=move, 2=up. x/y in compositor output space (0..1919, 0..1079). */
|
||||
public static native void nativeSendPointer(int action, int x, int y);
|
||||
|
||||
public static native void nativeSendTouch(int action, int pointerId, int x, int y);
|
||||
|
||||
/** Inject a key event. evdev = Linux input keycode (KEY_A=30…); state: 1=down, 0=up. */
|
||||
public static native void nativeSendKey(int evdev, int state);
|
||||
|
||||
|
||||
Reference in new issue
Block a user