mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
Merge remote-tracking branch 'origin/main' into fix/update-channel-guess
This commit is contained in:
commit
97480e5e83
262 files changed
+15340
-1290
No files matched your search
@@ -52,6 +52,7 @@ import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import com.droiddeck.launcher.core.WifiDiscovery
|
||||
import com.droiddeck.launcher.core.SteamIntegration
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.ui.CoreRow
|
||||
import com.droiddeck.launcher.ui.PerformancePage
|
||||
@@ -91,12 +92,17 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private val components = ComponentsMenu(this, ui)
|
||||
private val decky = DeckyMenu(this, ui)
|
||||
private val updates = UpdatesMenu(this, ui)
|
||||
private val protons = ProtonMenu(this, ui) { !busy && flood == null && pkgStage == null && components.compBusy == null }
|
||||
private val protons = ProtonMenu(this, ui) { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null }
|
||||
|
||||
private var installed by mutableStateOf<String?>(null)
|
||||
private var flood by mutableStateOf<PendingFlood?>(null)
|
||||
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
|
||||
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
|
||||
private class CompatLaunch(val intent: Intent, val loading: com.droiddeck.launcher.session.LoadingState, var menuInstall: Boolean)
|
||||
private var compatLaunch by mutableStateOf<CompatLaunch?>(null)
|
||||
private var compatFlood by mutableStateOf<androidx.compose.ui.graphics.Color?>(null)
|
||||
private var compatLaunchPoll: Runnable? = null
|
||||
private var compatLaunchVisible = false
|
||||
private var returning by mutableStateOf<ReturningFlood?>(null)
|
||||
private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?)
|
||||
private var ready by mutableStateOf(false)
|
||||
@@ -134,9 +140,14 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
|
||||
private var catalogLoading by mutableStateOf(false)
|
||||
private var packageRows by mutableStateOf<List<PackageRow>?>(null)
|
||||
private var pkgId by mutableStateOf<String?>(null)
|
||||
private var pkgStage by mutableStateOf<String?>(null)
|
||||
private var pkgPercent by mutableIntStateOf(-1)
|
||||
private object PackageOperation {
|
||||
val id = mutableStateOf<String?>(null)
|
||||
val stage = mutableStateOf<String?>(null)
|
||||
val percent = mutableIntStateOf(-1)
|
||||
}
|
||||
private var pkgId by PackageOperation.id
|
||||
private var pkgStage by PackageOperation.stage
|
||||
private var pkgPercent by PackageOperation.percent
|
||||
private var desktopInstalled by mutableStateOf(false)
|
||||
private var desktopPresent by mutableStateOf(false)
|
||||
private var battleNetInstalled by mutableStateOf(false)
|
||||
@@ -168,6 +179,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var picturePosition by mutableStateOf("center")
|
||||
private var stretch16x9 by mutableStateOf(false)
|
||||
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
private var launcherFullscreen by mutableStateOf(true)
|
||||
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
|
||||
private var downloadMirror by mutableStateOf("")
|
||||
@@ -187,6 +199,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var wifiDiscoveryLocation by mutableStateOf(false)
|
||||
private var wifiDiscoveryAsked by mutableStateOf(false)
|
||||
private var wifiDiscoveryBlocked by mutableStateOf(false)
|
||||
private var integrationState by mutableStateOf(SteamIntegration.State())
|
||||
private var integrationFocus by mutableStateOf<SteamIntegration.Feature?>(null)
|
||||
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: android.content.Context?, intent: Intent?) {
|
||||
refreshWifiDiscovery()
|
||||
@@ -255,8 +269,65 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
}
|
||||
wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this)
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
|
||||
private var shortcutsTried = false
|
||||
|
||||
private fun readIntegration() = SteamIntegration.read(this)
|
||||
.copy(locationBlocked = wifiDiscoveryBlocked, shortcutsTried = shortcutsTried)
|
||||
|
||||
private fun openIntegration(feature: SteamIntegration.Feature? = null) {
|
||||
SteamIntegration.dismissSuggestion(this)
|
||||
refreshWifiDiscovery()
|
||||
integrationState = readIntegration()
|
||||
integrationFocus = feature
|
||||
navRequest = "setup:integration"
|
||||
}
|
||||
|
||||
private fun readIntegrationIntent(incoming: Intent) {
|
||||
if (incoming.action != SteamIntegration.ACTION_SETUP) return
|
||||
openIntegration(incoming.getStringExtra(SteamIntegration.EXTRA_FEATURE)?.let {
|
||||
runCatching { SteamIntegration.Feature.valueOf(it) }.getOrNull()
|
||||
})
|
||||
}
|
||||
|
||||
private fun integrationSettings(intent: Intent, fallback: String = android.provider.Settings.ACTION_SETTINGS) {
|
||||
try { startActivity(intent) }
|
||||
catch (_: android.content.ActivityNotFoundException) { startActivity(Intent(fallback)) }
|
||||
catch (_: SecurityException) { startActivity(Intent(fallback)) }
|
||||
}
|
||||
|
||||
private fun configureIntegration(feature: SteamIntegration.Feature) {
|
||||
when (feature) {
|
||||
SteamIntegration.Feature.WIFI -> {
|
||||
if (wifiDiscovery && wifiDiscoveryPermission) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
} else if (wifiDiscoveryPermission) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, true)
|
||||
} else {
|
||||
SessionPrefs.setWifiDiscoveryAsked(this)
|
||||
wifiLocationPermission.launch(WifiDiscovery.permissions)
|
||||
}
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
|
||||
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else {
|
||||
HomeApp.setHomeScreenEnabled(this, true)
|
||||
refreshHomeAppState()
|
||||
manageHomeApp()
|
||||
}
|
||||
SteamIntegration.Feature.SHORTCUTS -> {
|
||||
if (!integrationState.shortcuts) shortcutsTried = true
|
||||
if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME)
|
||||
else integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openAppInfo() =
|
||||
integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
|
||||
|
||||
private fun openWifiDiscoverySettings() {
|
||||
if (!WifiDiscovery.permissionGranted(this)) {
|
||||
wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
@@ -391,8 +462,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var theme by mutableStateOf("graphite")
|
||||
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
|
||||
private var hdrOn by mutableStateOf(false)
|
||||
private var fpsLimit by mutableStateOf(0)
|
||||
private var performanceMode by mutableStateOf(false)
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
private var hdrReason by mutableStateOf<String?>(null)
|
||||
@@ -426,6 +495,21 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
private var defaultHomeLabel by mutableStateOf<String?>(null)
|
||||
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
|
||||
private var androidAppsListing = 0
|
||||
private val packageCallback = object : android.content.pm.LauncherApps.Callback() {
|
||||
private fun changed() {
|
||||
refreshAndroidApps()
|
||||
if (HomeWidgets.providers != null) HomeWidgets.refreshProviders(this@FrontEndActivity)
|
||||
}
|
||||
override fun onPackageRemoved(packageName: String, user: android.os.UserHandle) = changed()
|
||||
override fun onPackageAdded(packageName: String, user: android.os.UserHandle) = changed()
|
||||
override fun onPackageChanged(packageName: String, user: android.os.UserHandle) = changed()
|
||||
override fun onPackagesAvailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
|
||||
override fun onPackagesUnavailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
|
||||
override fun onShortcutsChanged(packageName: String, shortcuts: MutableList<android.content.pm.ShortcutInfo>, user: android.os.UserHandle) {
|
||||
if (homeAppSelected) HomePins.refresh(this@FrontEndActivity)
|
||||
}
|
||||
}
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
|
||||
@@ -439,16 +523,15 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun startActivity(intent: Intent?) {
|
||||
val compat = protons.protonBusyId != null || ProtonExtras.installInProgress
|
||||
if (intent?.component?.className == SessionActivity::class.java.name) {
|
||||
if (compatLaunch != null) return
|
||||
when {
|
||||
busy || LinuxRuntimeInstaller.isBusy() -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
compat -> Unit
|
||||
pkgStage != null -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
@@ -463,6 +546,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
if (compat) {
|
||||
waitForCompat(intent)
|
||||
return
|
||||
}
|
||||
}
|
||||
super.startActivity(intent)
|
||||
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
|
||||
@@ -474,6 +561,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
flood = null
|
||||
floodProgress = 0f
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
if (!busy && !LinuxRuntimeInstaller.isBusy() &&
|
||||
(protons.protonBusyId != null || ProtonExtras.installInProgress)) {
|
||||
compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal
|
||||
waitForCompat(f.intent)
|
||||
}
|
||||
return
|
||||
}
|
||||
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
|
||||
@@ -481,6 +573,72 @@ class FrontEndActivity : ComponentActivity() {
|
||||
overridePendingTransition(0, 0)
|
||||
}
|
||||
|
||||
private fun waitForCompat(next: Intent, menuInstall: Boolean = protons.protonBusyId != null) {
|
||||
if (compatLaunch != null) return
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.take()
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
val waiting = CompatLaunch(Intent(next), com.droiddeck.launcher.session.LoadingState(this), menuInstall)
|
||||
compatLaunch = waiting
|
||||
val poll = object : Runnable {
|
||||
override fun run() {
|
||||
if (isDestroyed || isFinishing || compatLaunch !== waiting) return
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress) {
|
||||
waiting.menuInstall = waiting.menuInstall || protons.protonBusyId != null
|
||||
val percent = if (protons.protonBusyId != null) protons.protonPercent else -1
|
||||
val stage = protons.protonStage ?: getString(R.string.load_compat_wait)
|
||||
waiting.loading.say(if (percent >= 0) getString(R.string.load_compat_progress, stage, percent) else stage,
|
||||
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
|
||||
waiting.loading.percent = percent
|
||||
waiting.loading.tick()
|
||||
ui.postDelayed(this, 250)
|
||||
return
|
||||
}
|
||||
if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
|
||||
val problem = protons.protonProblem.takeIf { waiting.menuInstall }
|
||||
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null)) {
|
||||
waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
|
||||
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
|
||||
waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
|
||||
waiting.loading.tick()
|
||||
ui.postDelayed(this, 250)
|
||||
return
|
||||
}
|
||||
compatLaunchPoll = null
|
||||
if (problem != null) waiting.loading.showEnded(problem)
|
||||
else {
|
||||
compatLaunch = null
|
||||
startActivity(waiting.intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
compatLaunchPoll = poll
|
||||
poll.run()
|
||||
}
|
||||
|
||||
private fun cancelCompatLaunch() {
|
||||
compatLaunchPoll?.let(ui::removeCallbacks)
|
||||
compatLaunchPoll = null
|
||||
compatLaunch = null
|
||||
compatFlood = null
|
||||
}
|
||||
|
||||
private fun restoreCompatLaunch(state: Bundle) {
|
||||
savedIntent(state, KEY_COMPAT_LAUNCH)?.let { next ->
|
||||
val problem = state.getString(KEY_COMPAT_PROBLEM)
|
||||
if (problem == null) waitForCompat(next, state.getBoolean(KEY_COMPAT_MENU_INSTALL))
|
||||
else compatLaunch = CompatLaunch(next,
|
||||
com.droiddeck.launcher.session.LoadingState(this).apply { showEnded(problem) }, false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveCompatLaunch(state: Bundle) {
|
||||
compatLaunch?.let {
|
||||
state.putParcelable(KEY_COMPAT_LAUNCH, it.intent)
|
||||
state.putBoolean(KEY_COMPAT_MENU_INSTALL, it.menuInstall)
|
||||
if (it.loading.ended) state.putString(KEY_COMPAT_PROBLEM, it.loading.step)
|
||||
}
|
||||
}
|
||||
|
||||
private var shortcutPicker by mutableStateOf(false)
|
||||
private var shortcutLibraryScanning by mutableStateOf(false)
|
||||
@Volatile private var libraryScanGeneration = 0
|
||||
@@ -542,7 +700,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
if (pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
@@ -654,7 +812,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
android.widget.Toast.makeText(this, R.string.epic_client_uninstalling, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
if (pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
@@ -762,6 +920,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
if (savedInstanceState == null) readIntegrationIntent(intent)
|
||||
readGameIntent(intent)
|
||||
gameSyncFolder = GameFileSync.folder(this)
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
@@ -775,7 +934,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
steamGamesX64 = cachedX64
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
requestedOrientation = orientation
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
|
||||
downloadSource = DownloadSource.mode(this)
|
||||
downloadMirror = DownloadSource.mirror(this)
|
||||
@@ -827,6 +987,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
isHomeApp = homeAppSelected,
|
||||
homeScreenEnabled = homeScreenEnabled,
|
||||
defaultHomeLabel = defaultHomeLabel,
|
||||
integration = integrationState,
|
||||
integrationFocus = integrationFocus,
|
||||
androidApps = androidApps,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
packages = packageRows,
|
||||
@@ -844,6 +1006,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
phantomProcessStatus = phantomProcessStatus,
|
||||
showPhantomGate = showPhantomGate,
|
||||
orientation = orientation,
|
||||
launcherOrientation = launcherOrientation,
|
||||
launcherFullscreen = launcherFullscreen,
|
||||
downloadSource = downloadSource,
|
||||
downloadMirror = downloadMirror,
|
||||
@@ -1026,6 +1189,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onOrientation = { value ->
|
||||
SessionPrefs.setOrientation(this, value)
|
||||
orientation = value
|
||||
},
|
||||
onLauncherOrientation = { value ->
|
||||
com.droiddeck.launcher.core.AppUiPrefs.setOrientation(this, value)
|
||||
launcherOrientation = value
|
||||
requestedOrientation = value
|
||||
},
|
||||
onLauncherFullscreen = { on ->
|
||||
@@ -1061,6 +1228,14 @@ class FrontEndActivity : ComponentActivity() {
|
||||
downloadProxy = DownloadSource.proxyHostPort(this)
|
||||
},
|
||||
onHomeApp = { manageHomeApp() },
|
||||
onSteamIntegration = ::openIntegration,
|
||||
onIntegration = { integrationFocus = null; configureIntegration(it) },
|
||||
onIntegrationAppInfo = ::openAppInfo,
|
||||
onIntegrationLocation = ::openWifiDiscoverySettings,
|
||||
onDismissIntegration = {
|
||||
SteamIntegration.dismissSuggestion(this)
|
||||
integrationState = readIntegration()
|
||||
},
|
||||
onHomeScreen = { on ->
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
@@ -1114,7 +1289,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDismissPhantomGate = { showPhantomGate = false },
|
||||
onShowPhantomGate = {
|
||||
refreshPhantomStatus()
|
||||
showPhantomGate = true
|
||||
},
|
||||
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
||||
onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) },
|
||||
onOpenNotificationSettings = {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
|
||||
@@ -1210,12 +1390,23 @@ class FrontEndActivity : ComponentActivity() {
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
}
|
||||
}
|
||||
androidx.activity.compose.BackHandler(compatLaunch != null) { cancelCompatLaunch() }
|
||||
compatLaunch?.loading?.let { loading ->
|
||||
if (!loading.ended) com.droiddeck.launcher.ui.VeilRing()
|
||||
com.droiddeck.launcher.ui.LoadingOverlay(
|
||||
loading.step, loading.percent, loading.elapsed, getString(R.string.load_compat_hint), loading.ended,
|
||||
loading.topic, loading.readable, title = getString(R.string.load_compat_title),
|
||||
onCancel = ::cancelCompatLaunch, onClose = ::cancelCompatLaunch,
|
||||
flood = compatFlood, onFlooded = { compatFlood = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
|
||||
else {
|
||||
restoreCompatLaunch(savedInstanceState)
|
||||
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
|
||||
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
|
||||
}
|
||||
@@ -1244,6 +1435,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
if (intent.action == SteamIntegration.ACTION_SETUP) {
|
||||
readIntegrationIntent(intent)
|
||||
return
|
||||
}
|
||||
readGameIntent(intent)
|
||||
refresh()
|
||||
startSteamAtStartupIfEnabled()
|
||||
@@ -1301,24 +1496,15 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onUserInteraction() {
|
||||
super.onUserInteraction()
|
||||
com.droiddeck.launcher.ui.Ambient.poke()
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (event.actionMasked == android.view.MotionEvent.ACTION_UP || event.actionMasked == android.view.MotionEvent.ACTION_CANCEL) {
|
||||
com.droiddeck.launcher.ui.Ambient.poke()
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
|
||||
com.droiddeck.launcher.ui.Ambient.poke()
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (compatLaunch != null) {
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
|
||||
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
|
||||
return true
|
||||
}
|
||||
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
|
||||
}
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
|
||||
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
@@ -1335,16 +1521,28 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
|
||||
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
compatLaunchVisible = false
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
compatLaunchVisible = true
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
requestedOrientation = orientation
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
refreshWifiDiscovery()
|
||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
com.droiddeck.launcher.ui.Ambient.poke()
|
||||
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
|
||||
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
|
||||
}
|
||||
@@ -1385,10 +1583,20 @@ class FrontEndActivity : ComponentActivity() {
|
||||
})
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
refreshSecondScreenDisplays()
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
|
||||
HomeWidgets.startListening(this)
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) return
|
||||
@Suppress("DEPRECATION")
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
saveCompatLaunch(outState)
|
||||
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
|
||||
switchingTo?.let {
|
||||
outState.putParcelable(KEY_SWITCHING_TO, it)
|
||||
@@ -1401,6 +1609,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
else @Suppress("DEPRECATION") state.getParcelable(key)
|
||||
|
||||
override fun onDestroy() {
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -1408,6 +1617,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onStop() {
|
||||
unregisterReceiver(wifiLocationReceiver)
|
||||
unregisterReceiver(mediaReceiver)
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
|
||||
HomeWidgets.stopListening(this)
|
||||
ui.removeCallbacks(mediaRefresh)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = null
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
|
||||
@@ -1423,7 +1634,22 @@ class FrontEndActivity : ComponentActivity() {
|
||||
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
||||
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||
androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
|
||||
refreshAndroidApps()
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
|
||||
private fun refreshAndroidApps() {
|
||||
if (!homeAppSelected) {
|
||||
++androidAppsListing
|
||||
androidApps = emptyList()
|
||||
return
|
||||
}
|
||||
val seq = ++androidAppsListing
|
||||
HomePins.refresh(this)
|
||||
Thread({
|
||||
val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList())
|
||||
ui.post { if (seq == androidAppsListing) androidApps = apps }
|
||||
}, "home-apps").start()
|
||||
}
|
||||
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
@@ -1605,7 +1831,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun openBattleNet(args: List<String> = emptyList()) {
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
if (pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
@@ -1713,7 +1939,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
ModeSettings(
|
||||
mode = mode, resolution = resolution,
|
||||
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
||||
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, performanceMode = performanceMode,
|
||||
hdr = hdrOn, hdrReason = hdrReason,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
gpuDrivers = drivers.summary(),
|
||||
touchMode = touchMode,
|
||||
@@ -1721,8 +1947,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
steamDownloadsInBackground = steamDownloadsInBackground,
|
||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
|
||||
com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM) unfoldedControls else null,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
@@ -1748,11 +1973,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
bootMovieCustomName = bootMovieCustomName,
|
||||
bootMovieImporting = bootMovieImporting,
|
||||
bootMovieProgress = bootMovieProgress,
|
||||
wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null,
|
||||
wifiDiscoveryPermission = wifiDiscoveryPermission,
|
||||
wifiDiscoveryLocation = wifiDiscoveryLocation,
|
||||
wifiDiscoveryAsked = wifiDiscoveryAsked,
|
||||
wifiDiscoveryBlocked = wifiDiscoveryBlocked,
|
||||
integration = if (mode == SessionService.MODE_STEAM) integrationState else null,
|
||||
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
|
||||
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyLatest else null,
|
||||
deckyBranch = decky.deckyBranch,
|
||||
@@ -1761,26 +1982,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
onWifiDiscovery = { on ->
|
||||
if (!on) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
refreshWifiDiscovery()
|
||||
} else if (WifiDiscovery.permissionGranted(this)) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, true)
|
||||
refreshWifiDiscovery()
|
||||
} else if (wifiDiscoveryBlocked) {
|
||||
openWifiDiscoverySettings()
|
||||
} else {
|
||||
SessionPrefs.setWifiDiscoveryAsked(this)
|
||||
wifiLocationPermission.launch(WifiDiscovery.permissions)
|
||||
}
|
||||
},
|
||||
onWifiDiscoverySettings = { openWifiDiscoverySettings() },
|
||||
onIntegration = ::configureIntegration,
|
||||
onIntegrationAppInfo = ::openAppInfo,
|
||||
onIntegrationLocation = ::openWifiDiscoverySettings,
|
||||
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
|
||||
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
|
||||
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
|
||||
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
|
||||
onPerformanceMode = { on -> SessionPrefs.setPerformanceMode(this, mode, on); performanceMode = on },
|
||||
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
|
||||
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||
@@ -2031,8 +2238,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
|
||||
loadBootMovie()
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
fpsLimit = SessionPrefs.fpsLimit(this, mode)
|
||||
performanceMode = SessionPrefs.performanceMode(this, mode)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
||||
@@ -2138,7 +2343,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
val scanGeneration = ++libraryScanGeneration
|
||||
val artRefreshesAtStart = HashMap(steamArtRefreshes)
|
||||
if (shortcutPicker) shortcutLibraryScanning = true
|
||||
if (SessionPrefs.steamClientArch(this) == "x86_64" && !OfflineMode.enabled(this)) {
|
||||
if (!OfflineMode.enabled(this)) {
|
||||
Thread({ com.droiddeck.launcher.session.FexCatalog.refresh(this) }, "fex-catalog").start()
|
||||
}
|
||||
Thread({
|
||||
@@ -2330,6 +2535,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private const val SESSION_SWITCH_WAIT_MS = 30_000L
|
||||
private const val SESSION_SWITCH_POLL_MS = 250L
|
||||
private const val KEY_PENDING_SWITCH = "pending_switch"
|
||||
private const val KEY_COMPAT_LAUNCH = "compat_launch"
|
||||
private const val KEY_COMPAT_MENU_INSTALL = "compat_menu_install"
|
||||
private const val KEY_COMPAT_PROBLEM = "compat_problem"
|
||||
private const val KEY_SWITCHING_TO = "switching_to"
|
||||
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
|
||||
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
|
||||
|
||||
@@ -13,7 +13,7 @@ class HomeActivity : Activity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
routeHome()
|
||||
}
|
||||
|
||||
|
||||
@@ -6,20 +6,41 @@ import android.graphics.Bitmap
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.content.pm.LauncherApps
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Rect
|
||||
import android.os.Process
|
||||
import android.os.UserHandle
|
||||
import android.os.UserManager
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object HomeApp {
|
||||
private const val ICON_DP = 72
|
||||
|
||||
data class LaunchableApp(
|
||||
val label: String,
|
||||
val packageName: String,
|
||||
val className: String,
|
||||
val icon: Bitmap?,
|
||||
)
|
||||
val system: Boolean = false,
|
||||
val game: Boolean = false,
|
||||
val installedAt: Long = 0L,
|
||||
val updatedAt: Long = 0L,
|
||||
val user: UserHandle? = null,
|
||||
val userSerial: Long = 0L,
|
||||
) {
|
||||
val component get() = ComponentName(packageName, className)
|
||||
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
|
||||
val work get() = userSerial != 0L
|
||||
}
|
||||
|
||||
fun isHomeScreenEnabled(context: Context): Boolean =
|
||||
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
|
||||
@@ -69,33 +90,79 @@ object HomeApp {
|
||||
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
|
||||
|
||||
fun launchableApps(context: Context): List<LaunchableApp> {
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val users = context.getSystemService(UserManager::class.java)
|
||||
val pm = context.packageManager
|
||||
val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
val apps = pm.queryIntentActivities(launch, 0)
|
||||
.asSequence()
|
||||
.mapNotNull { result ->
|
||||
val activity = result.activityInfo ?: return@mapNotNull null
|
||||
if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null
|
||||
val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName }
|
||||
val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull()
|
||||
LaunchableApp(label, activity.packageName, activity.name, icon)
|
||||
val own = Process.myUserHandle()
|
||||
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
|
||||
val apps = users.userProfiles.flatMap { user ->
|
||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
||||
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
|
||||
val component = info.componentName
|
||||
if (component.packageName == context.packageName && user == own) return@mapNotNull null
|
||||
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
|
||||
val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
|
||||
val app = info.applicationInfo
|
||||
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
|
||||
@Suppress("DEPRECATION")
|
||||
val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0
|
||||
LaunchableApp(
|
||||
label, component.packageName, component.className, icon,
|
||||
system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0,
|
||||
game = game,
|
||||
installedAt = info.firstInstallTime,
|
||||
updatedAt = updated ?: info.firstInstallTime,
|
||||
user = user,
|
||||
userSerial = serial,
|
||||
)
|
||||
}
|
||||
.distinctBy { it.packageName }
|
||||
.toList()
|
||||
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
|
||||
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))
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (displayId == null) {
|
||||
context.startActivity(intent)
|
||||
return
|
||||
}
|
||||
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
|
||||
context.startActivity(intent, options.toBundle())
|
||||
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) {
|
||||
val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() }
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options)
|
||||
}
|
||||
|
||||
fun canUseShortcuts(context: Context): Boolean =
|
||||
runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false)
|
||||
|
||||
fun shortcuts(context: Context, app: LaunchableApp): List<ShortcutInfo> {
|
||||
if (!canUseShortcuts(context)) return emptyList()
|
||||
val query = LauncherApps.ShortcutQuery()
|
||||
.setPackage(app.packageName)
|
||||
.setActivity(app.component)
|
||||
.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST)
|
||||
return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) }
|
||||
.getOrNull().orEmpty()
|
||||
.filter { it.isEnabled }
|
||||
.sortedWith(compareBy<ShortcutInfo> { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank })
|
||||
.take(5)
|
||||
}
|
||||
|
||||
fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching {
|
||||
context.getSystemService(LauncherApps::class.java)
|
||||
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
|
||||
}.getOrNull()
|
||||
|
||||
fun startShortcut(context: Context, info: ShortcutInfo) {
|
||||
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
|
||||
}
|
||||
|
||||
fun openAppInfo(context: Context, app: LaunchableApp) {
|
||||
context.getSystemService(LauncherApps::class.java)
|
||||
.startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null)
|
||||
}
|
||||
|
||||
fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work
|
||||
|
||||
fun uninstall(context: Context, app: LaunchableApp) {
|
||||
context.startActivity(
|
||||
Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
|
||||
fun isActiveSteamSession(): Boolean =
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.UUID
|
||||
|
||||
object HomeFolders {
|
||||
data class Folder(val id: String, val name: String, val apps: List<String>)
|
||||
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "folders"
|
||||
|
||||
var folders by mutableStateOf<List<Folder>>(emptyList())
|
||||
private set
|
||||
private var loaded = false
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
|
||||
folders = runCatching {
|
||||
val array = JSONArray(raw)
|
||||
(0 until array.length()).map { i ->
|
||||
val o = array.getJSONObject(i)
|
||||
val apps = o.getJSONArray("apps")
|
||||
Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) })
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
fun create(context: Context, name: String, appKey: String): Folder {
|
||||
val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey))
|
||||
update(context, without(appKey) + folder)
|
||||
return folder
|
||||
}
|
||||
|
||||
fun add(context: Context, folderId: String, appKey: String) =
|
||||
update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it })
|
||||
|
||||
fun remove(context: Context, appKey: String) = update(context, without(appKey))
|
||||
|
||||
fun rename(context: Context, folderId: String, name: String) =
|
||||
update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it })
|
||||
|
||||
fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId })
|
||||
|
||||
fun migrateMembers(context: Context, keyFor: (String) -> String?) {
|
||||
if (folders.none { f -> f.apps.any { '/' !in it } }) return
|
||||
update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) })
|
||||
}
|
||||
|
||||
private fun without(appKey: String): List<Folder> =
|
||||
folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() }
|
||||
|
||||
private fun update(context: Context, next: List<Folder>) {
|
||||
folders = next
|
||||
val array = JSONArray()
|
||||
for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps)))
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
object HomeHidden {
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "hidden"
|
||||
|
||||
var keys by mutableStateOf<Set<String>>(emptySet())
|
||||
private set
|
||||
private var loaded = false
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet()
|
||||
}
|
||||
|
||||
fun set(context: Context, key: String, hidden: Boolean) {
|
||||
keys = if (hidden) keys + key else keys - key
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.LauncherApps
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.Process
|
||||
import android.os.UserManager
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
/** Shortcuts other apps asked to put on the home screen. The system keeps the pinned set per launcher. */
|
||||
object HomePins {
|
||||
class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) {
|
||||
val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else ""
|
||||
val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel }
|
||||
val work get() = userSerial != 0L
|
||||
}
|
||||
|
||||
var pinned by mutableStateOf<List<Pinned>>(emptyList())
|
||||
private set
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var listing = 0
|
||||
|
||||
fun refresh(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val seq = ++listing
|
||||
Thread({
|
||||
val list = runCatching { load(app) }.getOrDefault(emptyList())
|
||||
main.post { if (seq == listing) pinned = list }
|
||||
}, "home-pins").start()
|
||||
}
|
||||
|
||||
private fun load(context: Context): List<Pinned> {
|
||||
if (!HomeApp.canUseShortcuts(context)) return emptyList()
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val users = context.getSystemService(UserManager::class.java)
|
||||
val pm = context.packageManager
|
||||
val own = Process.myUserHandle()
|
||||
val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
|
||||
return users.userProfiles.flatMap { user ->
|
||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
||||
runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty()
|
||||
.filter { it.isEnabled && it.isPinned }
|
||||
.map { info ->
|
||||
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() }
|
||||
.getOrDefault(info.`package`)
|
||||
Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean {
|
||||
val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false)
|
||||
if (ok) refresh(context)
|
||||
return ok
|
||||
}
|
||||
|
||||
fun unpin(context: Context, pinned: Pinned) {
|
||||
val info = pinned.info
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
|
||||
val unpinned = runCatching {
|
||||
val current = checkNotNull(launcher.getShortcuts(query, info.userHandle))
|
||||
val keep = current.map { it.id } - info.id
|
||||
launcher.pinShortcuts(info.`package`, keep, info.userHandle)
|
||||
}.isSuccess
|
||||
if (!unpinned) return
|
||||
listing++
|
||||
this.pinned = this.pinned.filterNot { it.key == pinned.key }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.Activity
|
||||
import android.appwidget.AppWidgetHost
|
||||
import android.appwidget.AppWidgetHostView
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProviderInfo
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.LauncherApps
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.SizeF
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewConfiguration
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object HomeWidgets {
|
||||
data class Placed(val id: Int, val widthDp: Int, val heightDp: Int)
|
||||
|
||||
data class Provider(
|
||||
val info: AppWidgetProviderInfo,
|
||||
val label: String,
|
||||
val appLabel: String,
|
||||
val preview: Bitmap?,
|
||||
val widthDp: Int,
|
||||
val heightDp: Int,
|
||||
)
|
||||
|
||||
private const val HOST_ID = 0x0DDE
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "widgets"
|
||||
private const val REQUEST_BIND = 0x0DD1
|
||||
private const val REQUEST_CONFIGURE = 0x0DD2
|
||||
private const val REQUEST_RECONFIGURE = 0x0DD3
|
||||
const val MIN_WIDTH_DP = 96
|
||||
const val MIN_HEIGHT_DP = 56
|
||||
|
||||
var widgets by mutableStateOf<List<Placed>>(emptyList())
|
||||
private set
|
||||
var providers by mutableStateOf<List<Provider>?>(null)
|
||||
private set
|
||||
private var loaded = false
|
||||
private var host: Host? = null
|
||||
private var pending: AppWidgetProviderInfo? = null
|
||||
private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
private var pinRequest: LauncherApps.PinItemRequest? = null
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
private class Host(context: Context) : AppWidgetHost(context, HOST_ID) {
|
||||
override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView =
|
||||
HomeWidgetView(context)
|
||||
}
|
||||
|
||||
class HomeWidgetView(context: Context) : AppWidgetHostView(context) {
|
||||
var onLongPress: (() -> Unit)? = null
|
||||
private var fired = false
|
||||
private var downX = 0f
|
||||
private var downY = 0f
|
||||
private val slop = ViewConfiguration.get(context).scaledTouchSlop
|
||||
private val longPress = Runnable {
|
||||
fired = true
|
||||
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
||||
onLongPress?.invoke()
|
||||
}
|
||||
|
||||
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
|
||||
when (ev.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
fired = false
|
||||
downX = ev.x
|
||||
downY = ev.y
|
||||
postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong())
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress)
|
||||
}
|
||||
return fired
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (fired) {
|
||||
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false
|
||||
return true
|
||||
}
|
||||
return super.onTouchEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it }
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
|
||||
val manager = AppWidgetManager.getInstance(context)
|
||||
val parsed = runCatching {
|
||||
val array = JSONArray(raw)
|
||||
(0 until array.length()).map { i ->
|
||||
val o = array.getJSONObject(i)
|
||||
Placed(o.getInt("id"), o.getInt("w"), o.getInt("h"))
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null }
|
||||
parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) }
|
||||
widgets = live
|
||||
if (live.size != parsed.size) save(context)
|
||||
}
|
||||
|
||||
fun startListening(context: Context) {
|
||||
load(context)
|
||||
runCatching { host(context).startListening() }
|
||||
}
|
||||
|
||||
fun stopListening(context: Context) {
|
||||
runCatching { host(context).stopListening() }
|
||||
}
|
||||
|
||||
fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id)
|
||||
|
||||
fun createView(context: Context, id: Int): HomeWidgetView? {
|
||||
val info = info(context, id) ?: return null
|
||||
return host(context).createView(context, id, info) as? HomeWidgetView
|
||||
}
|
||||
|
||||
fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) {
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat())))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp)
|
||||
}
|
||||
}
|
||||
|
||||
fun loadProviders(context: Context) {
|
||||
if (providers != null) return
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val pm = app.packageManager
|
||||
val manager = AppWidgetManager.getInstance(app)
|
||||
val dpi = app.resources.displayMetrics.densityDpi
|
||||
val list = manager.installedProviders.mapNotNull { info ->
|
||||
runCatching {
|
||||
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() }
|
||||
.getOrDefault(info.provider.packageName)
|
||||
val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi)
|
||||
val preview = drawable?.let { d ->
|
||||
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
|
||||
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
|
||||
val scale = minOf(1f, 360f / maxOf(w, h))
|
||||
d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1))
|
||||
}
|
||||
val (w, h) = defaultSize(app, info)
|
||||
Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h)
|
||||
}.getOrNull()
|
||||
}.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label))
|
||||
main.post { providers = list }
|
||||
}, "widget-providers").start()
|
||||
}
|
||||
|
||||
fun refreshProviders(context: Context) {
|
||||
providers = null
|
||||
loadProviders(context)
|
||||
}
|
||||
|
||||
private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair<Int, Int> {
|
||||
val density = context.resources.displayMetrics.density
|
||||
var w = (info.minWidth / density).roundToInt()
|
||||
var h = (info.minHeight / density).roundToInt()
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80)
|
||||
if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80)
|
||||
}
|
||||
return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360)
|
||||
}
|
||||
|
||||
fun minSize(context: Context, id: Int): Pair<Int, Int> {
|
||||
val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP
|
||||
val density = context.resources.displayMetrics.density
|
||||
val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density
|
||||
val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density
|
||||
return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP)
|
||||
}
|
||||
|
||||
fun add(activity: Activity, provider: Provider) {
|
||||
if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null)
|
||||
}
|
||||
|
||||
/** Places a widget another app asked for; its own app has already configured it. */
|
||||
fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean {
|
||||
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false
|
||||
val info = request.getAppWidgetProviderInfo(activity) ?: return false
|
||||
load(activity)
|
||||
add(activity, info, request)
|
||||
return pending != null
|
||||
}
|
||||
|
||||
private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) {
|
||||
val h = host(activity)
|
||||
val id = h.allocateAppWidgetId()
|
||||
pending = info
|
||||
pendingId = id
|
||||
pinRequest = request
|
||||
val manager = AppWidgetManager.getInstance(activity)
|
||||
val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false)
|
||||
if (bound) {
|
||||
bound(activity, id, info)
|
||||
return
|
||||
}
|
||||
val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile)
|
||||
@Suppress("DEPRECATION")
|
||||
runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) }
|
||||
}
|
||||
|
||||
private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
|
||||
val request = pinRequest
|
||||
if (request == null) {
|
||||
configure(activity, id, info)
|
||||
return
|
||||
}
|
||||
val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) }
|
||||
.getOrDefault(false)
|
||||
if (accepted) place(activity, id, info) else abandon(activity)
|
||||
}
|
||||
|
||||
private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
|
||||
val optional = Build.VERSION.SDK_INT >= 31 &&
|
||||
info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
|
||||
if (info.configure == null || optional) {
|
||||
place(activity, id, info)
|
||||
return
|
||||
}
|
||||
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) }
|
||||
.onFailure { place(activity, id, info) }
|
||||
}
|
||||
|
||||
fun canReconfigure(context: Context, id: Int): Boolean {
|
||||
val info = info(context, id) ?: return false
|
||||
if (info.configure == null) return false
|
||||
return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0
|
||||
}
|
||||
|
||||
fun reconfigure(activity: Activity, id: Int) {
|
||||
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) }
|
||||
}
|
||||
|
||||
fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean {
|
||||
when (requestCode) {
|
||||
REQUEST_BIND -> {
|
||||
val info = pending
|
||||
if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity)
|
||||
}
|
||||
REQUEST_CONFIGURE -> {
|
||||
val info = pending
|
||||
if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity)
|
||||
}
|
||||
REQUEST_RECONFIGURE -> Unit
|
||||
else -> return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun abandon(context: Context) {
|
||||
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId)
|
||||
pending = null
|
||||
pinRequest = null
|
||||
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
}
|
||||
|
||||
private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) {
|
||||
val (w, h) = defaultSize(context, info)
|
||||
pending = null
|
||||
pinRequest = null
|
||||
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
widgets = widgets + Placed(id, w, h)
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) {
|
||||
widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it }
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun move(context: Context, id: Int, by: Int) {
|
||||
val i = widgets.indexOfFirst { it.id == id }
|
||||
val j = i + by
|
||||
if (i < 0 || j !in widgets.indices) return
|
||||
widgets = widgets.toMutableList().apply { add(j, removeAt(i)) }
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun remove(context: Context, id: Int) {
|
||||
host(context).deleteAppWidgetId(id)
|
||||
widgets = widgets.filterNot { it.id == id }
|
||||
save(context)
|
||||
}
|
||||
|
||||
private fun save(context: Context) {
|
||||
val array = JSONArray()
|
||||
for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp))
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.ActivityOptions
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import android.provider.Settings
|
||||
import android.util.Rational
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.animation.core.LinearEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.core.GlobalSettings
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
import com.droiddeck.launcher.ui.PrimaryButton
|
||||
import com.droiddeck.launcher.ui.SecondaryButton
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
class PairingGuideActivity : ComponentActivity() {
|
||||
enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
|
||||
|
||||
private var settingsDisplay: Int? = null
|
||||
private var inPip by mutableStateOf(false)
|
||||
private var launchPending = false
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
setContent { DroidDeckTheme { Guide() } }
|
||||
launchPending = savedInstanceState == null
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
launchPending = true
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (!launchPending) return
|
||||
if (inPip || settingsDisplay != null) {
|
||||
launchSettings()
|
||||
return
|
||||
}
|
||||
enterPip()
|
||||
if (!inPip) launchSettings()
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||
inPip = isInPictureInPictureMode
|
||||
if (isInPictureInPictureMode && launchPending) launchSettings()
|
||||
}
|
||||
|
||||
private fun launchSettings() {
|
||||
launchPending = false
|
||||
openSettings(stepFor(this, WirelessAdbPairingService.stage.value))
|
||||
}
|
||||
|
||||
private fun enterPip() {
|
||||
inPip = runCatching {
|
||||
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build())
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun openSettings(step: Step) {
|
||||
val intent = if (step == Step.BUILD_NUMBER) {
|
||||
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
|
||||
} else {
|
||||
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
|
||||
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val display = settingsDisplay
|
||||
runCatching {
|
||||
if (display == null) startActivity(intent)
|
||||
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
|
||||
}.onFailure {
|
||||
runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun returnToApp() {
|
||||
startActivity(Intent(this, FrontEndActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
|
||||
finish()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Guide() {
|
||||
val stage by WirelessAdbPairingService.stage.collectAsState()
|
||||
val settingsState by produceState(SettingsState.read(this)) {
|
||||
while (true) {
|
||||
value = SettingsState.read(this@PairingGuideActivity)
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
val step = stepFor(settingsState, stage)
|
||||
var previous by remember { mutableStateOf(step) }
|
||||
LaunchedEffect(step) {
|
||||
if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step)
|
||||
previous = step
|
||||
when (step) {
|
||||
Step.DONE -> { delay(1_500); returnToApp() }
|
||||
Step.FAILED -> { delay(3_000); returnToApp() }
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
LaunchedEffect(stage) { if (stage == Stage.Idle) finish() }
|
||||
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
|
||||
|
||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
|
||||
if (inPip) CompactStep(step, stage)
|
||||
else FullGuide(step, stage)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CompactStep(step: Step, stage: Stage) {
|
||||
Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(
|
||||
instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
StepVisual(step, compact = true)
|
||||
StepDots(step)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FullGuide(step: Step, stage: Stage) {
|
||||
Column(
|
||||
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground)
|
||||
StepVisual(step, compact = false)
|
||||
StepDots(step)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
if (step == Step.DONE || step == Step.FAILED) {
|
||||
PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp)
|
||||
} else {
|
||||
PrimaryButton(stringResource(R.string.gate_open_dev), onClick = {
|
||||
if (settingsDisplay == null) enterPip()
|
||||
openSettings(step)
|
||||
})
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
|
||||
WirelessAdbPairingService.cancel(this@PairingGuideActivity)
|
||||
returnToApp()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun instruction(step: Step, stage: Stage): String = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_pair)
|
||||
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
|
||||
Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working)
|
||||
Step.DONE -> stringResource(R.string.adbpair_title_done)
|
||||
Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepVisual(step: Step, compact: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.signal
|
||||
val pulse = rememberInfiniteTransition(label = "guidePulse")
|
||||
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
|
||||
val label = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
|
||||
Step.CODE -> stringResource(R.string.adbpair_enter_code)
|
||||
Step.WORKING, Step.DONE, Step.FAILED -> return
|
||||
}
|
||||
val rowHeight = if (compact) 34.dp else 56.dp
|
||||
Row(
|
||||
Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp))
|
||||
.border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
|
||||
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
when (step) {
|
||||
Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat)
|
||||
.background(accent, CircleShape))
|
||||
Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Toggle(on: Boolean, accent: Color, compact: Boolean) {
|
||||
val width = if (compact) 26.dp else 40.dp
|
||||
val knob = if (compact) 12.dp else 18.dp
|
||||
Box(
|
||||
Modifier.width(width).height(knob + 4.dp)
|
||||
.background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp),
|
||||
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) { Box(Modifier.size(knob).background(Color.White, CircleShape)) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepDots(step: Step) {
|
||||
val accent = LocalPalette.current.signal
|
||||
val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
|
||||
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
shown.forEachIndexed { index, _ ->
|
||||
Box(Modifier.size(if (index == at) 8.dp else 6.dp)
|
||||
.background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape))
|
||||
}
|
||||
Spacer(Modifier.width(2.dp))
|
||||
}
|
||||
}
|
||||
|
||||
private data class SettingsState(val developerOptions: Boolean, val wirelessDebugging: Boolean) {
|
||||
companion object {
|
||||
fun read(context: Context) = SettingsState(
|
||||
GlobalSettings.developerOptionsOn(context),
|
||||
GlobalSettings.wirelessDebuggingOn(context),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXTRA_DISPLAY = "settingsDisplay"
|
||||
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
|
||||
|
||||
private fun stepFor(context: Context, stage: Stage) = stepFor(SettingsState.read(context), stage)
|
||||
|
||||
private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) {
|
||||
is Stage.Working -> Step.WORKING
|
||||
Stage.Done -> Step.DONE
|
||||
is Stage.Failed -> Step.FAILED
|
||||
is Stage.CodeNeeded -> Step.CODE
|
||||
else -> when {
|
||||
!settings.developerOptions -> Step.BUILD_NUMBER
|
||||
!settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING
|
||||
else -> Step.PAIR
|
||||
}
|
||||
}
|
||||
|
||||
fun canFloat(context: Context): Boolean {
|
||||
if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false
|
||||
val ops = context.getSystemService(AppOpsManager::class.java) ?: return true
|
||||
val mode = if (Build.VERSION.SDK_INT >= 29) {
|
||||
ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
|
||||
}
|
||||
return mode == AppOpsManager.MODE_ALLOWED
|
||||
}
|
||||
|
||||
fun start(context: Context, settingsDisplay: Int?): Boolean {
|
||||
if (settingsDisplay == null && !canFloat(context)) return false
|
||||
context.startActivity(Intent(context, PairingGuideActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Intent
|
||||
import android.content.pm.LauncherApps
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.PinRequestPrompt
|
||||
|
||||
class PinRequestActivity : ComponentActivity() {
|
||||
override fun attachBaseContext(newBase: android.content.Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull()
|
||||
if (request == null || !request.isValid) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val prompt = when (request.requestType) {
|
||||
LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info ->
|
||||
val appLabel = appLabel(info.`package`)
|
||||
Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info))
|
||||
}
|
||||
LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info ->
|
||||
val appLabel = appLabel(info.provider.packageName)
|
||||
val dpi = resources.displayMetrics.densityDpi
|
||||
val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull()
|
||||
Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon)
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
if (prompt == null) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val (label, appLabel, icon) = prompt
|
||||
val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET
|
||||
setContent {
|
||||
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
|
||||
PinRequestPrompt(
|
||||
label = label, appLabel = appLabel, icon = icon, wide = widget,
|
||||
onAdd = {
|
||||
if (!widget) {
|
||||
HomePins.accept(this, request)
|
||||
finish()
|
||||
} else if (!HomeWidgets.addPinned(this, request)) finish()
|
||||
},
|
||||
onCancel = { finish() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
private fun appLabel(packageName: String): String =
|
||||
runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() }
|
||||
.getOrDefault(packageName)
|
||||
|
||||
private fun scaled(d: android.graphics.drawable.Drawable): Bitmap {
|
||||
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
|
||||
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
|
||||
val k = minOf(1f, 480f / maxOf(w, h))
|
||||
return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1))
|
||||
}
|
||||
}
|
||||
@@ -20,10 +20,19 @@ internal class ProtonMenu(
|
||||
private val ui: Handler,
|
||||
private val idle: () -> Boolean = { true },
|
||||
) {
|
||||
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
var protonBusyId by mutableStateOf<String?>(null)
|
||||
var protonStage by mutableStateOf<String?>(null)
|
||||
var protonPercent by mutableIntStateOf(-1)
|
||||
// Install workers and their results outlive the activity that starts them.
|
||||
private object Operation {
|
||||
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
val busyId = mutableStateOf<String?>(null)
|
||||
val stage = mutableStateOf<String?>(null)
|
||||
val percent = mutableIntStateOf(-1)
|
||||
val problem = mutableStateOf<String?>(null)
|
||||
}
|
||||
var protonRows by Operation.rows
|
||||
var protonBusyId by Operation.busyId
|
||||
var protonStage by Operation.stage
|
||||
var protonPercent by Operation.percent
|
||||
var protonProblem by Operation.problem
|
||||
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
||||
@@ -33,6 +42,7 @@ internal class ProtonMenu(
|
||||
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
|
||||
ProtonExtras.unqueue(activity, tool)
|
||||
protonBusyId = id
|
||||
protonProblem = null
|
||||
protonStage = activity.getString(R.string.store_starting)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
@@ -43,6 +53,7 @@ internal class ProtonMenu(
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
||||
ui.post {
|
||||
protonProblem = problem
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
protonPercent = -1
|
||||
@@ -60,6 +71,7 @@ internal class ProtonMenu(
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
protonBusyId = id
|
||||
protonProblem = null
|
||||
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
@@ -98,6 +110,7 @@ internal class ProtonMenu(
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
||||
protonBusyId = ProtonExtras.OWN
|
||||
protonProblem = null
|
||||
Thread({
|
||||
ProtonExtras.tidy(activity)
|
||||
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
|
||||
|
||||
@@ -9,6 +9,7 @@ import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.database.ContentObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
@@ -67,6 +68,7 @@ import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.input.EvdevKeys
|
||||
import com.droiddeck.launcher.input.HomeGuideInput
|
||||
import com.droiddeck.launcher.input.InputSpace
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
@@ -257,6 +259,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false }
|
||||
private val uiHandler = Handler(Looper.getMainLooper())
|
||||
private var pendingBackAction: Runnable? = null
|
||||
private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
|
||||
setPressed = { padBridge?.setBackQamPressed(it) },
|
||||
onTap = { performBackAction(double = it) },
|
||||
doubleTapMs = { backDoubleTapMs.toLong() },
|
||||
onCancel = { padBridge?.cancelBackQam() },
|
||||
)
|
||||
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
private var drawerDirectionDownTime = 0L
|
||||
private var drawerDirectionDeviceId = -1
|
||||
@@ -318,8 +326,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
||||
private var drawerControllerActive by mutableStateOf(false)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var lowLatencyController by mutableStateOf(false)
|
||||
private var lowLatencyTouch by mutableStateOf(false)
|
||||
private var backDoubleTapMs by mutableStateOf(500)
|
||||
private var lowLatency by mutableStateOf(true)
|
||||
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
|
||||
private var pcKeyboardOpen by mutableStateOf(false)
|
||||
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
|
||||
@@ -426,6 +434,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
// A higher refresh rate allowed in Android's settings does not change the display while this window
|
||||
// still asks for a lower mode, so the mode is chosen again when the setting changes.
|
||||
private val refreshSettingObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
|
||||
override fun onChange(selfChange: Boolean) {
|
||||
applyOutputPacing()
|
||||
}
|
||||
}
|
||||
|
||||
private fun followPanelRefresh(displayId: Int) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val output = glassesScreen?.display
|
||||
@@ -447,6 +463,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
override fun onInputDeviceRemoved(deviceId: Int) {
|
||||
Log.i(TAG, "input device $deviceId disconnected")
|
||||
backQamInput.onDeviceRemoved(deviceId)
|
||||
joyConVr?.refresh()
|
||||
padBridge?.onDeviceRemoved(deviceId)
|
||||
if (::padMouse.isInitialized) padMouse.reset()
|
||||
@@ -491,11 +508,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
if (!SessionState.running) {
|
||||
val prefMode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
|
||||
SessionState.fpsLimit = SessionPrefs.fpsLimit(this, prefMode)
|
||||
SessionState.performanceMode = SessionPrefs.performanceMode(this, prefMode)
|
||||
}
|
||||
applyOutputPacing()
|
||||
if (!SessionState.running) SessionState.followScreen = followChoice()
|
||||
applyFollowOrientation(resources.configuration)
|
||||
@@ -526,6 +538,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam)
|
||||
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
|
||||
padBridge = bridge
|
||||
bridge.setOnChordInput(backQamInput::onChordInput)
|
||||
SessionState.padBridge = bridge
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
val vr = com.droiddeck.launcher.input.JoyConVr(this, File(filesDir, ".wayland-rt/${com.droiddeck.launcher.input.JoyConVr.FILE}")) { taken, released ->
|
||||
@@ -550,12 +563,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
uiHandler.removeCallbacks(cursorHide)
|
||||
cursorVisible = false
|
||||
}
|
||||
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) }
|
||||
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { controls ->
|
||||
controls.onTouchMiss = miss@{ event ->
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
|
||||
event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
root.addView(controls)
|
||||
}
|
||||
screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this)
|
||||
screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys ->
|
||||
keys.onTouchMiss = miss@{ event ->
|
||||
if (routedTouchMode == SessionPrefs.TOUCH_GESTURES &&
|
||||
!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
|
||||
event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
@@ -580,8 +599,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// game surface and on-screen buttons, in either finger-down order.
|
||||
root.isMotionEventSplittingEnabled = true
|
||||
surfaceView.setOnTouchListener { _, event ->
|
||||
if (routedTouchMode != SessionPrefs.TOUCH_GESTURES) {
|
||||
gestureTouchStreamGate.reset()
|
||||
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
false
|
||||
} else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) {
|
||||
false
|
||||
@@ -775,6 +793,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
|
||||
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
|
||||
backQamInput.cancel()
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
|
||||
cancelTouchGestures()
|
||||
screenKeys?.stopEditing()
|
||||
}
|
||||
@@ -1015,20 +1035,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
padType = id
|
||||
},
|
||||
backActionsInverted = backActionsInverted,
|
||||
backDoubleTapMs = backDoubleTapMs,
|
||||
onBackDoubleTapMs = { ms ->
|
||||
SessionPrefs.setBackDoubleTapMs(this@SessionActivity, ms)
|
||||
backDoubleTapMs = ms
|
||||
},
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
lowLatencyController = lowLatencyController,
|
||||
lowLatencyTouch = lowLatencyTouch,
|
||||
onLowLatencyController = { on ->
|
||||
SessionPrefs.setLowLatencyController(this@SessionActivity, on)
|
||||
lowLatencyController = on
|
||||
applyLowLatency()
|
||||
},
|
||||
onLowLatencyTouch = { on ->
|
||||
SessionPrefs.setLowLatencyTouch(this@SessionActivity, on)
|
||||
lowLatencyTouch = on
|
||||
lowLatency = lowLatency,
|
||||
onLowLatency = { on ->
|
||||
SessionPrefs.setLowLatency(this@SessionActivity, on)
|
||||
lowLatency = on
|
||||
applyLowLatency()
|
||||
},
|
||||
onOsc = { v ->
|
||||
@@ -1092,7 +1111,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
pipAutoEnter = on
|
||||
pip.refresh(true)
|
||||
},
|
||||
unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null,
|
||||
unfoldedControls = unfoldedControls,
|
||||
onUnfoldedControls = ::chooseUnfoldedControls,
|
||||
unfoldedControlsWithController = unfoldedControlsWithController,
|
||||
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
|
||||
@@ -1299,7 +1318,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
performBackAction(double = false)
|
||||
}
|
||||
pendingBackAction = pending
|
||||
uiHandler.postDelayed(pending, 500L)
|
||||
uiHandler.postDelayed(pending, backDoubleTapMs.toLong())
|
||||
}
|
||||
|
||||
private fun performBackAction(double: Boolean) {
|
||||
@@ -1312,7 +1331,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return
|
||||
incoming.action = null
|
||||
setIntent(incoming)
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
if (SessionState.suspended) SessionService.resume(this)
|
||||
else if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
}
|
||||
|
||||
|
||||
@@ -1633,8 +1653,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
lowLatencyController = SessionPrefs.lowLatencyController(this)
|
||||
lowLatencyTouch = SessionPrefs.lowLatencyTouch(this)
|
||||
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
||||
lowLatency = SessionPrefs.lowLatency(this)
|
||||
padType = SessionPrefs.steamController(this)
|
||||
}
|
||||
|
||||
@@ -1795,9 +1815,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
||||
|
||||
val previous = SessionState.outputSize
|
||||
val live = if (SessionState.followScreen && !isInPictureInPictureMode)
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||
else null
|
||||
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||
val size = live ?: if (SessionState.running) previous else glassesOutputSize() ?: outputSize()
|
||||
SessionState.outputSize = size
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz()
|
||||
@@ -1854,7 +1872,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
)
|
||||
onOutputAttached(holder)
|
||||
if (SessionState.running && size != previous) {
|
||||
Log.i(TAG, "follow screen: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
||||
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
||||
WaylandCompositor.nativeResizeOutput(size.first, size.second)
|
||||
}
|
||||
if (!SessionState.running) SessionEvents.record("compositor.started")
|
||||
@@ -1886,15 +1904,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
cancelTouchGestures()
|
||||
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
|
||||
CompositorHost.resize(holder.surface) { applyFrameGen() }
|
||||
followWindow(width, height)
|
||||
resizeOutputForWindow(width, height)
|
||||
}
|
||||
}
|
||||
|
||||
private fun followWindow(width: Int, height: Int) {
|
||||
if (!SessionState.followScreen || isInPictureInPictureMode || !CompositorHost.isStarted) return
|
||||
val size = com.droiddeck.launcher.session.SessionDisplay.followSize(width, height) ?: return
|
||||
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
|
||||
if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
|
||||
return if (SessionState.followScreen)
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, controlsBelowWanted())
|
||||
else if (glassesScreen == null) outputSize() else null
|
||||
}
|
||||
|
||||
private fun resizeOutputForWindow(width: Int, height: Int) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val size = windowOutputSize(width, height) ?: return
|
||||
if (size == SessionState.outputSize) return
|
||||
Log.i(TAG, "follow screen: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
SessionState.outputSize = size
|
||||
val panel = panelBounds()
|
||||
SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1)
|
||||
@@ -1908,11 +1933,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun applyFollowOrientation(config: android.content.res.Configuration) {
|
||||
val wanted = if (SessionState.followScreen && config.smallestScreenWidthDp >= 600) {
|
||||
android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER
|
||||
} else {
|
||||
SessionPrefs.orientation(this)
|
||||
}
|
||||
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
|
||||
if (requestedOrientation != wanted) requestedOrientation = wanted
|
||||
}
|
||||
|
||||
@@ -1924,6 +1945,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
cancelTouchGestures()
|
||||
applyFollowOrientation(newConfig)
|
||||
applyUnfoldedControls()
|
||||
resizeOutputForWindow(surfaceW, surfaceH)
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
@@ -1965,7 +1987,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
|
||||
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
|
||||
else SessionPrefs.resolutionChoice(this, mode, panel)
|
||||
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice)
|
||||
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice,
|
||||
SessionPrefs.portrait(this) && !controlsBelowWanted())
|
||||
}
|
||||
|
||||
private fun refreshHz(): Float {
|
||||
@@ -1983,9 +2006,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun mirrorRefreshLimit(): Int =
|
||||
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
|
||||
|
||||
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
|
||||
GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit()), SessionState.performanceMode,
|
||||
)
|
||||
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit())
|
||||
|
||||
private fun applyOutputPacing() {
|
||||
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
|
||||
@@ -2082,7 +2103,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile)
|
||||
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
showEnded(status, hint)
|
||||
@@ -2112,6 +2133,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun releasePads() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
|
||||
backQamInput.cancel()
|
||||
padBridge?.releaseAll()
|
||||
joyConVr?.releaseButtons()
|
||||
}
|
||||
@@ -2145,6 +2168,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true)
|
||||
}
|
||||
|
||||
private fun prootFailureHint(): EndHint? {
|
||||
if (SessionState.failureCode != "PROOT_MISSING") return null
|
||||
val message = SessionState.failureMessage ?: return null
|
||||
return EndHint(message)
|
||||
}
|
||||
|
||||
private fun sessionEndHint(log: File?): EndHint? {
|
||||
if (log == null || !log.isFile) return null
|
||||
return try {
|
||||
@@ -2181,8 +2210,28 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
|
||||
val steamVolume =
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
|
||||
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
|
||||
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
||||
!gestureSettingsOpen && !screenKeyTextFocus && window.decorView.hasWindowFocus()
|
||||
if (steamVolume) {
|
||||
val audio = getSystemService(android.media.AudioManager::class.java)
|
||||
if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction ->
|
||||
audio.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, direction, 0)
|
||||
}) return true
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
}
|
||||
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
|
||||
!SessionState.suspended && padBridge?.canHoldQam() == true
|
||||
if (backQamInput.onKeyEvent(event, backToQam)) {
|
||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||
pendingBackAction = null
|
||||
return true
|
||||
}
|
||||
if (pipUi) return true
|
||||
if (screenKeyTextFocus) return super.dispatchKeyEvent(event)
|
||||
@@ -2241,7 +2290,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return true
|
||||
}
|
||||
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START ||
|
||||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || event.keyCode == KeyEvent.KEYCODE_HOME
|
||||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || HomeGuideInput.isHome(event.keyCode)
|
||||
val resumeKeyId = event.deviceId to event.keyCode
|
||||
if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
@@ -2312,6 +2361,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (pipUi) return true
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
drawerControllerActive = false
|
||||
gestureTouchStreamGate.reset()
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
@@ -2685,21 +2735,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
screenKeys?.refreshAppearance()
|
||||
}
|
||||
|
||||
private fun controlsBelowWanted(): Boolean {
|
||||
if (!::sessionRoot.isInitialized || glassesScreen != null || cardboard.enabled) return false
|
||||
return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height,
|
||||
pipUi || isInPictureInPictureMode)
|
||||
}
|
||||
|
||||
private fun applyUnfoldedControls() {
|
||||
if (!::sessionRoot.isInitialized) return
|
||||
val width = sessionRoot.width
|
||||
val height = sessionRoot.height
|
||||
val wanted = com.droiddeck.launcher.session.SessionDisplay.unfoldedControlsWanted(
|
||||
enabled = unfoldedControls,
|
||||
foldable = com.droiddeck.launcher.session.SessionDisplay.foldable(this),
|
||||
controllerConnected = PadBridge.anyControllerConnected() || SteamControllerBle.connected,
|
||||
keepWithController = unfoldedControlsWithController,
|
||||
steamDeckPad = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad,
|
||||
pip = pipUi || isInPictureInPictureMode,
|
||||
width = width,
|
||||
height = height,
|
||||
smallestWidthDp = resources.configuration.smallestScreenWidthDp,
|
||||
)
|
||||
val wanted = controlsBelowWanted()
|
||||
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
|
||||
else FrameLayout.LayoutParams.MATCH_PARENT
|
||||
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
|
||||
@@ -2709,13 +2755,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
else "unfolded controls: game full screen")
|
||||
}
|
||||
var panel = unfoldedPanel
|
||||
if (panel != null && panel.deckControls != SessionState.deckPad) {
|
||||
sessionRoot.removeView(panel)
|
||||
unfoldedPanel = null
|
||||
panel = null
|
||||
}
|
||||
if (!wanted) {
|
||||
if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() }
|
||||
return
|
||||
}
|
||||
if (panel == null) {
|
||||
panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) },
|
||||
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge)
|
||||
onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge,
|
||||
portraitDock = !com.droiddeck.launcher.session.SessionDisplay.foldable(this))
|
||||
sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1)
|
||||
unfoldedPanel = panel
|
||||
updateOnScreenControls()
|
||||
@@ -2960,6 +3012,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
uiHandler.postDelayed({ updateOnScreenControls() }, 700)
|
||||
}
|
||||
view.onStyle = { screenKeys?.refreshAppearance() }
|
||||
view.onTouchMiss = miss@{ event ->
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
|
||||
event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
root.addView(view, root.indexOfChild(onScreenControls) + 1)
|
||||
steamTouchControls = view
|
||||
steamTouchAvailable = true
|
||||
@@ -3151,7 +3208,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
|
||||
super.onPictureInPictureModeChanged(inPip, newConfig)
|
||||
if (::pip.isInitialized) pip.changed(inPip)
|
||||
if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH)
|
||||
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
|
||||
applyUnfoldedControls()
|
||||
updateGlassesScreen()
|
||||
}
|
||||
@@ -3170,6 +3227,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = true
|
||||
refreshActivityDisplayId()
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) {
|
||||
contentResolver.registerContentObserver(android.provider.Settings.System.getUriFor(name), false, refreshSettingObserver)
|
||||
}
|
||||
refreshSecondScreenDisplays()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
startedScreens++
|
||||
@@ -3184,6 +3244,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = false
|
||||
updateHandCamera()
|
||||
displayManager.unregisterDisplayListener(displayListener)
|
||||
contentResolver.unregisterContentObserver(refreshSettingObserver)
|
||||
closeSecondScreen(reset = false)
|
||||
startedScreens = (startedScreens - 1).coerceAtLeast(0)
|
||||
updateGlassesScreen()
|
||||
@@ -3239,6 +3300,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onScreenControls?.reload()
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
resumed = true
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this,
|
||||
enabled = {
|
||||
resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen &&
|
||||
!achievementsOpen && !gestureSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended &&
|
||||
SessionState.mode == SessionService.MODE_STEAM && padBridge != null
|
||||
},
|
||||
setPressed = { padBridge?.setHomeGuidePressed(it) },
|
||||
onCancel = { padBridge?.cancelHomeGuide() },
|
||||
)
|
||||
updatePointerCapture()
|
||||
if (!pipUi) sessionClipboard.start()
|
||||
updatePadMotion()
|
||||
@@ -3250,7 +3320,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
|
||||
if (runtimeRemovalBlocked) { super.onPause(); return }
|
||||
backQamInput.cancel()
|
||||
capturePausedFrame()
|
||||
sessionClipboard.stop()
|
||||
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
|
||||
@@ -3625,15 +3697,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun unbufferedSources() =
|
||||
if (lowLatencyTouch) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES
|
||||
if (lowLatency) UNBUFFERED_SOURCES or InputDevice.SOURCE_CLASS_POINTER else UNBUFFERED_SOURCES
|
||||
|
||||
private fun applyLowLatency() {
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatencyController, lowLatencyTouch)
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(lowLatency)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) window.decorView.requestUnbufferedDispatch(unbufferedSources())
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
|
||||
if (!hasFocus) backQamInput.cancel()
|
||||
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
|
||||
if (runtimeRemovalBlocked) return
|
||||
if (!hasFocus) {
|
||||
@@ -3681,6 +3755,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
|
||||
backQamInput.cancel()
|
||||
steamVrRecovery.close()
|
||||
uiHandler.removeCallbacks(steamTouchRetry)
|
||||
if (runtimeRemovalBlocked) { super.onDestroy(); return }
|
||||
|
||||
@@ -26,6 +26,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
|
||||
private final File workingDir;
|
||||
private final File deviceControls;
|
||||
private File logFile;
|
||||
private final String micFifoPath;
|
||||
private volatile int pid = -1;
|
||||
@@ -36,6 +37,8 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
public PulseAudioComponent(Context context, String micFifoPath) {
|
||||
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
|
||||
this.deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent.directory(
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context));
|
||||
this.micFifoPath = micFifoPath;
|
||||
}
|
||||
|
||||
@@ -94,7 +97,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
|
||||
+ socket().getAbsolutePath() + "\"");
|
||||
config.add(".nofail");
|
||||
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0");
|
||||
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
|
||||
config.add("set-default-sink DirectAudio");
|
||||
config.add(".fail");
|
||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||
@@ -139,7 +142,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
||||
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
||||
} else {
|
||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
|
||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
||||
&& pactl("set-default-sink", "AAudioSink") != null;
|
||||
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
|
||||
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
|
||||
|
||||
@@ -1,11 +1,32 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ActivityInfo
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
object AppUiPrefs {
|
||||
const val DEFAULT_SCALE = 100
|
||||
val scales = listOf(75, 85, 100, 115, 125, 150)
|
||||
|
||||
val orientationOptions = listOf(
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait,
|
||||
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
|
||||
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
|
||||
)
|
||||
|
||||
fun orientation(context: Context): Int =
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE)
|
||||
.getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
||||
?: ActivityInfo.SCREEN_ORIENTATION_USER
|
||||
|
||||
fun setOrientation(context: Context, value: Int) {
|
||||
require(orientationOptions.any { it.first == value })
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply()
|
||||
}
|
||||
|
||||
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
||||
|
||||
fun scale(context: Context): Int = normalizeScale(
|
||||
|
||||
@@ -261,6 +261,8 @@ object DeviceReport {
|
||||
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
||||
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
|
||||
object GlobalSettings {
|
||||
// Settings.Global caches values in-process and misses deletions made over adb; ask the provider directly.
|
||||
fun read(context: Context, name: String): String? {
|
||||
val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
|
||||
context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor ->
|
||||
return if (cursor.moveToFirst()) cursor.getString(0) else null
|
||||
}
|
||||
return Settings.Global.getString(context.contentResolver, name)
|
||||
}
|
||||
|
||||
fun isOn(context: Context, name: String): Boolean =
|
||||
runCatching { read(context, name)?.trim() == "1" }.getOrDefault(false)
|
||||
|
||||
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
|
||||
|
||||
// Settings.Global.ADB_WIFI_ENABLED is hidden; the key is stable since Android 11.
|
||||
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
|
||||
}
|
||||
@@ -60,14 +60,14 @@ object PhantomProcessLimit {
|
||||
if (usesDeviceConfig(sdk)) {
|
||||
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
|
||||
val global = try {
|
||||
Settings.Global.getString(context.contentResolver, SETTING)
|
||||
GlobalSettings.read(context, SETTING)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY))
|
||||
}
|
||||
val global = try {
|
||||
Settings.Global.getString(context.contentResolver, SETTING)
|
||||
GlobalSettings.read(context, SETTING)
|
||||
} catch (_: Exception) {
|
||||
return PhantomProcessStatus.UNREADABLE
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.accessibilityservice.AccessibilityServiceInfo
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import android.view.accessibility.AccessibilityManager
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.input.HomeButtonService
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
object SteamIntegration {
|
||||
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
|
||||
const val EXTRA_FEATURE = "integration_feature"
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
||||
|
||||
data class State(
|
||||
val wifi: Boolean = false,
|
||||
val locationPermission: Boolean = false,
|
||||
val locationOn: Boolean = false,
|
||||
val locationBlocked: Boolean = false,
|
||||
val brightness: Boolean = false,
|
||||
val home: Boolean = false,
|
||||
val shortcuts: Boolean = false,
|
||||
val shortcutsRestricted: Boolean = false,
|
||||
val shortcutsTried: Boolean = false,
|
||||
val suggested: Boolean = true,
|
||||
)
|
||||
|
||||
fun read(context: Context) = State(
|
||||
wifi = SessionPrefs.wifiDiscoveryEnabled(context),
|
||||
locationPermission = WifiDiscovery.permissionGranted(context),
|
||||
locationOn = WifiDiscovery.locationEnabled(context),
|
||||
brightness = Settings.System.canWrite(context),
|
||||
home = HomeApp.isDefault(context),
|
||||
shortcuts = context.getSystemService(AccessibilityManager::class.java)
|
||||
.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any {
|
||||
val service = it.resolveInfo.serviceInfo
|
||||
ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java)
|
||||
},
|
||||
shortcutsRestricted = restrictedSettings(context),
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
|
||||
// Android 13+ blocks accessibility services for sideloaded APKs until the user allows restricted settings in App info.
|
||||
// MODE_DEFAULT is inconclusive on Android 15, so only an explicit denial counts here.
|
||||
private fun restrictedSettings(context: Context): Boolean {
|
||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||
val mode = runCatching {
|
||||
context.getSystemService(android.app.AppOpsManager::class.java)
|
||||
.unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName)
|
||||
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
|
||||
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
||||
}
|
||||
|
||||
fun dismissSuggestion(context: Context) {
|
||||
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
|
||||
}
|
||||
|
||||
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
||||
Uri.parse("package:${context.packageName}"))
|
||||
|
||||
// ACCESSIBILITY_DETAILS_SETTINGS is restricted to system apps; the fragment args key highlights our entry in the list.
|
||||
fun shortcutSettings(context: Context): Intent {
|
||||
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
|
||||
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
.putExtra(":settings:fragment_args_key", service)
|
||||
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
|
||||
}
|
||||
}
|
||||
@@ -184,12 +184,15 @@ class WirelessAdbPairingService : Service() {
|
||||
setSound(null, null)
|
||||
enableVibration(false)
|
||||
})
|
||||
manager?.createNotificationChannel(NotificationChannel(PROGRESS_CHANNEL_ID, getString(R.string.adbpair_progress_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
|
||||
val open = PendingIntent.getActivity(this, 0,
|
||||
Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||
PendingIntent.FLAG_IMMUTABLE)
|
||||
val cancel = PendingIntent.getService(this, 1,
|
||||
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
|
||||
val builder = Notification.Builder(this, CHANNEL_ID)
|
||||
val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
|
||||
val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentIntent(open)
|
||||
.setShowWhen(false)
|
||||
@@ -239,6 +242,7 @@ class WirelessAdbPairingService : Service() {
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "wireless-adb-pairing"
|
||||
private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress"
|
||||
private const val NOTIFICATION_ID = 3
|
||||
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
|
||||
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.background
|
||||
@@ -181,14 +183,14 @@ fun CollapsibleRail(
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (!state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp).focusGlide(CircleShape)) {
|
||||
Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (collapsed && !state.portraitLocked) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) {
|
||||
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp).focusGlide(CircleShape)) {
|
||||
Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||
}
|
||||
}
|
||||
@@ -197,14 +199,14 @@ fun CollapsibleRail(
|
||||
if (collapsed) {
|
||||
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
links.forEach { link ->
|
||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) {
|
||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp).focusGlide(CircleShape)) {
|
||||
Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
links.forEach { link ->
|
||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) {
|
||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp).focusGlide(CircleShape)) {
|
||||
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(link.label, fontSize = 12.sp)
|
||||
@@ -250,11 +252,11 @@ fun CollapsibleRail(
|
||||
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
|
||||
shape,
|
||||
)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
|
||||
} else {
|
||||
base
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
||||
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
|
||||
}
|
||||
@@ -361,6 +363,7 @@ private fun TopTabCell(
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.focusGlide(RoundedCornerShape(9.dp))
|
||||
.then(
|
||||
if (isTab) {
|
||||
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
|
||||
|
||||
@@ -21,7 +21,7 @@ class FileManagerActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
@@ -39,7 +41,7 @@ import androidx.compose.material.icons.filled.Storage
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
@@ -105,12 +107,14 @@ private fun FileContextMenuItems(
|
||||
text = { Text(stringResource(R.string.fm_select)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onSelect() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_properties)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onProperties() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
if (isDir) {
|
||||
@@ -124,6 +128,7 @@ private fun FileContextMenuItems(
|
||||
)
|
||||
},
|
||||
onClick = { onToggleFavorite() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
}
|
||||
@@ -131,24 +136,28 @@ private fun FileContextMenuItems(
|
||||
text = { Text(stringResource(R.string.fm_rename)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onRename() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_copy)) },
|
||||
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onCopy() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_cut)) },
|
||||
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onCut() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.common_delete)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onDelete() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -193,7 +202,7 @@ internal fun FileItemRow(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||
onLongClick = onLongPress,
|
||||
),
|
||||
@@ -212,7 +221,7 @@ internal fun FileItemRow(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
|
||||
) {
|
||||
if (selectionMode) {
|
||||
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
|
||||
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() }, modifier = Modifier.focusGlide())
|
||||
Spacer(Modifier.width(4.dp))
|
||||
}
|
||||
when {
|
||||
@@ -270,7 +279,7 @@ internal fun FileItemRow(
|
||||
)
|
||||
}
|
||||
if (showActions) Box {
|
||||
IconButton(onClick = onMenu) {
|
||||
IconButton(onClick = onMenu, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
DropdownMenu(
|
||||
@@ -302,7 +311,7 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
|
||||
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||
@@ -370,6 +379,7 @@ internal fun FavoritesList(
|
||||
TextButton(
|
||||
onClick = onPinCurrent,
|
||||
enabled = !currentAlreadyPinned,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
@@ -422,7 +432,7 @@ private fun FavoriteCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
|
||||
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||
@@ -480,7 +490,7 @@ private fun FavoriteCard(
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onUnpin) {
|
||||
IconButton(onClick = onUnpin, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Filled.Star,
|
||||
contentDescription = stringResource(R.string.fm_unpin_favorite),
|
||||
@@ -526,7 +536,7 @@ internal fun FileGridTile(
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.padding(4.dp)
|
||||
.combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||
onLongClick = onLongPress,
|
||||
),
|
||||
@@ -570,7 +580,7 @@ internal fun FileGridTile(
|
||||
androidx.compose.material3.Checkbox(
|
||||
checked = selected,
|
||||
onCheckedChange = { onToggleSelect() },
|
||||
modifier = Modifier.align(Alignment.TopStart),
|
||||
modifier = Modifier.align(Alignment.TopStart).focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
@@ -19,6 +23,7 @@ import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
@@ -50,7 +55,7 @@ import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.SportsEsports
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -318,10 +323,10 @@ fun FileManagerScreen(
|
||||
navigate(action)
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.fm_accept)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_accept)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingNavigation = null }) {
|
||||
TextButton(onClick = { pendingNavigation = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.fm_decline))
|
||||
}
|
||||
},
|
||||
@@ -509,15 +514,16 @@ fun FileManagerScreen(
|
||||
onValueChange = { folderName = it },
|
||||
label = { Text(stringResource(R.string.fm_folder_name)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
showNewFolderDialog = false
|
||||
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
|
||||
}) { Text(stringResource(R.string.fm_create)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_create)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -532,6 +538,7 @@ fun FileManagerScreen(
|
||||
onValueChange = { newName = it },
|
||||
label = { Text(stringResource(R.string.fm_new_name)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
@@ -539,9 +546,9 @@ fun FileManagerScreen(
|
||||
val file = renameTarget
|
||||
renameTarget = null
|
||||
if (file != null && newName.isNotBlank()) performRename(file, newName)
|
||||
}) { Text(stringResource(R.string.fm_rename)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_rename)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { renameTarget = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -563,9 +570,9 @@ fun FileManagerScreen(
|
||||
TextButton(onClick = {
|
||||
selectedEntry = null
|
||||
performDelete(file)
|
||||
}) { Text(stringResource(R.string.common_delete)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { selectedEntry = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -611,9 +618,9 @@ fun FileManagerScreen(
|
||||
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -636,6 +643,7 @@ fun FileManagerScreen(
|
||||
androidx.compose.material3.Checkbox(
|
||||
checked = conflictApplyToAll,
|
||||
onCheckedChange = { conflictApplyToAll = it },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp)
|
||||
}
|
||||
@@ -648,7 +656,7 @@ fun FileManagerScreen(
|
||||
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip),
|
||||
).forEach { (choice, label) ->
|
||||
TextButton(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier.fillMaxWidth().focusGlide(CircleShape),
|
||||
onClick = { conflictChoice = choice; pendingConflict = null },
|
||||
) { Text(label, modifier = Modifier.fillMaxWidth()) }
|
||||
}
|
||||
@@ -656,13 +664,14 @@ fun FileManagerScreen(
|
||||
},
|
||||
confirmButton = {},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
|
||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
||||
Text(
|
||||
@@ -681,7 +690,7 @@ fun FileManagerScreen(
|
||||
onClick = { onPick?.invoke(currentDir) },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp).focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
@@ -693,9 +702,10 @@ fun FileManagerScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
|
||||
@@ -744,6 +754,7 @@ fun FileManagerScreen(
|
||||
).show()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
linuxRoot?.let { root ->
|
||||
@@ -754,6 +765,7 @@ fun FileManagerScreen(
|
||||
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
},
|
||||
onClick = { showDriveMenu = false; openDrive(root) },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -769,10 +781,10 @@ fun FileManagerScreen(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
||||
)
|
||||
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
if (!compactToolbar) Spacer(Modifier.weight(1f))
|
||||
} else {
|
||||
Text(
|
||||
text = currentDir.name.ifBlank { currentDir.absolutePath },
|
||||
@@ -781,12 +793,12 @@ fun FileManagerScreen(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
if (launchDir != null) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
|
||||
@@ -798,7 +810,7 @@ fun FileManagerScreen(
|
||||
onClick = { showNewFolderDialog = true },
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
|
||||
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
|
||||
modifier = Modifier.height(32.dp),
|
||||
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(5.dp))
|
||||
@@ -808,18 +820,18 @@ fun FileManagerScreen(
|
||||
IconButton(onClick = {
|
||||
gridView = !gridView
|
||||
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
|
||||
}) {
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
||||
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
|
||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showSortMenu = true }) {
|
||||
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
|
||||
@@ -836,6 +848,7 @@ fun FileManagerScreen(
|
||||
showSortMenu = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
||||
@@ -846,6 +859,7 @@ fun FileManagerScreen(
|
||||
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
||||
showSortMenu = false
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
||||
@@ -855,12 +869,13 @@ fun FileManagerScreen(
|
||||
showSortMenu = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
},
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
IconButton(onClick = { showFavorites = !showFavorites }) {
|
||||
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
if (showFavorites) {
|
||||
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
|
||||
} else {
|
||||
@@ -868,7 +883,7 @@ fun FileManagerScreen(
|
||||
}
|
||||
}
|
||||
if (!pickMode && onExit != null) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation) {
|
||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
@@ -880,7 +895,7 @@ fun FileManagerScreen(
|
||||
onValueChange = { searchQuery = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).focusGlide(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -918,13 +933,14 @@ fun FileManagerScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f))
|
||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.fm_selected_count, selectedPaths.size),
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontSize = 13.sp,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = if (compactToolbar) Modifier.padding(end = 12.dp) else Modifier.weight(1f),
|
||||
)
|
||||
val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths }
|
||||
val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths }
|
||||
@@ -935,6 +951,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -946,6 +963,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = emptySet()
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -957,6 +975,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = emptySet()
|
||||
},
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
@@ -964,11 +983,13 @@ fun FileManagerScreen(
|
||||
onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } },
|
||||
contentPadding = selBarPadding,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
OutlinedButton(
|
||||
onClick = { selectionMode = false; selectedPaths = emptySet() },
|
||||
contentPadding = selBarPadding,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
@@ -990,7 +1011,7 @@ fun FileManagerScreen(
|
||||
if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what),
|
||||
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
|
||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
@@ -1021,7 +1042,7 @@ fun FileManagerScreen(
|
||||
isOperationRunning = false
|
||||
operationDeterminate = false
|
||||
loadDirectory(currentDir, resetScroll = false)
|
||||
}) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
|
||||
@@ -25,7 +25,7 @@ class FilePickerActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
@@ -128,7 +130,7 @@ internal fun FilePropertiesDialog(
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.fm_done)) } },
|
||||
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_done)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -182,6 +184,7 @@ private fun AttributeToggleRow(
|
||||
checked = checked,
|
||||
enabled = enabled,
|
||||
onCheckedChange = onToggle,
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
@@ -32,12 +32,6 @@ internal object GlassesRendering {
|
||||
return if (hz == 30 && kotlin.math.abs(state.hz - 30f) >= 0.5f) 60 else hz
|
||||
}
|
||||
|
||||
fun fpsLimit(requested: Int, mirrorRefreshLimit: Int): Int = when {
|
||||
mirrorRefreshLimit <= 0 -> requested
|
||||
requested <= 0 -> mirrorRefreshLimit
|
||||
else -> minOf(requested, mirrorRefreshLimit)
|
||||
}
|
||||
|
||||
fun usesGlasses(state: GlassesState, outputActive: Boolean, steamVrRunning: Boolean): Boolean =
|
||||
outputActive || (steamVrRunning && state.usable)
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.KeyEvent
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
|
||||
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit,
|
||||
private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {}) {
|
||||
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val presses = mutableMapOf<Int, Press>()
|
||||
private val cancelled = mutableSetOf<Int>()
|
||||
private var tapPending = false
|
||||
private val singleTap = Runnable { tapPending = false; onTap(false) }
|
||||
|
||||
private fun cancelTap() {
|
||||
handler.removeCallbacks(singleTap)
|
||||
tapPending = false
|
||||
}
|
||||
|
||||
fun onChordInput() {
|
||||
if (presses.isEmpty()) return
|
||||
val alreadyHeld = presses.values.any { it.held }
|
||||
presses.values.forEach {
|
||||
handler.removeCallbacks(it.hold)
|
||||
it.held = true
|
||||
it.used = true
|
||||
}
|
||||
cancelTap()
|
||||
if (!alreadyHeld) setPressed(true)
|
||||
}
|
||||
|
||||
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
|
||||
if (!enabled) cancel()
|
||||
if (event.keyCode != KeyEvent.KEYCODE_BACK) return false
|
||||
val device = event.deviceId
|
||||
return when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> {
|
||||
if (event.repeatCount > 0) return enabled || device in presses || device in cancelled
|
||||
cancelled.remove(device)
|
||||
if (!enabled || event.isCanceled) return false
|
||||
if (device in presses) return true
|
||||
handler.removeCallbacks(singleTap)
|
||||
val hold = Runnable {
|
||||
val press = presses[device] ?: return@Runnable
|
||||
val alreadyHeld = presses.values.any { it.held }
|
||||
press.held = true
|
||||
presses.values.forEach { it.used = true }
|
||||
cancelTap()
|
||||
if (!alreadyHeld) setPressed(true)
|
||||
}
|
||||
presses[device] = Press(hold, used = presses.values.any { it.held })
|
||||
handler.postDelayed(hold, 700)
|
||||
true
|
||||
}
|
||||
KeyEvent.ACTION_UP -> {
|
||||
val press = presses.remove(device)
|
||||
val wasCancelled = cancelled.remove(device)
|
||||
if (press != null) {
|
||||
handler.removeCallbacks(press.hold)
|
||||
if (press.held && presses.values.none { it.held }) setPressed(false)
|
||||
if (!press.used && !event.isCanceled) {
|
||||
if (tapPending) { cancelTap(); onTap(true) }
|
||||
else { tapPending = true; handler.postDelayed(singleTap, doubleTapMs()) }
|
||||
} else if (event.isCanceled) cancelTap()
|
||||
}
|
||||
press != null || wasCancelled || enabled
|
||||
}
|
||||
else -> device in presses || device in cancelled
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
cancelTap()
|
||||
val wasHeld = presses.values.any { it.held }
|
||||
presses.values.forEach { handler.removeCallbacks(it.hold) }
|
||||
cancelled.addAll(presses.keys)
|
||||
presses.clear()
|
||||
onCancel()
|
||||
if (wasHeld) setPressed(false)
|
||||
}
|
||||
|
||||
fun onDeviceRemoved(device: Int) {
|
||||
cancelled.remove(device)
|
||||
val press = presses.remove(device) ?: return
|
||||
handler.removeCallbacks(press.hold)
|
||||
cancelTap()
|
||||
if (press.held && presses.values.none { it.held }) {
|
||||
onCancel()
|
||||
setPressed(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
@@ -104,6 +105,7 @@ class ControllerEditorActivity : ComponentActivity() {
|
||||
else -> Color.White.copy(alpha = 0.06f)
|
||||
},
|
||||
)
|
||||
.focusGlide(RoundedCornerShape(50))
|
||||
.then(
|
||||
if (selected == null) Modifier.clickable(onClick = onClick)
|
||||
else Modifier.toggleable(value = selected, role = Role.Switch, onValueChange = { onClick() }),
|
||||
|
||||
@@ -525,8 +525,8 @@ public class FakeInputWriter {
|
||||
}
|
||||
}
|
||||
|
||||
public static void setLowLatency(boolean controller, boolean touch) {
|
||||
int flags = (controller ? LATENCY_CONTROLLER : 0) | (touch ? LATENCY_TOUCH : 0);
|
||||
public static void setLowLatency(boolean enabled) {
|
||||
int flags = enabled ? LATENCY_CONTROLLER | LATENCY_TOUCH : 0;
|
||||
latency = flags;
|
||||
RingSlot ringSlot;
|
||||
synchronized (RING_LOCK) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import android.view.MotionEvent
|
||||
|
||||
/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
|
||||
internal class GestureTouchStreamGate {
|
||||
enum class Source { SURFACE, SCREEN_KEYS }
|
||||
enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
|
||||
|
||||
private var owner: Source? = null
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.input.InputManager
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.KeyEvent
|
||||
import android.view.accessibility.AccessibilityEvent
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
|
||||
object HomeButtonShortcuts {
|
||||
private var owner: Any? = null
|
||||
private var enabled: () -> Boolean = { false }
|
||||
private var setPressed: (Boolean) -> Unit = {}
|
||||
private var onCancel: () -> Unit = {}
|
||||
private val input = HomeGuideInput({ setPressed(it) }, { onCancel() })
|
||||
|
||||
fun attach(owner: Any, enabled: () -> Boolean, setPressed: (Boolean) -> Unit, onCancel: () -> Unit) {
|
||||
input.cancel()
|
||||
this.owner = owner
|
||||
this.enabled = enabled
|
||||
this.setPressed = setPressed
|
||||
this.onCancel = onCancel
|
||||
}
|
||||
|
||||
fun cancel(owner: Any) { if (this.owner === owner) input.cancel() }
|
||||
|
||||
fun detach(owner: Any) {
|
||||
if (this.owner !== owner) return
|
||||
input.cancel()
|
||||
this.owner = null
|
||||
enabled = { false }
|
||||
setPressed = {}
|
||||
onCancel = {}
|
||||
}
|
||||
|
||||
fun onKeyEvent(context: Context, event: KeyEvent): Boolean {
|
||||
// AYN maps its system-assistant key (gpio-keys KEY_F24) to HOME too; only the pad's Home is Guide.
|
||||
if (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false
|
||||
return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context))
|
||||
}
|
||||
|
||||
fun release() = input.cancel()
|
||||
fun onDeviceRemoved(device: Int) = input.onDeviceRemoved(device)
|
||||
}
|
||||
|
||||
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
|
||||
override fun onServiceConnected() {
|
||||
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
|
||||
}
|
||||
|
||||
override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event)
|
||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) {}
|
||||
override fun onInterrupt() { HomeButtonShortcuts.release() }
|
||||
override fun onInputDeviceAdded(deviceId: Int) {}
|
||||
override fun onInputDeviceChanged(deviceId: Int) {}
|
||||
override fun onInputDeviceRemoved(deviceId: Int) { HomeButtonShortcuts.onDeviceRemoved(deviceId) }
|
||||
|
||||
override fun onUnbind(intent: Intent?): Boolean {
|
||||
HomeButtonShortcuts.release()
|
||||
return super.onUnbind(intent)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
HomeButtonShortcuts.release()
|
||||
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.KeyEvent
|
||||
|
||||
class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCancel: () -> Unit = {}) {
|
||||
private val presses = mutableSetOf<Int>()
|
||||
private val cancelled = mutableSetOf<Int>()
|
||||
|
||||
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
|
||||
if (!isHome(event.keyCode)) return false
|
||||
if (!enabled) cancel()
|
||||
val device = event.deviceId
|
||||
return when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> {
|
||||
if (event.repeatCount > 0) return device in presses || device in cancelled
|
||||
cancelled.remove(device)
|
||||
if (!enabled || event.isCanceled) return false
|
||||
if (presses.add(device) && presses.size == 1) setPressed(true)
|
||||
true
|
||||
}
|
||||
KeyEvent.ACTION_UP -> {
|
||||
val owned = presses.remove(device)
|
||||
val wasCancelled = cancelled.remove(device)
|
||||
if (owned && presses.isEmpty()) setPressed(false)
|
||||
owned || wasCancelled
|
||||
}
|
||||
else -> device in presses || device in cancelled
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
val held = presses.isNotEmpty()
|
||||
cancelled.addAll(presses)
|
||||
presses.clear()
|
||||
if (held) { onCancel(); setPressed(false) }
|
||||
}
|
||||
|
||||
fun onDeviceRemoved(device: Int) {
|
||||
cancelled.remove(device)
|
||||
if (presses.remove(device) && presses.isEmpty()) { onCancel(); setPressed(false) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
// The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME.
|
||||
fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,8 @@ class OnScreenControls(
|
||||
private var quickHidden = false
|
||||
private var quickPressedBy = -1
|
||||
private var keyboardPressedBy = -1
|
||||
private var forwardedPointerBits = 0
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)? = null
|
||||
private var settings = ControllerPrefs.read(context)
|
||||
private var snap = settings.snap
|
||||
private var safe = Rect()
|
||||
@@ -515,6 +517,9 @@ class OnScreenControls(
|
||||
val index = event.actionIndex
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
|
||||
if (event.actionMasked == MotionEvent.ACTION_POINTER_DOWN && forwardMiss(event, x, y)) return true
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && keyboardContains(x, y)) {
|
||||
keyboardPressedBy = event.getPointerId(index)
|
||||
invalidate()
|
||||
@@ -542,11 +547,13 @@ class OnScreenControls(
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
if (keyboardPressedBy != -1) return true
|
||||
if (quickPressedBy != -1) return true
|
||||
var changed = false
|
||||
for (index in 0 until event.pointerCount) {
|
||||
val pointer = event.getPointerId(index)
|
||||
if (forwardedPointerBits and (1 shl pointer) != 0) continue
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
|
||||
@@ -568,10 +575,16 @@ class OnScreenControls(
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
val pointer = event.getPointerId(event.actionIndex)
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
if (event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
forwardedPointerBits = 0
|
||||
releaseAll()
|
||||
return true
|
||||
}
|
||||
if (forwardedPointerBits and (1 shl pointer) != 0) {
|
||||
forwardedPointerBits = forwardedPointerBits and (1 shl pointer).inv()
|
||||
return true
|
||||
}
|
||||
if (keyboardPressedBy == pointer) {
|
||||
val tapped = event.actionMasked == MotionEvent.ACTION_UP && keyboardContains(event.x, event.y)
|
||||
keyboardPressedBy = -1
|
||||
@@ -604,6 +617,23 @@ class OnScreenControls(
|
||||
return false
|
||||
}
|
||||
|
||||
private fun forwardMiss(event: MotionEvent, x: Float, y: Float): Boolean {
|
||||
if (onTouchMiss == null || keyboardPressedBy != -1 || quickPressedBy != -1) return false
|
||||
if (!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null) return false
|
||||
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(event.actionIndex))
|
||||
forwardPointers(event, forwardedPointerBits)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
|
||||
val split = event.pointerSubset(pointerIdBits) ?: return
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
split.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun onEditTouch(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
|
||||
@@ -53,6 +53,7 @@ public final class PadBridge {
|
||||
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
|
||||
private final PadState[] playerStates = new PadState[SLOTS];
|
||||
private final PadState effectiveState = new PadState();
|
||||
private final PadState homeGuideReport = new PadState();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private boolean open;
|
||||
private volatile boolean selectSteam;
|
||||
@@ -61,12 +62,21 @@ public final class PadBridge {
|
||||
private final PadState routedTouch = new PadState();
|
||||
private boolean systemGuidePressed;
|
||||
private boolean systemQamPressed;
|
||||
private boolean backQamPressed;
|
||||
private boolean homeGuidePressed;
|
||||
private int homeGuideSlot = -1;
|
||||
private final PadState lastBackQamReport = new PadState();
|
||||
private final PadState lastWrittenReport = new PadState();
|
||||
private boolean backQamAxesBlocked;
|
||||
private final java.util.Set<Runnable> backQamWrites = new java.util.HashSet<>();
|
||||
private long backQamDelayMs, backQamWriteAt;
|
||||
private boolean qamChordActive;
|
||||
private int chordButton = -1;
|
||||
private boolean chordButtonPressed;
|
||||
private boolean qamTapPressed;
|
||||
private int qamChordGeneration;
|
||||
private volatile Runnable onPlayerInput;
|
||||
private Runnable onChordInput;
|
||||
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
|
||||
private static final long STATS_WINDOW_MS = 10_000;
|
||||
@@ -129,9 +139,12 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
private void resetBuiltin() {
|
||||
homeGuidePressed = false;
|
||||
clearBackQamWrites();
|
||||
routedTouch.clear();
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
backQamPressed = false;
|
||||
qamTapPressed = false;
|
||||
qamChordActive = false;
|
||||
chordButtonPressed = false;
|
||||
@@ -150,6 +163,9 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
homeGuidePressed = false;
|
||||
homeGuideSlot = -1;
|
||||
clearBackQamWrites();
|
||||
releaseBackPaddles();
|
||||
activeControllerId = NO_CONTROLLER;
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
@@ -165,6 +181,7 @@ public final class PadBridge {
|
||||
}
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
backQamPressed = false;
|
||||
qamChordActive = false;
|
||||
chordButtonPressed = false;
|
||||
qamTapPressed = false;
|
||||
@@ -215,6 +232,7 @@ public final class PadBridge {
|
||||
case KeyEvent.KEYCODE_BACK:
|
||||
case KeyEvent.KEYCODE_MENU:
|
||||
case KeyEvent.KEYCODE_HOME:
|
||||
case KeyEvent.KEYCODE_MOVE_HOME:
|
||||
if (!isFromController(device)) return false;
|
||||
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|
||||
|| device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC
|
||||
@@ -273,6 +291,14 @@ public final class PadBridge {
|
||||
onPlayerInput = listener;
|
||||
}
|
||||
|
||||
public synchronized void setOnChordInput(Runnable listener) {
|
||||
onChordInput = listener;
|
||||
}
|
||||
|
||||
private void noteChordInput(int slot) {
|
||||
if (slot == 0 && onChordInput != null) onChordInput.run();
|
||||
}
|
||||
|
||||
private void notePlayerInput() {
|
||||
Runnable listener = onPlayerInput;
|
||||
if (listener == null || !playerInputPosted.compareAndSet(false, true)) return;
|
||||
@@ -307,7 +333,8 @@ public final class PadBridge {
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_MODE:
|
||||
case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break;
|
||||
case KeyEvent.KEYCODE_HOME:
|
||||
case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_Z:
|
||||
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed);
|
||||
break;
|
||||
@@ -323,6 +350,7 @@ public final class PadBridge {
|
||||
default: return false;
|
||||
}
|
||||
noteDevice(event.getDevice(), slot);
|
||||
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
|
||||
if (pressed) notePlayerInput();
|
||||
statButtons++;
|
||||
scheduleStats();
|
||||
@@ -352,6 +380,7 @@ public final class PadBridge {
|
||||
pad.rightX = x;
|
||||
pad.rightY = y;
|
||||
}
|
||||
if (x != 0f || y != 0f) noteChordInput(slot);
|
||||
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
|
||||
publish(slot);
|
||||
return true;
|
||||
@@ -382,6 +411,8 @@ public final class PadBridge {
|
||||
pad.up = hatY < -0.5f;
|
||||
pad.down = hatY > 0.5f;
|
||||
}
|
||||
if (pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|
||||
|| lt > 0f || rt > 0f || pad.up || pad.right || pad.down || pad.left) noteChordInput(slot);
|
||||
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|
||||
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
|
||||
notePlayerInput();
|
||||
@@ -458,7 +489,11 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void releaseAll() {
|
||||
homeGuidePressed = false;
|
||||
homeGuideSlot = -1;
|
||||
clearBackQamWrites();
|
||||
routedTouch.clear();
|
||||
backQamPressed = false;
|
||||
releaseBackPaddles();
|
||||
state.clear();
|
||||
publish();
|
||||
@@ -479,6 +514,146 @@ public final class PadBridge {
|
||||
return SessionState.getDeckPad() && FakeInputWriter.padHasQam();
|
||||
}
|
||||
|
||||
public boolean canHoldQam() {
|
||||
return builtinPad && nativeQam();
|
||||
}
|
||||
|
||||
public synchronized void setHomeGuidePressed(boolean pressed) {
|
||||
int slot = pressed ? firstPlayerSlot() : homeGuideSlot;
|
||||
if (slot > 0) {
|
||||
homeGuideSlot = pressed ? slot : -1;
|
||||
publish(slot);
|
||||
return;
|
||||
}
|
||||
if (homeGuidePressed == pressed) return;
|
||||
homeGuidePressed = pressed;
|
||||
updateHeldModifier(PadState.GUIDE, pressed);
|
||||
}
|
||||
|
||||
public synchronized void cancelHomeGuide() {
|
||||
int slot = homeGuideSlot;
|
||||
if (slot > 0) {
|
||||
homeGuideSlot = -1;
|
||||
publish(slot);
|
||||
}
|
||||
if (!homeGuidePressed) return;
|
||||
clearBackQamWrites();
|
||||
homeGuidePressed = false;
|
||||
state.clear();
|
||||
publish();
|
||||
}
|
||||
|
||||
public synchronized void setBackQamPressed(boolean pressed) {
|
||||
if (pressed && !canHoldQam()) return;
|
||||
if (backQamPressed == pressed) return;
|
||||
backQamPressed = pressed;
|
||||
updateHeldModifier(PadState.QAM, pressed);
|
||||
}
|
||||
|
||||
private void updateHeldModifier(int button, boolean pressed) {
|
||||
if (pressed && (open || start())) {
|
||||
backQamAxesBlocked = false;
|
||||
long now = android.os.SystemClock.uptimeMillis();
|
||||
long modifierAt = Math.max(now, backQamWriteAt);
|
||||
backQamDelayMs = modifierAt - now + QAM_GUIDE_LEAD_MIN_MS;
|
||||
PadState modifier = new PadState();
|
||||
modifier.copyFrom(lastBackQamReport);
|
||||
modifier.press(button, true);
|
||||
writeBackQamReport(modifier, modifierAt);
|
||||
}
|
||||
if (!pressed && !backQamPressed && !homeGuidePressed) {
|
||||
backQamAxesBlocked = hasAxes(state);
|
||||
if (!backQamWrites.isEmpty()) {
|
||||
PadState neutral = new PadState();
|
||||
neutral.copyFrom(lastWrittenReport);
|
||||
clearAxes(neutral);
|
||||
writer.writePad(neutral);
|
||||
lastWrittenReport.copyFrom(neutral);
|
||||
}
|
||||
}
|
||||
publish();
|
||||
}
|
||||
|
||||
public synchronized void cancelBackQam() {
|
||||
if (!backQamPressed && backQamWrites.isEmpty()) return;
|
||||
clearBackQamWrites();
|
||||
backQamPressed = false;
|
||||
state.clear();
|
||||
publish();
|
||||
}
|
||||
|
||||
private void clearBackQamWrites() {
|
||||
for (Runnable pending : backQamWrites) mainHandler.removeCallbacks(pending);
|
||||
backQamWrites.clear();
|
||||
backQamDelayMs = backQamWriteAt = 0;
|
||||
lastBackQamReport.clear();
|
||||
lastWrittenReport.clear();
|
||||
backQamAxesBlocked = false;
|
||||
}
|
||||
|
||||
private void writeBackQamReport(PadState report, long at) {
|
||||
lastBackQamReport.copyFrom(report);
|
||||
if (backQamWrites.isEmpty() && at <= android.os.SystemClock.uptimeMillis()) {
|
||||
writeReport(report, false);
|
||||
return;
|
||||
}
|
||||
PadState queued = new PadState();
|
||||
queued.copyFrom(report);
|
||||
Runnable pending = new Runnable() {
|
||||
@Override public void run() {
|
||||
synchronized (PadBridge.this) {
|
||||
if (!backQamWrites.remove(this)) return;
|
||||
writeReport(queued, true);
|
||||
if (backQamWrites.isEmpty() && !hasButtons(lastBackQamReport)) backQamDelayMs = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
backQamWrites.add(pending);
|
||||
backQamWriteAt = at;
|
||||
mainHandler.postAtTime(pending, at);
|
||||
}
|
||||
|
||||
private void writePad(PadState report) {
|
||||
if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false;
|
||||
long at = android.os.SystemClock.uptimeMillis();
|
||||
// Steam must see the modifier before a partner; preserve quick press/release pairs in order.
|
||||
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
|
||||
writeBackQamReport(report, at);
|
||||
}
|
||||
|
||||
private static boolean hasAxes(PadState pad) {
|
||||
return pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|
||||
|| pad.leftTrigger != 0f || pad.rightTrigger != 0f;
|
||||
}
|
||||
|
||||
private static void clearAxes(PadState pad) {
|
||||
pad.leftX = pad.leftY = pad.rightX = pad.rightY = pad.leftTrigger = pad.rightTrigger = 0f;
|
||||
}
|
||||
|
||||
private static boolean hasButtons(PadState pad) {
|
||||
for (int i = 0; i < 10; i++) if (pad.isDown(i)) return true;
|
||||
return pad.isDown(PadState.GUIDE) || pad.up || pad.right || pad.down || pad.left;
|
||||
}
|
||||
|
||||
private void writeReport(PadState report, boolean queued) {
|
||||
if (!queued && !backQamAxesBlocked) {
|
||||
lastWrittenReport.copyFrom(report);
|
||||
writer.writePad(report);
|
||||
return;
|
||||
}
|
||||
PadState live = new PadState();
|
||||
live.copyFrom(report);
|
||||
if (queued) {
|
||||
live.leftX = state.leftX; live.leftY = state.leftY;
|
||||
live.rightX = state.rightX; live.rightY = state.rightY;
|
||||
live.leftTrigger = state.leftTrigger; live.rightTrigger = state.rightTrigger;
|
||||
}
|
||||
boolean held = (backQamPressed && report.isDown(PadState.QAM)) || (homeGuidePressed && report.isDown(PadState.GUIDE));
|
||||
if ((queued && !held) || backQamAxesBlocked) clearAxes(live);
|
||||
lastWrittenReport.copyFrom(live);
|
||||
writer.writePad(live);
|
||||
}
|
||||
|
||||
public synchronized void triggerQam() {
|
||||
if (!builtinPad) return;
|
||||
if (!nativeQam()) {
|
||||
@@ -557,7 +732,9 @@ public final class PadBridge {
|
||||
slotJoyCons.set(slot * 2 + side, id);
|
||||
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
if (slot == 0) clearBackQamWrites();
|
||||
stateFor(slot).clear();
|
||||
if (slot == 0) publish();
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
|
||||
return slot;
|
||||
}
|
||||
@@ -592,6 +769,7 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
private void leave(int slot, int id) {
|
||||
if (slot == 0) clearBackQamWrites();
|
||||
if (partners[slot] == NO_CONTROLLER) {
|
||||
free(slot);
|
||||
return;
|
||||
@@ -618,6 +796,7 @@ public final class PadBridge {
|
||||
partners[slot] = NO_CONTROLLER;
|
||||
clearJoyCons(slot);
|
||||
slotControllers.set(slot, NO_CONTROLLER);
|
||||
if (slot == homeGuideSlot) homeGuideSlot = -1;
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
if (slot == 0) {
|
||||
state.clear();
|
||||
@@ -674,7 +853,13 @@ public final class PadBridge {
|
||||
}
|
||||
playerWriters[slot] = player;
|
||||
}
|
||||
player.writePad(playerStates[slot]);
|
||||
PadState report = playerStates[slot];
|
||||
if (slot == homeGuideSlot) {
|
||||
homeGuideReport.copyFrom(report);
|
||||
homeGuideReport.press(PadState.GUIDE, true);
|
||||
report = homeGuideReport;
|
||||
}
|
||||
player.writePad(report);
|
||||
}
|
||||
|
||||
private void publish() {
|
||||
@@ -683,17 +868,17 @@ public final class PadBridge {
|
||||
statDropped++;
|
||||
return;
|
||||
}
|
||||
boolean guide = systemGuidePressed || qamChordActive;
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed);
|
||||
boolean guide = systemGuidePressed || qamChordActive || homeGuidePressed;
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed);
|
||||
if (!guide && !qam) {
|
||||
writer.writePad(state);
|
||||
writePad(state);
|
||||
return;
|
||||
}
|
||||
effectiveState.copyFrom(state);
|
||||
if (guide) effectiveState.press(PadState.GUIDE, true);
|
||||
if (qam) effectiveState.press(PadState.QAM, true);
|
||||
if (chordButtonPressed) effectiveState.press(chordButton, true);
|
||||
writer.writePad(effectiveState);
|
||||
writePad(effectiveState);
|
||||
}
|
||||
|
||||
public static boolean wiredXboxLayout(MotionEvent event) {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.MotionEvent
|
||||
|
||||
internal fun MotionEvent.pointerSubset(pointerIdBits: Int): MotionEvent? {
|
||||
val indices = (0 until pointerCount).filter { index ->
|
||||
pointerIdBits and (1 shl getPointerId(index)) != 0
|
||||
}
|
||||
if (indices.isEmpty()) return null
|
||||
val splitIndex = indices.indexOf(actionIndex)
|
||||
val splitAction = when (actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> if (splitIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_POINTER_DOWN -> if (splitIndex >= 0) {
|
||||
if (indices.size == 1) MotionEvent.ACTION_DOWN
|
||||
else MotionEvent.ACTION_POINTER_DOWN or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
} else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_UP -> if (splitIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_POINTER_UP -> if (splitIndex >= 0) {
|
||||
if (indices.size == 1) MotionEvent.ACTION_UP
|
||||
else MotionEvent.ACTION_POINTER_UP or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
} else MotionEvent.ACTION_MOVE
|
||||
else -> action
|
||||
}
|
||||
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
|
||||
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
|
||||
indices.forEachIndexed { target, index ->
|
||||
getPointerProperties(index, properties[target])
|
||||
getPointerCoords(index, coordinates[target])
|
||||
}
|
||||
return MotionEvent.obtain(
|
||||
downTime, eventTime, splitAction, indices.size, properties, coordinates,
|
||||
metaState, buttonState, xPrecision, yPrecision,
|
||||
deviceId, edgeFlags, source, flags,
|
||||
)
|
||||
}
|
||||
@@ -926,35 +926,7 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
|
||||
}
|
||||
|
||||
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
|
||||
val indices = (0 until event.pointerCount).filter { index ->
|
||||
pointerIdBits and (1 shl event.getPointerId(index)) != 0
|
||||
}
|
||||
if (indices.isEmpty()) return
|
||||
val actionIndex = indices.indexOf(event.actionIndex)
|
||||
val action = when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> if (actionIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_POINTER_DOWN -> if (actionIndex >= 0) {
|
||||
if (indices.size == 1) MotionEvent.ACTION_DOWN
|
||||
else MotionEvent.ACTION_POINTER_DOWN or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
} else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_UP -> if (actionIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_POINTER_UP -> if (actionIndex >= 0) {
|
||||
if (indices.size == 1) MotionEvent.ACTION_UP
|
||||
else MotionEvent.ACTION_POINTER_UP or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
} else MotionEvent.ACTION_MOVE
|
||||
else -> event.action
|
||||
}
|
||||
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
|
||||
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
|
||||
indices.forEachIndexed { target, source ->
|
||||
event.getPointerProperties(source, properties[target])
|
||||
event.getPointerCoords(source, coordinates[target])
|
||||
}
|
||||
val split = MotionEvent.obtain(
|
||||
event.downTime, event.eventTime, action, indices.size, properties, coordinates,
|
||||
event.metaState, event.buttonState, event.xPrecision, event.yPrecision,
|
||||
event.deviceId, event.edgeFlags, event.source, event.flags,
|
||||
)
|
||||
val split = event.pointerSubset(pointerIdBits) ?: return
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
|
||||
@@ -103,6 +103,8 @@ class SteamTouchControls(
|
||||
|
||||
private class Finger(val element: Element?, var x: Float, var y: Float, val toolbar: Int = -1)
|
||||
private val fingers = HashMap<Int, Finger>()
|
||||
private var forwardedPointerBits = 0
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)? = null
|
||||
|
||||
private var editing = false
|
||||
private var editElements: MutableList<Element> = mutableListOf()
|
||||
@@ -629,7 +631,17 @@ class SteamTouchControls(
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
val e = hit(live(), x, y) ?: return event.actionMasked == MotionEvent.ACTION_POINTER_DOWN
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
|
||||
val e = hit(live(), x, y)
|
||||
if (e == null) {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) return false
|
||||
if (onTouchMiss != null) {
|
||||
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(index))
|
||||
forwardPointers(event, forwardedPointerBits)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
fingers[event.getPointerId(index)] = Finger(e, x, y)
|
||||
if (feedback) performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
requestUnbufferedDispatch(event)
|
||||
@@ -637,6 +649,7 @@ class SteamTouchControls(
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
for (i in 0 until event.pointerCount) {
|
||||
val f = fingers[event.getPointerId(i)] ?: continue
|
||||
f.x = event.getX(i)
|
||||
@@ -655,12 +668,14 @@ class SteamTouchControls(
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
val id = event.getPointerId(index)
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
forwardedPointerBits = if (event.actionMasked == MotionEvent.ACTION_CANCEL) 0 else forwardedPointerBits and (1 shl id).inv()
|
||||
val f = fingers.remove(id)
|
||||
if (event.actionMasked == MotionEvent.ACTION_CANCEL) fingers.clear()
|
||||
val e = f?.element
|
||||
if (event.actionMasked != MotionEvent.ACTION_CANCEL && e != null && reach(e, event.getX(index), event.getY(index)) <= 1.3f) {
|
||||
when (e.type) {
|
||||
SteamTouchConfig.THUMB -> openMenu()
|
||||
SteamTouchConfig.THUMB -> { cancelForwarded(event); openMenu() }
|
||||
SteamTouchConfig.KEYBOARD -> onKeyboard()
|
||||
SteamTouchConfig.PASTE -> onPaste()
|
||||
}
|
||||
@@ -673,6 +688,25 @@ class SteamTouchControls(
|
||||
}
|
||||
|
||||
|
||||
private fun cancelForwarded(event: MotionEvent) {
|
||||
val split = event.pointerSubset(forwardedPointerBits).also { forwardedPointerBits = 0 } ?: return
|
||||
split.action = MotionEvent.ACTION_CANCEL
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
split.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
|
||||
val split = event.pointerSubset(pointerIdBits) ?: return
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
split.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
val isEditing get() = editing
|
||||
|
||||
fun startEditing() {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.media.AudioManager
|
||||
import android.view.KeyEvent
|
||||
|
||||
/** Use Steam's PulseAudio bridge for feedback instead of requesting Android's volume UI. */
|
||||
internal object SteamVolumeKeys {
|
||||
fun dispatch(event: KeyEvent, enabled: Boolean, adjust: (Int) -> Unit): Boolean {
|
||||
val direction = when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP -> AudioManager.ADJUST_RAISE
|
||||
KeyEvent.KEYCODE_VOLUME_DOWN -> AudioManager.ADJUST_LOWER
|
||||
KeyEvent.KEYCODE_VOLUME_MUTE -> AudioManager.ADJUST_TOGGLE_MUTE
|
||||
else -> return false
|
||||
}
|
||||
if (!enabled) return false
|
||||
if (event.action == KeyEvent.ACTION_DOWN &&
|
||||
(event.keyCode != KeyEvent.KEYCODE_VOLUME_MUTE || event.repeatCount == 0)) {
|
||||
adjust(direction)
|
||||
}
|
||||
return event.action == KeyEvent.ACTION_DOWN || event.action == KeyEvent.ACTION_UP
|
||||
}
|
||||
}
|
||||
@@ -17,45 +17,45 @@ object BattleNet {
|
||||
|
||||
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
|
||||
|
||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null)
|
||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null)
|
||||
|
||||
internal val TITLES = listOf(
|
||||
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight"),
|
||||
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades"),
|
||||
Title("wow_classic_era", "World of Warcraft Classic", "WoWC"),
|
||||
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC"),
|
||||
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii"),
|
||||
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow"),
|
||||
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic"),
|
||||
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era"),
|
||||
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary"),
|
||||
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
|
||||
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
|
||||
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii"),
|
||||
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered"),
|
||||
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone"),
|
||||
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm"),
|
||||
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch"),
|
||||
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged"),
|
||||
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4"),
|
||||
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare"),
|
||||
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered"),
|
||||
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war"),
|
||||
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard"),
|
||||
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii"),
|
||||
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii"),
|
||||
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4"),
|
||||
Title("osi", "Diablo II: Resurrected", "OSI"),
|
||||
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection"),
|
||||
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal"),
|
||||
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
|
||||
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
|
||||
Title("d1", "Diablo", "D1", shop = "diablo"),
|
||||
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans"),
|
||||
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition"),
|
||||
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered"),
|
||||
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered"),
|
||||
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble"),
|
||||
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages"),
|
||||
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves"),
|
||||
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2"),
|
||||
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710),
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed"),
|
||||
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
|
||||
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered", product = "s1"),
|
||||
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone", product = "hsb"),
|
||||
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm", product = "hero"),
|
||||
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch", product = "pro"),
|
||||
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged", product = "w3"),
|
||||
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4", product = "viper"),
|
||||
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare", product = "odin"),
|
||||
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered", product = "lazr"),
|
||||
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war", product = "zeus"),
|
||||
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard", product = "fore"),
|
||||
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii", product = "auks"),
|
||||
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii", product = "pinta"),
|
||||
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4", product = "wlby"),
|
||||
Title("osi", "Diablo II: Resurrected", "OSI", product = "osi"),
|
||||
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection", product = "rtro"),
|
||||
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal", product = "anbs"),
|
||||
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
|
||||
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
|
||||
Title("d1", "Diablo", "D1", shop = "diablo", product = "drtl"),
|
||||
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans", product = "war1"),
|
||||
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition", product = "w2bn"),
|
||||
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered", product = "w1r"),
|
||||
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered", product = "w2r"),
|
||||
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble", product = "gryphon"),
|
||||
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages", product = "aris"),
|
||||
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves", product = "scor"),
|
||||
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2", product = "ark"),
|
||||
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710, product = "lbra"),
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
||||
)
|
||||
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
|
||||
@@ -104,7 +104,7 @@ object BattleNet {
|
||||
|
||||
private val NOT_GAMES = setOf("agent", "bna", "battle.net")
|
||||
|
||||
class Game(val uid: String, val name: String, val code: String, val folder: File) {
|
||||
class Game(val uid: String, val name: String, val code: String, val folder: File, val installUid: String = uid) {
|
||||
val title: Title get() = title(uid) ?: Title(uid, name, code)
|
||||
}
|
||||
|
||||
@@ -161,8 +161,10 @@ object BattleNet {
|
||||
|
||||
fun games(context: Context): List<Game> {
|
||||
val pfx = File(prefix(context), "pfx")
|
||||
val entries = runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()) +
|
||||
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrDefault(emptyList())
|
||||
val entries = installs(
|
||||
runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()),
|
||||
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull(),
|
||||
)
|
||||
val found = LinkedHashMap<String, Game>()
|
||||
for ((uid, path) in entries) {
|
||||
val title = title(uid)
|
||||
@@ -172,11 +174,17 @@ object BattleNet {
|
||||
}
|
||||
if (title.code in found) continue
|
||||
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
|
||||
found[title.code] = Game(title.uid, title.name, title.code, folder)
|
||||
found[title.code] = Game(title.uid, title.name, title.code, folder, uid)
|
||||
}
|
||||
return found.values.toList()
|
||||
}
|
||||
|
||||
internal fun installs(registry: List<Pair<String, String>>, agent: List<Pair<String, String>>?): List<Pair<String, String>> {
|
||||
if (agent == null) return registry
|
||||
val tracked = agent.map { it.first.lowercase() }.toSet()
|
||||
return registry.filter { it.first.lowercase() in tracked } + agent
|
||||
}
|
||||
|
||||
internal fun hostFolder(context: Context, path: String): File? {
|
||||
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
|
||||
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
|
||||
@@ -242,9 +250,9 @@ object BattleNet {
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>> {
|
||||
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrDefault(emptyList()).filter { it.first == 1 }
|
||||
return installs.mapNotNull { (_, start, end) ->
|
||||
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? {
|
||||
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
|
||||
return installs.map { (_, start, end) ->
|
||||
runCatching {
|
||||
val install = fields(bytes, start, end)
|
||||
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
|
||||
@@ -253,8 +261,8 @@ object BattleNet {
|
||||
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
|
||||
?.let { s -> varints(bytes, s.second, s.third)[1] }
|
||||
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
|
||||
}.getOrNull()
|
||||
}
|
||||
}.getOrElse { return null }
|
||||
}.filterNotNull()
|
||||
}
|
||||
|
||||
private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> }
|
||||
@@ -352,6 +360,8 @@ object BattleNet {
|
||||
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
|
||||
ComponentsManager.setGameComponent(context, scope, "fex", file)
|
||||
Log.i(TAG, "FEX for the Battle.net prefix: $file")
|
||||
} else if (ComponentsManager.republish(context)) {
|
||||
Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton")
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.database.ContentObserver
|
||||
import android.media.AudioManager
|
||||
import android.os.FileObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.R
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class DeviceControlsComponent(context: Context, root: File, private val activityVisible: () -> Boolean = { false }) : SessionPart() {
|
||||
private val context = context.applicationContext
|
||||
private val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
private val directory = directory(root)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var running = false
|
||||
private var permissionNotified = false
|
||||
private var previous = ""
|
||||
private var revision = 0L
|
||||
init { prepareBacklight(context, root) }
|
||||
private val observer = object : ContentObserver(handler) {
|
||||
override fun onChange(selfChange: Boolean) { if (running) publish() }
|
||||
}
|
||||
private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) {
|
||||
override fun onEvent(event: Int, path: String?) {
|
||||
if (path in REQUESTS) handler.post { if (running) consume() }
|
||||
}
|
||||
}
|
||||
private val refresh = object : Runnable {
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
consume()
|
||||
if (permissionNotified && Settings.System.canWrite(context))
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
publish()
|
||||
handler.postDelayed(this, 250)
|
||||
}
|
||||
}
|
||||
|
||||
fun publish(force: Boolean = false) {
|
||||
try {
|
||||
directory.mkdirs()
|
||||
val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
|
||||
val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1)
|
||||
val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC)
|
||||
write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n")
|
||||
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
|
||||
write("backlight/droiddeck/brightness", "$value\n")
|
||||
write("backlight/droiddeck/actual_brightness", "$value\n")
|
||||
val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0)
|
||||
.put("brightnessWritable", Settings.System.canWrite(context)).toString()
|
||||
if (force || state != previous) {
|
||||
write("state.json", JSONObject(state).put("revision", ++revision).toString())
|
||||
previous = state
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not publish Android controls", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
handler.post {
|
||||
REQUESTS.forEach {
|
||||
File(directory, it).delete()
|
||||
File(directory, "$it.processing").delete()
|
||||
}
|
||||
running = true
|
||||
permissionNotified = false
|
||||
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
|
||||
requests.startWatching()
|
||||
refresh.run()
|
||||
}
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
handler.post {
|
||||
running = false
|
||||
handler.removeCallbacks(refresh)
|
||||
requests.stopWatching()
|
||||
context.contentResolver.unregisterContentObserver(observer)
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
}
|
||||
}
|
||||
|
||||
private fun consume() {
|
||||
for (name in REQUESTS) {
|
||||
val file = File(directory, name)
|
||||
if (!file.isFile) continue
|
||||
val claimed = File(directory, "$name.processing")
|
||||
try {
|
||||
Files.move(file.toPath(), claimed.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
|
||||
if (claimed.length() > 64) continue
|
||||
val text = claimed.readText().trim()
|
||||
when (name) {
|
||||
"brightness.request" -> text.toFloatOrNull()?.takeIf { it.isFinite() && it in 0f..1f }?.let(::brightness)
|
||||
"volume.request" -> text.toIntOrNull()?.let {
|
||||
audio.setStreamVolume(AudioManager.STREAM_MUSIC,
|
||||
it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0)
|
||||
}
|
||||
"mute.request" -> if (text == "0" || text == "1") {
|
||||
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
|
||||
if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not apply $name", e)
|
||||
} finally {
|
||||
publish(force = true)
|
||||
claimed.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun brightness(value: Float) {
|
||||
if (!Settings.System.canWrite(context)) {
|
||||
if (!permissionNotified) {
|
||||
permissionNotified = true
|
||||
try {
|
||||
val intent = Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java)
|
||||
.setAction(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP)
|
||||
.putExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE, "BRIGHTNESS")
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(NotificationChannel(PERMISSION_CHANNEL,
|
||||
context.getString(R.string.brightness_permission_title), NotificationManager.IMPORTANCE_DEFAULT))
|
||||
val action = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
|
||||
manager.notify(PERMISSION_NOTIFICATION, Notification.Builder(context, PERMISSION_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(context.getString(R.string.brightness_permission_title))
|
||||
.setContentText(context.getString(R.string.brightness_permission_text))
|
||||
.setContentIntent(action).setOnlyAlertOnce(true).setAutoCancel(true).build())
|
||||
if (activityVisible()) android.widget.Toast.makeText(context, R.string.integration_brightness_needed,
|
||||
android.widget.Toast.LENGTH_LONG).show()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not open brightness permission", e)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val level = 1 + (value * 254).roundToInt()
|
||||
try {
|
||||
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
|
||||
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
|
||||
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, level)
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Brightness permission was revoked", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(name: String, text: String) {
|
||||
val file = File(directory, name)
|
||||
if (file.isFile && file.readText() == text) return
|
||||
val staged = File(directory, "$name.tmp")
|
||||
staged.writeText(text)
|
||||
Files.move(staged.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DeviceControls"
|
||||
private const val PERMISSION_CHANNEL = "brightness_permission"
|
||||
private const val PERMISSION_NOTIFICATION = 0x4442
|
||||
private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request")
|
||||
@JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls")
|
||||
@JvmStatic fun prepareBacklight(context: Context, root: File): File {
|
||||
val base = File(directory(root), "backlight")
|
||||
val panel = File(base, "droiddeck").apply { mkdirs() }
|
||||
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
|
||||
for ((name, text) in mapOf("type" to "raw", "max_brightness" to "255", "brightness" to "$value",
|
||||
"actual_brightness" to "$value", "bl_power" to "0", "scale" to "linear")) {
|
||||
File(panel, name).writeText("$text\n")
|
||||
}
|
||||
return base
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,15 +63,48 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
private static final String HOST_DIR = "opt/android-host";
|
||||
/** The downloaded add-on pack. The APK does not ship this binary. */
|
||||
public static final String PROOT_PACK = "add-on pack";
|
||||
/** Termux's unpatched proot inside the rootfs. Developer switch only. */
|
||||
public static final String PROOT_ROOTFS = "rootfs fallback";
|
||||
public static final String PROOT_MISSING = "missing";
|
||||
|
||||
private static File rootfsProot(Context context) {
|
||||
return new File(rootDir(context), HOST_DIR + "/proot");
|
||||
}
|
||||
|
||||
private static File rootfsLoader(Context context) {
|
||||
return new File(rootDir(context), HOST_DIR + "/loader");
|
||||
}
|
||||
|
||||
private static boolean rootfsProotReady(Context context) {
|
||||
return rootfsProot(context).isFile() && rootfsLoader(context).isFile();
|
||||
}
|
||||
|
||||
/** Patched proot is the add-on pack. The rootfs copy is not that binary. */
|
||||
public static boolean patchedProot(Context context) {
|
||||
return AddonPack.PROOT.installed(context);
|
||||
}
|
||||
|
||||
public static File prootBinary(Context context) {
|
||||
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so");
|
||||
return new File(rootDir(context), HOST_DIR + "/proot");
|
||||
if (SessionPrefs.allowStockProot(context)) return rootfsProot(context);
|
||||
return AddonPack.PROOT.file(context, "libproot.so");
|
||||
}
|
||||
|
||||
public static File prootLoader(Context context) {
|
||||
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
return new File(rootDir(context), HOST_DIR + "/loader");
|
||||
if (SessionPrefs.allowStockProot(context)) return rootfsLoader(context);
|
||||
return AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
}
|
||||
|
||||
/** Where {@link #prootBinary} came from: {@link #PROOT_PACK}, {@link #PROOT_ROOTFS} or {@link #PROOT_MISSING}. */
|
||||
public static String prootSource(Context context) {
|
||||
File bin = prootBinary(context);
|
||||
if (!bin.isFile()) return PROOT_MISSING;
|
||||
if (AddonPack.PROOT.installed(context)
|
||||
&& bin.getPath().equals(AddonPack.PROOT.file(context, "libproot.so").getPath())) return PROOT_PACK;
|
||||
return PROOT_ROOTFS;
|
||||
}
|
||||
|
||||
public static String prootLibraryPath(Context context) {
|
||||
@@ -85,8 +118,7 @@ public final class LinuxRuntime {
|
||||
return new File(root, "usr/bin/gamescope").isFile()
|
||||
&& (new File(root, SESSION_SCRIPT.substring(1)).isFile()
|
||||
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile())
|
||||
&& prootBinary(context).isFile()
|
||||
&& prootLoader(context).isFile();
|
||||
&& (patchedProot(context) || rootfsProotReady(context));
|
||||
}
|
||||
|
||||
public static File vulkanIcd(Context context) {
|
||||
@@ -160,6 +192,7 @@ public final class LinuxRuntime {
|
||||
bind(cmd, "/dev");
|
||||
bind(cmd, "/proc");
|
||||
bind(cmd, "/sys");
|
||||
bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight");
|
||||
bind(cmd, "/dev/urandom:/dev/random");
|
||||
bind(cmd, "/proc/self/fd:/dev/fd");
|
||||
bind(cmd, "/proc/self/fd/0:/dev/stdin");
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.util.Log;
|
||||
|
||||
|
||||
import com.droiddeck.launcher.R;
|
||||
import com.droiddeck.launcher.session.SessionPrefs;
|
||||
import com.droiddeck.launcher.core.ArchivePaths;
|
||||
import com.droiddeck.launcher.core.Downloader;
|
||||
import com.droiddeck.launcher.core.Hashes;
|
||||
@@ -262,7 +263,9 @@ public final class LinuxRuntimeInstaller {
|
||||
emptyTrash(LinuxRuntime.rootDir(context).getParentFile());
|
||||
String downloading = context.getString(R.string.rtinst_downloading);
|
||||
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||
if (!AddonPack.PROOT.await(context)) throw new IOException("Cannot download proot");
|
||||
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context)
|
||||
&& !SessionPrefs.allowStockProot(context))
|
||||
throw new IOException("Cannot download proot");
|
||||
if (!AddonPack.DIRECTAUDIO.await(context)) throw new IOException("Cannot download DirectAudio");
|
||||
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
|
||||
if (listener != null) {
|
||||
|
||||
@@ -1,18 +1,32 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
object ProotFastPath {
|
||||
private const val TAG = "ProotFastPath"
|
||||
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
fun enabled(context: Context): Boolean =
|
||||
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context) &&
|
||||
LinuxRuntime.prootBinary(context).parentFile == AddonPack.PROOT.dir(context)
|
||||
/**
|
||||
* The fast path's trampoline is let through only by the proot built with patches/0014.
|
||||
* The rootfs copy (Termux's stock proot) is not that binary, so the library stays out.
|
||||
*/
|
||||
fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean =
|
||||
preference && !noSeccomp && source == LinuxRuntime.PROOT_PACK
|
||||
|
||||
fun enabled(context: Context): Boolean {
|
||||
val preference = SessionPrefs.prootFastPath(context)
|
||||
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
|
||||
val source = LinuxRuntime.prootSource(context)
|
||||
val on = allows(preference, noSeccomp, source)
|
||||
if (preference && !noSeccomp && !on)
|
||||
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
|
||||
return on
|
||||
}
|
||||
|
||||
fun key(root: File, binds: List<String>): String? {
|
||||
if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null
|
||||
|
||||
@@ -155,8 +155,7 @@ object ComponentsManager {
|
||||
if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" }
|
||||
}
|
||||
|
||||
private fun saveState(context: Context, state: JSONObject) {
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
private fun saveState(context: Context, state: JSONObject, prepared: PreparedLaunchState = prepareLaunchState(context, state)) {
|
||||
val dir = launchDir(context)
|
||||
val tmp = File(dir, "desired.tsv.tmp")
|
||||
try {
|
||||
@@ -175,6 +174,17 @@ object ComponentsManager {
|
||||
?.forEach { it.deleteRecursively() }
|
||||
}
|
||||
|
||||
fun republish(context: Context): Boolean = synchronized(lock) {
|
||||
recoverState(context)
|
||||
val saved = stateFile(context)
|
||||
if (saved.exists() && runCatching { JSONObject(saved.readText()) }.isFailure) return false
|
||||
val state = loadState(context)
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
if ((FileUtils.readString(File(launchDir(context), "desired.tsv")) ?: "") == prepared.text) return false
|
||||
saveState(context, state, prepared)
|
||||
true
|
||||
}
|
||||
|
||||
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
||||
|
||||
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
|
||||
|
||||
@@ -8,7 +8,7 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The FEX build DroidDeck-Components' fex.json names for the x86-64 client. A session uses the last copy read.
|
||||
* The FEX build DroidDeck-Components' fex.json names for x86 programs. A session uses the last copy read.
|
||||
* Components' build-fex.yml replaces the archive on its single `fex` release and records the build's version;
|
||||
* a release per build (fex-2610-r5) is still read.
|
||||
*/
|
||||
@@ -62,7 +62,7 @@ object FexCatalog {
|
||||
return build
|
||||
}
|
||||
|
||||
/** For droiddeck-steam-x64: the build and every source its archive may come from (it checks the sha256). */
|
||||
/** For droiddeck-fex-update: the build and every source its archive may come from (it checks the sha256). */
|
||||
fun environment(build: Build, sources: List<String> = DownloadSource.candidates(build.url)): List<String> = listOf(
|
||||
"BL_FEX_TAG=${build.tag}",
|
||||
"BL_FEX_SHA256=${build.sha256}",
|
||||
|
||||
@@ -51,7 +51,8 @@ object NoSteamLaunch {
|
||||
|
||||
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
|
||||
val id = game.appId.toLong() and 0xFFFFFFFFL
|
||||
return AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
val one = game.gameFiles?.let { AddedGames.single(context, it.path) }
|
||||
return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
}
|
||||
|
||||
fun nameFor(program: String?, args: List<String>): String? = when (program) {
|
||||
|
||||
@@ -18,7 +18,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
class PerfHud(context: Context) {
|
||||
var text by mutableStateOf("")
|
||||
@@ -32,9 +31,9 @@ class PerfHud(context: Context) {
|
||||
private var lastFps = 0f
|
||||
private var running = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val intervals = FloatArray(GRAPH)
|
||||
private val graphWrite = AtomicInteger()
|
||||
private val lastFrameNs = AtomicLong()
|
||||
private val samples = FloatArray(GRAPH)
|
||||
private var graphBase = 0L
|
||||
private var graphSeen = 0L
|
||||
|
||||
@Volatile private var showFps = true
|
||||
@Volatile private var showBattery = true
|
||||
@@ -59,14 +58,6 @@ class PerfHud(context: Context) {
|
||||
}
|
||||
override fun onGameFrame() {
|
||||
frames.incrementAndGet()
|
||||
if (!showGraph) return
|
||||
val now = System.nanoTime()
|
||||
val previous = lastFrameNs.getAndSet(now)
|
||||
if (previous == 0L) return
|
||||
val ms = ((now - previous) / 1_000_000f).coerceIn(0f, 50f)
|
||||
val slot = graphWrite.get()
|
||||
intervals[slot and (GRAPH - 1)] = ms
|
||||
graphWrite.compareAndSet(slot, slot + 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,9 +91,9 @@ class PerfHud(context: Context) {
|
||||
if (!enabled || !anyPart || running) return
|
||||
running = true
|
||||
lastTick = SystemClock.elapsedRealtime()
|
||||
lastFrameNs.set(0L)
|
||||
frames.set(0)
|
||||
graphWrite.set(0)
|
||||
graphBase = shownTotal()
|
||||
graphSeen = graphBase
|
||||
WaylandCompositor.setGameListener(listener)
|
||||
handler.postDelayed(tick, TICK_MS)
|
||||
}
|
||||
@@ -135,23 +126,19 @@ class PerfHud(context: Context) {
|
||||
return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
|
||||
}
|
||||
|
||||
private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L }
|
||||
|
||||
private fun clearGraph() {
|
||||
lastFrameNs.set(0L)
|
||||
graphWrite.set(0)
|
||||
graphBase = shownTotal()
|
||||
graphSeen = graphBase
|
||||
if (graph.isNotEmpty()) graph = FloatArray(0)
|
||||
}
|
||||
|
||||
private fun publishGraph() {
|
||||
val count = graphWrite.get()
|
||||
val shown = minOf(count, GRAPH)
|
||||
if (shown < 2) {
|
||||
graph = FloatArray(0)
|
||||
return
|
||||
}
|
||||
val out = FloatArray(shown)
|
||||
val start = count - shown
|
||||
for (i in 0 until shown) out[i] = intervals[(start + i) and (GRAPH - 1)]
|
||||
graph = out
|
||||
val total = shownTotal()
|
||||
if (total == graphSeen && graph.isNotEmpty()) return
|
||||
graphSeen = total
|
||||
graph = recent(samples, total, graphBase)
|
||||
}
|
||||
|
||||
private fun line(base: Float): String {
|
||||
@@ -176,6 +163,14 @@ class PerfHud(context: Context) {
|
||||
companion object {
|
||||
private const val TICK_MS = 1_000L
|
||||
private const val GRAPH = 128
|
||||
internal const val GRAPH_MAX_MS = 50f
|
||||
|
||||
internal fun recent(samples: FloatArray, total: Long, base: Long): FloatArray {
|
||||
val filled = minOf(total, samples.size.toLong()).toInt()
|
||||
val shown = minOf(filled.toLong(), (total - base).coerceAtLeast(0L)).toInt()
|
||||
if (shown < 2) return FloatArray(0)
|
||||
return FloatArray(shown) { samples[filled - shown + it].coerceIn(0f, GRAPH_MAX_MS) }
|
||||
}
|
||||
|
||||
internal fun batteryCelsius(deci: Int): String? =
|
||||
if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f)
|
||||
|
||||
@@ -30,6 +30,7 @@ class RumbleComponent : SessionPart() {
|
||||
private val joyConPairs = HashMap<Long, Motors>()
|
||||
private var preferences: SharedPreferences? = null
|
||||
private var enabled = false
|
||||
private var quiet = false
|
||||
private var motorThread: HandlerThread? = null
|
||||
private var handler: Handler? = null
|
||||
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
@@ -44,6 +45,11 @@ class RumbleComponent : SessionPart() {
|
||||
if (!enabled) cancelAll()
|
||||
}
|
||||
|
||||
@Synchronized fun quiet(on: Boolean) {
|
||||
quiet = on
|
||||
if (on) cancelAll()
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
val ctx = app() ?: return
|
||||
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
|
||||
@@ -89,7 +95,7 @@ class RumbleComponent : SessionPart() {
|
||||
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
|
||||
|
||||
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
|
||||
if (!enabled) return
|
||||
if (!enabled || quiet) return
|
||||
val target = target(slot)
|
||||
val previous = playing[slot]
|
||||
if (target !== previous) {
|
||||
|
||||
@@ -17,12 +17,13 @@ object SessionDisplay {
|
||||
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
|
||||
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
|
||||
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> {
|
||||
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return screenSize(panel)
|
||||
presetHeight(choice)?.let { return resolve(panel, it, SessionPrefs.SHAPE_AUTO) }
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String, portrait: Boolean = false): Pair<Int, Int> {
|
||||
fun orient(size: Pair<Int, Int>) = if (portrait) size.second to size.first else size
|
||||
if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return orient(screenSize(panel))
|
||||
presetHeight(choice)?.let { return orient(resolve(panel, it, SessionPrefs.SHAPE_AUTO)) }
|
||||
val parts = choice.split('x').map { it.toIntOrNull() }
|
||||
return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
|
||||
else resolve(panel, 720, SessionPrefs.SHAPE_AUTO)
|
||||
else orient(resolve(panel, 720, SessionPrefs.SHAPE_AUTO))
|
||||
}
|
||||
|
||||
fun resolutionOptions(panel: Pair<Int, Int>): List<String> {
|
||||
@@ -31,8 +32,10 @@ object SessionDisplay {
|
||||
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN + FOLLOW_SCREEN
|
||||
}
|
||||
|
||||
fun followSize(width: Int, height: Int): Pair<Int, Int>? =
|
||||
if (minOf(width, height) < FOLLOW_MIN_SIDE) null else (width and 1.inv()) to (height and 1.inv())
|
||||
fun followSize(width: Int, height: Int, controlsBelow: Boolean = false): Pair<Int, Int>? =
|
||||
if (width <= 0 || height <= 0 ||
|
||||
(if (controlsBelow) width else minOf(width, height)) < FOLLOW_MIN_SIDE) null
|
||||
else (width and 1.inv()) to (height and 1.inv())
|
||||
|
||||
const val UNFOLDED_MAX_GAME_SHARE = 0.8f
|
||||
|
||||
@@ -49,13 +52,14 @@ object SessionDisplay {
|
||||
foldable: Boolean,
|
||||
controllerConnected: Boolean,
|
||||
keepWithController: Boolean,
|
||||
steamDeckPad: Boolean,
|
||||
gamepadAvailable: Boolean,
|
||||
pip: Boolean,
|
||||
width: Int,
|
||||
height: Int,
|
||||
smallestWidthDp: Int,
|
||||
): Boolean = enabled && foldable && (keepWithController || !controllerConnected) && steamDeckPad &&
|
||||
!pip && width > 0 && height > 0 && smallestWidthDp >= UNFOLDED_MIN_DP
|
||||
): Boolean = enabled && (keepWithController || !controllerConnected) && gamepadAvailable &&
|
||||
!pip && width > 0 && height > 0 &&
|
||||
(height > width || (foldable && smallestWidthDp >= UNFOLDED_MIN_DP))
|
||||
|
||||
|
||||
fun panelSize(context: Context): Pair<Int, Int> {
|
||||
|
||||
@@ -81,6 +81,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
|
||||
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
|
||||
"usr/local/bin/droiddeck-steam-x64" to "usr/local/bin/droiddeck-steam-x64",
|
||||
"usr/local/bin/droiddeck-fex-update" to "usr/local/bin/droiddeck-fex-update",
|
||||
"usr/local/bin/droiddeck-steamrt-shim" to "usr/local/bin/droiddeck-steamrt-shim",
|
||||
"usr/local/bin/droiddeck-x64-arm-proton" to "usr/local/bin/droiddeck-x64-arm-proton",
|
||||
"usr/local/bin/droiddeck-x64-arm-webhelper" to "usr/local/bin/droiddeck-x64-arm-webhelper",
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object SessionPrefs {
|
||||
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
|
||||
@@ -43,6 +44,8 @@ object SessionPrefs {
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
val orientationOptions = listOf(
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait,
|
||||
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
|
||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
|
||||
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
|
||||
@@ -58,6 +61,17 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("orientation", orientation).apply()
|
||||
}
|
||||
|
||||
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int =
|
||||
if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation"))
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context)
|
||||
|
||||
fun portrait(context: Context): Boolean = when (orientation(context)) {
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true
|
||||
ActivityInfo.SCREEN_ORIENTATION_USER ->
|
||||
context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
|
||||
else -> false
|
||||
}
|
||||
|
||||
fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true)
|
||||
|
||||
fun setLauncherFullscreen(context: Context, on: Boolean) {
|
||||
@@ -111,6 +125,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
|
||||
}
|
||||
|
||||
fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false)
|
||||
|
||||
fun setLibraryShowUninstalled(context: Context, show: Boolean) {
|
||||
prefs(context).edit().putBoolean("libraryShowUninstalled", show).apply()
|
||||
}
|
||||
|
||||
fun storesTabOrder(context: Context): List<String> = idList(prefs(context).getString("storesTabOrder", null))
|
||||
|
||||
fun setStoresTabOrder(context: Context, order: List<String>) {
|
||||
@@ -223,16 +243,10 @@ object SessionPrefs {
|
||||
private fun mangoappSession(context: Context) =
|
||||
SessionState.mode == SessionService.MODE_STEAM && mangoapp(context)
|
||||
|
||||
fun lowLatencyController(context: Context): Boolean = prefs(context).getBoolean("lowLatencyController", false)
|
||||
fun lowLatency(context: Context): Boolean = prefs(context).getBoolean("lowLatency", true)
|
||||
|
||||
fun setLowLatencyController(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("lowLatencyController", on).apply()
|
||||
}
|
||||
|
||||
fun lowLatencyTouch(context: Context): Boolean = prefs(context).getBoolean("lowLatencyTouch", false)
|
||||
|
||||
fun setLowLatencyTouch(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("lowLatencyTouch", on).apply()
|
||||
fun setLowLatency(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("lowLatency", on).apply()
|
||||
}
|
||||
|
||||
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
|
||||
@@ -241,6 +255,16 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("backActionsInverted", inverted).apply()
|
||||
}
|
||||
|
||||
val BACK_DOUBLE_TAP_MS_OPTIONS = (100..800 step 100).toList()
|
||||
|
||||
fun backDoubleTapMs(context: Context): Int =
|
||||
prefs(context).getInt("backDoubleTapMs", 500).takeIf { it in BACK_DOUBLE_TAP_MS_OPTIONS } ?: 500
|
||||
|
||||
fun setBackDoubleTapMs(context: Context, ms: Int) {
|
||||
require(ms in BACK_DOUBLE_TAP_MS_OPTIONS)
|
||||
prefs(context).edit().putInt("backDoubleTapMs", ms).apply()
|
||||
}
|
||||
|
||||
const val TOUCH_AUTO = "auto"
|
||||
const val TOUCH_PAD = "touchpad"
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
@@ -527,6 +551,15 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("cursorComposite", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The rootfs ships Termux's unpatched proot. A session uses it only when this file exists,
|
||||
* so a missing add-on pack cannot silently fall back to it.
|
||||
* Path: Android/data/<package>/files/droiddeck-stock-proot
|
||||
*/
|
||||
@JvmStatic
|
||||
fun allowStockProot(context: Context): Boolean =
|
||||
context.getExternalFilesDir(null)?.let { File(it, "droiddeck-stock-proot").isFile } == true
|
||||
|
||||
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
|
||||
|
||||
@JvmStatic
|
||||
@@ -569,6 +602,7 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
|
||||
fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true)
|
||||
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
|
||||
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
@@ -654,8 +688,10 @@ object SessionPrefs {
|
||||
parseResolution(value)?.let { return "${it.first}x${it.second}" }
|
||||
}
|
||||
if (!resolutionChosen(context, mode) && !saved.contains("shape")) return SessionDisplay.DEFAULT_RESOLUTION
|
||||
val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), customResolution(context, mode))
|
||||
val custom = customResolution(context, mode)
|
||||
val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), custom)
|
||||
return if (legacy == SessionDisplay.screenSize(panel)) SessionDisplay.MATCH_SCREEN
|
||||
else if (custom == null && legacy == SessionDisplay.resolve(panel, legacy.second, SHAPE_AUTO)) "${legacy.second}p"
|
||||
else "${legacy.first}x${legacy.second}"
|
||||
}
|
||||
|
||||
@@ -903,32 +939,15 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
|
||||
}
|
||||
|
||||
fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0).coerceAtLeast(0)
|
||||
|
||||
fun setFpsLimit(context: Context, mode: String, fps: Int) {
|
||||
prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply()
|
||||
}
|
||||
|
||||
val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120")
|
||||
|
||||
fun fpsLimitChoices(context: Context): List<Pair<Int, String>> =
|
||||
fpsLimitChoices.map { (fps, label) -> fps to if (fps == 0) context.getString(R.string.frame_gen_off) else label }
|
||||
|
||||
/**
|
||||
* Performance mode: without a frame limit, buffers go back to the game as soon as they are replaced
|
||||
* instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks.
|
||||
*/
|
||||
fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false)
|
||||
|
||||
fun setPerformanceMode(context: Context, mode: String, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("performanceMode.$mode", on).apply()
|
||||
}
|
||||
|
||||
/** Compositor frame limit that releases buffers to the game unpaced. */
|
||||
const val FPS_UNPACED = -1
|
||||
|
||||
/** The limit handed to the compositor: Performance mode without a limit is unpaced, a chosen limit still paces. */
|
||||
fun compositorFpsLimit(limit: Int, performanceMode: Boolean): Int = if (performanceMode && limit <= 0) FPS_UNPACED else limit
|
||||
/**
|
||||
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
|
||||
* Steam's Frame Limit in the Quick Access menu caps games. Mirroring still follows the glasses' refresh rate.
|
||||
*/
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int): Int =
|
||||
if (mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
|
||||
|
||||
val upscalerChoices = listOf(
|
||||
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
|
||||
@@ -1117,6 +1136,18 @@ object SessionPrefs {
|
||||
|
||||
fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", false)
|
||||
|
||||
fun controlsBelowWanted(context: Context, mode: String, width: Int, height: Int, pip: Boolean = false): Boolean =
|
||||
SessionDisplay.unfoldedControlsWanted(
|
||||
enabled = unfoldedControls(context),
|
||||
foldable = SessionDisplay.foldable(context),
|
||||
controllerConnected = com.droiddeck.launcher.input.PadBridge.anyControllerConnected() ||
|
||||
com.droiddeck.launcher.input.SteamControllerBle.connected,
|
||||
keepWithController = unfoldedControlsWithController(context),
|
||||
gamepadAvailable = mode == SessionService.MODE_STEAM && builtinPad(context),
|
||||
pip = pip, width = width, height = height,
|
||||
smallestWidthDp = context.resources.configuration.smallestScreenWidthDp,
|
||||
)
|
||||
|
||||
fun setUnfoldedControls(context: Context, enabled: Boolean) {
|
||||
prefs(context).edit().putBoolean("unfoldedControls", enabled).apply()
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import android.os.PowerManager
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.view.Display
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
import com.droiddeck.launcher.audio.DirectAudioRelayComponent
|
||||
@@ -430,8 +431,30 @@ class SessionService : Service() {
|
||||
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO))
|
||||
if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable")
|
||||
val stillStarting = { gen == sessionGen && SessionState.running }
|
||||
val prootPack = LinuxRuntime.patchedProot(this) || AddonPack.PROOT.await(this, stillStarting)
|
||||
val directAudioPack = AddonPack.DIRECTAUDIO.await(this, stillStarting)
|
||||
if (!stillStarting()) {
|
||||
Log.i(TAG, "session stopped while add-on packs were downloading")
|
||||
return
|
||||
}
|
||||
if (!directAudioPack) {
|
||||
Log.w(TAG, "directaudio pack unavailable; game audio drivers will not be staged")
|
||||
mainHandler.post {
|
||||
Toast.makeText(this, R.string.session_directaudio_missing, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (!LinuxRuntime.patchedProot(this)) {
|
||||
if (SessionPrefs.allowStockProot(this)) {
|
||||
Log.w(TAG, "proot: patched proot missing; droiddeck-stock-proot allows the rootfs copy")
|
||||
} else {
|
||||
val message = getString(R.string.session_proot_missing)
|
||||
Log.e(TAG, "$message (pack ready=$prootPack)")
|
||||
SessionEvents.fail("PROOT_MISSING", message, -1)
|
||||
stopSession(-1)
|
||||
return
|
||||
}
|
||||
}
|
||||
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
|
||||
.onFailure { Log.w(TAG, "agent environment skipped", it) }
|
||||
.getOrDefault(emptyList())
|
||||
@@ -446,6 +469,10 @@ class SessionService : Service() {
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})"
|
||||
Log.i(TAG, prootLine)
|
||||
runCatching { sessionLog.appendText(prootLine + "\n") }
|
||||
.onFailure { Log.w(TAG, "could not write the proot line to ${sessionLog.path}", it) }
|
||||
|
||||
Log.i(TAG, GpuClockPin.start(this))
|
||||
Log.i(TAG, GameThreadHints.start(this))
|
||||
@@ -453,6 +480,9 @@ class SessionService : Service() {
|
||||
val size = SessionState.outputSize
|
||||
val guest = ArrayList<String>()
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
runCatching { ComponentsManager.republish(this) }
|
||||
.onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") }
|
||||
.onFailure { Log.w(TAG, "component selections", it) }
|
||||
if (steamHere) {
|
||||
runCatching { ComponentsManager.ensureForcedPackages(this) }
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
@@ -462,7 +492,7 @@ class SessionService : Service() {
|
||||
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
|
||||
val fastPathAt = guest.size
|
||||
|
||||
val pulse = startAudio(guest, sessionDir)
|
||||
val pulse = startAudio(guest, sessionDir, directAudioPack)
|
||||
if (steamHere) {
|
||||
val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock"))
|
||||
encoder.attach(this)
|
||||
@@ -472,23 +502,21 @@ class SessionService : Service() {
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
if (SessionState.followScreen) guest.add("BL_FOLLOW_OUTPUT=1")
|
||||
if (SessionState.followScreen || size.first < size.second ||
|
||||
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
|
||||
guest.add("BL_FOLLOW_OUTPUT=1")
|
||||
if (SessionState.hdr) {
|
||||
guest.add("BL_HDR=1")
|
||||
guest.add("DXVK_HDR=1")
|
||||
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
|
||||
}
|
||||
guest.add("BL_FPS=" + SessionState.fpsLimit)
|
||||
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long; 0 checks on every present.
|
||||
val windowCheckMs = if (SessionState.performanceMode) 100 else 0
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs")
|
||||
if (SessionPrefs.compositorFpsLimit(SessionState.fpsLimit, SessionState.performanceMode) == SessionPrefs.FPS_UNPACED) {
|
||||
// gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing.
|
||||
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
|
||||
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
|
||||
}
|
||||
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off") + ", frame limit " + SessionState.fpsLimit)
|
||||
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long.
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
|
||||
// gamescope turns buffers around slower than an uncapped game draws; more images keep it drawing.
|
||||
// The WSI layer goes back to its default count while Steam's Frame Limit holds the game.
|
||||
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
|
||||
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
|
||||
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
|
||||
guest.add("BL_LOG=" + sessionLog.path)
|
||||
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
|
||||
@@ -602,6 +630,10 @@ class SessionService : Service() {
|
||||
networkLink.attach(this)
|
||||
networkLink.publish()
|
||||
components.add(networkLink)
|
||||
val deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent(this, root) { activityVisible && screenOn }
|
||||
deviceControls.attach(this)
|
||||
deviceControls.publish()
|
||||
components.add(deviceControls)
|
||||
if (gen != sessionGen || !SessionState.running) {
|
||||
Log.i(TAG, "session stopped while it was starting; not launching it")
|
||||
if (gen == sessionGen) components.clear()
|
||||
@@ -749,8 +781,8 @@ class SessionService : Service() {
|
||||
SessionArtifacts.recordClient(it, arch)
|
||||
SessionArtifacts.markSteamLogs(it, File(SessionPrefs.steamRoot(this, arch), "logs"))
|
||||
}
|
||||
if (arch == "x86_64") FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
|
||||
}
|
||||
FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
|
||||
}
|
||||
@@ -782,8 +814,9 @@ class SessionService : Service() {
|
||||
private fun noSteamGame(): Boolean =
|
||||
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
|
||||
|
||||
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
|
||||
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
|
||||
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
|
||||
val wantsDirectAudio = directAudioPack &&
|
||||
(SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
|
||||
SessionPrefs.directAudio(this)
|
||||
val wantsMic = SessionPrefs.micEnabled(this) &&
|
||||
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
@@ -852,7 +885,7 @@ class SessionService : Service() {
|
||||
SessionState.deckPad = deckBinds.isNotEmpty()
|
||||
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
|
||||
logControllersAtStart()
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatencyController(this), SessionPrefs.lowLatencyTouch(this))
|
||||
com.droiddeck.launcher.input.FakeInputWriter.setLowLatency(SessionPrefs.lowLatency(this))
|
||||
if (uinput) {
|
||||
guest.add("FAKE_EVDEV_UINPUT=1")
|
||||
if (SessionState.deckPad) {
|
||||
@@ -1525,6 +1558,9 @@ class SessionService : Service() {
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend
|
||||
else -> false
|
||||
}
|
||||
// A frozen game never sends the stop for a held rumble, so the keepalive would run on.
|
||||
val quietRumble = !screenOn || shouldSuspend || SessionState.suspended
|
||||
components.forEach { (it as? RumbleComponent)?.quiet(quietRumble) }
|
||||
if (freezePending && !shouldSuspend && !freezeCancelled) {
|
||||
freezeCancelled = true
|
||||
controller.cancelFreeze()
|
||||
|
||||
@@ -103,12 +103,6 @@ object SessionState {
|
||||
@Volatile
|
||||
var upscaleRatio: Float = 0f
|
||||
|
||||
@Volatile
|
||||
var fpsLimit: Int = 0
|
||||
|
||||
@Volatile
|
||||
var performanceMode = false
|
||||
|
||||
@Volatile
|
||||
var firstFrameSeen = false
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ object SettingsReset {
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
|
||||
@@ -88,6 +88,7 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
store = Store.byId(intent.getStringExtra(EXTRA_STORE))
|
||||
clientUrl = intent.getStringExtra(EXTRA_CLIENT_URL)?.takeIf { store == Store.EPIC }
|
||||
oauthState = savedInstanceState?.getString(KEY_STATE) ?: generateState()
|
||||
|
||||
@@ -130,7 +130,7 @@ object StoresState {
|
||||
|
||||
fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem(
|
||||
store, id, library[store].orEmpty(),
|
||||
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items else emptyList(),
|
||||
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items + com.droiddeck.launcher.stores.itch.ItchCollections.items() else emptyList(),
|
||||
shelves[store],
|
||||
)
|
||||
|
||||
@@ -191,6 +191,7 @@ object StoresState {
|
||||
backend?.signOut(app)
|
||||
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
|
||||
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
|
||||
if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchCollections.clear()
|
||||
main.post {
|
||||
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
|
||||
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
|
||||
@@ -236,7 +237,7 @@ object StoresState {
|
||||
fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) {
|
||||
val app = context.applicationContext
|
||||
val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app)
|
||||
if (item.store == Store.BATTLENET) {
|
||||
if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) {
|
||||
backends[item.store]?.install(app, item, targetRoot)
|
||||
return
|
||||
}
|
||||
@@ -273,7 +274,7 @@ object StoresState {
|
||||
uninstalling[key] = 0f
|
||||
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
|
||||
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
|
||||
if (game.sidecar.store == Store.BATTLENET) {
|
||||
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
|
||||
main.post { uninstalling.remove(key); onDone() }
|
||||
return@background
|
||||
}
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
package com.droiddeck.launcher.stores.battlenet
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object BattleNetInstall {
|
||||
private const val TAG = "BattleNetInstall"
|
||||
internal const val PROGRESS = "BNET_PROGRESS "
|
||||
internal const val STATE = "BNET_STATE "
|
||||
internal const val DONE = "BNET_DONE "
|
||||
internal const val ERROR = "BNET_ERROR "
|
||||
private const val VERSIONS = "https://%s.version.battle.net/v2/products/%s/versions"
|
||||
private const val BUILD_INFO = ".build.info"
|
||||
private const val CHECK_AGAIN_MS = 30 * 60_000L
|
||||
private const val START_WAIT_MS = 60_000L
|
||||
|
||||
internal val LOCALES = listOf(
|
||||
"enUS", "enGB", "esMX", "esES", "ptBR", "ptPT", "frFR", "deDE", "itIT", "ruRU", "jaJP", "koKR", "plPL", "trTR",
|
||||
"zhTW", "zhCN", "thTH", "arSA",
|
||||
)
|
||||
|
||||
internal val checks = Executors.newSingleThreadExecutor { r -> Thread(r, "battlenet-updates") }
|
||||
internal val checkedAt = HashMap<String, Long>()
|
||||
|
||||
val updates = mutableStateMapOf<String, Boolean>()
|
||||
|
||||
fun product(id: String): String? = BattleNet.title(id)?.product
|
||||
|
||||
fun headless(item: CatalogItem): Boolean = item.store == Store.BATTLENET && product(item.id) != null
|
||||
|
||||
internal fun locale(locale: Locale): String {
|
||||
val language = locale.language.lowercase(Locale.ROOT)
|
||||
if (language == "zh") {
|
||||
val traditional = locale.script.equals("Hant", true) || locale.country.uppercase(Locale.ROOT) in setOf("TW", "HK", "MO")
|
||||
return if (traditional) "zhTW" else "zhCN"
|
||||
}
|
||||
val exact = language + locale.country.uppercase(Locale.ROOT)
|
||||
return LOCALES.firstOrNull { it == exact } ?: LOCALES.firstOrNull { it.startsWith(language) } ?: "enUS"
|
||||
}
|
||||
|
||||
internal fun country(locale: Locale): Pair<String, String> {
|
||||
val two = locale.country.uppercase(Locale.ROOT)
|
||||
val three = runCatching { locale.isO3Country.uppercase(Locale.ROOT) }.getOrDefault("")
|
||||
return if (two.matches(Regex("[A-Z]{2}")) && three.matches(Regex("[A-Z]{3}"))) three to two else "USA" to "US"
|
||||
}
|
||||
|
||||
internal fun binds(context: Context): List<String> {
|
||||
val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context))
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
GameStorage.effective(context)?.let { library ->
|
||||
if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage))
|
||||
val content = SecondaryLibrary.contentPath(File(library.path)).path
|
||||
for (guest in SecondaryLibrary.CARD_GUESTS) {
|
||||
File(root, guest.removePrefix("/")).mkdirs()
|
||||
out += "$content:$guest"
|
||||
}
|
||||
}
|
||||
for (folder in AddedGames.roots(context)) {
|
||||
if (!folder.host.isDirectory || !folder.host.canRead()) continue
|
||||
File(root, folder.guest.removePrefix("/")).mkdirs()
|
||||
out += folder.host.path + ":" + folder.guest
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
|
||||
GuestCommand.run(
|
||||
context, listOf(BattleNet.PROGRAM) + args, logName = "battlenet-agent",
|
||||
extraBinds = binds(context), fastPath = true, cancelled = cancelled, onLine = onLine,
|
||||
)
|
||||
|
||||
fun enqueue(context: Context, item: CatalogItem, folder: File, update: Boolean = false) {
|
||||
val app = context.applicationContext
|
||||
val entry = DownloadEntry(
|
||||
Store.BATTLENET, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl,
|
||||
location = StoreInstallRoot.labelFor(app, folder),
|
||||
)
|
||||
DownloadQueue.enqueue(app, entry) { BattleNetInstaller(app, item, folder, update) }
|
||||
}
|
||||
|
||||
fun update(context: Context, game: InstalledStoreGame) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val item = CatalogItem(
|
||||
Store.BATTLENET, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true,
|
||||
extra = mapOf(INSTALL_UID to installUid(app, game)),
|
||||
)
|
||||
game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) }
|
||||
enqueue(app, item, game.folder, update = true)
|
||||
}, "battlenet-update").start()
|
||||
}
|
||||
|
||||
internal const val INSTALL_UID = "installUid"
|
||||
|
||||
internal fun installUid(context: Context, game: InstalledStoreGame): String =
|
||||
runCatching { BattleNet.games(context).firstOrNull { it.uid == game.sidecar.id }?.installUid }.getOrNull() ?: game.sidecar.id
|
||||
|
||||
fun uninstall(context: Context, game: InstalledStoreGame): Boolean {
|
||||
if (product(game.sidecar.id) == null || !BattleNet.installed(context)) return false
|
||||
val done = agentUninstall(context, installUid(context, game))
|
||||
if (done) StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) }
|
||||
return done
|
||||
}
|
||||
|
||||
internal fun agentUninstall(context: Context, uid: String): Boolean {
|
||||
val stop = AtomicBoolean(false)
|
||||
val started = AtomicBoolean(false)
|
||||
val done = AtomicBoolean(false)
|
||||
val guard = Thread({
|
||||
try {
|
||||
Thread.sleep(START_WAIT_MS)
|
||||
if (!started.get()) stop.set(true)
|
||||
} catch (_: InterruptedException) {
|
||||
}
|
||||
}, "battlenet-uninstall-wait").apply { isDaemon = true; start() }
|
||||
val code = runCatching {
|
||||
run(context, listOf("agent-uninstall", uid), stop) { line ->
|
||||
if (line == STATE + "starting") started.set(true)
|
||||
if (line.startsWith(DONE)) done.set(true)
|
||||
}
|
||||
}.onFailure { Log.w(TAG, "uninstall $uid", it) }.getOrDefault(-1)
|
||||
guard.interrupt()
|
||||
Log.i(TAG, "uninstall $uid: ${if (done.get()) "done" else if (stop.get()) "Battle.net stayed busy" else "exit $code"}")
|
||||
return done.get()
|
||||
}
|
||||
|
||||
internal fun buildKey(text: String): Pair<String, String>? {
|
||||
val rows = text.lines().filter { it.isNotBlank() }
|
||||
if (rows.size < 2) return null
|
||||
val head = rows[0].split('|').map { it.substringBefore('!') }
|
||||
val branch = head.indexOf("Branch")
|
||||
val active = head.indexOf("Active")
|
||||
val key = head.indexOf("Build Key")
|
||||
if (branch < 0 || key < 0) return null
|
||||
val row = rows.drop(1).map { it.split('|') }.firstOrNull { active < 0 || it.getOrNull(active) == "1" } ?: return null
|
||||
val region = row.getOrNull(branch)?.takeIf { it.matches(Regex("[a-z]{2}")) } ?: return null
|
||||
val build = row.getOrNull(key)?.takeIf { it.matches(Regex("[0-9a-f]{32}")) } ?: return null
|
||||
return region to build
|
||||
}
|
||||
|
||||
internal fun latestBuild(text: String, region: String): String? {
|
||||
val rows = text.lines().filter { it.isNotBlank() && !it.startsWith("##") }
|
||||
if (rows.isEmpty()) return null
|
||||
val head = rows[0].split('|').map { it.substringBefore('!') }
|
||||
val at = head.indexOf("Region")
|
||||
val key = head.indexOf("BuildConfig")
|
||||
if (at < 0 || key < 0) return null
|
||||
return rows.drop(1).map { it.split('|') }.firstOrNull { it.getOrNull(at) == region }?.getOrNull(key)
|
||||
?.takeIf { it.matches(Regex("[0-9a-f]{32}")) }
|
||||
}
|
||||
|
||||
fun checkUpdate(context: Context, game: InstalledStoreGame, force: Boolean = false) = check(game.sidecar.id, game.folder, force)
|
||||
|
||||
internal fun check(id: String, folder: File, force: Boolean) {
|
||||
val product = product(id) ?: return
|
||||
val now = System.currentTimeMillis()
|
||||
synchronized(checkedAt) {
|
||||
if (!force && now - (checkedAt[id] ?: 0L) < CHECK_AGAIN_MS) return
|
||||
checkedAt[id] = now
|
||||
}
|
||||
fun retryLater() = synchronized(checkedAt) { if (checkedAt[id] == now) checkedAt.remove(id) }
|
||||
checks.execute {
|
||||
val local = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
|
||||
?: return@execute retryLater()
|
||||
val latest = runCatching { latestBuild(fetch(VERSIONS.format(Locale.ROOT, local.first, product)), local.first) }
|
||||
.onFailure { Log.w(TAG, "versions of $product: ${it.javaClass.simpleName}") }.getOrNull()
|
||||
?: return@execute retryLater()
|
||||
val behind = latest != local.second
|
||||
Log.i(TAG, "$id: ${if (behind) "update available" else "up to date"}")
|
||||
StoresState.post { if (behind) updates[id] = true else updates.remove(id) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun fetch(url: String): String {
|
||||
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 15_000
|
||||
readTimeout = 15_000
|
||||
setRequestProperty("User-Agent", "DroidDeck")
|
||||
}
|
||||
try {
|
||||
if (conn.responseCode != 200) throw java.io.IOException("HTTP ${conn.responseCode}")
|
||||
return conn.inputStream.bufferedReader().use { it.readText() }
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun failure(context: Context, reason: String?, code: Int): String {
|
||||
val detail = when {
|
||||
reason == null -> "exit $code"
|
||||
reason == "client" -> return context.getString(R.string.bnet_dl_client_first)
|
||||
reason.startsWith("agent ") -> context.getString(R.string.bnet_dl_agent_error, reason.removePrefix("agent "))
|
||||
else -> reason.removePrefix("stopped ")
|
||||
}
|
||||
return context.getString(R.string.bnet_dl_failed, detail)
|
||||
}
|
||||
|
||||
internal fun localeTag(context: Context): String = locale(StoreLanguage.localeFor(null, context))
|
||||
|
||||
internal enum class Step { PREPARING, DOWNLOADING, APPLYING }
|
||||
|
||||
internal fun step(state: Int, phase: Int, current: Long, total: Long): Step = when {
|
||||
state == DONE_STATE || phase == APPLY_PHASE || total > 0L && current >= total -> Step.APPLYING
|
||||
total > 0L -> Step.DOWNLOADING
|
||||
else -> Step.PREPARING
|
||||
}
|
||||
|
||||
private const val DONE_STATE = 1004
|
||||
private const val APPLY_PHASE = 2000
|
||||
}
|
||||
|
||||
internal class BattleNetInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
private val update: Boolean,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private val started = AtomicBoolean(false)
|
||||
private val ended = java.util.concurrent.CountDownLatch(1)
|
||||
private var before = 0L
|
||||
private var kept = -1L
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
started.set(true)
|
||||
try {
|
||||
return if (cancelled.get()) null else work(handle)
|
||||
} finally {
|
||||
ended.countDown()
|
||||
}
|
||||
}
|
||||
|
||||
private fun work(handle: DownloadQueue.JobHandle): String? {
|
||||
before = DownloadQueue.entry(handle.key)?.bytesTotal ?: 0L
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
|
||||
if (!BattleNet.installed(app)) throw IllegalStateException(app.getString(R.string.bnet_dl_client_first))
|
||||
val title = BattleNet.title(item.id)
|
||||
val product = title?.product ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, item.id))
|
||||
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: title.uid
|
||||
if (!update) folder.mkdirs()
|
||||
val guest = AddedGames.guestPath(app, folder) ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, folder.path))
|
||||
val (country, region) = BattleNetInstall.country(Locale.getDefault())
|
||||
val args = if (update) listOf("agent-update", uid)
|
||||
else listOf("agent-install", uid, product, guest, BattleNetInstall.localeTag(app), country, region)
|
||||
var done: JSONObject? = null
|
||||
var reason: String? = null
|
||||
val code = BattleNetInstall.run(app, args, cancelled) { line ->
|
||||
when {
|
||||
line.startsWith(BattleNetInstall.PROGRESS) ->
|
||||
runCatching { JSONObject(line.removePrefix(BattleNetInstall.PROGRESS)) }.getOrNull()?.let { progress(handle, it) }
|
||||
line == BattleNetInstall.STATE + "waiting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_waiting))
|
||||
line == BattleNetInstall.STATE + "queued" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_queued))
|
||||
line == BattleNetInstall.STATE + "starting" -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.bnet_dl_starting))
|
||||
line.startsWith(BattleNetInstall.DONE) -> done = runCatching { JSONObject(line.removePrefix(BattleNetInstall.DONE)) }.getOrNull()
|
||||
line.startsWith(BattleNetInstall.ERROR) -> reason = line.removePrefix(BattleNetInstall.ERROR)
|
||||
}
|
||||
}
|
||||
if (cancelled.get()) return null
|
||||
if (done == null) throw IllegalStateException(BattleNetInstall.failure(app, reason, code))
|
||||
handle.log("Battle.net: ${item.title} ${if (update) "updated" else "installed"} ${done?.optString("version").orEmpty()}".trimEnd())
|
||||
StoresState.post {
|
||||
BattleNetInstall.updates.remove(item.id)
|
||||
StoresState.notifyLibraryChanged(app)
|
||||
}
|
||||
BattleNetInstall.check(item.id, folder, force = true)
|
||||
return folder.absolutePath
|
||||
}
|
||||
|
||||
private fun progress(handle: DownloadQueue.JobHandle, status: JSONObject) {
|
||||
val current = status.optLong("download_current", 0L)
|
||||
val total = status.optLong("download_total", 0L)
|
||||
when (BattleNetInstall.step(status.optInt("state", 0), status.optInt("phase", 0), current, total)) {
|
||||
BattleNetInstall.Step.PREPARING -> handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_stage_checking))
|
||||
BattleNetInstall.Step.DOWNLOADING -> {
|
||||
if (kept < 0L) kept = (before - total).coerceAtLeast(0L)
|
||||
handle.progress(kept + current, kept + total)
|
||||
}
|
||||
BattleNetInstall.Step.APPLYING -> handle.stage(DownloadStage.INSTALL)
|
||||
}
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (!deleteFiles || update) return
|
||||
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: BattleNet.title(item.id)?.uid ?: return
|
||||
Thread({
|
||||
if (started.get() && !ended.await(END_WAIT_S, TimeUnit.SECONDS)) Log.w("BattleNetInstall", "the cancelled install of $uid is still stopping")
|
||||
val gone = BattleNetInstall.agentUninstall(app, uid)
|
||||
if (folder.isDirectory && (gone || folder.list().isNullOrEmpty())) com.droiddeck.launcher.core.FileUtils.delete(folder)
|
||||
Log.i("BattleNetInstall", "cancelled install of $uid: ${if (gone) "removed" else "left for Battle.net to remove"}")
|
||||
}, "battlenet-cancel").start()
|
||||
}
|
||||
}
|
||||
|
||||
private const val END_WAIT_S = 120L
|
||||
@@ -189,9 +189,15 @@ object BattleNetBackend : StoreBackend {
|
||||
override fun search(context: Context, query: String): List<CatalogItem> =
|
||||
BattleNet.STORE.filter { it.name.contains(query, ignoreCase = true) }.map { item(context, it) }
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) = BattleNetClient.installGame(context, item.id, root)
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
if (!BattleNetInstall.headless(item)) return BattleNetClient.installGame(context, item.id, root)
|
||||
val app = context.applicationContext
|
||||
BattleNetInstall.enqueue(app, item, StoreInstallRoot.folderFor(app, store, item.id, item.title, root))
|
||||
}
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) = BattleNetClient.open(emptyList())
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {
|
||||
if (!BattleNetInstall.uninstall(context, game)) BattleNetClient.open(emptyList())
|
||||
}
|
||||
|
||||
fun installed(context: Context): List<BattleNet.Game> = if (BattleNet.installed(context)) BattleNet.games(context) else emptyList()
|
||||
|
||||
|
||||
@@ -19,6 +19,11 @@ internal object ItchApi {
|
||||
|
||||
fun ownedKeys(key: String, page: Int): JSONObject? = get("/profile/owned-keys?page=$page&per_page=500", key)
|
||||
|
||||
fun collections(key: String): JSONArray? = get("/profile/collections", key)?.optJSONArray("collections")
|
||||
|
||||
fun collectionGames(key: String, collectionId: String, page: Int): JSONObject? =
|
||||
get("/collections/$collectionId/collection-games?page=$page", key)
|
||||
|
||||
fun uploads(key: String, gameId: String, downloadKeyId: String): JSONArray? =
|
||||
get("/games/$gameId/uploads" + keyQuery(downloadKeyId), key)?.optJSONArray("uploads")
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
internal class ItchCollection(val id: String, val title: String, val count: Int)
|
||||
|
||||
internal object ItchCollections {
|
||||
var list by mutableStateOf<List<ItchCollection>>(emptyList())
|
||||
private set
|
||||
var selected by mutableStateOf<String?>(null)
|
||||
private set
|
||||
private val games = mutableStateMapOf<String, List<CatalogItem>>()
|
||||
private val loading = ConcurrentHashMap.newKeySet<String>()
|
||||
@Volatile private var generation = 0
|
||||
|
||||
fun items(): List<CatalogItem> = games.values.flatten()
|
||||
|
||||
fun gamesOf(id: String): List<CatalogItem>? = games[id]
|
||||
|
||||
fun chosen(): ItchCollection? = list.firstOrNull { it.id == selected }
|
||||
|
||||
fun clear() {
|
||||
generation++
|
||||
StoresState.post {
|
||||
list = emptyList()
|
||||
selected = null
|
||||
games.clear()
|
||||
}
|
||||
}
|
||||
|
||||
fun load(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val started = generation
|
||||
val guard = "$started:"
|
||||
if (!loading.add(guard)) return
|
||||
Thread({
|
||||
try {
|
||||
val key = ItchAuth.key(app)
|
||||
if (key.isBlank()) return@Thread
|
||||
val parsed = parseCollections(ItchApi.collections(key) ?: return@Thread)
|
||||
if (started != generation) return@Thread
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
list = parsed
|
||||
if (selected != null && parsed.none { it.id == selected }) selected = null
|
||||
}
|
||||
StoresState.logLine("itch.io: ${parsed.size} collections")
|
||||
selected?.let { fetchGames(key, it, started) }
|
||||
} finally {
|
||||
loading.remove(guard)
|
||||
}
|
||||
}, "itch-collections").start()
|
||||
}
|
||||
|
||||
fun select(context: Context, id: String?) {
|
||||
selected = id
|
||||
if (id == null) return
|
||||
val app = context.applicationContext
|
||||
val started = generation
|
||||
Thread({
|
||||
val key = ItchAuth.key(app)
|
||||
if (key.isNotBlank()) fetchGames(key, id, started)
|
||||
}, "itch-collection-games").start()
|
||||
}
|
||||
|
||||
private fun fetchGames(key: String, id: String, started: Int) {
|
||||
val guard = "$started:$id"
|
||||
if (!loading.add(guard)) return
|
||||
try {
|
||||
val out = ArrayList<CatalogItem>()
|
||||
val seen = HashSet<String>()
|
||||
var page = 1
|
||||
while (true) {
|
||||
val body = ItchApi.collectionGames(key, id, page)
|
||||
if (body == null) {
|
||||
StoresState.logLine("itch.io: collection $id page $page failed")
|
||||
return
|
||||
}
|
||||
val batch = parseGames(body)
|
||||
if (batch.isEmpty()) break
|
||||
val before = out.size
|
||||
out.addAll(batch.filter { seen.add(it.id) })
|
||||
if (out.size == before) break
|
||||
page++
|
||||
}
|
||||
val distinct = out.toList()
|
||||
StoresState.post { if (started == generation) games[id] = distinct }
|
||||
StoresState.logLine("itch.io: collection $id has ${distinct.size} games")
|
||||
} finally {
|
||||
loading.remove(guard)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun parseCollections(array: JSONArray): List<ItchCollection> = (0 until array.length()).mapNotNull { i ->
|
||||
val c = array.optJSONObject(i) ?: return@mapNotNull null
|
||||
val id = c.opt("id")?.toString().orEmpty().takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
|
||||
val title = c.optString("title").ifBlank { return@mapNotNull null }
|
||||
ItchCollection(id, title, c.optInt("games_count", c.optInt("gamesCount")))
|
||||
}
|
||||
|
||||
internal fun parseGames(body: JSONObject): List<CatalogItem> {
|
||||
val rows = body.optJSONArray("collection_games") ?: body.optJSONArray("collectionGames") ?: return emptyList()
|
||||
return (0 until rows.length()).mapNotNull { i ->
|
||||
rows.optJSONObject(i)?.optJSONObject("game")?.let { ItchLibrary.item(it, "") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
@@ -45,7 +47,7 @@ class XboxCloudSettingsActivity : ComponentActivity() {
|
||||
}
|
||||
Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).verticalScroll(rememberScrollState())) {
|
||||
Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedButton(onClick = { finish() }) { Text("Back") }
|
||||
OutlinedButton(onClick = { finish() }, modifier = Modifier.focusGlide(CircleShape)) { Text("Back") }
|
||||
Text("Xbox Cloud Gaming", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 16.dp))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import com.droiddeck.launcher.ui.glideBorder
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
@@ -16,7 +19,6 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
@@ -148,7 +150,7 @@ private fun PanelContent(
|
||||
Toggle("Toon", "Cartoon outlines.", settings.toon) { onChange(settings.copy(toon = it)) }
|
||||
Choice("Frame-rate cap", listOf(0 to "Off", 30 to "30 fps", 45 to "45 fps", 60 to "60 fps"), settings.maxFps) { onChange(settings.copy(maxFps = it)) }
|
||||
Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = { onChange(settings.withoutEffects()) }) { Text("Reset picture") }
|
||||
OutlinedButton(onClick = { onChange(settings.withoutEffects()) }, modifier = Modifier.focusGlide(CircleShape)) { Text("Reset picture") }
|
||||
}
|
||||
Text("Effects cost a little GPU time; with none set the stream is shown directly.", style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
|
||||
@@ -220,7 +222,7 @@ private fun SettingRow(
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 1.dp).clip(shape)
|
||||
.background(if (focused) cs.primary.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.border(2.dp, if (focused) cs.primary else Color.Transparent, shape)
|
||||
.glideBorder(focused, shape, cs.primary, hotFillAlpha = 0f)
|
||||
.let { if (panel != null && index >= 0) it.focusRequester(panel.requester(index)) else it }
|
||||
.onFocusChanged { state -> focused = state.isFocused; if (state.isFocused && index >= 0) panel?.onFocused?.invoke(index) }
|
||||
.onKeyEvent { event ->
|
||||
@@ -299,8 +301,9 @@ internal fun XboxMenuEntry(title: String, note: String?, focus: FocusRequester?
|
||||
val shape = RoundedCornerShape(10.dp)
|
||||
androidx.compose.material3.Surface(
|
||||
onClick = onClick, color = if (focused) cs.primary.copy(alpha = 0.2f) else cs.surfaceContainerHigh, shape = shape,
|
||||
border = if (focused) androidx.compose.foundation.BorderStroke(2.dp, cs.primary) else null,
|
||||
border = null,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 3.dp)
|
||||
.glideBorder(focused, shape, cs.primary, hotFillAlpha = 0f)
|
||||
.let { if (focus != null) it.focusRequester(focus) else it }
|
||||
.onFocusChanged { state -> focused = state.isFocused; if (state.isFocused) onFocused() }
|
||||
.onKeyEvent { event -> if (event.type == KeyEventType.KeyDown && event.key == Key.ButtonA) { onClick(); true } else false },
|
||||
|
||||
@@ -36,6 +36,7 @@ class XboxLoginActivity : ComponentActivity() {
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
host = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setBackgroundColor(Color.BLACK) }
|
||||
status = TextView(this).apply { setTextColor(Color.WHITE); text = "Preparing Microsoft sign-in…"; setPadding(24, 16, 24, 16) }
|
||||
host.addView(status)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
@@ -181,10 +183,10 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
||||
fun NoticeButton(label: String, focus: androidx.compose.ui.focus.FocusRequester?, onClick: () -> Unit) =
|
||||
androidx.compose.material3.TextButton(onClick = onClick,
|
||||
modifier = androidx.compose.ui.Modifier.let { if (focus != null) it.focusRequester(focus) else it }
|
||||
.onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }) {
|
||||
.onKeyEvent { e -> if (e.type == KeyEventType.KeyDown && e.key == Key.ButtonA) { onClick(); true } else false }.focusGlide(CircleShape)) {
|
||||
androidx.compose.material3.Text(label)
|
||||
}
|
||||
androidx.compose.material3.AlertDialog(
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = { finish() },
|
||||
properties = androidx.compose.ui.window.DialogProperties(dismissOnClickOutside = false),
|
||||
title = { androidx.compose.material3.Text(title) },
|
||||
|
||||
@@ -88,7 +88,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.droiddeck.launcher.ui.GlideDialog as Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
|
||||
@@ -475,7 +475,7 @@ internal fun TextEntryDialog(title: String, initial: String, onDismiss: () -> Un
|
||||
AppDialog(shown, close, "textEntry", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(title, onClose = close)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus),
|
||||
value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus).focusGlide(),
|
||||
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { onSave(value.trim()); close() }),
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Done),
|
||||
)
|
||||
@@ -644,7 +644,7 @@ private fun SgdbSearchDialog(
|
||||
SmallIconButton(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.common_back), colors.onBackground, onClick = back)
|
||||
})
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth(),
|
||||
query, { query = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusGlide(),
|
||||
label = { Text(stringResource(R.string.art_sgdb_search_label)) },
|
||||
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onSearch = { leaveField(); search() }),
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Search),
|
||||
|
||||
@@ -0,0 +1,959 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.view.KeyEvent
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
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.imePadding
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyGridState
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.FilterAlt
|
||||
import androidx.compose.material.icons.filled.Sort
|
||||
import androidx.compose.material.icons.filled.Widgets
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.HomeFolders
|
||||
import com.droiddeck.launcher.HomeHidden
|
||||
import com.droiddeck.launcher.HomePins
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Bitmap
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import com.droiddeck.launcher.HomeWidgets
|
||||
import com.droiddeck.launcher.R
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private sealed interface AppEntry : AppEntryKey {
|
||||
val key: String
|
||||
|
||||
class App(val app: HomeApp.LaunchableApp) : AppEntry {
|
||||
override val label get() = app.label
|
||||
override val key get() = "app:" + app.key
|
||||
override val installedAt get() = app.installedAt
|
||||
override val updatedAt get() = app.updatedAt
|
||||
}
|
||||
|
||||
class Folder(val folder: HomeFolders.Folder, val apps: List<HomeApp.LaunchableApp>) : AppEntry {
|
||||
override val label get() = folder.name
|
||||
override val key get() = "folder:" + folder.id
|
||||
override val installedAt get() = apps.maxOf { it.installedAt }
|
||||
override val updatedAt get() = apps.maxOf { it.updatedAt }
|
||||
}
|
||||
|
||||
class Shortcut(val pinned: HomePins.Pinned) : AppEntry {
|
||||
override val label get() = pinned.label
|
||||
override val key get() = pinned.key
|
||||
override val installedAt get() = 0L
|
||||
override val updatedAt get() = 0L
|
||||
}
|
||||
}
|
||||
|
||||
private fun indexLetter(label: String): String {
|
||||
val c = label.trim().firstOrNull()?.uppercaseChar() ?: return "#"
|
||||
return if (c in 'A'..'Z') c.toString() else if (c.isLetter()) c.toString() else "#"
|
||||
}
|
||||
|
||||
private fun searchRank(label: String, q: String): Int? {
|
||||
if (label.startsWith(q, ignoreCase = true)) return 0
|
||||
if (label.split(' ', '-', '_', '.').any { it.startsWith(q, ignoreCase = true) }) return 1
|
||||
if (label.contains(q, ignoreCase = true)) return 2
|
||||
return null
|
||||
}
|
||||
|
||||
internal fun Context.findActivity(): Activity? {
|
||||
var c: Context? = this
|
||||
while (c is ContextWrapper) {
|
||||
if (c is Activity) return c
|
||||
c = c.baseContext
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun Modifier.menuKey(onMenu: () -> Unit): Modifier = onPreviewKeyEvent { event ->
|
||||
val k = event.nativeKeyEvent
|
||||
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y && k.keyCode != KeyEvent.KEYCODE_MENU) false
|
||||
else {
|
||||
if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) onMenu()
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
internal object AppsView {
|
||||
const val ALL = "all"
|
||||
const val GAMES = "games"
|
||||
const val DOWNLOADED = "downloaded"
|
||||
const val SYSTEM = "system"
|
||||
const val HIDDEN = "hidden"
|
||||
val FILTERS = listOf(ALL, GAMES, DOWNLOADED, SYSTEM, HIDDEN)
|
||||
const val NAME_ASC = "nameAsc"
|
||||
const val NAME_DESC = "nameDesc"
|
||||
const val INSTALLED = "installed"
|
||||
const val UPDATED = "updated"
|
||||
val SORTS = listOf(NAME_ASC, NAME_DESC, INSTALLED, UPDATED)
|
||||
|
||||
var filter by mutableStateOf(ALL)
|
||||
var sort by mutableStateOf(NAME_ASC)
|
||||
private var loaded = false
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE)
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val p = prefs(context)
|
||||
filter = p.getString("filter", ALL)?.takeIf { it in FILTERS } ?: ALL
|
||||
sort = p.getString("sort", NAME_ASC)?.takeIf { it in SORTS } ?: NAME_ASC
|
||||
}
|
||||
|
||||
fun setFilter(context: Context, value: String) {
|
||||
filter = value
|
||||
prefs(context).edit().putString("filter", value).apply()
|
||||
}
|
||||
|
||||
fun setSort(context: Context, value: String) {
|
||||
sort = value
|
||||
prefs(context).edit().putString("sort", value).apply()
|
||||
}
|
||||
|
||||
fun keeps(app: HomeApp.LaunchableApp): Boolean {
|
||||
val hidden = app.key in HomeHidden.keys
|
||||
return when (filter) {
|
||||
HIDDEN -> hidden
|
||||
GAMES -> !hidden && app.game
|
||||
DOWNLOADED -> !hidden && !app.system
|
||||
SYSTEM -> !hidden && app.system
|
||||
else -> !hidden
|
||||
}
|
||||
}
|
||||
|
||||
fun comparator(): Comparator<AppEntryKey> = when (sort) {
|
||||
NAME_DESC -> compareBy<AppEntryKey, String>(String.CASE_INSENSITIVE_ORDER) { it.label }.reversed()
|
||||
INSTALLED -> compareByDescending<AppEntryKey> { it.installedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label }
|
||||
UPDATED -> compareByDescending<AppEntryKey> { it.updatedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label }
|
||||
else -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }
|
||||
}
|
||||
}
|
||||
|
||||
internal interface AppEntryKey {
|
||||
val label: String
|
||||
val installedAt: Long
|
||||
val updatedAt: Long
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); true }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
val padH = if (narrow) 16.dp else 22.dp
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var openFolder by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var renameOnOpen by rememberSaveable { mutableStateOf(false) }
|
||||
var picking by rememberSaveable { mutableStateOf(false) }
|
||||
val folders = HomeFolders.folders
|
||||
val byKey = remember(s.androidApps) { s.androidApps.associateBy { it.key } }
|
||||
val byPkg = remember(s.androidApps) { s.androidApps.filterNot { it.work }.groupBy { it.packageName }.mapNotNull { (pkg, apps) -> apps.singleOrNull()?.let { pkg to it } }.toMap() }
|
||||
LaunchedEffect(byPkg) { if (byPkg.isNotEmpty()) HomeFolders.migrateMembers(ctx) { byPkg[it]?.key } }
|
||||
val member: (String) -> HomeApp.LaunchableApp? = { byKey[it] ?: byPkg[it] }
|
||||
val pins = HomePins.pinned
|
||||
val hidden = HomeHidden.keys
|
||||
val q = query.trim()
|
||||
val filter = AppsView.filter
|
||||
val sort = AppsView.sort
|
||||
val entries: List<AppEntry> = remember(s.androidApps, folders, q, filter, sort, pins, hidden) {
|
||||
val kept = s.androidApps.filter { AppsView.keeps(it) }
|
||||
val shortcuts = if (filter == AppsView.ALL) pins.map { AppEntry.Shortcut(it) } else emptyList()
|
||||
if (q.isNotEmpty()) {
|
||||
(kept.map { AppEntry.App(it) } + shortcuts).mapNotNull { e -> searchRank(e.label, q)?.let { it to e } }
|
||||
.sortedWith(compareBy<Pair<Int, AppEntry>> { it.first }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.second.label })
|
||||
.map { it.second }
|
||||
} else if (filter != AppsView.ALL) {
|
||||
kept.map { AppEntry.App(it) }.sortedWith(AppsView.comparator())
|
||||
} else {
|
||||
val folderEntries = folders.mapNotNull { f ->
|
||||
val apps = f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
if (apps.isEmpty()) null else AppEntry.Folder(f, apps)
|
||||
}
|
||||
val grouped = folderEntries.flatMap { f -> f.apps.map { it.key } }.toSet()
|
||||
(folderEntries + kept.filter { it.key !in grouped }.map { AppEntry.App(it) } + shortcuts).sortedWith(AppsView.comparator())
|
||||
}
|
||||
}
|
||||
val grid = rememberLazyGridState()
|
||||
LaunchedEffect(q, filter, sort) { grid.scrollToItem(0) }
|
||||
val widgetsShown = q.isEmpty() && filter == AppsView.ALL && HomeWidgets.widgets.isNotEmpty()
|
||||
val leadItems = if (widgetsShown) 1 else 0
|
||||
val byName = sort == AppsView.NAME_ASC || sort == AppsView.NAME_DESC
|
||||
val newFolder: (HomeApp.LaunchableApp) -> Unit = { app ->
|
||||
val f = HomeFolders.create(ctx, ctx.getString(R.string.apps_folder_default), app.key)
|
||||
renameOnOpen = true
|
||||
openFolder = f.id
|
||||
}
|
||||
|
||||
Box(modifier) {
|
||||
Column(Modifier.fillMaxSize().imePadding()) {
|
||||
Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = if (narrow) 8.dp else 12.dp)) {
|
||||
ModeHeader(
|
||||
stringResource(R.string.content_android_apps), query, { query = it },
|
||||
placeholder = stringResource(R.string.apps_search_hint),
|
||||
clearSearchFocus = openFolder != null || picking,
|
||||
lead = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
|
||||
Text(stringResource(R.string.content_android_apps), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
|
||||
val shownCount = s.androidApps.count { AppsView.keeps(it) } + if (filter == AppsView.ALL) pins.size else 0
|
||||
Text(androidx.compose.ui.res.pluralStringResource(R.plurals.apps_count, shownCount, shownCount), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
},
|
||||
) {
|
||||
AppsFilterButton()
|
||||
AppsSortButton()
|
||||
HeaderIconButton(stringResource(R.string.apps_add_widget), Icons.Filled.Widgets, "add-widget") {
|
||||
HomeWidgets.loadProviders(ctx)
|
||||
picking = true
|
||||
}
|
||||
}
|
||||
}
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val scroller = q.isEmpty() && byName && entries.size > 16
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(if (narrow) 84.dp else 96.dp),
|
||||
state = grid,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(start = padH, end = if (scroller) padH + 22.dp else padH, top = 12.dp, bottom = 16.dp),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
if (widgetsShown) item(key = "widgets", span = { GridItemSpan(maxLineSpan) }) {
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val maxW = maxWidth
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp),
|
||||
) {
|
||||
for (w in HomeWidgets.widgets) key(w.id) { WidgetCard(w, maxW.value.toInt()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (entries.isEmpty()) item(key = "empty", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Note(
|
||||
when {
|
||||
q.isNotEmpty() -> stringResource(R.string.apps_no_match, q)
|
||||
filter == AppsView.HIDDEN -> stringResource(R.string.apps_hidden_none)
|
||||
else -> stringResource(R.string.content_no_android_apps)
|
||||
},
|
||||
)
|
||||
}
|
||||
items(entries, key = { it.key }) { entry ->
|
||||
when (entry) {
|
||||
is AppEntry.App -> AppTile(
|
||||
entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder,
|
||||
first = entry === entries.first(),
|
||||
)
|
||||
is AppEntry.Shortcut -> PinnedTile(entry.pinned, first = entry === entries.first())
|
||||
is AppEntry.Folder -> FolderTile(entry, first = entry === entries.first(), onOpen = { renameOnOpen = false; openFolder = entry.folder.id }) {
|
||||
renameOnOpen = true
|
||||
openFolder = entry.folder.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (scroller) AlphabetScroller(entries, grid, leadItems, Modifier.align(Alignment.CenterEnd).fillMaxHeight().padding(end = 4.dp, top = 8.dp, bottom = 8.dp))
|
||||
}
|
||||
}
|
||||
|
||||
val folder = folders.firstOrNull { it.id == openFolder }
|
||||
LaunchedEffect(folder == null, openFolder) { if (folder == null && openFolder != null) openFolder = null }
|
||||
AnimatedVisibility(
|
||||
folder != null, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
|
||||
modifier = Modifier.fillMaxSize().zIndex(2f),
|
||||
) {
|
||||
var last by remember { mutableStateOf(folder) }
|
||||
if (folder != null) last = folder
|
||||
last?.let { f ->
|
||||
FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder) {
|
||||
openFolder = null
|
||||
renameOnOpen = false
|
||||
}
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(
|
||||
picking, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
|
||||
modifier = Modifier.fillMaxSize().zIndex(3f),
|
||||
) { WidgetPicker(padH) { picking = false } }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SwipeLock() {
|
||||
DisposableEffect(Unit) {
|
||||
PageSwipe.locks++
|
||||
onDispose { PageSwipe.locks-- }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun appsFilterLabel(filter: String): String = stringResource(
|
||||
when (filter) {
|
||||
AppsView.GAMES -> R.string.apps_filter_games
|
||||
AppsView.DOWNLOADED -> R.string.apps_filter_downloaded
|
||||
AppsView.SYSTEM -> R.string.apps_filter_system
|
||||
AppsView.HIDDEN -> R.string.apps_filter_hidden
|
||||
else -> R.string.apps_filter_all
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun appsSortLabel(sort: String): String = stringResource(
|
||||
when (sort) {
|
||||
AppsView.NAME_DESC -> R.string.apps_sort_name_desc
|
||||
AppsView.INSTALLED -> R.string.apps_sort_installed
|
||||
AppsView.UPDATED -> R.string.apps_sort_updated
|
||||
else -> R.string.apps_sort_name_asc
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun AppsFilterButton() = HeaderChoiceButton(
|
||||
stringResource(R.string.apps_filter), Icons.Filled.FilterAlt, "apps-filter",
|
||||
AppsView.FILTERS, AppsView.filter, { appsFilterLabel(it) }, AppsView::setFilter,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun AppsSortButton() = HeaderChoiceButton(
|
||||
stringResource(R.string.stores_sort), Icons.Filled.Sort, "apps-sort",
|
||||
AppsView.SORTS, AppsView.sort, { appsSortLabel(it) }, AppsView::setSort,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun HeaderChoiceButton(
|
||||
title: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String,
|
||||
options: List<String>, current: String, label: @Composable (String) -> String, onPick: (Context, String) -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
var at by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
|
||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
||||
HeaderIconButton("$title · ${label(current)}", icon, key) {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = options.size,
|
||||
handle = { Icon(icon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
options.forEachIndexed { i, option ->
|
||||
StepChoice(
|
||||
label(option), selected = option == current, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (option == current) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
onPick(ctx, option)
|
||||
Steps.fold()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val firstAt = remember(entries) {
|
||||
val map = LinkedHashMap<String, Int>()
|
||||
entries.forEachIndexed { i, e -> map.putIfAbsent(indexLetter(e.label), i) }
|
||||
map
|
||||
}
|
||||
val letters = remember(firstAt) { firstAt.keys.toList() }
|
||||
var dragging by remember { mutableStateOf<String?>(null) }
|
||||
val current by remember(entries, leadItems) {
|
||||
derivedStateOf {
|
||||
val i = (grid.firstVisibleItemIndex - leadItems).coerceIn(0, (entries.size - 1).coerceAtLeast(0))
|
||||
entries.getOrNull(i)?.let { indexLetter(it.label) }
|
||||
}
|
||||
}
|
||||
var height by remember { mutableIntStateOf(1) }
|
||||
val jump: (Float) -> Unit = { y ->
|
||||
val i = ((y / height) * letters.size).toInt().coerceIn(0, letters.size - 1)
|
||||
val letter = letters[i]
|
||||
if (letter != dragging) {
|
||||
dragging = letter
|
||||
val at = firstAt[letter] ?: 0
|
||||
scope.launch { grid.scrollToItem(if (at == 0) 0 else leadItems + at) }
|
||||
}
|
||||
}
|
||||
Box(modifier.width(22.dp)) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.fillMaxSize()
|
||||
.clip(RoundedCornerShape(11.dp))
|
||||
.background(if (dragging != null) colors.surface.copy(alpha = 0.85f) else Color.Transparent)
|
||||
.onSizeChanged { height = it.height.coerceAtLeast(1) }
|
||||
.pointerInput(letters) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown()
|
||||
down.consume()
|
||||
jump(down.position.y)
|
||||
while (true) {
|
||||
val event = awaitPointerEvent()
|
||||
val c = event.changes.firstOrNull { it.id == down.id } ?: break
|
||||
if (!c.pressed) break
|
||||
c.consume()
|
||||
jump(c.position.y)
|
||||
}
|
||||
dragging = null
|
||||
}
|
||||
},
|
||||
) {
|
||||
for (l in letters) {
|
||||
val on = l == (dragging ?: current)
|
||||
Text(
|
||||
l, fontSize = 10.sp, lineHeight = 11.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Medium,
|
||||
color = if (on) pal.signal else colors.onSurfaceVariant, textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
dragging?.let { l ->
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.align(Alignment.Center).offset { IntOffset(-64.dp.roundToPx(), 0) }.size(56.dp)
|
||||
.clip(CircleShape).background(pal.signal),
|
||||
) { Text(l, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = pal.onPrimary) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun TileFrame(
|
||||
id: String, first: Boolean, onClick: () -> Unit, onMenu: () -> Unit,
|
||||
content: @Composable (hot: Boolean) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.95f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "appScale")
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.paneItem("tile:$id").then(if (first) Modifier.firstTile().paneEntry() else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(Shape12)
|
||||
.background(if (hot) colors.surface else colors.surface.copy(alpha = 0.55f))
|
||||
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
|
||||
.hoverable(src)
|
||||
.combinedClickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onLongClick = onMenu, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.menuKey(onMenu)
|
||||
.padding(horizontal = 6.dp, vertical = 10.dp),
|
||||
) { content(hot) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TileLabel(text: String) = Text(
|
||||
text, fontSize = 12.sp, lineHeight = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.Dp) {
|
||||
val icon = app.icon
|
||||
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(size))
|
||||
else Box(Modifier.size(size).clip(CircleShape).background(artBrush(hueOf(app.label))))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AppTile(
|
||||
app: HomeApp.LaunchableApp, folderId: String?, first: Boolean,
|
||||
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
|
||||
) {
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) {
|
||||
AppIcon(app, 52.dp)
|
||||
TileLabel(app.label)
|
||||
}
|
||||
AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AppMenu(
|
||||
app: HomeApp.LaunchableApp, folderId: String?, open: Boolean,
|
||||
onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
var choosing by remember { mutableStateOf(false) }
|
||||
var shortcuts by remember { mutableStateOf<List<Pair<ShortcutInfo, Bitmap?>>>(emptyList()) }
|
||||
LaunchedEffect(open) {
|
||||
if (!open) {
|
||||
choosing = false
|
||||
return@LaunchedEffect
|
||||
}
|
||||
shortcuts = withContext(Dispatchers.IO) {
|
||||
HomeApp.shortcuts(ctx, app).map { it to HomeApp.shortcutIcon(ctx, it, 64) }
|
||||
}
|
||||
}
|
||||
val isHidden = app.key in HomeHidden.keys
|
||||
AnchoredMenu(open, onDismiss = onDismiss, title = app.label, compact = true, minWidth = 200.dp) { first ->
|
||||
if (choosing) {
|
||||
val others = HomeFolders.folders.filter { it.id != folderId }
|
||||
var firstUsed = false
|
||||
for (f in others) key(f.id) {
|
||||
MenuItem(f.name, checked = false, focusRequester = if (!firstUsed) first.also { firstUsed = true } else null) {
|
||||
HomeFolders.add(ctx, f.id, app.key)
|
||||
onDismiss()
|
||||
}
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_new_folder), checked = false, focusRequester = if (others.isEmpty()) first else null) {
|
||||
onDismiss()
|
||||
onNewFolder(app)
|
||||
}
|
||||
} else {
|
||||
shortcuts.forEachIndexed { i, (info, icon) ->
|
||||
key(info.id) {
|
||||
MenuItem(
|
||||
info.shortLabel?.toString().orEmpty(), checked = false,
|
||||
focusRequester = if (i == 0) first else null,
|
||||
leading = { MenuIcon(icon) },
|
||||
) {
|
||||
onDismiss()
|
||||
runCatching { HomeApp.startShortcut(ctx, info) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shortcuts.isNotEmpty()) Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(LocalPalette.current.line))
|
||||
if (!isHidden) MenuItem(stringResource(R.string.apps_add_to_folder), checked = false, focusRequester = if (shortcuts.isEmpty()) first else null) { choosing = true }
|
||||
if (folderId != null) MenuItem(stringResource(R.string.apps_remove_from_folder), checked = false) {
|
||||
HomeFolders.remove(ctx, app.key)
|
||||
onDismiss()
|
||||
}
|
||||
MenuItem(stringResource(if (isHidden) R.string.apps_unhide else R.string.apps_hide), checked = false,
|
||||
focusRequester = if (isHidden && shortcuts.isEmpty()) first else null) {
|
||||
onDismiss()
|
||||
HomeHidden.set(ctx, app.key, !isHidden)
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_app_info), checked = false) {
|
||||
onDismiss()
|
||||
runCatching { HomeApp.openAppInfo(ctx, app) }
|
||||
}
|
||||
if (HomeApp.canUninstall(app)) MenuItem(stringResource(R.string.apps_uninstall), checked = false) {
|
||||
onDismiss()
|
||||
runCatching { HomeApp.uninstall(ctx, app) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MenuIcon(icon: Bitmap?) {
|
||||
if (icon != null) Image(icon.asImageBitmap(), null, modifier = Modifier.size(20.dp))
|
||||
else Spacer(Modifier.size(20.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PinnedTile(pinned: HomePins.Pinned, first: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
TileFrame(pinned.key, first, onClick = { runCatching { HomeApp.startShortcut(ctx, pinned.info) } }, onMenu = { menu = true }) {
|
||||
Box {
|
||||
val icon = pinned.icon
|
||||
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
|
||||
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label))))
|
||||
}
|
||||
TileLabel(pinned.label)
|
||||
}
|
||||
AnchoredMenu(menu, onDismiss = { menu = false }, title = pinned.label, compact = true, minWidth = 180.dp) { firstItem ->
|
||||
MenuItem(stringResource(R.string.apps_shortcut_remove), checked = false, detail = pinned.appLabel, focusRequester = firstItem) {
|
||||
menu = false
|
||||
HomePins.unpin(ctx, pinned)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderIcon(apps: List<HomeApp.LaunchableApp>, size: androidx.compose.ui.unit.Dp) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val cell = (size - 14.dp) / 2
|
||||
Box(
|
||||
Modifier.size(size).clip(RoundedCornerShape(size / 3.5f)).background(colors.surfaceVariant)
|
||||
.glideBorder(false, RoundedCornerShape(size / 3.5f), pal.signal, pal.line2)
|
||||
.padding(5.dp),
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
for (row in apps.take(4).chunked(2)) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
for (a in row) AppIcon(a, cell)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Unit, onRename: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
TileFrame(entry.key, first, onClick = onOpen, onMenu = { menu = true }) {
|
||||
FolderIcon(entry.apps, 52.dp)
|
||||
TileLabel(entry.folder.name)
|
||||
}
|
||||
AnchoredMenu(menu, onDismiss = { menu = false }, title = entry.folder.name, compact = true, minWidth = 160.dp) { firstItem ->
|
||||
MenuItem(stringResource(R.string.apps_folder_rename), checked = false, focusRequester = firstItem) {
|
||||
menu = false
|
||||
onRename()
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_folder_ungroup), checked = false) {
|
||||
menu = false
|
||||
HomeFolders.delete(ctx, entry.folder.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderSheet(
|
||||
folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean,
|
||||
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit,
|
||||
) {
|
||||
SwipeLock()
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var renaming by remember(folder.id) { mutableStateOf(renameFirst) }
|
||||
var name by remember(folder.id) { mutableStateOf(if (renameFirst) "" else folder.name) }
|
||||
val commit = {
|
||||
val n = name.trim()
|
||||
if (n.isNotEmpty() && n != folder.name) HomeFolders.rename(ctx, folder.id, n)
|
||||
renaming = false
|
||||
}
|
||||
val close = { if (renaming) commit(); onClose() }
|
||||
BackHandler { close() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
|
||||
.pointerInput(Unit) { awaitEachGesture { val d = awaitFirstDown(); d.consume(); close() } },
|
||||
) {
|
||||
val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true }
|
||||
AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160)), exit = scaleOut(Motion.tw(140)) + fadeOut(Motion.tw(140))) {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 620.dp).fillMaxWidth(0.9f).heightIn(max = 520.dp)
|
||||
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
|
||||
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
|
||||
.controllerBack(close)
|
||||
.padding(16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) {
|
||||
if (renaming) Box(Modifier.weight(1f)) {
|
||||
AdbTextField(
|
||||
value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name),
|
||||
keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false,
|
||||
placeholder = folder.name, focusOnShow = true, onDone = { commit() },
|
||||
)
|
||||
} else {
|
||||
Text(folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
SmallIconButton(Icons.Filled.Edit, stringResource(R.string.apps_folder_rename), tint = colors.onSurfaceVariant) { renaming = true }
|
||||
Spacer(Modifier.weight(1f))
|
||||
}
|
||||
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant) { close() }
|
||||
}
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(92.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(apps, key = { it.key }) { app ->
|
||||
AppTile(app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WidgetCard(w: HomeWidgets.Placed, maxWidthDp: Int) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val width = w.widthDp.coerceAtMost(maxWidthDp)
|
||||
val activity = remember(ctx) { ctx.findActivity() }
|
||||
Box {
|
||||
Box(
|
||||
Modifier.size(width.dp, w.heightDp.dp)
|
||||
.clip(Shape16)
|
||||
.background(colors.surface.copy(alpha = 0.35f))
|
||||
.glideBorder(hot || menu, Shape16, pal.signal)
|
||||
.hoverable(src).focusable(interactionSource = src)
|
||||
.controllerConfirm { menu = true }
|
||||
.menuKey { menu = true },
|
||||
) {
|
||||
AndroidView(
|
||||
factory = { c ->
|
||||
(HomeWidgets.createView(c, w.id) ?: android.view.View(c)).apply {
|
||||
val radius = 16 * c.resources.displayMetrics.density
|
||||
outlineProvider = object : android.view.ViewOutlineProvider() {
|
||||
override fun getOutline(view: android.view.View, outline: android.graphics.Outline) =
|
||||
outline.setRoundRect(0, 0, view.width, view.height, radius)
|
||||
}
|
||||
clipToOutline = true
|
||||
}
|
||||
},
|
||||
update = { v ->
|
||||
if (v is HomeWidgets.HomeWidgetView) {
|
||||
v.onLongPress = { menu = true }
|
||||
HomeWidgets.applySize(v, width, w.heightDp)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
val (minW, minH) = remember(w.id) { HomeWidgets.minSize(ctx, w.id) }
|
||||
val index = HomeWidgets.widgets.indexOfFirst { it.id == w.id }
|
||||
val label = remember(w.id) { HomeWidgets.info(ctx, w.id)?.loadLabel(ctx.packageManager) ?: "" }
|
||||
AnchoredMenu(menu, onDismiss = { menu = false }, title = label, compact = true, minWidth = 180.dp) { first ->
|
||||
val step = 48
|
||||
MenuItem(stringResource(R.string.apps_widget_wider), checked = false, enabled = width < maxWidthDp, focusRequester = first) {
|
||||
HomeWidgets.resize(ctx, w.id, (width + step).coerceAtMost(maxWidthDp), w.heightDp)
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_widget_narrower), checked = false, enabled = width > minW) {
|
||||
HomeWidgets.resize(ctx, w.id, (width - step).coerceAtLeast(minW), w.heightDp)
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_widget_taller), checked = false, enabled = w.heightDp < 480) {
|
||||
HomeWidgets.resize(ctx, w.id, width, (w.heightDp + step).coerceAtMost(480))
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_widget_shorter), checked = false, enabled = w.heightDp > minH) {
|
||||
HomeWidgets.resize(ctx, w.id, width, (w.heightDp - step).coerceAtLeast(minH))
|
||||
}
|
||||
if (index > 0) MenuItem(stringResource(R.string.apps_widget_move_earlier), checked = false) { HomeWidgets.move(ctx, w.id, -1) }
|
||||
if (index in 0 until HomeWidgets.widgets.size - 1) MenuItem(stringResource(R.string.apps_widget_move_later), checked = false) { HomeWidgets.move(ctx, w.id, 1) }
|
||||
if (activity != null && HomeWidgets.canReconfigure(ctx, w.id)) MenuItem(stringResource(R.string.apps_widget_configure), checked = false) {
|
||||
menu = false
|
||||
HomeWidgets.reconfigure(activity, w.id)
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_widget_remove), checked = false) {
|
||||
menu = false
|
||||
HomeWidgets.remove(ctx, w.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WidgetPicker(padH: androidx.compose.ui.unit.Dp, onClose: () -> Unit) {
|
||||
SwipeLock()
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val activity = remember(ctx) { ctx.findActivity() }
|
||||
BackHandler { onClose() }
|
||||
val providers = HomeWidgets.providers
|
||||
Column(Modifier.fillMaxSize().background(colors.background).pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false) } }) {
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(150.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(horizontal = padH, vertical = 14.dp),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
item(key = "back", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column {
|
||||
Box(Modifier.padding(bottom = 10.dp)) { BackLink(stringResource(R.string.rail_apps), compact = true, onClick = onClose) }
|
||||
PageHeader(stringResource(R.string.apps_add_widget)) {
|
||||
if (providers != null) Chip(providers.size.toString(), ok = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
when {
|
||||
providers == null -> item(key = "loading", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_loading)) }
|
||||
providers.isEmpty() -> item(key = "none", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_none)) }
|
||||
else -> items(providers, key = { it.info.provider.flattenToString() }) { p ->
|
||||
ProviderCard(p, first = p === providers.first()) {
|
||||
onClose()
|
||||
if (activity != null) HomeWidgets.add(activity, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProviderCard(p: HomeWidgets.Provider, first: Boolean, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().paneItem("widget:" + p.info.provider.flattenToString()).then(if (first) Modifier.firstTile() else Modifier)
|
||||
.clip(Shape12).background(colors.surface)
|
||||
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
|
||||
.hoverable(src)
|
||||
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick),
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxWidth().aspectRatio(1.6f).background(colors.surfaceVariant).padding(10.dp),
|
||||
) {
|
||||
val preview = p.preview
|
||||
if (preview != null) Image(preview.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
Column(Modifier.padding(horizontal = 10.dp, vertical = 8.dp)) {
|
||||
Text(p.label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val cells = "${(p.widthDp / 80f).roundToInt().coerceAtLeast(1)} × ${(p.heightDp / 80f).roundToInt().coerceAtLeast(1)}"
|
||||
Text(if (p.appLabel == p.label) cells else "${p.appLabel} · $cells", fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun PinRequestPrompt(label: String, appLabel: String, icon: Bitmap?, wide: Boolean, onAdd: () -> Unit, onCancel: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
BackHandler { onCancel() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); onCancel() } },
|
||||
) {
|
||||
val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true }
|
||||
AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160))) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.widthIn(min = 280.dp, max = 420.dp)
|
||||
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
|
||||
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
|
||||
.controllerBack(onCancel)
|
||||
.padding(18.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.apps_pin_title).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
letterSpacing = 1.5.sp, color = colors.onSurfaceVariant,
|
||||
)
|
||||
if (wide && icon != null) Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = 180.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface).padding(10.dp),
|
||||
) { Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxWidth()) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
if (!wide) {
|
||||
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
|
||||
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(label))))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(appLabel, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = onCancel)
|
||||
PrimaryButton(stringResource(R.string.apps_pin_add), onClick = onAdd)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,12 +308,12 @@ private fun InstalledMoviesDialog(a: ModeSettingsActions, onDismiss: () -> Unit)
|
||||
|
||||
@Composable
|
||||
private fun RemoveMovieDialog(entry: BootMovieLibrary.Entry, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.boot_movie_remove_confirm, entry.title)) },
|
||||
text = { Text(stringResource(R.string.boot_movie_remove_confirm_body)) },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm) { Text(stringResource(R.string.boot_movie_remove)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.boot_movie_remove)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.vector.addPathNodes
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
internal val CollectionsIcon: ImageVector = ImageVector.Builder("Collections", 24.dp, 24.dp, 24f, 24f).apply {
|
||||
for (d in listOf(
|
||||
"M2.65,4.6H7.33V22H2.65Z",
|
||||
"M8.32,2H13V22H8.32Z",
|
||||
"M13.9,5.4H18.5L21.4,22H16.8Z",
|
||||
)) addPath(addPathNodes(d), fill = SolidColor(Color.Black))
|
||||
}.build()
|
||||
@@ -38,7 +38,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Refresh
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -699,7 +699,7 @@ fun ComponentsPage(
|
||||
|
||||
Box(Modifier.fillMaxSize().onGloballyPositioned { pageAt = it.positionInRoot() }.onFocusChanged { pageFocused = it.hasFocus }) {
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)
|
||||
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp).padding(top = if (narrow) 12.dp else 18.dp)
|
||||
.then(if (selectedGame == null) Modifier.bumpers(
|
||||
onPrevious = { pick(layerStep(layer, -1)) },
|
||||
onNext = { pick(layerStep(layer, 1)) },
|
||||
@@ -972,7 +972,7 @@ private fun Stack(
|
||||
onFocus = { onFocus(l) }, onClick = { onOpen(l) },
|
||||
)
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
StackHeading(stringResource(R.string.comp_this_device))
|
||||
card(GPU_TAB)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
@@ -37,10 +37,12 @@ class DeckControlsPanel(
|
||||
private val onSteamMenu: () -> Unit,
|
||||
private val onQam: () -> Unit,
|
||||
private val pad: PadBridge? = null,
|
||||
private val portraitDock: Boolean = false,
|
||||
) : LinearLayout(context) {
|
||||
private enum class Tab(val label: Int) { GAMEPAD(R.string.deck_tab_gamepad), GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
|
||||
|
||||
private val content = FrameLayout(context)
|
||||
val deckControls = pad == null || SessionState.deckPad
|
||||
private val tabViews = HashMap<Tab, TextView>()
|
||||
private val topBar: View by lazy { topBar() }
|
||||
|
||||
@@ -49,7 +51,7 @@ class DeckControlsPanel(
|
||||
setBackgroundColor(Color.BLACK)
|
||||
addView(topBar, LayoutParams(LayoutParams.MATCH_PARENT, dp(64)))
|
||||
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
|
||||
select(if (pad != null) selectedWithPad else selected)
|
||||
select(if (pad != null && !deckControls) Tab.GAMEPAD else if (pad != null) selectedWithPad else selected)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
@@ -67,6 +69,7 @@ class DeckControlsPanel(
|
||||
background = outline(CORNER_PILL, SURFACE)
|
||||
setPadding(dp(4), dp(4), dp(4), dp(4))
|
||||
for (tab in Tab.values()) {
|
||||
if (!deckControls && tab != Tab.GAMEPAD) continue
|
||||
if (tab == Tab.GAMEPAD && pad == null) continue
|
||||
val view = TextView(context).apply {
|
||||
text = context.getString(tab.label)
|
||||
@@ -170,7 +173,7 @@ class DeckControlsPanel(
|
||||
addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84)))
|
||||
}
|
||||
|
||||
private fun gamepad(pad: PadBridge): View = GamepadLayout(context).apply {
|
||||
private fun gamepad(pad: PadBridge): View = GamepadLayout(context, portraitDock).apply {
|
||||
fun pill(label: String, write: (PadState, Boolean) -> Unit) = PadButton(context, pad, label, write)
|
||||
place(surfaceSlot(pad, right = false), GamepadGeometry.Slot.LEFT_MAIN)
|
||||
place(DirectionPad(context, pad), GamepadGeometry.Slot.LEFT_SECOND)
|
||||
@@ -186,14 +189,22 @@ class DeckControlsPanel(
|
||||
place(centreTap("\u2022\u2022\u2022", context.getString(R.string.drawer_open_qam), onQam), GamepadGeometry.Slot.QAM)
|
||||
}
|
||||
place(pill("MENU") { st, d -> st.press(PadState.START, d) }, GamepadGeometry.Slot.MENU)
|
||||
place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
|
||||
if (deckControls) place(centreTap("\u25a6 " + context.getString(R.string.deck_panels), context.getString(R.string.deck_more_controls)) { select(Tab.BOTH) },
|
||||
GamepadGeometry.Slot.PANELS)
|
||||
if (portraitDock && deckControls) {
|
||||
place(GripButton(context, "L4", null, DeckControls.L4), GamepadGeometry.Slot.L4)
|
||||
place(GripButton(context, "L5", null, DeckControls.L5), GamepadGeometry.Slot.L5)
|
||||
place(GripButton(context, "R5", null, DeckControls.R5), GamepadGeometry.Slot.R5)
|
||||
place(GripButton(context, "R4", null, DeckControls.R4), GamepadGeometry.Slot.R4)
|
||||
}
|
||||
}
|
||||
|
||||
private fun centreTap(label: String, description: String, onClick: () -> Unit) = TextView(context).apply {
|
||||
text = label
|
||||
contentDescription = description
|
||||
textSize = 13f
|
||||
maxLines = 1
|
||||
setAutoSizeTextTypeUniformWithConfiguration(9, 13, 1, android.util.TypedValue.COMPLEX_UNIT_SP)
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
letterSpacing = 0.08f
|
||||
gravity = Gravity.CENTER
|
||||
@@ -206,6 +217,11 @@ class DeckControlsPanel(
|
||||
}
|
||||
|
||||
private fun surfaceSlot(pad: PadBridge, right: Boolean): View = FrameLayout(context).apply {
|
||||
if (!deckControls) {
|
||||
addView(StickView(context, pad, right),
|
||||
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
|
||||
return@apply
|
||||
}
|
||||
val slot = this
|
||||
fun show() {
|
||||
slot.removeAllViews()
|
||||
@@ -617,7 +633,7 @@ class DeckControlsPanel(
|
||||
}
|
||||
}
|
||||
|
||||
private class GamepadLayout(context: Context) : ViewGroup(context) {
|
||||
private class GamepadLayout(context: Context, private val portraitDock: Boolean) : ViewGroup(context) {
|
||||
private val slots = LinkedHashMap<View, GamepadGeometry.Slot>()
|
||||
|
||||
fun place(view: View, slot: GamepadGeometry.Slot) {
|
||||
@@ -625,7 +641,7 @@ class DeckControlsPanel(
|
||||
addView(view)
|
||||
}
|
||||
|
||||
private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density)
|
||||
private fun boxes(w: Int, h: Int) = GamepadGeometry.layout(w.toFloat(), h.toFloat(), resources.displayMetrics.density, portraitDock)
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
val w = MeasureSpec.getSize(widthMeasureSpec)
|
||||
|
||||
@@ -31,7 +31,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Refresh
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -23,6 +24,7 @@ import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
@@ -54,10 +56,21 @@ internal class GlideSource {
|
||||
var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape)
|
||||
var color by mutableStateOf(Color.Transparent)
|
||||
var width by mutableStateOf(2.dp)
|
||||
var fillAlpha by mutableFloatStateOf(RING_FILL)
|
||||
val requester = androidx.compose.ui.focus.FocusRequester()
|
||||
}
|
||||
|
||||
internal class FocusGlide(val view: View) {
|
||||
internal class FocusGlide(view: View?) {
|
||||
private val deferredWindow = view == null
|
||||
var view = view
|
||||
private set
|
||||
|
||||
fun accepts(view: View): Boolean {
|
||||
// DropdownMenu recreates its popup view after closing.
|
||||
if (this.view == null || deferredWindow && this.view !== view && host?.isAttached != true) this.view = view
|
||||
return this.view === view
|
||||
}
|
||||
|
||||
var host: LayoutCoordinates? = null
|
||||
val hot = mutableStateListOf<GlideSource>()
|
||||
var moves by mutableIntStateOf(0)
|
||||
@@ -107,15 +120,17 @@ internal fun Modifier.glideBorder(
|
||||
restColor: Color = Color.Transparent,
|
||||
hotWidth: Dp = 2.dp,
|
||||
restWidth: Dp = 1.dp,
|
||||
hotFillAlpha: Float = RING_FILL,
|
||||
): Modifier {
|
||||
val glide = LocalFocusGlide.current
|
||||
if (glide == null || glide.view !== LocalView.current) {
|
||||
if (glide == null || !glide.accepts(LocalView.current)) {
|
||||
return border(if (hot) hotWidth else restWidth, if (hot) hotColor else restColor, shape)
|
||||
}
|
||||
val src = remember { GlideSource() }
|
||||
src.shape = shape
|
||||
src.color = hotColor
|
||||
src.width = hotWidth
|
||||
src.fillAlpha = hotFillAlpha
|
||||
DisposableEffect(glide, hot) {
|
||||
if (hot) glide.claim(src)
|
||||
onDispose { glide.release(src) }
|
||||
@@ -140,12 +155,36 @@ private const val REPEAT_MS = 180L
|
||||
|
||||
private val FAR = 360.dp
|
||||
|
||||
@Composable
|
||||
internal fun Modifier.focusGlide(
|
||||
shape: Shape = Shape12,
|
||||
color: Color = LocalPalette.current.signal,
|
||||
): Modifier {
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
return glideBorder(focused, shape, color, hotFillAlpha = 0f)
|
||||
.onFocusChanged { focused = it.isFocused }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
|
||||
val view = LocalView.current
|
||||
val glide = remember(view) { FocusGlide(view) }
|
||||
Box(modifier.focusGlideOverlay(glide)) {
|
||||
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FocusGlideWindow(content: @Composable (Modifier) -> Unit) {
|
||||
val glide = remember { FocusGlide(null) }
|
||||
val overlay = Modifier.focusGlideOverlay(glide)
|
||||
CompositionLocalProvider(LocalFocusGlide provides glide) { content(overlay) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val density = LocalDensity.current
|
||||
val dir = LocalLayoutDirection.current
|
||||
val glide = remember(view) { FocusGlide(view) }
|
||||
val edges = remember { List(4) { Animatable(0f) } }
|
||||
val corner = remember { Animatable(0f) }
|
||||
val solid = remember { Animatable(0f) }
|
||||
@@ -162,6 +201,8 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
||||
val color by animateColorAsState(cur?.color ?: lastColor, Motion.tw(160), label = "glideColor")
|
||||
var width by remember { mutableStateOf(2.dp) }
|
||||
if (cur != null) width = cur.width
|
||||
var fillAlpha by remember { mutableFloatStateOf(RING_FILL) }
|
||||
if (cur != null) fillAlpha = cur.fillAlpha
|
||||
|
||||
LaunchedEffect(glide, Motion.scale) {
|
||||
var shown: GlideSource? = null
|
||||
@@ -339,8 +380,7 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier
|
||||
return this
|
||||
.onGloballyPositioned { glide.host = it }
|
||||
.drawWithContent {
|
||||
drawContent()
|
||||
@@ -359,15 +399,12 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
|
||||
if (f < 0.99f) {
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * RING_FILL,
|
||||
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha,
|
||||
)
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.snap
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
@@ -105,7 +107,7 @@ import java.io.File
|
||||
internal fun Pane(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
|
||||
) {
|
||||
BoxWithConstraints(modifier = modifier) {
|
||||
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
|
||||
@@ -138,12 +140,19 @@ internal fun Pane(
|
||||
before[0] = target
|
||||
val targetNow by rememberUpdatedState(target)
|
||||
val leave = if (Hops.linking) PageLeave.Link else PageLeave.Ordinary
|
||||
LaunchedEffect(target) { Hops.linking = false }
|
||||
LaunchedEffect(target) {
|
||||
Hops.linking = false
|
||||
PageSwipe.direction = 0
|
||||
}
|
||||
AnimatedContent(
|
||||
targetState = target,
|
||||
modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() },
|
||||
transitionSpec = {
|
||||
val swipe = PageSwipe.direction
|
||||
when {
|
||||
swipe != 0 -> (fadeIn(Motion.tw(260, 40)) + slideInHorizontally(Motion.tw(360)) { it * swipe / 8 })
|
||||
.togetherWith(fadeOut(Motion.tw(160)) + slideOutHorizontally(Motion.tw(220)) { -it * swipe / 8 })
|
||||
.apply { targetContentZIndex = 1f }
|
||||
targetState in origins -> (fadeIn(Motion.tw(120)))
|
||||
.togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f))
|
||||
.apply { targetContentZIndex = 1f }
|
||||
@@ -162,7 +171,7 @@ internal fun Pane(
|
||||
label = "pane",
|
||||
) { key ->
|
||||
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
|
||||
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb) }
|
||||
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
|
||||
val hopSink by androidx.compose.animation.core.animateFloatAsState(
|
||||
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
|
||||
)
|
||||
@@ -223,7 +232,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L
|
||||
private fun Content(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
|
||||
@@ -232,13 +241,13 @@ private fun Content(
|
||||
val padH = if (narrow) 16.dp else 22.dp
|
||||
val padV = if (narrow) 12.dp else 18.dp
|
||||
if (selected == "setup") {
|
||||
Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) {
|
||||
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
|
||||
Column(modifier = modifier.padding(horizontal = padH).padding(top = padV)) {
|
||||
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (selected == "updates") {
|
||||
UpdatesPage(s, a, modifier.padding(horizontal = padH, vertical = padV))
|
||||
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "steam") {
|
||||
@@ -261,24 +270,12 @@ private fun Content(
|
||||
DesktopPage(s, a, modifier, onSelect)
|
||||
return
|
||||
}
|
||||
if (selected == "android-apps" && s.isHomeApp) {
|
||||
AndroidAppsPage(s, modifier, onAndroidAppClick)
|
||||
return
|
||||
}
|
||||
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
|
||||
when {
|
||||
selected == "android-apps" && s.isHomeApp -> {
|
||||
Rise(0) { PageHeader(stringResource(R.string.content_android_apps)) { Chip(stringResource(R.string.content_apps_count, s.androidApps.size), ok = false) } }
|
||||
if (s.androidApps.isEmpty()) Rise(3) { Note(stringResource(R.string.content_no_android_apps)) }
|
||||
else Rise(3, Modifier.fillMaxWidth()) {
|
||||
ArtGrid(s.androidApps.map { app ->
|
||||
Tile(
|
||||
app.label,
|
||||
null,
|
||||
null,
|
||||
"android:${app.packageName}",
|
||||
onClick = { onAndroidAppClick(app) },
|
||||
iconBitmap = app.icon,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
selected.startsWith("user:") -> {
|
||||
val app = UserAppsState.items.firstOrNull { "user:${it.key}" == selected }
|
||||
if (app == null) Note(stringResource(R.string.user_apps_gone)) else UserAppPage(app, s, a, onSelect)
|
||||
|
||||
@@ -41,6 +41,9 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.relocation.BringIntoViewRequester
|
||||
import androidx.compose.foundation.relocation.bringIntoViewRequester
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Apps
|
||||
@@ -81,12 +84,48 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.layout.boundsInParent
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
|
||||
|
||||
internal val AttentionAmber = Color(0xFFFFB547)
|
||||
|
||||
@Composable
|
||||
internal fun BottomBar(
|
||||
s: FrontEndState, selected: String,
|
||||
onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier,
|
||||
) {
|
||||
val shown = Hops.railPreview ?: selected
|
||||
val keys = navigationKeys(s)
|
||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
|
||||
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
|
||||
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
|
||||
Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) {
|
||||
BoxWithConstraints(Modifier.weight(1f)) {
|
||||
val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp)
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) {
|
||||
NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth,
|
||||
place = { key -> Modifier.onGloballyPositioned { item -> content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }; Hops.railBounds[key] = item.boundsInRoot() } },
|
||||
onSelect = onSelect, onFocusSelect = onFocusSelect)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.running != null) ResumeRailItem(s.running, compact = true, iconOnly = true, a.onResume)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun navigationKeys(s: FrontEndState) = buildList {
|
||||
add("steam"); add("games")
|
||||
if (s.gameStoresEnabled) add("stores")
|
||||
add("desktop"); add("components")
|
||||
if (s.isHomeApp) add("android-apps")
|
||||
add("setup"); add("updates")
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SideRail(
|
||||
s: FrontEndState, selected: String,
|
||||
@@ -95,8 +134,6 @@ internal fun SideRail(
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val compact = LocalConfiguration.current.screenHeightDp < 420
|
||||
val iconOnly = isNarrowScreen()
|
||||
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
|
||||
@@ -105,38 +142,24 @@ internal fun SideRail(
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
|
||||
val shown = Hops.railPreview ?: selected
|
||||
val keys = buildList {
|
||||
add("steam"); add("games")
|
||||
if (s.gameStoresEnabled) add("stores")
|
||||
add("desktop")
|
||||
add("components")
|
||||
if (s.isHomeApp) add("android-apps")
|
||||
add("setup"); add("updates")
|
||||
}
|
||||
val keys = navigationKeys(s)
|
||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
|
||||
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
|
||||
var railAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
|
||||
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onGloballyPositioned { railAt = it.boundsInRoot().topLeft }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-railAt), tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
|
||||
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.fillMaxWidth().selectableGroup(),
|
||||
) {
|
||||
val place: (String) -> Modifier = { key ->
|
||||
Modifier.onGloballyPositioned {
|
||||
bounds[key] = it.boundsInRoot()
|
||||
Hops.railBounds[key] = it.boundsInRoot()
|
||||
Modifier.onGloballyPositioned { item ->
|
||||
content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }
|
||||
Hops.railBounds[key] = item.boundsInRoot()
|
||||
}
|
||||
}
|
||||
RailItem(stringResource(R.string.rail_steam), Icons.Outlined.SportsEsports, "steam", shown == "steam", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
|
||||
RailItem(stringResource(R.string.rail_games), Icons.Outlined.VideoLibrary, "games", shown == "games", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("games") }) { onSelect("games") }
|
||||
if (s.gameStoresEnabled) RailItem(stringResource(R.string.rail_stores), Icons.Outlined.LocalMall, "stores", shown == "stores", compact, iconOnly, fit, count = s.storeDownloadsActive, place = place, onFocus = { onFocusSelect("stores") }) { onSelect("stores") }
|
||||
RailItem(stringResource(R.string.rail_desktop), Icons.Outlined.DesktopWindows, "desktop", shown == "desktop", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
|
||||
RailItem(stringResource(R.string.rail_components), Icons.Outlined.Layers, "components", shown == "components", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("components") }) { onSelect("components") }
|
||||
if (s.isHomeApp) RailItem(stringResource(R.string.rail_apps), Icons.Outlined.Apps, "android-apps", shown == "android-apps", compact, iconOnly, fit, place = place, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
|
||||
RailItem(stringResource(R.string.rail_setup), Icons.Outlined.Tune, "setup", shown == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, place = place, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
|
||||
RailItem(stringResource(R.string.rail_updates), Icons.Outlined.SystemUpdate, "updates", shown == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, place = place, onFocus = { onFocusSelect("updates") }) { onSelect("updates") }
|
||||
NavigationItems(s, shown, compact, iconOnly, fit, if (iconOnly) 52.dp else 80.dp, place, onSelect, onFocusSelect)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,8 +174,36 @@ internal fun SideRail(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NavigationItems(
|
||||
s: FrontEndState, shown: String, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp,
|
||||
place: (String) -> Modifier, onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit,
|
||||
) {
|
||||
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
for (key in navigationKeys(s)) {
|
||||
val (label, icon) = when (key) {
|
||||
"steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports
|
||||
"games" -> R.string.rail_games to Icons.Outlined.VideoLibrary
|
||||
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
|
||||
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
|
||||
"components" -> R.string.rail_components to Icons.Outlined.Layers
|
||||
"android-apps" -> R.string.rail_apps to Icons.Outlined.Apps
|
||||
"setup" -> R.string.rail_setup to Icons.Outlined.Tune
|
||||
else -> R.string.rail_updates to Icons.Outlined.SystemUpdate
|
||||
}
|
||||
key(key) {
|
||||
RailItem(stringResource(label), icon, key, shown == key, compact, iconOnly, height, width,
|
||||
badge = (key == "setup" && setupNeedsAttention) || (key == "updates" && s.updates.hasUpdate),
|
||||
count = if (key == "stores") s.storeDownloadsActive else 0,
|
||||
place = place, onFocus = { onFocusSelect(key) }) { onSelect(key) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
private fun RailItem(
|
||||
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp,
|
||||
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp,
|
||||
badge: Boolean = false,
|
||||
count: Int = 0,
|
||||
place: (String) -> Modifier = { Modifier },
|
||||
@@ -181,6 +232,8 @@ private fun RailItem(
|
||||
Motion.tw(220), label = "railFill",
|
||||
)
|
||||
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale")
|
||||
val bringIntoView = remember { BringIntoViewRequester() }
|
||||
LaunchedEffect(current) { if (current) bringIntoView.bringIntoView() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier
|
||||
@@ -189,7 +242,8 @@ private fun RailItem(
|
||||
.then(place(key))
|
||||
.landingPop(Hops.railLanded[key] ?: 0)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.size(width = if (iconOnly) 52.dp else 80.dp, height = height)
|
||||
.size(width = width, height = height)
|
||||
.bringIntoViewRequester(bringIntoView)
|
||||
.clip(Shape14)
|
||||
.background(fill)
|
||||
.glideBorder(focused, Shape14, pal.signal)
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import android.provider.Settings
|
||||
import android.view.Display
|
||||
@@ -120,6 +121,8 @@ class FrontEndState(
|
||||
val isHomeApp: Boolean = false,
|
||||
val homeScreenEnabled: Boolean = false,
|
||||
val defaultHomeLabel: String? = null,
|
||||
val integration: com.droiddeck.launcher.core.SteamIntegration.State = com.droiddeck.launcher.core.SteamIntegration.State(suggested = false),
|
||||
val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null,
|
||||
val androidApps: List<HomeApp.LaunchableApp> = emptyList(),
|
||||
val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(),
|
||||
val packages: List<PackageRow>? = null,
|
||||
@@ -138,6 +141,7 @@ class FrontEndState(
|
||||
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
|
||||
val showPhantomGate: Boolean = false,
|
||||
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
|
||||
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
|
||||
val launcherFullscreen: Boolean = true,
|
||||
val downloadSource: String = DownloadSource.MODE_AUTO,
|
||||
val downloadMirror: String = "",
|
||||
@@ -219,6 +223,7 @@ class FrontEndActions(
|
||||
val onAppScale: (Int) -> Unit = {},
|
||||
val onLauncherIcon: (String) -> Unit = {},
|
||||
val onOrientation: (Int) -> Unit = {},
|
||||
val onLauncherOrientation: (Int) -> Unit = {},
|
||||
val onLauncherFullscreen: (Boolean) -> Unit = {},
|
||||
val onAnimationsEnabled: (Boolean) -> Unit = {},
|
||||
val onDownloadSource: (String) -> Unit = {},
|
||||
@@ -234,6 +239,11 @@ class FrontEndActions(
|
||||
val onLibraryChanged: () -> Unit = {},
|
||||
val onHomeApp: () -> Unit = {},
|
||||
val onHomeScreen: (Boolean) -> Unit = {},
|
||||
val onSteamIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature?) -> Unit = {},
|
||||
val onDismissIntegration: () -> Unit = {},
|
||||
val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {},
|
||||
val onIntegrationAppInfo: () -> Unit = {},
|
||||
val onIntegrationLocation: () -> Unit = {},
|
||||
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onRefreshPhantomStatus: () -> Unit = {},
|
||||
@@ -245,6 +255,8 @@ class FrontEndActions(
|
||||
val onCopyPhantomCommand: (Boolean) -> Unit = {},
|
||||
val onDismissPhantomGate: () -> Unit = {},
|
||||
val onStartWirelessAdbPairing: () -> Unit = {},
|
||||
val onStartPairingGuide: (Int?) -> Boolean = { false },
|
||||
val onShowPhantomGate: () -> Unit = {},
|
||||
val onOpenNotificationSettings: () -> Unit = {},
|
||||
val controller: ControllerActions? = null,
|
||||
val updates: UpdatesActions = UpdatesActions(),
|
||||
@@ -265,12 +277,6 @@ internal object Motion {
|
||||
if (scale == 0f) snap() else spring(damping, stiffness)
|
||||
}
|
||||
|
||||
internal object Ambient {
|
||||
var poked by mutableStateOf(0L)
|
||||
private set
|
||||
fun poke() { poked = android.os.SystemClock.uptimeMillis() }
|
||||
}
|
||||
|
||||
private val Shape10 = RoundedCornerShape(10.dp)
|
||||
|
||||
internal val Shape12 = RoundedCornerShape(12.dp)
|
||||
@@ -392,7 +398,12 @@ internal suspend fun focusSoon(target: () -> FocusRequester) {
|
||||
@Composable
|
||||
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
|
||||
val frontFocus = remember { FrontFocus() }
|
||||
CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) }
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
CompositionLocalProvider(
|
||||
LocalFrontFocus provides frontFocus,
|
||||
LocalNarrowPane provides (maxWidth < NarrowPaneWidth),
|
||||
) { FrontEndScreenBody(s, a, page, frontFocus) }
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@@ -406,6 +417,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
"stores:downloads" -> { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" }
|
||||
"components" -> a.onComponents(true)
|
||||
"setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" }
|
||||
"setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" }
|
||||
else -> selected = target
|
||||
}
|
||||
a.onNavigated()
|
||||
@@ -415,6 +427,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
}
|
||||
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
|
||||
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -423,9 +436,36 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
|
||||
val requestDeveloperOptions = {
|
||||
developerChoiceGuided = false
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
|
||||
if (developerChoiceGuided) a.onStartWirelessAdbPairing()
|
||||
if (!developerChoiceGuided || !a.onStartPairingGuide(displayId)) a.onOpenDeveloperOptions(displayId)
|
||||
developerChoiceGuided = false
|
||||
}
|
||||
val startGuidedPairing = {
|
||||
if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
|
||||
wirelessAdbDesiredEnabled = false
|
||||
showWirelessAdbFix = true
|
||||
} else {
|
||||
developerChoiceGuided = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
var applyingSavedPairing by remember { mutableStateOf(false) }
|
||||
val fixPhantomLimit = {
|
||||
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing()
|
||||
else if (!applyingSavedPairing) {
|
||||
applyingSavedPairing = true
|
||||
a.onSetPhantomProcessLimit(false) { error ->
|
||||
applyingSavedPairing = false
|
||||
if (error != null) startGuidedPairing()
|
||||
}
|
||||
}
|
||||
}
|
||||
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
|
||||
wirelessAdbDesiredEnabled = enabled
|
||||
showWirelessAdbFix = true
|
||||
@@ -467,6 +507,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop"
|
||||
else -> s.pageKey ?: selected
|
||||
}
|
||||
val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection)
|
||||
var railPicks by remember { mutableStateOf(0) }
|
||||
val showRailPage: (String, Boolean) -> Unit = { key, focusContent ->
|
||||
if (key == "components") a.onComponents(focusContent)
|
||||
@@ -492,11 +533,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
val window = LocalWindowInfo.current
|
||||
val androidContext = androidx.compose.ui.platform.LocalContext.current
|
||||
var anyFocused by remember { mutableStateOf(false) }
|
||||
Box(
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(
|
||||
modifier = Modifier.fillMaxSize().background(colors.background)
|
||||
.windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
|
||||
.onFocusChanged { anyFocused = it.hasFocus },
|
||||
) {
|
||||
val bottomNavigation = maxHeight > maxWidth
|
||||
LaunchedEffect(processSettingsPageVisible) {
|
||||
if (processSettingsPageVisible) return@LaunchedEffect
|
||||
snapshotFlow { window.isWindowFocused }.first { it }
|
||||
@@ -533,10 +575,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
focusWithinFrames({ frontFocus.focusedRail == null && anyFocused }) { frontFocus.paneEntry() }
|
||||
}
|
||||
val paneFocus = Modifier
|
||||
.focusProperties { enter = { frontFocus.paneEntry() } }
|
||||
.focusProperties {
|
||||
enter = { frontFocus.paneEntry() }
|
||||
exit = { direction ->
|
||||
if (bottomNavigation && direction == FocusDirection.Down) frontFocus.railFor(railSelection)
|
||||
else FocusRequester.Default
|
||||
}
|
||||
}
|
||||
.focusGroup()
|
||||
val railFocus = Modifier
|
||||
.focusProperties { enter = { frontFocus.railFor(railSelection) } }
|
||||
.focusProperties {
|
||||
enter = { frontFocus.railFor(railSelection) }
|
||||
if (bottomNavigation) up = frontFocus.paneEntry()
|
||||
}
|
||||
.focusGroup()
|
||||
LaunchedEffect(Hops.restore) {
|
||||
val r = Hops.restore ?: return@LaunchedEffect
|
||||
@@ -550,25 +601,39 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
}
|
||||
var screenAt by remember { mutableStateOf(Offset.Zero) }
|
||||
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
|
||||
Row(modifier = Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }) {
|
||||
SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
|
||||
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
|
||||
Column(modifier = Modifier.weight(1f).fillMaxHeight()) {
|
||||
LauncherLayout(
|
||||
bottomNavigation, pal.line,
|
||||
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() },
|
||||
navigation = {
|
||||
if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
|
||||
else SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
|
||||
},
|
||||
) {
|
||||
Pane(
|
||||
s, selected, a, page, Modifier.weight(1f).fillMaxWidth().then(paneFocus), { selected = it },
|
||||
s, selected, a, page,
|
||||
Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir ->
|
||||
val keys = navigationKeys(s)
|
||||
val at = keys.indexOf(railSelectionNow.value)
|
||||
if (at >= 0) keys.getOrNull(at + dir)?.let { key ->
|
||||
PageSwipe.direction = dir
|
||||
showRailPage(key, false)
|
||||
}
|
||||
},
|
||||
{ selected = it },
|
||||
onAndroidAppClick = { app ->
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
},
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onRequestWirelessAdb = requestWirelessAdbFix,
|
||||
onPairWirelessDebugging = startGuidedPairing,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
FlightsLayer(screenAt)
|
||||
GamesDialogs(a, s.steamGames)
|
||||
StoreTheme(com.droiddeck.launcher.stores.Store.XBOX) { XboxStoreDialogs() }
|
||||
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
|
||||
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
|
||||
StepsLayer(screenAt)
|
||||
@@ -595,10 +660,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
status = s.phantomProcessStatus,
|
||||
onDismiss = a.onDismissPhantomGate,
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onFixWithWirelessDebugging = {
|
||||
a.onStartWirelessAdbPairing()
|
||||
requestDeveloperOptions()
|
||||
},
|
||||
applyingSavedPairing = applyingSavedPairing,
|
||||
onFixWithWirelessDebugging = fixPhantomLimit,
|
||||
onEnterAddressManually = { requestWirelessAdbFix(false) },
|
||||
onCopyCommand = { a.onCopyPhantomCommand(false) },
|
||||
onOpenNotificationSettings = a.onOpenNotificationSettings,
|
||||
@@ -624,13 +687,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
},
|
||||
onMainScreen = {
|
||||
showDeveloperDisplayChoice = false
|
||||
a.onOpenDeveloperOptions(null)
|
||||
openDeveloperOptionsOn(null)
|
||||
},
|
||||
onSecondaryScreen = { displayId ->
|
||||
showDeveloperDisplayChoice = false
|
||||
a.onOpenDeveloperOptions(displayId)
|
||||
openDeveloperOptionsOn(displayId)
|
||||
},
|
||||
onDismiss = {
|
||||
showDeveloperDisplayChoice = false
|
||||
developerChoiceGuided = false
|
||||
},
|
||||
onDismiss = { showDeveloperDisplayChoice = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ private const val LAUNCHER_TAB = 2
|
||||
|
||||
internal object SetupTabs {
|
||||
var openLauncher = false
|
||||
var openOverview = false
|
||||
}
|
||||
private const val GLASSES_TAB = 5
|
||||
|
||||
@@ -140,6 +141,7 @@ internal fun SetupPanel(
|
||||
a: FrontEndActions,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
onPairWirelessDebugging: () -> Unit,
|
||||
) {
|
||||
val host = rememberMenuHost()
|
||||
val ctx = LocalContext.current
|
||||
@@ -191,6 +193,7 @@ internal fun SetupPanel(
|
||||
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
|
||||
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
|
||||
SetupTabs.openLauncher = false
|
||||
if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false }
|
||||
val chipFocus = remember { List(tabs.size) { FocusRequester() } }
|
||||
var tabTurned by remember { mutableStateOf(false) }
|
||||
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
|
||||
@@ -201,6 +204,12 @@ internal fun SetupPanel(
|
||||
tab = STORAGE_TAB
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
kotlinx.coroutines.delay(2_000)
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(tab) {
|
||||
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
@@ -277,7 +286,7 @@ internal fun SetupPanel(
|
||||
},
|
||||
divider = divider && !showLimitDetails,
|
||||
) {
|
||||
if (limitBlocks) PrimaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_fix_it), compact = true) { showLimitDetails = !showLimitDetails }
|
||||
if (limitBlocks) PrimaryButton(stringResource(R.string.setup_fix_it), compact = true, onClick = a.onShowPhantomGate)
|
||||
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
|
||||
SecondaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true) { showLimitDetails = !showLimitDetails }
|
||||
}
|
||||
@@ -290,11 +299,7 @@ internal fun SetupPanel(
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
|
||||
)
|
||||
Actions {
|
||||
if (limitBlocks) {
|
||||
PrimaryButton(stringResource(R.string.setup_dev_options), compact = true, onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton(stringResource(R.string.setup_use_wireless), compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
|
||||
SecondaryButton(stringResource(R.string.setup_check_again), compact = true, onClick = a.onRefreshPhantomStatus)
|
||||
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
|
||||
if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
|
||||
SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
|
||||
}
|
||||
}
|
||||
@@ -341,6 +346,7 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.setup_runtime)) { runtimeCheck(false) }
|
||||
SteamIntegrationGroup(s.integration, s.integrationFocus, a.onIntegration, a.onIntegrationAppInfo, a.onIntegrationLocation)
|
||||
}
|
||||
1 -> {
|
||||
val controller = s.controller
|
||||
@@ -398,7 +404,12 @@ internal fun SetupPanel(
|
||||
ActionRow(stringResource(R.string.setup_default_home), s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp)
|
||||
}
|
||||
ChoiceRow(
|
||||
host, "orientation", stringResource(R.string.setup_orientation), null,
|
||||
host, "launcher-orientation", stringResource(R.string.setup_launcher_orientation), null,
|
||||
com.droiddeck.launcher.core.AppUiPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
|
||||
s.launcherOrientation, onPick = a.onLauncherOrientation,
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint),
|
||||
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
|
||||
s.orientation, onPick = a.onOrientation,
|
||||
)
|
||||
@@ -501,7 +512,7 @@ internal fun SetupPanel(
|
||||
)
|
||||
if (!s.adbPaired) ActionRow(
|
||||
stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint),
|
||||
stringResource(R.string.setup_adb_pair_button), { onRequestWirelessAdb(false) },
|
||||
stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +186,7 @@ internal fun PrimaryButton(
|
||||
.clip(Shape12)
|
||||
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
|
||||
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12))
|
||||
.then(if (hot) Modifier.border(2.dp, pal.signal, Shape12) else Modifier)
|
||||
.glideBorder(hot, Shape12, pal.signal, hotFillAlpha = 0f)
|
||||
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) {
|
||||
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
|
||||
onClick()
|
||||
|
||||
@@ -56,6 +56,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
@@ -86,6 +87,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
@@ -217,6 +219,9 @@ internal fun GameDetail(
|
||||
}
|
||||
}
|
||||
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
|
||||
if (!s.shortcutPicker) Rise(2) {
|
||||
GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game, Modifier.padding(top = 6.dp))
|
||||
}
|
||||
if (tab != null) Rise(2) {
|
||||
Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
val labels = tabs.map { t ->
|
||||
@@ -267,13 +272,15 @@ private fun GameHero(
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.55f to colors.background.copy(alpha = 0.58f), 1f to Color.Transparent)))
|
||||
var scoresWidth by remember { mutableStateOf(0) }
|
||||
if (scores != null) {
|
||||
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0.45f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
|
||||
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp))
|
||||
HeroScores(scores, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 18.dp).onSizeChanged { scoresWidth = it.width })
|
||||
}
|
||||
val scoresSpace = with(LocalDensity.current) { if (scores != null && scoresWidth > 0) scoresWidth.toDp() + 16.dp else 0.dp }
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp),
|
||||
modifier = Modifier.align(Alignment.BottomStart).padding(start = 22.dp, end = 22.dp + scoresSpace, top = 18.dp, bottom = 18.dp),
|
||||
content = content,
|
||||
)
|
||||
Box(Modifier.align(Alignment.TopEnd).padding(12.dp), content = corner)
|
||||
@@ -319,7 +326,7 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameActions(
|
||||
internal fun GameActions(
|
||||
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
|
||||
s: FrontEndState, a: FrontEndActions, leadOn: Modifier,
|
||||
) {
|
||||
@@ -328,22 +335,14 @@ private fun GameActions(
|
||||
val rawDownload = storeKey?.let { StoresState.download(it) }
|
||||
val download = rawDownload?.takeIf { it.isActive }
|
||||
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
|
||||
val cloud = game?.library == Library.XBOX_CLOUD && installed == null
|
||||
Actions {
|
||||
when {
|
||||
s.shortcutPicker && game != null -> {
|
||||
PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
|
||||
FileButtons(game, a)
|
||||
}
|
||||
game?.library == Library.XBOX_CLOUD -> {
|
||||
val cloudId = game.storeId.orEmpty()
|
||||
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
|
||||
if (download != null) ActionChip(downloadLabel(download), ok = false)
|
||||
else if (item?.installable == true) SecondaryButton(
|
||||
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
|
||||
) { StoresState.requestInstall(ctx, item) }
|
||||
XboxLibraryButton(cloudId, item)
|
||||
}
|
||||
game != null || installed != null -> {
|
||||
!cloud && (game != null || installed != null) -> {
|
||||
val gone = storeKey?.let { StoresState.uninstalling[it] }
|
||||
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
|
||||
PrimaryButton(
|
||||
@@ -366,7 +365,19 @@ private fun GameActions(
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
|
||||
}
|
||||
if (store == Store.BATTLENET) SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
if (store == Store.BATTLENET) {
|
||||
if (installed != null && id != null) {
|
||||
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
|
||||
if (download != null) {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
|
||||
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
|
||||
} else if (BattleNetInstall.updates[id] == true) {
|
||||
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
|
||||
}
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
}
|
||||
}
|
||||
download != null -> {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
@@ -381,6 +392,19 @@ private fun GameActions(
|
||||
}
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
|
||||
}
|
||||
cloud -> {
|
||||
val cloudId = game.storeId.orEmpty()
|
||||
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
|
||||
if (item?.installable == true && item.xboxPc) {
|
||||
SecondaryButton(
|
||||
if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install)
|
||||
else if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes))
|
||||
else stringResource(R.string.stores_install),
|
||||
) { StoresState.requestInstall(ctx, item) }
|
||||
}
|
||||
if (item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
XboxLibraryButton(cloudId, item)
|
||||
}
|
||||
store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> {
|
||||
XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
|
||||
@@ -408,6 +432,10 @@ private fun GameActions(
|
||||
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
|
||||
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
if (cloud && (download != null || failed != null)) {
|
||||
XboxStreamButton(game.storeId.orEmpty(), game.name)
|
||||
XboxLibraryButton(game.storeId.orEmpty(), item)
|
||||
}
|
||||
BusyChip(s)
|
||||
}
|
||||
}
|
||||
@@ -525,7 +553,7 @@ private fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, la
|
||||
private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id) return
|
||||
if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id && installed?.sidecar?.id?.let(BattleNetInstall::product) == null) return
|
||||
if (installed != null) {
|
||||
val key = installed.key
|
||||
val gone = StoresState.uninstalling[key]
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal data class GameResource(@StringRes val label: Int, val url: String, @StringRes val detail: Int? = null)
|
||||
|
||||
internal fun gameResources(title: String, game: Library.SteamGame?): List<GameResource> {
|
||||
if (title.isBlank()) return emptyList()
|
||||
val query = URLEncoder.encode(title.trim(), "UTF-8").replace("+", "%20")
|
||||
val steamId = game?.takeIf { Library.fromSteamClient(it) && it.appId > 0 }?.appId
|
||||
return buildList {
|
||||
add(GameResource(R.string.game_resource_pcgw, "https://www.pcgamingwiki.com/w/index.php?search=$query"))
|
||||
add(GameResource(R.string.game_resource_guides, "https://gamefaqs.gamespot.com/search?game=$query"))
|
||||
if (steamId != null) {
|
||||
add(GameResource(R.string.game_resource_protondb, "https://www.protondb.com/app/$steamId", R.string.game_resource_protondb_detail))
|
||||
add(GameResource(R.string.game_resource_steam_cloud, "https://store.steampowered.com/account/remotestorageapp/?appid=$steamId", R.string.game_resource_steam_cloud_detail))
|
||||
}
|
||||
add(GameResource(R.string.game_resource_search, "https://www.google.com/search?q=$query"))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) {
|
||||
val links = remember(title, game) { gameResources(title, game) }
|
||||
if (links.isEmpty()) return
|
||||
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
links.forEach { ResourceLink(it) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ResourceLink(link: GameResource) {
|
||||
val ctx = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(source)
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
val label = stringResource(link.label)
|
||||
val description = listOfNotNull(label, link.detail?.let { stringResource(it) }, stringResource(R.string.game_resources_browser)).joinToString(". ")
|
||||
val open = { openUrl(ctx, link.url) }
|
||||
val tint = if (hot) pal.signal else pal.onSurfaceVariant
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.08f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal, restColor = Color.Transparent)
|
||||
.semantics { contentDescription = description }
|
||||
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open).padding(horizontal = 8.dp),
|
||||
) {
|
||||
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = tint, maxLines = 1)
|
||||
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp))
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ object GamepadGeometry {
|
||||
LEFT_OUTER_SHOULDER, LEFT_INNER_SHOULDER, RIGHT_INNER_SHOULDER, RIGHT_OUTER_SHOULDER,
|
||||
VIEW, STEAM, QAM, MENU,
|
||||
PANELS,
|
||||
L4, L5, R5, R4,
|
||||
}
|
||||
|
||||
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
|
||||
@@ -25,8 +26,11 @@ object GamepadGeometry {
|
||||
|
||||
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
|
||||
|
||||
fun layout(w: Float, h: Float, density: Float): Map<Slot, Box> {
|
||||
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> {
|
||||
if (w <= 0f || h <= 0f) return emptyMap()
|
||||
if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) {
|
||||
return portraitLayout(w, h, density)
|
||||
}
|
||||
val pad = 8 * density
|
||||
val buttonH = 40 * density
|
||||
val rowButton = 64 * density
|
||||
@@ -67,7 +71,7 @@ object GamepadGeometry {
|
||||
}
|
||||
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
|
||||
} else {
|
||||
val side = min(w * 0.5f, h * 0.70f)
|
||||
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
|
||||
val main = side * 0.62f
|
||||
val second = side * 0.46f
|
||||
val secondCy = h - side * 0.97f
|
||||
@@ -87,4 +91,39 @@ object GamepadGeometry {
|
||||
}
|
||||
return boxes
|
||||
}
|
||||
|
||||
private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> {
|
||||
val pad = 8 * density
|
||||
val gap = 8 * density
|
||||
val buttonH = 44 * density
|
||||
val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f))
|
||||
val main = w * 0.4f * scale
|
||||
val second = w * 0.3f * scale
|
||||
val mainY = h - pad - main / 2f
|
||||
val secondY = mainY - main / 2f - gap - second / 2f
|
||||
val shoulderY = secondY - second / 2f - gap - buttonH / 2f
|
||||
val boxes = linkedMapOf(
|
||||
Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main),
|
||||
Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main),
|
||||
Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second),
|
||||
Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second),
|
||||
)
|
||||
val utilityW = (w - 2 * pad - 3 * gap) / 4f
|
||||
for ((i, slot) in middle.withIndex()) {
|
||||
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH)
|
||||
}
|
||||
val gripTop = pad + buttonH + gap
|
||||
val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop)
|
||||
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
|
||||
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH)
|
||||
}
|
||||
val panelsW = min(112 * density, w * 0.22f)
|
||||
val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f
|
||||
boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
|
||||
boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH)
|
||||
boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH)
|
||||
return boxes
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -32,8 +34,8 @@ internal fun GlassesCalibrationControls(
|
||||
onDismissRequest = { reset = false },
|
||||
title = { Text(stringResource(R.string.glasses_calibration_reset)) },
|
||||
text = { Text(stringResource(R.string.glasses_calibration_reset_hint)) },
|
||||
confirmButton = { TextButton(onClick = { onReset(); reset = false }) { Text(stringResource(R.string.glasses_calibration_reset_button)) } },
|
||||
dismissButton = { TextButton(onClick = { reset = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { TextButton(onClick = { onReset(); reset = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.glasses_calibration_reset_button)) } },
|
||||
dismissButton = { TextButton(onClick = { reset = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
if (shown) AlertDialog(
|
||||
onDismissRequest = { onCancel(); shown = false },
|
||||
@@ -57,8 +59,8 @@ internal fun GlassesCalibrationControls(
|
||||
if (!state.running) TextButton(onClick = {
|
||||
if (state.phase == CalibrationPhase.SAVED) { onDone(); onCancel(); shown = false }
|
||||
else onStart()
|
||||
}) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(if (state.phase == CalibrationPhase.SAVED) R.string.glasses_calibration_done else R.string.glasses_calibration_start)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { onCancel(); shown = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = { onCancel(); shown = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -347,6 +347,7 @@ internal fun GlassesCornerButton(slot: Int, tint: Int, opacity: Int, onClick: ()
|
||||
.clip(CircleShape)
|
||||
.background(fill)
|
||||
.border(1.5.dp, line, CircleShape)
|
||||
.focusGlide(CircleShape)
|
||||
.clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick)
|
||||
.testTag("glasses-button"),
|
||||
) {
|
||||
@@ -382,6 +383,7 @@ private fun GlassesRecenterAction(label: String, tag: String, tint: Int, opacity
|
||||
.clip(shape)
|
||||
.background(fill)
|
||||
.border(1.5.dp, line, shape)
|
||||
.focusGlide(shape)
|
||||
.clickable(interactionSource = source, indication = null, role = Role.Button, onClick = onClick)
|
||||
.padding(horizontal = 18.dp)
|
||||
.testTag(tag),
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AlertDialogDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpOffset
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupPositionProvider
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
|
||||
@Composable
|
||||
internal fun GlideDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Dialog(onDismissRequest, properties) { FocusGlideHost(content = content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GlidePopup(
|
||||
popupPositionProvider: PopupPositionProvider,
|
||||
onDismissRequest: (() -> Unit)? = null,
|
||||
properties: PopupProperties = PopupProperties(),
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Popup(popupPositionProvider, onDismissRequest, properties) { FocusGlideHost(content = content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GlideAlertDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
confirmButton: @Composable () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
dismissButton: (@Composable () -> Unit)? = null,
|
||||
icon: (@Composable () -> Unit)? = null,
|
||||
title: (@Composable () -> Unit)? = null,
|
||||
text: (@Composable () -> Unit)? = null,
|
||||
shape: Shape = AlertDialogDefaults.shape,
|
||||
containerColor: Color = AlertDialogDefaults.containerColor,
|
||||
iconContentColor: Color = AlertDialogDefaults.iconContentColor,
|
||||
titleContentColor: Color = AlertDialogDefaults.titleContentColor,
|
||||
textContentColor: Color = AlertDialogDefaults.textContentColor,
|
||||
tonalElevation: Dp = AlertDialogDefaults.TonalElevation,
|
||||
properties: DialogProperties = DialogProperties(),
|
||||
) {
|
||||
FocusGlideWindow { overlay ->
|
||||
AlertDialog(
|
||||
onDismissRequest, confirmButton, modifier.then(overlay), dismissButton, icon, title, text,
|
||||
shape, containerColor, iconContentColor, titleContentColor, textContentColor, tonalElevation, properties,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GlideDropdownMenu(
|
||||
expanded: Boolean,
|
||||
onDismissRequest: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
offset: DpOffset = DpOffset.Zero,
|
||||
scrollState: ScrollState = rememberScrollState(),
|
||||
properties: PopupProperties = PopupProperties(focusable = true),
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
FocusGlideWindow { overlay ->
|
||||
DropdownMenu(expanded, onDismissRequest, modifier.then(overlay), offset, scrollState, properties, content)
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.Memory
|
||||
import androidx.compose.material.icons.outlined.Tune
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
@@ -28,7 +29,7 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.RadioButton
|
||||
@@ -63,7 +64,7 @@ import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.droiddeck.launcher.ui.GlideDialog as Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
@@ -129,7 +130,7 @@ internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, on
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))
|
||||
.selectable(side == id, role = Role.RadioButton) { side = id }
|
||||
.focusGlide(RoundedCornerShape(8.dp)).selectable(side == id, role = Role.RadioButton) { side = id }
|
||||
.testTag("hand-camera-$id")
|
||||
.padding(vertical = 4.dp),
|
||||
) {
|
||||
@@ -144,12 +145,12 @@ internal fun HandCameraPrompt(sides: Set<String>, onAllow: (String?) -> Unit, on
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow")) {
|
||||
TextButton(onClick = { onAllow(if (choose) side else null) }, modifier = Modifier.testTag("hand-camera-allow").focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.hand_camera_allow))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now")) { Text(stringResource(R.string.hand_camera_not_now)) }
|
||||
TextButton(onClick = onNotNow, modifier = Modifier.testTag("hand-camera-not-now").focusGlide(CircleShape)) { Text(stringResource(R.string.hand_camera_not_now)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -9,7 +10,7 @@ import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -91,7 +92,7 @@ internal fun ItchKeyDialog(onDismiss: () -> Unit) {
|
||||
Row(horizontalArrangement = Arrangement.Start) {
|
||||
TextButton(onClick = {
|
||||
ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ItchApi.KEYS_PAGE)))
|
||||
}) { Text(stringResource(R.string.stores_itch_get_key)) }
|
||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.stores_itch_get_key)) }
|
||||
}
|
||||
if (rejected) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
@@ -104,12 +105,12 @@ internal fun ItchKeyDialog(onDismiss: () -> Unit) {
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = key.isNotBlank() && !busy, onClick = { submit() }) {
|
||||
TextButton(enabled = key.isNotBlank() && !busy, onClick = { submit() }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.game_env_save))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(enabled = !busy, onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
|
||||
TextButton(enabled = !busy, onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -2,6 +2,12 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.Layout
|
||||
import androidx.compose.ui.unit.Constraints
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@@ -13,3 +19,38 @@ val LocalNarrowPane = compositionLocalOf { false }
|
||||
@Composable
|
||||
internal fun isNarrowScreen(): Boolean = LocalConfiguration.current.screenWidthDp < 600
|
||||
|
||||
@Composable
|
||||
internal fun LauncherLayout(
|
||||
bottomNavigation: Boolean, divider: Color, modifier: Modifier = Modifier,
|
||||
navigation: @Composable () -> Unit, content: @Composable () -> Unit,
|
||||
) {
|
||||
Layout(modifier = modifier, content = {
|
||||
Box { content() }
|
||||
Box(Modifier.background(divider))
|
||||
Box { navigation() }
|
||||
}) { children, constraints ->
|
||||
val width = constraints.maxWidth
|
||||
val height = constraints.maxHeight
|
||||
val line = 1.dp.roundToPx()
|
||||
val nav = children[2].measure(Constraints(
|
||||
minWidth = if (bottomNavigation) width else 0, maxWidth = width,
|
||||
minHeight = if (bottomNavigation) 0 else height, maxHeight = height,
|
||||
))
|
||||
val contentWidth = if (bottomNavigation) width else (width - nav.width - line).coerceAtLeast(0)
|
||||
val contentHeight = if (bottomNavigation) (height - nav.height - line).coerceAtLeast(0) else height
|
||||
val pane = children[0].measure(Constraints.fixed(contentWidth, contentHeight))
|
||||
val edge = children[1].measure(Constraints.fixed(if (bottomNavigation) width else line, if (bottomNavigation) line else height))
|
||||
layout(width, height) {
|
||||
if (bottomNavigation) {
|
||||
pane.placeRelative(0, 0)
|
||||
edge.placeRelative(0, contentHeight)
|
||||
nav.placeRelative(0, contentHeight + line)
|
||||
} else {
|
||||
nav.placeRelative(0, 0)
|
||||
edge.placeRelative(nav.width, 0)
|
||||
pane.placeRelative(nav.width + line, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.FilterList
|
||||
import androidx.compose.material.icons.filled.FilterAlt
|
||||
import androidx.compose.material.icons.filled.GridView
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Sort
|
||||
@@ -86,8 +86,11 @@ import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.arrangeStoreTabs
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollection
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollections
|
||||
import com.droiddeck.launcher.stores.retainOrder
|
||||
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
|
||||
import com.droiddeck.launcher.stores.sortGames
|
||||
@@ -108,12 +111,16 @@ internal fun libraryEntries(
|
||||
): List<LibraryEntry> {
|
||||
val claimed = HashSet<String>()
|
||||
val out = ArrayList<LibraryEntry>()
|
||||
for (g in games) {
|
||||
for (g in games.sortedBy { it.library == Library.XBOX_CLOUD }) {
|
||||
if (g.library == Library.EPIC_LAUNCHER) continue
|
||||
val storeKey = g.storeId?.let { "${g.source}:$it" }
|
||||
val item = storeKey?.let { k -> Store.byId(g.source)?.let { st -> owned[st]?.firstOrNull { it.key == k } } }
|
||||
if (storeKey != null) claimed += storeKey
|
||||
out += LibraryEntry(GameRef.key(g), g.source, g.name, g, item, installed = true)
|
||||
if (storeKey != null) {
|
||||
if (g.library == Library.XBOX_CLOUD && storeKey in claimed) continue
|
||||
claimed.add(storeKey)
|
||||
}
|
||||
out += LibraryEntry(GameRef.key(g), g.source, g.name, g, item,
|
||||
installed = g.library != Library.XBOX_CLOUD || storeKey in installedStore)
|
||||
}
|
||||
for (store in Store.entries) for (item in owned[store].orEmpty()) {
|
||||
if (!claimed.add(item.key)) continue
|
||||
@@ -122,18 +129,32 @@ internal fun libraryEntries(
|
||||
return out.distinctBy { it.key }
|
||||
}
|
||||
|
||||
internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>): List<LibraryEntry> {
|
||||
val keys = items.map { it.key }.toSet()
|
||||
val itch = all.filter { it.source == Store.ITCH.id }
|
||||
val have = itch.mapNotNull { it.storeKey }.toSet()
|
||||
return itch.filter { it.storeKey in keys } +
|
||||
items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), Store.ITCH.id, it.title, null, it, false) }
|
||||
}
|
||||
|
||||
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
|
||||
|
||||
internal const val LIBRARY_ALL = "all"
|
||||
internal val LIBRARY_SOURCES = listOf(Library.SOURCE_STEAM) + Store.entries.map { it.id } + Library.ADDED
|
||||
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>): List<String> =
|
||||
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED)
|
||||
.filter { source -> entries.any { it.source == source } }
|
||||
|
||||
/** Survives leaving the page, so Stores can open the Library on one store's owned games. */
|
||||
internal object LibraryView {
|
||||
var source by mutableStateOf(LIBRARY_ALL)
|
||||
var query by mutableStateOf("")
|
||||
var focusFirst = false
|
||||
var ownedRequest by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
fun showOwned(store: Store) {
|
||||
fun showOwned(context: android.content.Context, store: Store) {
|
||||
SessionPrefs.setLibraryShowUninstalled(context, true)
|
||||
ownedRequest++
|
||||
source = store.id
|
||||
query = ""
|
||||
focusFirst = true
|
||||
@@ -157,13 +178,31 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
val cloudRows = rememberXboxCloudRows(s)
|
||||
val all = remember(s.steamGames, cloudRows, owned, installedStore) { libraryEntries(s.steamGames + cloudRows, owned, installedStore) }
|
||||
LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) }
|
||||
val sources = LIBRARY_SOURCES.filter { src -> all.any { it.source == src } }
|
||||
var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) }
|
||||
var collectionShows by remember { mutableStateOf<Pair<String, Boolean>?>(null) }
|
||||
val setShowUninstalled = { show: Boolean ->
|
||||
val picked = ItchCollections.selected.takeIf { LibraryView.source == Store.ITCH.id }
|
||||
if (picked != null) collectionShows = picked to show
|
||||
else {
|
||||
showUninstalled = show
|
||||
SessionPrefs.setLibraryShowUninstalled(ctx, show)
|
||||
}
|
||||
}
|
||||
val itchSignedIn = owned.containsKey(Store.ITCH)
|
||||
val listed = librarySources(all, SessionPrefs.storesTabOrder(ctx))
|
||||
val sources = if (itchSignedIn && Store.ITCH.id !in listed) listed + Store.ITCH.id else listed
|
||||
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
|
||||
val q = LibraryView.query.trim().lowercase()
|
||||
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
|
||||
val candidates = all.filter {
|
||||
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) ItchCollections.load(ctx) }
|
||||
val collection = if (source == Store.ITCH.id) ItchCollections.chosen() else null
|
||||
val pool = if (collection == null) all else collectionEntries(all, ItchCollections.gamesOf(collection.id).orEmpty())
|
||||
val matching = pool.filter {
|
||||
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
|
||||
}
|
||||
val listUninstalled = if (collection == null) showUninstalled else collectionShows?.takeIf { it.first == collection.id }?.second ?: true
|
||||
val candidates = if (listUninstalled) matching else matching.filter { it.installed }
|
||||
val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed }
|
||||
val sort = s.storesSort
|
||||
val sizeSort = sort == "sizeAsc" || sort == "sizeDesc"
|
||||
val installedAt = StoresState.installed.associate { it.key to it.sidecar.installedAt }
|
||||
@@ -246,7 +285,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
kotlinx.coroutines.delay(Motion.ms(240).toLong())
|
||||
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
|
||||
}
|
||||
if (all.isEmpty() && open == null) {
|
||||
if (all.isEmpty() && open == null && !itchSignedIn) {
|
||||
LibraryEmpty(s, a, modifier)
|
||||
return
|
||||
}
|
||||
@@ -254,7 +293,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
val detailScroll = rememberScrollState()
|
||||
var cycled by remember { mutableIntStateOf(0) }
|
||||
var gridFocused by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(source, sort) { grid.scrollToItem(0) }
|
||||
LaunchedEffect(source, sort, listUninstalled) { grid.scrollToItem(0) }
|
||||
LaunchedEffect(cycled) {
|
||||
if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
|
||||
focusWithinFrames({ gridFocused }) {
|
||||
@@ -265,11 +304,13 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
open, detailScroll,
|
||||
gridScrolled = { grid.firstVisibleItemIndex > 0 || grid.firstVisibleItemScrollOffset > 0 },
|
||||
onDetailFocus = { detailFocused = it },
|
||||
modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp),
|
||||
modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp),
|
||||
wrap = { key, content -> StoreTheme(GameRef.parse(key).let { r -> r.store ?: r.game(s.steamGames)?.source?.let { Store.byId(it) } }) { content() } },
|
||||
grid = {
|
||||
LibraryGrid(
|
||||
s, a, grid, visible, split, all.size, sources, source, sizesPending, syncing,
|
||||
s, a, grid, visible, split, visible.size, sources, source, sizesPending, syncing,
|
||||
showUninstalled = listUninstalled.takeIf { stores }, onShowUninstalled = setShowUninstalled,
|
||||
hiddenUninstalled = hiddenUninstalled,
|
||||
onSource = { LibraryView.source = it },
|
||||
onCycle = { step ->
|
||||
val ids = listOf(LIBRARY_ALL) + sources
|
||||
@@ -308,6 +349,7 @@ private fun LibraryEmpty(s: FrontEndState, a: FrontEndActions, modifier: Modifie
|
||||
private fun LibraryGrid(
|
||||
s: FrontEndState, a: FrontEndActions, grid: LazyGridState, visible: List<LibraryEntry>, split: Int, total: Int,
|
||||
sources: List<String>, source: String, sizesPending: Boolean, syncing: List<Pair<Store, String>>,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, hiddenUninstalled: Int,
|
||||
onSource: (String) -> Unit, onCycle: (Int) -> Unit, onOpen: (String) -> Unit, onFocus: (Boolean) -> Unit, searchCleared: Boolean,
|
||||
) {
|
||||
val listMode = s.storesView == "list"
|
||||
@@ -361,7 +403,9 @@ private fun LibraryGrid(
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
item(key = "header", span = { GridItemSpan(maxLineSpan) }) { Rise(0) { LibraryHeader(s, a, total, searchCleared, xbox = source == Store.XBOX.id) } }
|
||||
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = source == Store.ITCH.id) }
|
||||
}
|
||||
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(1) { LibraryFilters(sources, source, onSource) }
|
||||
}
|
||||
@@ -379,7 +423,13 @@ private fun LibraryGrid(
|
||||
}
|
||||
}
|
||||
val empty = R.string.stores_nothing_matches
|
||||
if (split == 0) libraryGrid(visible, empty, tile)
|
||||
if (visible.isEmpty() && hiddenUninstalled > 0) item(key = "browse-owned", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp)) {
|
||||
Text(stringResource(R.string.library_no_installed_matches), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
SecondaryButton(stringResource(R.string.library_browse_owned), modifier = Modifier.testTag("library-browse-owned")) { onShowUninstalled(true) }
|
||||
}
|
||||
}
|
||||
else if (split == 0) libraryGrid(visible, empty, tile)
|
||||
else {
|
||||
item(key = "installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_installed)) }
|
||||
libraryGrid(visible.take(split), empty, tile)
|
||||
@@ -399,7 +449,10 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LibraryHeader(s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean) {
|
||||
private fun LibraryHeader(
|
||||
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Boolean,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
ModeHeader(
|
||||
@@ -414,7 +467,8 @@ private fun LibraryHeader(s: FrontEndState, a: FrontEndActions, total: Int, sear
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (xbox) XboxFilterButton()
|
||||
if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
|
||||
if (collections) CollectionsButton()
|
||||
SortButton(s, a)
|
||||
ViewButton(s, a)
|
||||
GameFileFolderActions(s, a)
|
||||
@@ -428,7 +482,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
|
||||
if (sources.size < 2) return
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(top = 4.dp, bottom = 2.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp).horizontalScroll(rememberScrollState()),
|
||||
) {
|
||||
SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) }
|
||||
for (src in sources) {
|
||||
@@ -506,18 +560,31 @@ private fun LibraryTile(e: LibraryEntry, capsule: Boolean, first: Boolean, navig
|
||||
@Composable
|
||||
private fun RequestSize(e: LibraryEntry) {
|
||||
val ctx = LocalContext.current
|
||||
if (e.installed) {
|
||||
val inst = e.storeKey?.let { k -> StoresState.installed.firstOrNull { it.key == k } }
|
||||
LaunchedEffect(e.key, inst) {
|
||||
if (inst != null) StoreSizes.requestDisk(ctx, inst.key, inst)
|
||||
else e.game?.gameFiles?.let { FolderSizes.request(it) }
|
||||
}
|
||||
return
|
||||
}
|
||||
val item = e.item?.takeIf { !e.installed && it.accessible && it.sizeBytes <= 0 } ?: return
|
||||
LaunchedEffect(item.key) { StoreSizes.request(ctx, item) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
|
||||
internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
|
||||
val pal = LocalPalette.current
|
||||
val size = if (e.installed) e.storeKey?.let { StoreSizes.onDisk[it] }
|
||||
?: e.game?.gameFiles?.let { FolderSizes.known[it.path] }
|
||||
else e.item?.let { StoreSizes.size(it) }?.takeIf { it > 0 }
|
||||
when {
|
||||
download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
e.installed -> Unit
|
||||
e.item != null && StoresState.isUnfinished(e.item) -> Text(stringResource(R.string.stores_resume), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
else -> Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
if (size != null && size > 0) Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
|
||||
if (!e.installed) Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -571,7 +638,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) {
|
||||
internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
@@ -588,7 +655,7 @@ private fun HeaderIconButton(description: String, icon: androidx.compose.ui.grap
|
||||
|
||||
/** Choosing Library in the rail lands on the first game, as Play Steam does on the Steam page. */
|
||||
@Composable
|
||||
private fun Modifier.paneEntry(): Modifier {
|
||||
internal fun Modifier.paneEntry(): Modifier {
|
||||
val ff = LocalFrontFocus.current ?: return this
|
||||
androidx.compose.runtime.DisposableEffect(ff) {
|
||||
ff.primaryAttached++
|
||||
@@ -599,7 +666,7 @@ private fun Modifier.paneEntry(): Modifier {
|
||||
|
||||
internal fun keepsXbox(filter: String, e: LibraryEntry): Boolean = when {
|
||||
filter == XboxLibraryFilter.ALL || e.source != Store.XBOX.id -> true
|
||||
e.game?.library == Library.XBOX_CLOUD -> filter == XboxLibraryFilter.CLOUD
|
||||
e.game?.library == Library.XBOX_CLOUD && e.item == null -> filter == XboxLibraryFilter.CLOUD
|
||||
else -> e.item?.let { XboxLibraryFilter.keeps(filter, it) } == true
|
||||
}
|
||||
|
||||
@@ -612,24 +679,38 @@ private fun xboxFilterLabel(filter: String): String = when (filter) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun XboxFilterButton() {
|
||||
private fun LibraryFilterButton(showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, xbox: Boolean) {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val title = stringResource(R.string.xbox_filter_show)
|
||||
val title = stringResource(R.string.library_filter)
|
||||
val visibility = stringResource(if (showUninstalled == true) R.string.library_filter_all_owned else R.string.library_filter_installed)
|
||||
val description = title + " · " + if (showUninstalled == null) xboxFilterLabel(XboxLibraryFilter.current) else visibility
|
||||
val offset = if (showUninstalled == null) 0 else 2
|
||||
var at by remember { mutableStateOf<Rect?>(null) }
|
||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
||||
HeaderIconButton(title + " · " + xboxFilterLabel(XboxLibraryFilter.current), Icons.Filled.FilterList, "xbox-filter") {
|
||||
HeaderIconButton(description, Icons.Filled.FilterAlt, "library-filter") {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = XboxLibraryFilter.ALL_FILTERS.size,
|
||||
handle = { Text(title, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = offset + if (xbox) XboxLibraryFilter.ALL_FILTERS.size else 0,
|
||||
handle = { Icon(Icons.Filled.FilterAlt, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
XboxLibraryFilter.ALL_FILTERS.forEachIndexed { i, filter ->
|
||||
if (showUninstalled != null) listOf(false, true).forEachIndexed { i, show ->
|
||||
StepChoice(
|
||||
stringResource(if (show) R.string.library_filter_all_owned else R.string.library_filter_installed),
|
||||
selected = show == showUninstalled, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (show == showUninstalled) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
onShowUninstalled(show)
|
||||
Steps.fold()
|
||||
}
|
||||
}
|
||||
if (xbox && showUninstalled != null) Text(Store.XBOX.shortLabel, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.stepItem(offset).padding(start = 4.dp, top = 10.dp, bottom = 4.dp))
|
||||
if (xbox) XboxLibraryFilter.ALL_FILTERS.forEachIndexed { i, filter ->
|
||||
StepChoice(
|
||||
xboxFilterLabel(filter), selected = filter == XboxLibraryFilter.current, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (filter == XboxLibraryFilter.current) Modifier.focusRequester(first) else Modifier),
|
||||
modifier = Modifier.fillMaxWidth().stepItem(offset + i).then(if (showUninstalled == null && filter == XboxLibraryFilter.current) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
XboxLibraryFilter.set(ctx, filter)
|
||||
Steps.fold()
|
||||
@@ -641,6 +722,39 @@ private fun XboxFilterButton() {
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CollectionsButton() {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val title = stringResource(R.string.itch_collections)
|
||||
val all = stringResource(R.string.stores_tab_all)
|
||||
var at by remember { mutableStateOf<Rect?>(null) }
|
||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
||||
HeaderIconButton(title + " · " + (ItchCollections.chosen()?.title ?: all), CollectionsIcon, "itch-collections") {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
val choices = listOf<ItchCollection?>(null) + ItchCollections.list
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = choices.size,
|
||||
handle = { Icon(CollectionsIcon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
choices.forEachIndexed { i, c ->
|
||||
val picked = c?.id == ItchCollections.selected
|
||||
StepChoice(
|
||||
c?.let { it.title + " (" + it.count + ")" } ?: all, selected = picked, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (picked) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
ItchCollections.select(ctx, c?.id)
|
||||
Steps.fold()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SortButton(s: FrontEndState, a: FrontEndActions) {
|
||||
val pal = LocalPalette.current
|
||||
@@ -651,7 +765,7 @@ private fun SortButton(s: FrontEndState, a: FrontEndActions) {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = SessionPrefs.STORES_SORTS.size,
|
||||
handle = { Text(title, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
handle = { Icon(Icons.Filled.Sort, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
|
||||
@@ -641,7 +641,11 @@ internal fun LiftHero(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun handleBob(): Float {
|
||||
internal fun Handle(height: Dp, above: Boolean = false) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = if (above) RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) else RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)
|
||||
val still = Motion.scale == 0f
|
||||
val bob = androidx.compose.animation.core.rememberInfiniteTransition(label = "handle")
|
||||
val lift by bob.animateFloat(
|
||||
0f, 0f,
|
||||
@@ -656,16 +660,6 @@ private fun handleBob(): Float {
|
||||
),
|
||||
label = "handleBob",
|
||||
)
|
||||
return lift
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Handle(height: Dp, above: Boolean = false) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = if (above) RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp) else RoundedCornerShape(bottomStart = 12.dp, bottomEnd = 12.dp)
|
||||
val still = Motion.scale == 0f || !ambientAwake()
|
||||
val lift = if (still) 0f else handleBob()
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.height(height).clip(shape).background(colors.surface)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -12,7 +13,7 @@ import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -46,9 +47,9 @@ fun ChooseAppDisplayDialog(
|
||||
?: stringResource(R.string.main_secondary_gone),
|
||||
)
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onPrimary) { Text(stringResource(R.string.main_primary)) } },
|
||||
confirmButton = { TextButton(onClick = onPrimary, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.main_primary)) } },
|
||||
dismissButton = {
|
||||
TextButton(onClick = onSecondary, enabled = secondaryDisplay != null) {
|
||||
TextButton(onClick = onSecondary, enabled = secondaryDisplay != null, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.main_secondary))
|
||||
}
|
||||
},
|
||||
@@ -61,8 +62,8 @@ fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () ->
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(title) },
|
||||
text = { Text(text) },
|
||||
confirmButton = { TextButton(onClick = { onDismiss(); onConfirm() }) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { TextButton(onClick = { onDismiss(); onConfirm() }, modifier = Modifier.focusGlide(CircleShape)) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -72,11 +73,11 @@ fun RuntimeActionsDialog(onRepair: () -> Unit, onRemove: () -> Unit, onDismiss:
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.runtime_actions_title)) },
|
||||
text = { Text(stringResource(R.string.runtime_actions_text)) },
|
||||
confirmButton = { TextButton(onClick = onRepair) { Text(stringResource(R.string.runtime_repair)) } },
|
||||
confirmButton = { TextButton(onClick = onRepair, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.runtime_repair)) } },
|
||||
dismissButton = {
|
||||
Row {
|
||||
TextButton(onClick = onRemove) { Text(stringResource(R.string.store_remove)) }
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
|
||||
TextButton(onClick = onRemove, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.store_remove)) }
|
||||
TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -92,7 +93,7 @@ fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: (
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(stringResource(R.string.setup_reset_settings_body))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it },
|
||||
Modifier.fillMaxWidth().focusGlide().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(checked = gameProfiles, onCheckedChange = null)
|
||||
@@ -102,10 +103,10 @@ fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: (
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }) {
|
||||
TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.setup_reset_settings_button), color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -7,7 +8,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
@@ -59,8 +60,6 @@ class ModeSettings(
|
||||
val hdr: Boolean,
|
||||
val hdrReason: String?,
|
||||
val gpuDrivers: String? = null,
|
||||
val fpsLimit: Int = 0,
|
||||
val performanceMode: Boolean = false,
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
val touchMode: String,
|
||||
@@ -96,11 +95,7 @@ class ModeSettings(
|
||||
val bootMovieCustomName: String? = null,
|
||||
val bootMovieImporting: Boolean = false,
|
||||
val bootMovieProgress: Int = -1,
|
||||
val wifiDiscovery: Boolean? = null,
|
||||
val wifiDiscoveryPermission: Boolean = false,
|
||||
val wifiDiscoveryLocation: Boolean = false,
|
||||
val wifiDiscoveryAsked: Boolean = false,
|
||||
val wifiDiscoveryBlocked: Boolean = false,
|
||||
val integration: com.droiddeck.launcher.core.SteamIntegration.State? = null,
|
||||
val deckyInstalled: String? = null,
|
||||
val deckyLatestRelease: DeckyManager.Release? = null,
|
||||
val deckyBranch: Int = DeckyManager.BRANCH_STABLE,
|
||||
@@ -116,8 +111,6 @@ class ModeSettingsActions(
|
||||
val onResolution: (String) -> Unit,
|
||||
val onHdr: (Boolean) -> Unit,
|
||||
val onGpuDrivers: () -> Unit = {},
|
||||
val onFpsLimit: (Int) -> Unit = {},
|
||||
val onPerformanceMode: (Boolean) -> Unit = {},
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onTouch: (String) -> Unit,
|
||||
@@ -149,8 +142,9 @@ class ModeSettingsActions(
|
||||
val onBootMovieSound: (Boolean) -> Unit = {},
|
||||
val onImportBootMovie: () -> Unit = {},
|
||||
val onBootMovieChanged: () -> Unit = {},
|
||||
val onWifiDiscovery: (Boolean) -> Unit = {},
|
||||
val onWifiDiscoverySettings: () -> Unit = {},
|
||||
val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {},
|
||||
val onIntegrationAppInfo: () -> Unit = {},
|
||||
val onIntegrationLocation: () -> Unit = {},
|
||||
val onDeckyInstall: (DeckyManager.Release) -> Unit = {},
|
||||
val onDeckyCheck: () -> Unit = {},
|
||||
val onDeckyBranch: (Int) -> Unit = {},
|
||||
@@ -160,7 +154,7 @@ class ModeSettingsActions(
|
||||
val onDismiss: () -> Unit,
|
||||
)
|
||||
|
||||
/** "2610 r3" from droiddeck-steam-x64's FEX_TAG line (fex-2610-r3), the build the x86-64 client downloads. */
|
||||
/** "2610 r3" from droiddeck-fex-update's FEX_TAG line (fex-2610-r3), the build x86 programs fall back to. */
|
||||
internal fun fexVersionOf(script: String): String? =
|
||||
Regex("""(?m)^FEX_TAG=(fex-\d+-r\d+)\s*$""").find(script)?.let { fexVersionOfTag(it.groupValues[1]) }
|
||||
|
||||
@@ -175,7 +169,7 @@ private fun x64FexVersion(context: android.content.Context): String? = remember
|
||||
runCatching { java.io.File(root, "usr/local/share/fex-emu/.droiddeck-tag").readText() }.getOrNull()?.let(::fexVersionOfTag)
|
||||
?: com.droiddeck.launcher.session.FexCatalog.cached(context)?.tag?.let(::fexVersionOfTag)
|
||||
?: runCatching {
|
||||
context.assets.open("linuxfs/usr/local/bin/droiddeck-steam-x64").bufferedReader().use { fexVersionOf(it.readText()) }
|
||||
context.assets.open("linuxfs/usr/local/bin/droiddeck-fex-update").bufferedReader().use { fexVersionOf(it.readText()) }
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
@@ -209,11 +203,17 @@ class SheetExtras(
|
||||
fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
var explainWifiDiscovery by remember { mutableStateOf(false) }
|
||||
if (tab == SheetTab.DISPLAY) {
|
||||
val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution)
|
||||
val context = LocalContext.current
|
||||
val portraitWindow = SessionPrefs.portrait(context)
|
||||
val longSide = maxOf(s.panelSize.first, s.panelSize.second)
|
||||
val shortSide = minOf(s.panelSize.first, s.panelSize.second)
|
||||
val controlsBelow = SessionPrefs.controlsBelowWanted(context, s.mode,
|
||||
if (portraitWindow) shortSide else longSide, if (portraitWindow) longSide else shortSide)
|
||||
val portrait = portraitWindow && !controlsBelow
|
||||
val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution, portrait)
|
||||
SettingsGroup(stringResource(R.string.display_session)) {
|
||||
ResolutionRow(host, s.resolution, s.panelSize, a.onResolution)
|
||||
ResolutionRow(host, s.resolution, s.panelSize, a.onResolution, portrait = portrait)
|
||||
s.picturePosition?.let { position ->
|
||||
ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null,
|
||||
listOf("top" to stringResource(R.string.display_position_top),
|
||||
@@ -242,12 +242,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
format = { "$it%" }, onChange = a.onUpscaleSharpness,
|
||||
)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.display_frame_rate)) {
|
||||
ToggleRow(host, "performance", stringResource(R.string.mode_performance), stringResource(R.string.mode_performance_hint),
|
||||
s.performanceMode, onChange = a.onPerformanceMode)
|
||||
ChoiceRow(host, "fps", stringResource(R.string.mode_fps), stringResource(R.string.common_applies_next_session),
|
||||
SessionPrefs.fpsLimitChoices(LocalContext.current), s.fpsLimit, note = stringResource(R.string.mode_fps_note), onPick = a.onFpsLimit)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.mode_hdr)) {
|
||||
ToggleRow(
|
||||
host, "hdr", stringResource(R.string.mode_hdr10),
|
||||
@@ -309,6 +303,9 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU),
|
||||
), s.backActionsInverted, onPick = a.onBackActionsInverted,
|
||||
)
|
||||
if (steam && s.steamController in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) {
|
||||
Note(stringResource(R.string.back_native_qam_hint))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (tab == SheetTab.AUDIO && steam) {
|
||||
@@ -505,39 +502,9 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
)
|
||||
}
|
||||
if (s.bootMovie != null) BootMovieGroup(s, a, host)
|
||||
if (s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
|
||||
val hint = when {
|
||||
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
|
||||
!s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied)
|
||||
else -> stringResource(R.string.mode_wifi_discovery_hint)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.mode_wifi_discovery), hint) {
|
||||
Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
|
||||
horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)) {
|
||||
if (s.wifiDiscoveryBlocked || (s.wifiDiscovery && !s.wifiDiscoveryLocation)) {
|
||||
SecondaryButton(stringResource(R.string.mode_wifi_open_settings), onClick = a.onWifiDiscoverySettings)
|
||||
}
|
||||
ToggleSwitch(s.wifiDiscovery, label = stringResource(R.string.mode_wifi_discovery)) { on ->
|
||||
host.open = null
|
||||
if (on) explainWifiDiscovery = true else a.onWifiDiscovery(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.integration != null) SteamIntegrationGroup(s.integration,
|
||||
onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation)
|
||||
}
|
||||
if (explainWifiDiscovery) AlertDialog(
|
||||
onDismissRequest = { explainWifiDiscovery = false },
|
||||
title = { Text(stringResource(R.string.mode_wifi_explain_title)) },
|
||||
text = { Text(stringResource(R.string.mode_wifi_explain_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false; a.onWifiDiscovery(true) }) {
|
||||
Text(stringResource(if (s.wifiDiscoveryBlocked) R.string.mode_wifi_open_settings else R.string.mode_wifi_continue))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false }) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -582,14 +549,14 @@ internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit)
|
||||
title = { Text(stringResource(R.string.decky_zip_warning_title)) },
|
||||
text = { Text(stringResource(R.string.decky_zip_warning_text)) },
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(onClick = onConfirm, enabled = left == 0) {
|
||||
androidx.compose.material3.TextButton(onClick = onConfirm, enabled = left == 0, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(
|
||||
if (left > 0) androidx.compose.ui.res.pluralStringResource(R.plurals.decky_zip_warning_wait, left, left)
|
||||
else stringResource(R.string.decky_zip_warning_continue),
|
||||
)
|
||||
}
|
||||
},
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onCancel) { Text(stringResource(R.string.common_cancel)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onCancel, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -624,7 +591,7 @@ private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) {
|
||||
@Composable
|
||||
internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
var key by remember { mutableStateOf("") }
|
||||
androidx.compose.material3.AlertDialog(
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.mode_sgdb_key)) },
|
||||
text = {
|
||||
@@ -632,14 +599,14 @@ internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss:
|
||||
key, { v -> key = v.trim() }, label = { Text(stringResource(R.string.mode_sgdb_key)) },
|
||||
singleLine = true, visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(),
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Password),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier.fillMaxWidth().focusGlide(),
|
||||
)
|
||||
},
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = { onSave(key) }, enabled = key.isNotEmpty()) { Text(stringResource(R.string.common_ok)) } },
|
||||
confirmButton = { androidx.compose.material3.TextButton(onClick = { onSave(key) }, enabled = key.isNotEmpty(), modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_ok)) } },
|
||||
dismissButton = {
|
||||
androidx.compose.foundation.layout.Row {
|
||||
if (hasKey) androidx.compose.material3.TextButton(onClick = { onSave("") }) { Text(stringResource(R.string.common_delete)) }
|
||||
androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
|
||||
if (hasKey) androidx.compose.material3.TextButton(onClick = { onSave("") }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) }
|
||||
androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -651,7 +618,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
var w by remember { mutableStateOf(initial?.first?.toString() ?: "") }
|
||||
var h by remember { mutableStateOf(initial?.second?.toString() ?: "") }
|
||||
val parsed = SessionPrefs.parseResolution("${w}x$h")
|
||||
androidx.compose.material3.AlertDialog(
|
||||
com.droiddeck.launcher.ui.GlideAlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.mode_custom_res_title)) },
|
||||
text = {
|
||||
@@ -667,12 +634,12 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
val numbers = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
w, { v -> w = v.filter(Char::isDigit).take(4) }, label = { Text(stringResource(R.string.mode_width)) },
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f),
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f).focusGlide(),
|
||||
)
|
||||
Text("×", fontSize = 18.sp, modifier = Modifier.padding(horizontal = 10.dp))
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
h, { v -> h = v.filter(Char::isDigit).take(4) }, label = { Text(stringResource(R.string.mode_height)) },
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f),
|
||||
singleLine = true, keyboardOptions = numbers, modifier = Modifier.weight(1f).focusGlide(),
|
||||
)
|
||||
}
|
||||
androidx.compose.foundation.layout.FlowRow(
|
||||
@@ -683,6 +650,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
androidx.compose.material3.AssistChip(
|
||||
onClick = { w = pw.toString(); h = ph.toString() },
|
||||
label = { Text("$pw×$ph · $tag", fontSize = 12.sp) },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -692,7 +660,7 @@ internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { androidx.compose.material3.TextButton(enabled = parsed != null, onClick = { parsed?.let(onSave) }) { Text(stringResource(R.string.common_use)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { androidx.compose.material3.TextButton(enabled = parsed != null, onClick = { parsed?.let(onSave) }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_use)) } },
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.input.pointer.util.VelocityTracker
|
||||
import androidx.compose.ui.input.pointer.util.addPointerInputChange
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlin.math.abs
|
||||
|
||||
internal object PageSwipe {
|
||||
var locks by mutableIntStateOf(0)
|
||||
var direction by mutableIntStateOf(0)
|
||||
}
|
||||
|
||||
// Runs on the Final pass so carousels, sliders, scrollers and widgets that consumed the drag keep it.
|
||||
@Composable
|
||||
internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier {
|
||||
val enabledNow by rememberUpdatedState(enabled)
|
||||
val onSwipeNow by rememberUpdatedState(onSwipe)
|
||||
return pointerInput(Unit) {
|
||||
val distance = 72.dp.toPx()
|
||||
val flingDistance = 32.dp.toPx()
|
||||
val flingVelocity = 900.dp.toPx()
|
||||
val slop = viewConfiguration.touchSlop
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final)
|
||||
if (!enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture
|
||||
val tracker = VelocityTracker()
|
||||
tracker.addPointerInputChange(down)
|
||||
var total = Offset.Zero
|
||||
var mine = false
|
||||
while (true) {
|
||||
val event = awaitPointerEvent(PointerEventPass.Final)
|
||||
if (event.changes.size > 1) return@awaitEachGesture
|
||||
val change = event.changes.firstOrNull { it.id == down.id } ?: return@awaitEachGesture
|
||||
if (!change.pressed) break
|
||||
if (!mine && change.isConsumed) return@awaitEachGesture
|
||||
total += change.position - change.previousPosition
|
||||
tracker.addPointerInputChange(change)
|
||||
if (!mine && abs(total.x) > slop && abs(total.x) > abs(total.y) * 2f) mine = true
|
||||
if (mine) change.consume()
|
||||
}
|
||||
if (!mine || PageSwipe.locks > 0) return@awaitEachGesture
|
||||
val vx = tracker.calculateVelocity().x
|
||||
val horizontal = abs(total.x) > abs(total.y) * 1.5f
|
||||
val far = abs(total.x) > distance
|
||||
val flung = abs(total.x) > flingDistance && abs(vx) > flingVelocity && (vx > 0) == (total.x > 0)
|
||||
if (horizontal && (far || flung)) onSwipeNow(if (total.x < 0) 1 else -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -212,7 +212,7 @@ fun PerformancePage(
|
||||
},
|
||||
singleLine = true, isError = !valid && draft.isNotBlank(),
|
||||
placeholder = { Text(SessionPrefs.DEFAULT_GUEST_HOSTNAME) },
|
||||
modifier = Modifier.width(220.dp),
|
||||
modifier = Modifier.width(220.dp).focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import android.content.Context
|
||||
@@ -17,7 +18,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -44,6 +45,7 @@ import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
|
||||
@Composable
|
||||
fun PhantomProcessGatePage(
|
||||
status: PhantomProcessStatus,
|
||||
applyingSavedPairing: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
@@ -76,7 +78,7 @@ fun PhantomProcessGatePage(
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val wide = maxWidth >= 620.dp
|
||||
val fix: @Composable ColumnScope.() -> Unit = {
|
||||
FixGroup(hasToggle, stage, environment, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging,
|
||||
FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging,
|
||||
onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) })
|
||||
}
|
||||
val side: @Composable ColumnScope.() -> Unit = {
|
||||
@@ -118,6 +120,7 @@ private fun FixGroup(
|
||||
stage: Stage,
|
||||
environment: GateEnvironment,
|
||||
compact: Boolean,
|
||||
applyingSavedPairing: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
onOpenNotificationSettings: () -> Unit,
|
||||
@@ -130,6 +133,10 @@ private fun FixGroup(
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
when {
|
||||
applyingSavedPairing -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
Body(stringResource(R.string.adbpair_applying))
|
||||
}
|
||||
pairing -> PairingProgress(stage, onCancel)
|
||||
hasToggle -> {
|
||||
Body(stringResource(R.string.gate_toggle_steps))
|
||||
@@ -276,12 +283,12 @@ fun DeveloperDisplayChoiceDialog(
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.gate_choose_display))
|
||||
TextButton(modifier = Modifier.fillMaxWidth(), onClick = onMainScreen) { Text(stringResource(R.string.gate_main_screen)) }
|
||||
TextButton(modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = onMainScreen) { Text(stringResource(R.string.gate_main_screen)) }
|
||||
displays.forEach { (id, label) ->
|
||||
TextButton(modifier = Modifier.fillMaxWidth(), onClick = { onSecondaryScreen(id) }) { Text(label) }
|
||||
TextButton(modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = { onSecondaryScreen(id) }) { Text(label) }
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -14,16 +14,17 @@ import com.droiddeck.launcher.session.SessionDisplay
|
||||
fun ResolutionRow(
|
||||
host: MenuHost, choice: String, panel: Pair<Int, Int>, onPick: (String) -> Unit,
|
||||
chipModifier: Modifier = Modifier,
|
||||
portrait: Boolean = false,
|
||||
) {
|
||||
val custom = "custom"
|
||||
val size = SessionDisplay.resolveChoice(panel, choice)
|
||||
val screen = SessionDisplay.screenSize(panel)
|
||||
val size = SessionDisplay.resolveChoice(panel, choice, portrait)
|
||||
val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait)
|
||||
val choices = SessionDisplay.resolutionOptions(panel)
|
||||
val selected = if (choice == SessionDisplay.FOLLOW_SCREEN) choice
|
||||
else if (size == screen) SessionDisplay.MATCH_SCREEN else choice
|
||||
var editCustom by remember { mutableStateOf(false) }
|
||||
val options = choices.map { value ->
|
||||
val dimensions = SessionDisplay.resolveChoice(panel, value)
|
||||
val dimensions = SessionDisplay.resolveChoice(panel, value, portrait)
|
||||
value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second)
|
||||
else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen)
|
||||
else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
@@ -38,10 +39,10 @@ fun RomsDialog(path: String?, onChoose: () -> Unit, onClear: () -> Unit, onDismi
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onChoose) { Text(if (path == null) stringResource(R.string.roms_choose) else stringResource(R.string.roms_change)) } },
|
||||
confirmButton = { TextButton(onClick = onChoose, modifier = Modifier.focusGlide(CircleShape)) { Text(if (path == null) stringResource(R.string.roms_choose) else stringResource(R.string.roms_change)) } },
|
||||
dismissButton = {
|
||||
if (path != null) TextButton(onClick = onClear) { Text(stringResource(R.string.common_forget)) }
|
||||
else TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
|
||||
if (path != null) TextButton(onClick = onClear, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_forget)) }
|
||||
else TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -166,7 +166,7 @@ fun ScreenKeyEditor(
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
|
||||
modifier = Modifier.fillMaxWidth().onFocusChanged {
|
||||
if (it.isFocused) onTextFocus() else onTextBlur()
|
||||
},
|
||||
}.focusGlide(),
|
||||
)
|
||||
if (text.isEmpty()) {
|
||||
Text(
|
||||
@@ -177,26 +177,26 @@ fun ScreenKeyEditor(
|
||||
}
|
||||
}
|
||||
if (button) {
|
||||
IconButton(onClick = onBind, modifier = Modifier.width(38.dp)) {
|
||||
IconButton(onClick = onBind, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Default.Keyboard, stringResource(R.string.screen_key_bind),
|
||||
tint = p.onBackground.copy(alpha = 0.8f),
|
||||
)
|
||||
}
|
||||
}
|
||||
IconButton(onClick = { pickImage.launch("image/*") }, modifier = Modifier.width(38.dp)) {
|
||||
IconButton(onClick = { pickImage.launch("image/*") }, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Default.Image, stringResource(R.string.screen_key_image),
|
||||
tint = p.onBackground.copy(alpha = 0.8f),
|
||||
)
|
||||
}
|
||||
if (hasImage) IconButton(onClick = onClearImage, modifier = Modifier.width(34.dp)) {
|
||||
if (hasImage) IconButton(onClick = onClearImage, modifier = Modifier.width(34.dp).focusGlide(CircleShape)) {
|
||||
Icon(Icons.Default.Close, stringResource(R.string.screen_key_image_clear), tint = p.error)
|
||||
}
|
||||
IconButton(onClick = onRemove, modifier = Modifier.width(38.dp)) {
|
||||
IconButton(onClick = onRemove, modifier = Modifier.width(38.dp).focusGlide(CircleShape)) {
|
||||
Icon(Icons.Default.Delete, stringResource(R.string.common_delete), tint = p.error)
|
||||
}
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.width(34.dp)) {
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.width(34.dp).focusGlide(CircleShape)) {
|
||||
Icon(Icons.Default.Close, null, tint = p.onBackground)
|
||||
}
|
||||
}
|
||||
@@ -232,7 +232,7 @@ fun ScreenKeyEditor(
|
||||
stringResource(R.string.screen_key_toggle), Modifier.padding(start = 6.dp, end = 2.dp),
|
||||
style = MaterialTheme.typography.bodySmall, maxLines = 1,
|
||||
)
|
||||
Switch(checked = toggle, onCheckedChange = onToggle, modifier = Modifier.height(30.dp))
|
||||
Switch(checked = toggle, onCheckedChange = onToggle, modifier = Modifier.height(30.dp).focusGlide())
|
||||
}
|
||||
if (directions.isNotEmpty()) {
|
||||
Row(
|
||||
@@ -251,7 +251,7 @@ fun ScreenKeyEditor(
|
||||
stringResource(R.string.screen_key_text), Modifier.padding(start = 6.dp, end = 2.dp),
|
||||
style = MaterialTheme.typography.bodySmall, maxLines = 1,
|
||||
)
|
||||
Switch(checked = labels, onCheckedChange = onLabels, modifier = Modifier.height(30.dp))
|
||||
Switch(checked = labels, onCheckedChange = onLabels, modifier = Modifier.height(30.dp).focusGlide())
|
||||
}
|
||||
}
|
||||
Row(
|
||||
@@ -294,7 +294,7 @@ private fun KeySlider(
|
||||
) {
|
||||
Row(modifier, verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, style = MaterialTheme.typography.bodySmall, maxLines = 1)
|
||||
Slider(current, onChange, Modifier.weight(1f).height(28.dp), valueRange = min..max)
|
||||
Slider(current, onChange, Modifier.weight(1f).height(28.dp).focusGlide(), valueRange = min..max)
|
||||
Text(
|
||||
value, Modifier.width(32.dp), style = MaterialTheme.typography.bodySmall,
|
||||
fontWeight = FontWeight.SemiBold, maxLines = 1,
|
||||
@@ -317,7 +317,7 @@ private fun Chip(
|
||||
if (selected) p.primary.copy(alpha = 0.18f) else p.line2.copy(alpha = 0.28f),
|
||||
CircleShape,
|
||||
)
|
||||
.clickable(enabled = enabled, onClick = onClick)
|
||||
.focusGlide(RoundedCornerShape(8.dp)).clickable(enabled = enabled, onClick = onClick)
|
||||
.padding(vertical = 6.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
@@ -41,7 +42,7 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.droiddeck.launcher.ui.GlideDialog as Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.PC_KEYS
|
||||
@@ -86,7 +87,7 @@ fun ScreenKeyPicker(
|
||||
Column {
|
||||
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.screen_keys_add), Modifier.weight(1f), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
IconButton(onClick = onDismiss) { Icon(Icons.Default.Close, null) }
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Default.Close, null) }
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 26.dp).horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp),
|
||||
@@ -136,7 +137,7 @@ fun ScreenKeyPicker(
|
||||
Button(
|
||||
onClick = { onAdd(picked) },
|
||||
enabled = picked.isNotEmpty(),
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = Modifier.weight(1f).focusGlide(CircleShape),
|
||||
) {
|
||||
Text(stringResource(R.string.screen_keys_add))
|
||||
}
|
||||
@@ -155,7 +156,7 @@ private fun KeyCell(key: PcKey, selected: Boolean, modifier: Modifier, onClick:
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
color = if (selected) p.primary.copy(alpha = 0.2f) else p.surface,
|
||||
border = BorderStroke(1.dp, if (selected) p.primary else p.line),
|
||||
modifier = modifier.height(36.dp).clickable(onClick = onClick),
|
||||
modifier = modifier.height(36.dp).focusGlide(RoundedCornerShape(8.dp)).clickable(onClick = onClick),
|
||||
) {
|
||||
Box(Modifier.fillMaxSize().padding(horizontal = 2.dp), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
@@ -40,7 +41,7 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.droiddeck.launcher.ui.GlideDialog as Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
@@ -83,14 +84,14 @@ fun ScreenLayoutPanel(
|
||||
stringResource(R.string.screen_key_layout), Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
IconButton(onClick = onDismiss) { Icon(Icons.Default.Close, null) }
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Default.Close, null) }
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(end = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
TextButton(onClick = { naming = true }) { Text(stringResource(R.string.screen_key_layout_save)) }
|
||||
TextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "*/*")) }) {
|
||||
TextButton(onClick = { naming = true }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.screen_key_layout_save)) }
|
||||
TextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "*/*")) }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.boot_movie_import))
|
||||
}
|
||||
TextButton(onClick = { exporter.launch("droiddeck-layout.icp") }) {
|
||||
TextButton(onClick = { exporter.launch("droiddeck-layout.icp") }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.screen_key_layout_export))
|
||||
}
|
||||
}
|
||||
@@ -101,7 +102,7 @@ fun ScreenLayoutPanel(
|
||||
layout, Modifier.weight(1f).clickable { onLoad(layout) }.padding(vertical = 14.dp),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
TextButton(onClick = { onDelete(layout) }) {
|
||||
TextButton(onClick = { onDelete(layout) }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_delete), color = p.error)
|
||||
}
|
||||
}
|
||||
@@ -121,12 +122,12 @@ fun ScreenLayoutPanel(
|
||||
) {
|
||||
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedTextField(
|
||||
name, { name = it.take(24) }, Modifier.fillMaxWidth(), singleLine = true,
|
||||
name, { name = it.take(24) }, Modifier.fillMaxWidth().focusGlide(), singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
TextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) }
|
||||
Button(onClick = { onSave(name.trim()); naming = false }, enabled = name.isNotBlank()) {
|
||||
TextButton(onClick = { naming = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
Button(onClick = { onSave(name.trim()); naming = false }, enabled = name.isNotBlank(), modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.screen_key_layout_save))
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 262 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user