Merge remote-tracking branch 'droiddeck/main' into feat/malibridge

# Conflicts:
#	README.md
#	app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java
#	app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
#	app/src/main/res/values-ar/strings.xml
#	app/src/main/res/values-b+es+419/strings.xml
#	app/src/main/res/values-bg/strings.xml
#	app/src/main/res/values-cs/strings.xml
#	app/src/main/res/values-da/strings.xml
#	app/src/main/res/values-de/strings.xml
#	app/src/main/res/values-el/strings.xml
#	app/src/main/res/values-es/strings.xml
#	app/src/main/res/values-fi/strings.xml
#	app/src/main/res/values-fr/strings.xml
#	app/src/main/res/values-hi/strings.xml
#	app/src/main/res/values-hu/strings.xml
#	app/src/main/res/values-in/strings.xml
#	app/src/main/res/values-it/strings.xml
#	app/src/main/res/values-ja/strings.xml
#	app/src/main/res/values-ko/strings.xml
#	app/src/main/res/values-ms/strings.xml
#	app/src/main/res/values-nb/strings.xml
#	app/src/main/res/values-nl/strings.xml
#	app/src/main/res/values-pl/strings.xml
#	app/src/main/res/values-pt-rPT/strings.xml
#	app/src/main/res/values-pt/strings.xml
#	app/src/main/res/values-ro/strings.xml
#	app/src/main/res/values-ru/strings.xml
#	app/src/main/res/values-sv/strings.xml
#	app/src/main/res/values-th/strings.xml
#	app/src/main/res/values-tr/strings.xml
#	app/src/main/res/values-uk/strings.xml
#	app/src/main/res/values-vi/strings.xml
#	app/src/main/res/values-zh-rCN/strings.xml
#	app/src/main/res/values-zh-rHK/strings.xml
#	app/src/main/res/values-zh-rTW/strings.xml
#	app/src/main/res/values/strings.xml
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
This commit is contained in:
maxjivi05 committed 2026-10-30 11:58:55 -04:00
commit 0a5955d6fa
731 files changed
+54131 -2491

No files matched your search

@@ -46,6 +46,7 @@ class App : Application() {
com.droiddeck.launcher.glasses.Glasses.init(this)
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
BwrapSpawner.start(this)
com.droiddeck.launcher.runtime.RootSpawner.start(this)
com.droiddeck.launcher.frontend.GameFileSync.start(this)
com.droiddeck.launcher.stores.StoresState.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
@@ -44,6 +44,7 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.core.CpuCores
@@ -52,6 +53,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,17 +93,24 @@ 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)
private var removalPending by mutableStateOf(false)
private var available by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
private var catalogFresh = false
private var componentsQueueBusy by mutableStateOf(false)
private var busy by mutableStateOf(false)
private var stage by mutableStateOf("")
private var percent by mutableIntStateOf(-1)
@@ -134,9 +143,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)
@@ -192,6 +206,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()
@@ -203,6 +219,7 @@ class FrontEndActivity : ComponentActivity() {
}
private val mediaReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
usbScan++
ui.removeCallbacks(mediaRefresh)
ui.postDelayed(mediaRefresh, MEDIA_SETTLE_MS)
}
@@ -260,8 +277,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,
@@ -396,7 +470,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 performanceMode by mutableStateOf(false)
private var upscaler by mutableStateOf(0)
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null)
@@ -406,6 +479,16 @@ class FrontEndActivity : ComponentActivity() {
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var backActionsInverted by mutableStateOf(false)
private var gameStorage by mutableStateOf("")
private var slowUsb by mutableStateOf<com.droiddeck.launcher.session.UsbLink.SlowDrive?>(null)
private var usbScan = 0
private var slowUsbNever by mutableStateOf(false)
private fun showSlowUsb(drive: com.droiddeck.launcher.session.UsbLink.SlowDrive?) {
val off = slowUsbNever
if (off) SessionPrefs.setSlowUsbWarningOff(this)
slowUsbNever = false
slowUsb = drive.takeUnless { off }
}
private var storageDiagnostics by mutableStateOf(false)
private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList())
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
@@ -419,6 +502,8 @@ class FrontEndActivity : ComponentActivity() {
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
private var runningLabel by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true)
private var gameDebugLogsEnabled by mutableStateOf(false)
private var gameDebugLogsNeedsRestart by mutableStateOf(false)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
private var clearCachedApps by mutableStateOf(false)
@@ -430,7 +515,28 @@ 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 var dualDisplayId by mutableStateOf(-1)
private var dualScreenDevice by mutableStateOf(false)
private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
private var dualScreenLauncher by mutableStateOf(true)
private var dualScreenControls by mutableStateOf(true)
private var launcherStarted = false
private lateinit var displayManager: DisplayManager
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
@@ -443,16 +549,19 @@ 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()
SessionState.installing != null && !SessionState.running -> {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_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
@@ -467,17 +576,26 @@ 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)
}
private fun launchFlooded(f: PendingFlood) {
if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null ||
ProtonExtras.installInProgress || pkgStage != null) {
if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) ||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) &&
(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
@@ -485,10 +603,92 @@ 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() || (SessionState.installing != null && !SessionState.running) || 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
@Volatile private var lastComponentRestore = 0L
@Volatile private var componentRestoreRetry = false
private val componentRestoreLock = Any()
private fun retryComponentRestore() {
val run = synchronized(componentRestoreLock) {
componentRestoreRetry = false
val now = android.os.SystemClock.elapsedRealtime()
(!isDestroyed && now - lastComponentRestore >= COMPONENT_RESTORE_MS).also { if (it) lastComponentRestore = now }
}
if (run) Thread({
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
}, "components-restore").start()
}
private var pendingGameLink: String? = null
private var gameLinkReading = false
private var gameLinkTried = false
private var gameSyncFolder by mutableStateOf<String?>(null)
private fun pickGameExport(game: Library.SteamGame?) {
onSavePicked = { folder ->
@@ -529,16 +729,25 @@ class FrontEndActivity : ComponentActivity() {
shortcutLibraryScanning = true
} else shortcutLibraryScanning = false
pendingGameLink = null
gameLinkReading = false
gameLinkTried = false
if (GameLaunchIntent.accepts(request.action)) {
gameLinkReading = true
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
val copy = Intent(request)
Thread({
val id = GameLaunchIntent.read(this, copy)
ui.post {
if (intent === request && !isDestroyed) {
gameLinkReading = false
pendingGameLink = id
if (id == null) {
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
} else refresh()
} else {
handleGameLink(steamGames, scanned = false)
refresh()
}
}
}
}, "game-launch-file").start()
@@ -546,7 +755,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
}
@@ -658,7 +867,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
}
@@ -741,15 +950,21 @@ class FrontEndActivity : ComponentActivity() {
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
}
private fun handleGameLink(games: List<Library.SteamGame>) {
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val id = pendingGameLink ?: return
if (!scanned && games.none { it.gameIdString == id }) return
gameLinkTried = true
ui.postDelayed({
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
}, LINK_PANEL_MS)
val game = games.firstOrNull { it.gameIdString == id }
if (game == null) {
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
} else if (launchGame(game, returnHome = true)) {
pendingGameLink = null
@@ -766,6 +981,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
@@ -803,6 +1019,13 @@ class FrontEndActivity : ComponentActivity() {
if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog(
onConfirm = { decky.confirmPluginZip() }, onCancel = { decky.cancelPluginZip() },
)
slowUsb?.let { drive ->
com.droiddeck.launcher.ui.SlowUsbDialog(drive, slowUsbNever, { slowUsbNever = it }) {
com.droiddeck.launcher.session.UsbLink.markShown(this, drive)
showSlowUsb(null)
checkUsbLink()
}
}
val page: (@Composable () -> Unit)? = when {
showPerformance -> { { PerformanceHost() } }
showComponents -> { { ComponentsHost() } }
@@ -821,6 +1044,7 @@ class FrontEndActivity : ComponentActivity() {
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
@@ -833,8 +1057,15 @@ class FrontEndActivity : ComponentActivity() {
isHomeApp = homeAppSelected,
homeScreenEnabled = homeScreenEnabled,
defaultHomeLabel = defaultHomeLabel,
integration = integrationState,
integrationFocus = integrationFocus,
androidApps = androidApps,
secondScreenDisplays = secondScreenDisplays,
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
dualScreenDevice = dualScreenDevice,
dualScreenMode = dualScreenMode,
dualScreenLauncher = dualScreenLauncher,
dualScreenControls = dualScreenControls,
packages = packageRows,
packageCatalogLoading = catalogLoading,
packageBusyId = pkgId,
@@ -984,8 +1215,21 @@ class FrontEndActivity : ComponentActivity() {
.putExtra(com.droiddeck.launcher.files.FileManagerActivity.EXTRA_START_DIR, dir.absolutePath))
},
onLogs = {
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
val changed = SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
if (!changed) android.widget.Toast.makeText(
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
).show()
logsEnabled = SessionPrefs.logsEnabled(this)
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onGameDebugLogs = {
val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this))
if (!changed) android.widget.Toast.makeText(
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
).show()
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onVacDiagnostics = {
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
@@ -1059,6 +1303,18 @@ class FrontEndActivity : ComponentActivity() {
onStoresSort = { sort -> SessionPrefs.setStoresSort(this, sort); storesSort = sort },
onStoresView = { view -> SessionPrefs.setStoresView(this, view); storesView = view },
onLibraryChanged = { refreshAddedGames(); refresh() },
onDualScreenMode = { mode ->
SessionPrefs.setDualScreenMode(this, mode)
refreshSecondScreenDisplays()
},
onDualScreenLauncher = { on ->
SessionPrefs.setDualScreenLauncher(this, on)
refreshSecondScreenDisplays()
},
onDualScreenControls = { on ->
SessionPrefs.setDualScreenSessionControls(this, on)
dualScreenControls = on
},
onAnimationsEnabled = { on ->
SessionPrefs.setAnimationsEnabled(this, on)
animationsEnabled = on
@@ -1081,6 +1337,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()
@@ -1134,7 +1398,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, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
onOpenNotificationSettings = {
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
@@ -1230,12 +1499,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)) }
}
@@ -1264,6 +1544,13 @@ class FrontEndActivity : ComponentActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
if (intent.action == SteamIntegration.ACTION_SETUP) {
gameLinkReading = false
pendingGameLink = null
syncDualPanel()
readIntegrationIntent(intent)
return
}
readGameIntent(intent)
refresh()
startSteamAtStartupIfEnabled()
@@ -1322,6 +1609,14 @@ class FrontEndActivity : ComponentActivity() {
}
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) {
@@ -1338,8 +1633,21 @@ 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
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
orientation = SessionPrefs.orientation(this)
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
@@ -1357,14 +1665,21 @@ class FrontEndActivity : ComponentActivity() {
drivers.checkOnOpen()
resumeInterruptedPackages()
protons.checkUpdates()
if (!SessionState.running) Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
if (applied.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
}
ui.post { if (showComponents) components.refreshComponents() }
}, "components-queue").start()
else if (showComponents) components.refreshComponents()
catalogFresh = false
if (!SessionState.running && !componentsQueueBusy && !LinuxRuntimeInstaller.isBusy()) {
componentsQueueBusy = true
Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
if (applied.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
}
ui.post {
componentsQueueBusy = false
if (showComponents) components.refreshComponents()
autoUpdateRuntime()
}
}, "components-queue").start()
} else if (showComponents) components.refreshComponents()
oscMode = SessionPrefs.oscMode(this)
refreshController()
refreshHomeAppState()
@@ -1387,11 +1702,23 @@ class FrontEndActivity : ComponentActivity() {
addDataScheme("file")
})
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
launcherStarted = true
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)
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
switchingTo?.let {
outState.putParcelable(KEY_SWITCHING_TO, it)
@@ -1404,6 +1731,7 @@ class FrontEndActivity : ComponentActivity() {
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
cancelCompatLaunch()
updates.unregister()
super.onDestroy()
}
@@ -1411,10 +1739,14 @@ 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
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
launcherStarted = false
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
flood = null
returning = null
floodProgress = 0f
@@ -1426,20 +1758,53 @@ 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() {
if (!::displayManager.isInitialized) return
// The launcher can itself be shown on a non-default display (DeX, an external monitor); that one is not a "second screen".
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
dualScreenMode = SessionPrefs.dualScreenMode(this)
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
dualScreenLauncher = SessionPrefs.dualScreenLauncher(this)
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, ownDisplayId)
dualDisplayId = if (dualScreenLauncher) target?.displayId ?: -1 else -1
syncDualPanel()
}
private fun syncDualPanel() {
if (launchPending()) return
if (launcherStarted && dualDisplayId >= 0) com.droiddeck.launcher.ui.DualScreenPanel.show(this, dualDisplayId, taskId)
else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
}
private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried)
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
try {
HomeApp.launch(this, app, displayId)
} catch (_: Exception) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
val message = when {
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
@@ -1608,7 +1973,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
}
@@ -1716,7 +2081,7 @@ class FrontEndActivity : ComponentActivity() {
ModeSettings(
mode = mode, resolution = resolution,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, performanceMode = performanceMode,
hdr = hdrOn, hdrReason = hdrReason,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
@@ -1750,11 +2115,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,
@@ -1763,25 +2124,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) },
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 },
@@ -1971,6 +2319,7 @@ class FrontEndActivity : ComponentActivity() {
}
private fun refreshAddedGames() {
checkUsbLink()
sgdbKeyKnown()
fetchAddedGameArt()
}
@@ -2032,7 +2381,6 @@ class FrontEndActivity : ComponentActivity() {
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode)
performanceMode = SessionPrefs.performanceMode(this, mode)
upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
@@ -2076,6 +2424,20 @@ class FrontEndActivity : ComponentActivity() {
}
SessionPrefs.setGameStorage(this, path, label)
gameStorage = path
checkUsbLink()
}
private fun checkUsbLink() {
if (android.os.Looper.myLooper() != android.os.Looper.getMainLooper()) { ui.post { checkUsbLink() }; return }
val scan = ++usbScan
Thread({
val drive = runCatching { com.droiddeck.launcher.session.UsbLink.slowLibrary(this) }.getOrNull()
ui.post {
if (scan != usbScan || isFinishing) return@post
val due = drive?.takeIf { com.droiddeck.launcher.session.UsbLink.stillDue(this, it) }
if (due == null) { if (slowUsb != null) showSlowUsb(null) } else if (slowUsb?.key != due.key) showSlowUsb(due)
}
}, "usb-link").start()
}
private fun refreshCores() {
@@ -2105,6 +2467,10 @@ class FrontEndActivity : ComponentActivity() {
refreshPhantomStatus()
}
private fun gameDebugLogsNeedsRestart(): Boolean =
SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) &&
!SessionPaths.currentSessionLogsRetained(this)
private fun refresh() {
// Until the scan finishes, the other client's games would launch in this one.
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
@@ -2126,9 +2492,12 @@ class FrontEndActivity : ComponentActivity() {
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
ui.post { autoUpdateRuntime() }
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
clearCachedApps = SessionPrefs.clearCachedApps(this)
@@ -2166,15 +2535,32 @@ class FrontEndActivity : ComponentActivity() {
}
val scannedArch = SessionPrefs.activeSteamClientArch(this)
val scannedX64 = scannedArch == "x86_64"
val games = if (ready) Library.launchableGames(this, arch = scannedArch) else emptyList()
val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
val all = games.distinctBy { it.gameId }
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
if (ready && (!componentSweepDone || endedSession != null)) {
val sweepDue = ready && (!componentSweepDone || endedSession != null)
if (sweepDue) {
componentSweepDone = true
endedSession?.let { componentSweepSession = it }
ui.postDelayed({ Thread({ com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all) }, "components-sweep").start() }, 10_000)
}
val restoreDue = synchronized(componentRestoreLock) {
val now = android.os.SystemClock.elapsedRealtime()
val due = ready && (lastComponentRestore == 0L || now - lastComponentRestore >= COMPONENT_RESTORE_MS)
if (due) {
lastComponentRestore = now
} else if (ready && !componentRestoreRetry) {
componentRestoreRetry = true
ui.postDelayed({ retryComponentRestore() }, (COMPONENT_RESTORE_MS - (now - lastComponentRestore)).coerceAtLeast(0L))
}
due
}
if (restoreDue || sweepDue) ui.postDelayed({
Thread({
if (restoreDue) runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
if (sweepDue) com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all)
}, "components-restore").start()
}, 10_000)
ui.post {
if (scanGeneration == libraryScanGeneration) {
val current = steamGames.filter { it.library != Library.ADDED }.associateBy { it.appId }
@@ -2215,6 +2601,10 @@ class FrontEndActivity : ComponentActivity() {
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
if (busy || LinuxRuntimeInstaller.isBusy()) return false
if (SessionState.installing != null && !SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (com.droiddeck.launcher.storage.StorageState.cleaning) {
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
return false
@@ -2264,7 +2654,7 @@ class FrontEndActivity : ComponentActivity() {
private fun runtimeChangesBlocked(): Boolean =
busy || LinuxRuntimeInstaller.isBusy() || SessionState.running ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null ||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null || componentsQueueBusy ||
components.compBusy != null || saveBusy != null || com.droiddeck.launcher.store.UserAppsState.working != null
private fun removeDesktop() {
@@ -2324,18 +2714,38 @@ class FrontEndActivity : ComponentActivity() {
}, "runtime-operation").start()
}
private fun autoUpdateRuntime() {
val release = available?.takeIf { catalogFresh } ?: return
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) || runtimeChangesBlocked() || removalPending) return
if (release.version == installed || installed == null) return
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
Log.i(TAG, "runtime: updating $installed to ${release.version} by itself")
install(release)
}
}
private fun checkCatalog() {
val release = LinuxRuntimeInstaller.fetchRelease()
Log.i(TAG, "catalog: " + (release?.version ?: "unreachable"))
ui.post { if (release != null) available = release }
ui.post {
if (release == null) return@post
available = release
catalogFresh = true
autoUpdateRuntime()
}
}
companion object {
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
private const val COMPONENT_RESTORE_MS = 60_000L
private const val LINK_PANEL_MS = 1500L
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)
@@ -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,346 @@
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.PhantomProcessLimit
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, CHILD_PROCESS, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
private var settingsDisplay: Int? = null
private var toggleOnly = false
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 }
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
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 }
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
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(SettingsState.read(this), WirelessAdbPairingService.stage.value, toggleOnly))
}
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).apply {
if (step != Step.CHILD_PROCESS) 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, toggleOnly)
var previous by remember { mutableStateOf(step) }
LaunchedEffect(step) {
if (previous == Step.BUILD_NUMBER && (step == Step.WIRELESS_DEBUGGING || step == Step.CHILD_PROCESS)) 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 && !toggleOnly) 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 = {
if (!toggleOnly) 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.CHILD_PROCESS -> stringResource(R.string.pairguide_child_process)
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.CHILD_PROCESS -> stringResource(R.string.pairguide_row_child_process)
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, Step.CHILD_PROCESS -> 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 = if (toggleOnly) listOf(Step.BUILD_NUMBER, Step.CHILD_PROCESS)
else 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,
val childProcessBlocked: Boolean,
) {
companion object {
fun read(context: Context) = SettingsState(
GlobalSettings.developerOptionsOn(context),
GlobalSettings.wirelessDebuggingOn(context),
PhantomProcessLimit.blocksSteam(PhantomProcessLimit.read(context)),
)
}
}
companion object {
private const val EXTRA_DISPLAY = "settingsDisplay"
private const val EXTRA_TOGGLE_ONLY = "toggleOnly"
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
private fun stepFor(settings: SettingsState, stage: Stage, toggleOnly: Boolean): Step = if (toggleOnly) when {
!settings.developerOptions -> Step.BUILD_NUMBER
settings.childProcessBlocked -> Step.CHILD_PROCESS
else -> Step.DONE
} else 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?, toggleOnly: Boolean = false): Boolean {
if (settingsDisplay == null && !canFloat(context)) return false
context.startActivity(Intent(context, PairingGuideActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(EXTRA_TOGGLE_ONLY, toggleOnly)
.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
File diff suppressed because it is too large. Load diff
@@ -22,6 +22,14 @@ object AgentGuest {
private set
var steamKeyboard by mutableStateOf(false)
private set
var desktopTextField by mutableStateOf(false)
private set
var keyboardRequests by mutableIntStateOf(0)
private set
var keyboardDismissals by mutableIntStateOf(0)
private set
@Volatile private var keyboardRoute = false
@Volatile private var routeDir: File? = null
private const val TAG = "AgentGuest"
private const val POLL_MS = 50L
private val lock = Any()
@@ -35,10 +43,12 @@ object AgentGuest {
observer?.stopWatching()
observer = null
lastFocusKey = null
main.post { steamKeyboard = false }
main.post { steamKeyboard = false; desktopTextField = false }
val dir = dir(context)
dir.deleteRecursively()
dir.mkdirs()
routeDir = dir
writeKeyboardRoute(dir, keyboardRoute)
@Suppress("DEPRECATION")
observer = object : FileObserver(dir.path, MOVED_TO or CLOSE_WRITE) {
override fun onEvent(event: Int, path: String?) {
@@ -48,6 +58,9 @@ object AgentGuest {
}
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
"keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) }
"ime.json" -> readJson(File(dir, path))?.let { recordTextField(this, it) }
"keyboard-request.json" -> readJson(File(dir, path))?.let { recordKeyboardRequest(this) }
"keyboard-dismiss.json" -> readJson(File(dir, path))?.let { recordKeyboardDismiss(this) }
}
}
}.also { it.startWatching() }
@@ -58,10 +71,46 @@ object AgentGuest {
synchronized(lock) {
observer?.stopWatching()
observer = null
main.post { steamKeyboard = false }
main.post { steamKeyboard = false; desktopTextField = false }
}
}
fun routeKeyboard(context: Context, bottom: Boolean) {
synchronized(lock) {
if (keyboardRoute == bottom) return
keyboardRoute = bottom
writeKeyboardRoute(routeDir ?: dir(context), bottom)
}
}
private fun writeKeyboardRoute(dir: File, bottom: Boolean) {
val file = File(dir, "keyboard-route")
runCatching {
if (!bottom) file.delete()
else if (dir.isDirectory) {
val temp = File(dir, "keyboard-route.tmp")
temp.writeText("bottom")
if (!temp.renameTo(file)) temp.delete()
}
}.onFailure { Log.w(TAG, "keyboard route not written", it) }
}
private fun recordKeyboardRequest(source: FileObserver) {
synchronized(lock) {
if (source !== observer) return
main.post { keyboardRequests++ }
}
SessionEvents.record("keyboard.requested", emptyMap())
}
private fun recordKeyboardDismiss(source: FileObserver) {
synchronized(lock) {
if (source !== observer) return
main.post { keyboardDismissals++ }
}
SessionEvents.record("keyboard.dismissed", emptyMap())
}
private fun recordKeyboard(source: FileObserver, snapshot: JSONObject) {
val showing = snapshot.optBoolean("steamKeyboard")
synchronized(lock) {
@@ -71,6 +120,15 @@ object AgentGuest {
SessionEvents.record("keyboard.changed", mapOf("steamKeyboard" to showing, "seq" to snapshot.optInt("seq")))
}
private fun recordTextField(source: FileObserver, snapshot: JSONObject) {
val focused = snapshot.optBoolean("textField")
synchronized(lock) {
if (source !== observer) return
main.post { desktopTextField = focused }
}
SessionEvents.record("ime.changed", mapOf("textField" to focused, "seq" to snapshot.optInt("seq")))
}
private fun recordFocus(snapshot: JSONObject) {
val fields = linkedMapOf<String, Any?>(
"focusedApp" to snapshot.opt("focusedApp"),
@@ -23,6 +23,9 @@ class AgentStartActivity : Activity() {
Thread({
try {
AgentBridgeProvider.awaitRecovery()
val until = android.os.SystemClock.elapsedRealtime() + RUNTIME_WAIT_MS
while (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isBusy() && !isFinishing &&
android.os.SystemClock.elapsedRealtime() < until) Thread.sleep(RUNTIME_POLL_MS)
runOnUiThread {
if (!isFinishing) startSession(request)
}
@@ -51,6 +54,11 @@ class AgentStartActivity : Activity() {
}
private fun startSession(request: JSONObject) {
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isBusy()) {
Log.w(TAG, "the Linux runtime is being installed or changed")
finish()
return
}
try {
AgentAccess.requireStart(this, request)
} catch (e: AgentException) {
@@ -107,5 +115,7 @@ class AgentStartActivity : Activity() {
companion object {
const val EXTRA_REQUEST = "request"
private const val TAG = "AgentStartActivity"
private const val RUNTIME_WAIT_MS = 15 * 60_000L
private const val RUNTIME_POLL_MS = 500L
}
}
@@ -146,5 +146,7 @@ internal class AddonPack(
listOf("version", "xodus-cli", "xodus-service"))
val COMET = AddonPack("comet", BuildConfig.PACK_COMET_SHA256, BuildConfig.PACK_COMET_SIZE,
listOf("version", "comet"))
val BUTLER = AddonPack("butler", BuildConfig.PACK_BUTLER_SHA256, BuildConfig.PACK_BUTLER_SIZE,
listOf("version", "butler", "7z.so", "libc7zip.so"))
}
}
@@ -29,6 +29,11 @@ import java.util.Locale
object DeviceReport {
private const val TAG = "DeviceReport"
internal fun cpuFeaturesSummary(cpuInfo: String): String = cpuInfo.lineSequence()
.filter { it.substringBefore(':').trim() == "Features" }
.map { it.substringAfter(':').trim().split(Regex("\\s+")).filter(String::isNotEmpty).joinToString(" ") }
.filter(String::isNotEmpty).distinct().joinToString(" | ").ifEmpty { "not reported" }
fun write(context: Context, target: File, mode: String) {
try {
target.writeText(build(context, mode))
@@ -141,6 +146,7 @@ object DeviceReport {
h("CPU and memory")
k("Cores", CpuCores.all.size)
k("CPU features", cpuFeaturesSummary(FileUtils.readString(File("/proc/cpuinfo")).orEmpty()))
b.append("Core ceilings ")
b.append(CpuCores.all.joinToString(", ") { c ->
"cpu$c " + (CpuCores.maxGhz(c)?.let { String.format(Locale.US, "%.2f GHz", it) } ?: "?")
@@ -16,20 +16,83 @@ import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public final class Downloader {
private static final String TAG = "Downloader";
private static final int CONNECT_TIMEOUT_MS = 10_000;
private static final int STALL_TIMEOUT_MS = 15_000;
private static final int HTTP_RANGE_NOT_SATISFIABLE = 416;
private static final java.util.concurrent.ExecutorService CANCEL_EXECUTOR =
java.util.concurrent.Executors.newCachedThreadPool(r -> {
Thread thread = new Thread(r, "download-cancel");
thread.setDaemon(true);
return thread;
});
private Downloader() {}
public static final class Cancellation implements java.util.function.BooleanSupplier {
private final AtomicBoolean cancelled = new AtomicBoolean();
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
private final AtomicReference<InputStream> input = new AtomicReference<>();
private final java.util.function.BooleanSupplier external;
public Cancellation() { this(null); }
public Cancellation(java.util.function.BooleanSupplier external) { this.external = external; }
public void cancel() {
cancelled.set(true);
HttpURLConnection active = connection.get();
if (active != null) disconnectAsync(active);
InputStream activeInput = input.get();
if (activeInput != null) closeAsync(activeInput);
}
private static void disconnectAsync(HttpURLConnection active) {
CANCEL_EXECUTOR.execute(() -> {
try { active.disconnect(); } catch (RuntimeException ignored) { }
});
}
private static void closeAsync(InputStream active) {
CANCEL_EXECUTOR.execute(() -> {
try { active.close(); } catch (IOException ignored) { }
});
}
@Override public boolean getAsBoolean() {
return cancelled.get() || (external != null && external.getAsBoolean());
}
private void attach(HttpURLConnection active) {
connection.set(active);
if (getAsBoolean()) disconnectAsync(active);
}
private void detach(HttpURLConnection active) { connection.compareAndSet(active, null); }
private void attach(InputStream active) {
input.set(active);
if (getAsBoolean()) closeAsync(active);
}
private void detach(InputStream active) { input.compareAndSet(active, null); }
}
public static String downloadString(String url) {
return downloadString(url, null);
}
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
List<String> sources = DownloadSource.INSTANCE.candidates(url);
for (int i = 0; i < sources.size(); i++) {
if (isCancelled(cancelled)) return null;
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
Fetch fetch = fetch(sources.get(i));
Fetch fetch = fetch(sources.get(i), cancelled);
// A cancelled fetch says nothing about the source, so it must not count as a failure.
if (isCancelled(cancelled)) return null;
if (fetch.body != null) {
DownloadSource.INSTANCE.succeeded(sources.get(i));
return fetch.body;
@@ -53,30 +116,52 @@ public final class Downloader {
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
java.util.function.Consumer<Float> progress) {
return downloadFile(url, destination, resume, expectedSha256, null, progress);
}
/** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress);
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
}
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
static List<String> sources(String url, String expectedSha256) {
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
}
// Package-private for the local multi-source HTTP test.
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
String expectedSha256, java.util.function.Consumer<Float> progress) {
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
}
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
String expectedSha256, java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
Identity identity = loadIdentity(destination, resume, expectedSha256);
for (int i = 0; i < sources.size(); i++) {
String source = sources.get(i);
if (isCancelled(cancelled)) return false;
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress);
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
if (outcome == Outcome.CANCELLED) return false;
if (outcome == Outcome.DONE) {
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
if (!discardPartial(destination, identity)) return false;
continue;
if (expectedSha256 != null) {
String actualSha256 = Hashes.sha256(destination);
if (isCancelled(cancelled)) return false;
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
if (!discardPartial(destination, identity)) return false;
continue;
}
}
if (isCancelled(cancelled)) return false;
resumeFile(destination).delete();
DownloadSource.INSTANCE.succeeded(source);
if (progress != null) progress.accept(1f);
@@ -88,7 +173,11 @@ public final class Downloader {
return false;
}
private enum Outcome { DONE, RETRY, FATAL }
private enum Outcome { DONE, RETRY, FATAL, CANCELLED }
private static boolean isCancelled(java.util.function.BooleanSupplier cancelled) {
return cancelled != null && cancelled.getAsBoolean();
}
private static final class Identity {
private String source;
@@ -156,7 +245,9 @@ public final class Downloader {
}
private static Outcome attempt(String url, File destination, boolean resume, Identity identity,
String expectedSha256, java.util.function.Consumer<Float> progress) {
String expectedSha256, java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
if (isCancelled(cancelled)) return Outcome.CANCELLED;
HttpURLConnection connection = null;
long have = resume && destination.isFile() ? destination.length() : 0;
try {
@@ -166,6 +257,7 @@ public final class Downloader {
have = 0;
}
connection = open(url, STALL_TIMEOUT_MS);
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(connection);
if (have > 0) {
connection.setRequestProperty("Range", "bytes=" + have + "-");
connection.setRequestProperty("If-Range", identity.etag);
@@ -174,7 +266,7 @@ public final class Downloader {
if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
@@ -185,13 +277,13 @@ public final class Downloader {
if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
String etag = connection.getHeaderField("ETag");
if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
if (!appending && have > 0) {
// If-Range may legitimately return full 200 when representation changed.
@@ -208,26 +300,36 @@ public final class Downloader {
identity.etag = strongETag(etag) ? etag : null;
saveIdentity(destination, identity, expectedSha256);
long written = have;
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
InputStream input = connection.getInputStream();
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(input);
try (InputStream in = new BufferedInputStream(input, 1 << 16);
OutputStream out = new FileOutputStream(destination, appending)) {
byte[] buffer = new byte[1 << 16];
long lastReport = 0;
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
out.write(buffer, 0, read);
written += read;
if (isCancelled(cancelled)) return Outcome.CANCELLED;
if (progress != null && written - lastReport > (1 << 20)) {
lastReport = written;
progress.accept(total > 0 ? written / (float) total : -1f);
}
}
} finally {
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
}
if (isCancelled(cancelled)) return Outcome.CANCELLED;
if (total > 0 && written < total) return Outcome.RETRY;
return Outcome.DONE;
} catch (Exception e) {
if (isCancelled(cancelled)) return Outcome.CANCELLED;
Log.w(TAG, "download " + url, e);
return Outcome.RETRY;
} finally {
if (connection != null) connection.disconnect();
if (connection != null) {
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(connection);
connection.disconnect();
}
}
}
@@ -256,9 +358,15 @@ public final class Downloader {
}
private static Fetch fetch(String url) {
return fetch(url, null);
}
private static Fetch fetch(String url, java.util.function.BooleanSupplier cancelled) {
HttpURLConnection connection = null;
Cancellation token = cancelled instanceof Cancellation ? (Cancellation) cancelled : null;
try {
connection = open(url, STALL_TIMEOUT_MS);
if (token != null) token.attach(connection);
int code = connection.getResponseCode();
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
@@ -270,10 +378,14 @@ public final class Downloader {
return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false);
}
} catch (Exception e) {
if (isCancelled(cancelled)) return new Fetch(null, false);
Log.w(TAG, "GET " + url, e);
return new Fetch(null, false);
} finally {
if (connection != null) connection.disconnect();
if (connection != null) {
if (token != null) token.detach(connection);
connection.disconnect();
}
}
}
@@ -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")
}
@@ -1,21 +1,59 @@
package com.droiddeck.launcher.core
object LogRedactor {
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
private val HIDL_SHARED_LIBRARY = Regex(
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
)
private val hidlMatcher = object : ThreadLocal<java.util.regex.Matcher>() {
override fun initialValue(): java.util.regex.Matcher = HIDL_SHARED_LIBRARY.toPattern().matcher("")
internal const val MAX_LINE_LENGTH = 64 * 1024
internal const val OVERSIZED_LINE = "<oversized log line withheld>"
private data class MatcherKey(val pattern: String, val options: Set<RegexOption>)
private class MatcherCache : LinkedHashMap<MatcherKey, java.util.regex.Matcher>(32, 0.75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<MatcherKey, java.util.regex.Matcher>?): Boolean =
size > 32
}
private fun isHidlLoaderDiagnostic(input: String, match: MatchResult): Boolean {
val matcher = hidlMatcher.get()!!
val isLibrary = try { matcher.reset(match.value).matches() } finally { matcher.reset("") }
if (!isLibrary) return false
val start = match.range.first
val end = match.range.last + 1
// Android matchers own native state, so reuse them instead of creating one for every log line.
private val matchers = object : ThreadLocal<MatcherCache>() {
override fun initialValue(): MatcherCache = MatcherCache()
}
private fun <T> withMatcher(
regex: Regex,
input: CharSequence,
action: (java.util.regex.Matcher) -> T,
): T {
val key = MatcherKey(regex.pattern, regex.options)
val matcher = matchers.get()!!.getOrPut(key) { regex.toPattern().matcher("") }
return try {
action(matcher.reset(input))
} finally {
matcher.reset("")
}
}
private fun replaceMatches(input: String, regex: Regex, replacement: String): String =
replaceMatches(input, regex) { replacement }
private fun replaceMatches(
input: String,
regex: Regex,
replacement: (java.util.regex.Matcher) -> String,
): String = withMatcher(regex, input) { matcher ->
if (!matcher.find()) return@withMatcher input
val out = StringBuffer(input.length)
do {
matcher.appendReplacement(out, java.util.regex.Matcher.quoteReplacement(replacement(matcher)))
} while (matcher.find())
matcher.appendTail(out)
out.toString()
}
private fun matchesEntire(input: String, regex: Regex): Boolean =
withMatcher(regex, input) { it.matches() }
private fun isHidlLoaderDiagnostic(input: String, match: java.util.regex.Matcher): Boolean {
if (!matchesEntire(match.group(), HIDL_SHARED_LIBRARY)) return false
val start = match.start()
val end = match.end()
val prefix = "library \""
val suffix = "\" not found"
val earliestQuote = (start - 4096).coerceAtLeast(0)
@@ -39,6 +77,12 @@ object LogRedactor {
(suffixEnd == input.length || !(input[suffixEnd].isLetterOrDigit() || input[suffixEnd] == '_'))
}
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
private val HIDL_SHARED_LIBRARY = Regex(
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
)
private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})")
private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}")
private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b")
@@ -111,6 +155,7 @@ object LogRedactor {
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
)
matchers.remove()
}
@Volatile
@@ -178,8 +223,8 @@ object LogRedactor {
}
fun describeAddresses(text: String): String {
var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
var out = replaceMatches(text, IPV6) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
out = replaceMatches(out, IPV4) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
return out
}
@@ -204,23 +249,28 @@ object LogRedactor {
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
)
fun scrubTo(src: java.io.File, out: java.io.Writer) {
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
}
fun scrubTo(
src: java.io.File,
out: java.io.Writer,
shouldStop: () -> Boolean = { false },
): Boolean = scrubLines(src, out, ::redact, shouldStop)
fun redactForShare(line: String): String {
if (line.isEmpty()) return line
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
return try {
val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
LAN_IPV4.replace(out, "<lan-address>")
replaceMatches(out, LAN_IPV4, "<lan-address>")
} catch (t: Throwable) {
"<redaction failed; line withheld>"
}
}
private const val SHARE_LINE_MAX = 64 * 1024
fun scrubForShare(src: java.io.File, out: java.io.Writer) {
fun scrubForShare(
src: java.io.File,
out: java.io.Writer,
shouldStop: () -> Boolean = { false },
): Boolean {
src.inputStream().buffered().use { input ->
input.mark(2)
val first = input.read()
@@ -228,27 +278,30 @@ object LogRedactor {
input.reset()
if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) {
out.write("<unsupported encoding; file withheld>\n")
return
return true
}
val decoder = Charsets.UTF_8.newDecoder()
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
java.io.InputStreamReader(input, decoder).use { reader ->
val buffer = CharArray(8192)
val line = StringBuilder()
var withheld = false
val line = StringBuilder(4096)
var withheld: String? = null
var afterCr = false
fun emit() {
out.write(if (withheld) "<unsupported or oversized line withheld>" else redactForShare(line.toString()))
out.write(withheld ?: redactForShare(line.toString()))
out.write("\n")
line.setLength(0)
withheld = false
withheld = null
}
try {
while (true) {
if (shouldStop()) return false
val size = reader.read(buffer)
if (size < 0) break
if (shouldStop()) return false
for (i in 0 until size) {
if (shouldStop()) return false
val ch = buffer[i]
if (afterCr) {
afterCr = false
@@ -257,23 +310,79 @@ object LogRedactor {
if (ch == '\r' || ch == '\n') {
emit()
afterCr = ch == '\r'
} else if (!withheld) {
// Splitting a line can separate a credential from its label.
if (ch == '\u0000' || line.length == SHARE_LINE_MAX) {
withheld = true
} else if (withheld == null) {
if (ch == '\u0000' || line.length == MAX_LINE_LENGTH) {
withheld = if (ch == '\u0000') "<unsupported or oversized line withheld>" else OVERSIZED_LINE
line.setLength(0)
} else {
line.append(ch)
}
} else line.append(ch)
}
}
}
if (withheld || line.isNotEmpty()) emit()
if (withheld != null || line.isNotEmpty()) emit()
} catch (_: java.nio.charset.CharacterCodingException) {
out.write("<unsupported encoding; file withheld>\n")
}
}
}
return true
}
private fun scrubLines(
src: java.io.File,
out: java.io.Writer,
scrub: (String) -> String,
shouldStop: () -> Boolean,
): Boolean {
src.bufferedReader().use { input ->
val chunk = CharArray(8192)
val line = StringBuilder(4096)
var oversized = false
var pendingContent = false
var pendingCarriageReturn = false
fun emit() {
out.write(if (oversized) OVERSIZED_LINE else scrub(line.toString()))
out.write("\n")
line.setLength(0)
oversized = false
pendingContent = false
}
while (true) {
if (shouldStop()) return false
val count = input.read(chunk)
if (count < 0) break
if (shouldStop()) return false
for (i in 0 until count) {
val char = chunk[i]
if (pendingCarriageReturn) {
emit()
pendingCarriageReturn = false
if (char == '\n') continue
}
when (char) {
'\r' -> pendingCarriageReturn = true
'\n' -> emit()
else -> {
pendingContent = true
if (!oversized) {
if (line.length < MAX_LINE_LENGTH) line.append(char)
else {
line.setLength(0)
oversized = true
}
}
}
}
}
}
if (pendingCarriageReturn || pendingContent) {
if (shouldStop()) return false
emit()
}
}
return true
}
private fun quoted(value: String): String {
@@ -315,45 +424,51 @@ object LogRedactor {
fun redact(line: String): String {
if (line.isEmpty()) return line
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
return try {
val out = Line(line)
if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}<redacted:mac>" })
if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "<redacted:mac>"))
if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) {
val value = it.groupValues[2]
if (out.has("mac")) out.set(replaceMatches(out.text, MAC_FIELD) { "${it.group(1)}<redacted:mac>" })
if (out.holds(':', 5) || out.holds('-', 5)) out.set(replaceMatches(out.text, MAC, "<redacted:mac>"))
if (out.has("serial", "android")) out.set(replaceMatches(out.text, DEVICE_IDENTIFIER) {
val value = it.group(2)
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
"${it.group(1)}${quote}<redacted:serial>${quote}"
})
if (out.holds('-', 4)) out.set(GUID.replace(out.text, "<redacted:guid>"))
if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}<redacted:jwt>" })
if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "<redacted:jwt>"))
if (out.holds('-', 4)) out.set(replaceMatches(out.text, GUID, "<redacted:guid>"))
if (out.has("jwt")) out.set(replaceMatches(out.text, JWT_LABELLED) { "${it.group(1)}<redacted:jwt>" })
if ("ey" in out.text) out.set(replaceMatches(out.text, JWT_BASE64, "<redacted:jwt>"))
if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>${it.groupValues[2]}" })
out.set(replaceMatches(out.text, SECRET_KV) {
val quote = it.group(2).orEmpty()
"${it.group(1)}${quote}<redacted:token>${quote}"
})
}
if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}<redacted:code>" })
if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "<redacted:key>"))
if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" })
if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m ->
val id = m.groupValues[1]
if (out.has("guard", "factor", "2fa")) out.set(replaceMatches(out.text, GUARD_CODE) { "${it.group(1)}<redacted:code>" })
if (out.hasRun(32, ::isHex)) out.set(replaceMatches(out.text, WEBAPI_KEY, "<redacted:key>"))
if ("76561" in out.text) out.set(replaceMatches(out.text, STEAMID64) { "${it.group(1)}********${it.group(3)}" })
if ("[U:1:" in out.text) out.set(replaceMatches(out.text, STEAMID3) { m ->
val id = m.group(1)
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
})
if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}<redacted:ip>" })
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:ip>"))
if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
if (out.has("external")) out.set(replaceMatches(out.text, EXTERNAL_ADDR) { "${it.group(1)}<redacted:ip>" })
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:ip>"))
if (out.has("onloginstatechange")) out.set(replaceMatches(out.text, LOGIN_STATE) { "${it.group(1)}<redacted:account>" })
if ("OnLoginUsersChanged " in out.text) out.set(replaceMatches(out.text, LOGIN_USERS) { "${it.group(1)}<redacted:account>" })
if (out.has("account", "user")) {
out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
out.set(replaceMatches(out.text, ACCOUNT_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
}
if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:account>"))
if ('@' in out.text) out.set(EMAIL.replace(out.text) { m ->
m.value.takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
if (out.has("login")) out.set(replaceMatches(out.text, LOGIN_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:account>"))
if ('@' in out.text) out.set(replaceMatches(out.text, EMAIL) { m ->
m.group().takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
})
if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=<redacted:token>" })
out.set(replaceMatches(out.text, RESIDUAL) { "${it.group(1)}=<redacted:token>" })
}
if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) {
out.set(LONG_TOKEN.replace(out.text, "<redacted:token>"))
out.set(replaceMatches(out.text, LONG_TOKEN, "<redacted:token>"))
}
out.text
} catch (t: Throwable) {
@@ -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"
@@ -161,6 +161,25 @@ object AddedGames {
"appxmanifest.xml" to Regex("<Application\\b[^>]*?\\bExecutable\\s*=\\s*\"([^\"]+)\"", RegexOption.IGNORE_CASE),
)
private val GAME_PARTS = setOf(
"bin", "bin32", "bin64", "binaries", "x64", "x86", "win64", "win32", "windows",
"launcher", "game", "engine", "system", "data", "app",
)
internal fun groupGames(folder: File): List<File>? {
val files = folder.listFiles() ?: return null
if (files.any { it.isFile && it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) }) return null
if (declaredExes(folder).isNotEmpty()) return null
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") }.sortedBy { it.name.lowercase() }
if (dirs.size < 2 || dirs.any { it.name.lowercase() in GAME_PARTS }) return null
return dirs.takeIf { all -> all.all { rank(it).exes.isNotEmpty() } }
}
private fun expand(folder: File, entries: Set<String>): List<File> =
if (folder.path in entries) listOf(folder) else groupGames(folder) ?: listOf(folder)
private fun entryFolders(context: Context): Set<String> = AddedExes.list(context).map { it.folder }.toSet()
/** The card's Steam libraries: the arm64 client's steamapps and the x86-64 client's own folder beside it. */
internal fun isSteamLibraryFolder(name: String): Boolean =
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
@@ -173,6 +192,7 @@ object AddedGames {
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
)
val removed = SessionPrefs.removedAddedGames(context).toSet()
val entries = entryFolders(context)
for (dir in folders.distinctBy { it.absolutePath }) {
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
val steamInstalls = steamInstallDirs(dir)
@@ -180,7 +200,7 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
scanGame(context, folder, out)
for (game in expand(folder, entries)) if (game.path !in removed) scanGame(context, game, out)
}
}
for (entry in AddedExes.list(context)) {
@@ -232,8 +252,9 @@ object AddedGames {
val entries = AddedExes.list(context)
fun owns(f: File) = holds(f) && sameGame(f, currentExe(context, entries, f), exe)
entries.map { File(it.folder) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
SessionPrefs.removedAddedGames(context).map { File(it) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
SessionPrefs.removedAddedGames(context).map { File(it) }.filter { owns(it) && groupGames(it) == null }.maxByOrNull { canonical(it).length }?.let { return it }
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
val removed = SessionPrefs.removedAddedGames(context)
val dirs = listOfNotNull(
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
GameStorage.effective(context)?.let { File(it.path) },
@@ -242,7 +263,10 @@ object AddedGames {
val base = canonical(dir)
if (!inside(path, base)) continue
val first = path.removePrefix("$base/").substringBefore('/')
File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) }?.let { return it }
val top = File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) && it.path !in removed } ?: continue
val group = groupGames(top) ?: return top
if (top.path in entries.map { it.folder }) return null
return group.firstOrNull(::holds)
}
return null
}
@@ -295,10 +319,11 @@ object AddedGames {
if (guestPath(app, dir) == null) bindFolder(app, dir)
val removed = SessionPrefs.removedAddedGames(app).toSet()
val listed = listedFolders(app, removed)
val entries = entryFolders(app)
var already = 0
val fresh = ArrayList<String>()
val added = ArrayList<Game>()
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty()) {
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty().flatMap { expand(it, entries) }) {
val path = canonical(sub)
if (listed.any { it == path || inside(path, it) || inside(it, path) }) { already++; continue }
onChecking(sub.name)
@@ -332,6 +357,7 @@ object AddedGames {
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
val out = ArrayList<String>()
val entries = entryFolders(context)
GamesFolderMigration.run(context)
val dirs = listOfNotNull(
GameStorage.effective(context)?.let { File(it.path) },
@@ -341,7 +367,7 @@ object AddedGames {
for (folder in dir.listFiles { f -> f.isDirectory }.orEmpty()) {
if (folder.path in removed || isSteamLibraryFolder(folder.name)) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
out.add(canonical(folder))
expand(folder, entries).filter { it.path !in removed }.forEach { out.add(canonical(it)) }
}
}
AddedExes.list(context).filter { it.folder !in removed }.forEach { out.add(canonical(File(it.folder))) }
@@ -89,7 +89,13 @@ object AutoComponents {
private fun enqueue(context: Context, job: Job) {
if (!queuedKeys.add(job.key)) {
if (job.asked && jobs.removeIf { it.key == job.key && !it.asked }) jobs.add(job)
synchronized(jobs) {
val old = jobs.firstOrNull { it.key == job.key }
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession)) && jobs.remove(old)) {
jobs.add(Job(old.game ?: job.game, old.component, old.asked || job.asked,
if (job.asked && !old.asked) job.seq else old.seq, old.pics ?: job.pics, old.inSession || job.inSession))
}
}
if (runNow && !draining) drain(context)
return
}
@@ -185,18 +191,19 @@ object AutoComponents {
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val wanted = autoPicks(findings, catalog)
val user = WinComponents.selection(context, key).user
val before = WinComponents.selection(context, key).auto
val installed = installedOf(context)
val kept = LinkedHashMap<String, WinComponents.AutoReason>()
val missing = ArrayList<String>()
for ((id, reason) in wanted) {
if (user[id] == false) { kept[id] = reason; continue }
if (id in installed) { kept[id] = reason; continue }
if (id in before) kept[id] = reason
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
queueDownload(context, id, asked, inSession)
missing.add(id)
}
if (inSession) Pending.set(context, key, missing)
val before = WinComponents.selection(context, key).auto
if (inSession) Pending.set(context, key, (Pending.ids(context, key).filter { it !in installed && it !in wanted } + missing).distinct())
if (before.keys != kept.keys) {
WinComponents.setAuto(context, key, kept)
Log.i(TAG, "${game.name}: on by itself ${kept.keys.joinToString().ifEmpty { "(none)" }}")
@@ -235,6 +242,16 @@ object AutoComponents {
write(context, games)
}
@Synchronized fun ids(context: Context, key: String): List<String> =
read(context).optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
@Synchronized fun add(context: Context, key: String, ids: List<String>) {
val games = read(context)
val have = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
games.put(key, JSONArray((have + ids).distinct()))
write(context, games)
}
@Synchronized fun drop(context: Context, id: String) {
val games = read(context)
for (k in games.keys().asSequence().toList()) {
@@ -317,6 +334,32 @@ object AutoComponents {
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
fun restoreMissing(context: Context): List<String> {
val selections = WinComponents.selections(context)
if (selections.isEmpty()) return emptyList()
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return emptyList()
val installed = installedOf(context)
val lostFor = selections.mapValues { (_, selection) ->
withParts(selection.effective.filter { WinComponents.validId(it) }, catalog).filter { it !in installed && it in catalog }
}.filterValues { it.isNotEmpty() }
if (lostFor.isEmpty()) return emptyList()
val lost = lostFor.values.flatten().distinct()
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids) }
lost.forEach { queueDownload(context, it, asked = true, inSession = true) }
return lost
}
private fun withParts(ids: List<String>, catalog: Map<String, WinComponents.Component>): List<String> {
val out = LinkedHashSet<String>()
fun visit(id: String, depth: Int) {
if (depth > 8 || !out.add(id)) return
catalog[id]?.dependencies?.forEach { visit(it, depth + 1) }
}
ids.forEach { visit(it, 0) }
return out.toList()
}
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
fun sweep(context: Context, games: List<Library.SteamGame>) {
@@ -274,7 +274,7 @@ object Library {
Spec("duckstation", "DuckStation", "PS1", "/opt/appimages/duckstation.AppImage", listOf("ps1", "psx"), setOf("cue", "chd", "pbp", "iso", "bin", "img", "ecm", "m3u")),
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi"), atPanel = true),
Spec("cemu", "Cemu", "Wii U", "/opt/appimages/cemu.AppImage", listOf("wiiu", "wii u"), setOf("wua", "wud", "wux", "rpx")),
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
Spec("ppsspp", "PPSSPP", "PSP", "/usr/local/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
)
private fun displayTitle(name: String): String =
@@ -16,6 +16,7 @@ data class GpuInfo(
val modelSource: String = "",
val kgslChipId: String = "",
val platformGpuModel: Int = 0,
val verifiedDevice: Boolean = false,
) {
enum class Family(val label: String) {
A8XX("Adreno 8xx"),
@@ -36,6 +37,7 @@ data class GpuInfo(
get() = when {
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
isA850 -> Support.UNTESTED
verifiedDevice -> Support.TESTED
family == Family.A6XX && model == 650 -> Support.TESTED
family == Family.A8XX -> Support.TESTED
family == Family.A7XX && model >= 725 -> Support.TESTED
@@ -85,9 +87,13 @@ data class GpuInfo(
oneUi8Gen2 = samsung && model == 740,
kgslName = raw.orEmpty(), modelSource = source, kgslChipId = chipId,
platformGpuModel = platformGpuModel,
verifiedDevice = adreno && verifiedOn(model, Build.MODEL),
)
}
internal fun verifiedOn(model: Int, device: String): Boolean =
model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true)
internal fun threeDigits(text: String): Int = Regex("""(?i)\badreno\s*(?:\(TM\)\s*)?(\d{3})(?!\d)""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
internal fun modelFromNames(
@@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@@ -47,10 +48,16 @@ public final class TurnipDriver {
private final Context context;
private final File contentDir;
private final Supplier<GpuInfo> gpuDetector;
public TurnipDriver(Context context) {
this(context, GpuInfo.Companion::detect);
}
TurnipDriver(Context context, Supplier<GpuInfo> gpuDetector) {
this.context = context;
this.contentDir = new File(context.getFilesDir(), "graphics_driver");
this.gpuDetector = gpuDetector;
}
public String driverPath(String driverId) {
@@ -288,7 +295,12 @@ public final class TurnipDriver {
Log.i(TAG, "Mali bridge: the compositor uses the system Vulkan driver");
return null;
}
int model = GpuInfo.Companion.detect().getModel();
GpuInfo gpu = gpuDetector.get();
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) {
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
return null;
}
int model = gpu.getModel();
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.hud
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
/** artwork/droiddeck-mark.svg: the split D with its circular cut-out and the blue orb. */
internal object DroidDeckMark {
private const val VIEW_X = -55.98f
const val VIEW_W = 239.92f
const val VIEW_H = 223.72f
private val body: Path by lazy {
val d = Path().apply {
moveTo(-31.98f, 0f)
lineTo(63.97f, 0f)
cubicTo(125.81f, 0f, 175.93f, 50.08f, 175.93f, 111.86f)
cubicTo(175.93f, 173.64f, 125.81f, 223.72f, 63.97f, 223.72f)
lineTo(-31.98f, 223.72f)
close()
}
val cut = Path().apply {
addCircle(63.98f, 111.86f, 71.81f, Path.Direction.CW)
addRect(56.055f, 0f, 71.885f, 45f, Path.Direction.CW)
addRect(56.055f, 178.72f, 71.885f, 223.72f, Path.Direction.CW)
}
d.op(cut, Path.Op.DIFFERENCE)
d.offset(-VIEW_X, 0f)
d
}
private val scaled = Path()
private val matrix = Matrix()
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
fun widthFor(height: Float): Float = height * VIEW_W / VIEW_H
/** Where the drawn mark starts and ends inside [widthFor]: the artwork has empty space on both sides. */
fun inkLeftFor(height: Float): Float = (-31.98f - VIEW_X) * height / VIEW_H
fun inkRightFor(height: Float): Float = (175.93f - VIEW_X) * height / VIEW_H
fun draw(canvas: Canvas, left: Float, top: Float, height: Float, bodyColor: Int, orbColor: Int) {
val s = height / VIEW_H
matrix.setScale(s, s)
matrix.postTranslate(left, top)
body.transform(matrix, scaled)
paint.color = bodyColor
canvas.drawPath(scaled, paint)
paint.color = orbColor
canvas.drawCircle(left + (63.98f - VIEW_X) * s, top + 111.86f * s, 55.98f * s, paint)
}
}
@@ -0,0 +1,56 @@
package com.droiddeck.launcher.hud
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
/** FusionHUD's settings as one "key=value,…" string (FusionHudView.applyConfig), stored in SessionPrefs. */
internal object FusionHudConfig {
/**
* Bannerlator's Fusion defaults (DeckOverlaySettings), with the FPS graph from the old DroidDeck HUD. The HUD starts
* locked, so like the old HUD it lets touches through until it is unlocked to move it.
*/
val DEFAULTS: Map<String, String> = linkedMapOf(
"hudSize" to "minimal", "hudLocked" to "1", "hudScale" to "100", "hudOpacity" to "80", "hudColor" to "mid",
"hudOutline" to "40", "hudOutlineAccent" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
)
/** Switches Bannerlator sets together (DeckOverlaySettings twins). */
private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer")
fun load(context: Context): MutableMap<String, String> {
val values = LinkedHashMap(DEFAULTS)
val stored = SessionPrefs.fusionHudConfig(context)
if (stored == null) {
values["showFPS"] = flag(SessionPrefs.hudShowFps(context))
values["showFPSGraph"] = flag(SessionPrefs.hudShowGraph(context))
values["hudOpacity"] = SessionPrefs.hudOpacity(context).toString()
} else {
for (entry in KeyValueSet(stored)) if (entry.size == 2 && entry[0] in DEFAULTS) values[entry[0]] = entry[1]
}
return values
}
fun encode(values: Map<String, String>): String = values.entries.joinToString(",") { "${it.key}=${it.value}" }
fun set(context: Context, key: String, value: String): Map<String, String> {
val values = load(context)
if (key !in DEFAULTS) return values
values[key] = value
TWINS[key]?.let { values[it] = value }
SessionPrefs.setFusionHudConfig(context, encode(values))
return values
}
fun reset(context: Context): Map<String, String> {
SessionPrefs.setFusionHudConfig(context, encode(DEFAULTS))
return DEFAULTS
}
private fun flag(on: Boolean) = if (on) "1" else "0"
}
@@ -0,0 +1,236 @@
package com.droiddeck.launcher.hud
import android.content.Context
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.view.Choreographer
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import kotlin.math.roundToInt
/**
* FusionHUD on the session screen, in place of the old text HUD: the view, the frame feed from gamescope
* (MangoHud's frame times) and MangoHud's readings, started with the session's first frame.
*/
class FusionHudHost(context: Context) {
private val context = context.applicationContext
private val handler = Handler(Looper.getMainLooper())
private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH))
private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context))
private var view: FusionHudView? = null
private var parent: ViewGroup? = null
private var running = false
private var hidden = false
private var backgrounded = false
private var polling = false
private var wantX = Float.NaN
private var wantY = Float.NaN
private var engine = ""
private var gpuName = ""
private var protonPid = 0
private var proton = ""
@Volatile private var lastWindow: String? = null
var onPresentingWindowChanged: (() -> Unit)? = null
/** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */
var onConfigChanged: (() -> Unit)? = null
/** Screen point → whether an on-screen control takes a touch there; a locked HUD lets those through. */
var passesTouchAt: ((rawX: Float, rawY: Float) -> Boolean)? = null
private val listener = object : WaylandCompositor.GameListener {
override fun onGameSurface(window: String?, gpuName: String?) {
if (!gpuName.isNullOrBlank()) handler.post { this@FusionHudHost.gpuName = cleanGpuName(gpuName) }
if (window != null && window != lastWindow) {
lastWindow = window
handler.post { onPresentingWindowChanged?.invoke() }
}
}
override fun onGameFrame() {
feed.onCompositorFrame(System.nanoTime())
}
}
private val frameCallback = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
if (!running || !polling) return
if (feed.poll(System.nanoTime())) view?.onFrames()
Choreographer.getInstance().postFrameCallback(this)
}
}
private val enabled: Boolean
get() = SessionPrefs.hudEnabled(context) &&
!File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
/** Adds the HUD to [root] at [index] (above the game surface, under the session overlay). */
fun attach(root: FrameLayout, index: Int) {
if (view != null) return
val hud = FusionHudView(root.context)
hud.setFrameStats(feed.stats)
hud.setMangoReadings(readings)
hud.setGpuModel(cleanGpuName(GpuInfo.detect().displayName(context)))
hud.onRefresh = Runnable { refreshLabels(hud) }
hud.setOnMovedListener { x, y ->
wantX = x; wantY = y
keepOnScreen(hud)
wantX = hud.x; wantY = hud.y
SessionPrefs.setFusionHudPosition(context, hud.x, hud.y)
}
hud.setOnSizeCycledListener { size -> FusionHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
hud.setOnLockChangedListener { locked ->
FusionHudConfig.set(context, "hudLocked", if (locked) "1" else "0")
onConfigChanged?.invoke()
}
hud.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> if (!hud.isDragging) keepOnScreen(hud) }
hud.passesTouchAt = { x, y -> passesTouchAt?.invoke(x, y) == true }
hud.visibility = View.GONE
val margin = (16 * root.resources.displayMetrics.density).roundToInt()
root.addView(hud, index, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
leftMargin = margin
topMargin = margin
})
SessionPrefs.fusionHudPosition(context)?.let { (x, y) -> wantX = x; wantY = y; hud.post { keepOnScreen(hud) } }
view = hud
parent = root
applyConfig()
}
fun applyConfig() {
view?.applyConfig(FusionHudConfig.encode(FusionHudConfig.load(context)))
}
fun refresh() {
applyConfig()
if (!enabled) stop() else if (!running) start()
}
fun start() {
if (running || !enabled || view == null) return
running = true
WaylandCompositor.setGameListener(listener)
applyShown()
}
fun stop() {
running = false
showing = false
polling = false
Choreographer.getInstance().removeFrameCallback(frameCallback)
WaylandCompositor.clearGameListener(listener)
feed.close()
view?.visibility = View.GONE
}
/** Picture-in-picture and similar: keep running, draw nothing. */
fun setHidden(hide: Boolean) {
hidden = hide
applyShown()
}
/** The session screen is stopped (another app in front): draw nothing and stop reading sensors. */
fun setBackgrounded(stopped: Boolean) {
backgrounded = stopped
applyShown()
}
private fun applyShown() {
if (!running) return
val show = !hidden && !backgrounded
view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show
// Frames are read once per display frame only while the HUD is drawn.
if (show != polling) {
polling = show
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
else Choreographer.getInstance().removeFrameCallback(frameCallback)
}
}
/** A sensor report (FusionHUD's diagnostics) in Downloads/DroidDeck; null when it can't be written. */
fun exportDiagnostics(): File? = runCatching {
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck")
dir.mkdirs()
val stamp = java.text.SimpleDateFormat("yyyyMMdd-HHmmss", java.util.Locale.US).format(java.util.Date())
val file = File(dir, "HUD-diagnostics-$stamp.txt")
// Its own reader: the HUD's CPU load is the change since its previous sample, which an export must
// not move. Two samples half a second apart, MangoHud's sampling period.
val metrics = HudMetrics(context)
metrics.setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context)))
metrics.snapshot()
Thread.sleep(500)
val mango = metrics.snapshot()
file.writeText(metrics.also { it.setMangoReadings(null) }.buildDiagnosticsReport(context) + "\n== As the HUD shows them (MangoHud's sources) ==\n" +
"CPU ${mango.cpuPercent}% ${mango.cpuTempC}°C, GPU ${mango.gpuPercent}% ${mango.gpuClockMhz}MHz ${mango.gpuTempC}°C, " +
"RAM ${mango.ramUsedText()}/${mango.ramTotalText()}, VRAM ${mango.vramText()}, battery ${mango.battery.percent}% " +
"${mango.battery.watts}W charging=${mango.battery.charging}\n" +
"CPU temperature zones: ${LinuxRuntime.cpuTempZones().joinToString { it.name }}\n" +
"Frames: ${if (feed.engine.isNotEmpty() || feed.pid > 0) "gamescope (pid ${feed.pid}, ${feed.engine})" else "compositor"}, " +
"fps ${feed.stats.fps}\n")
file
}.getOrNull()
private fun refreshLabels(hud: FusionHudView) {
if (feed.engine.isNotBlank() && !feed.steamFocused) engine = feed.engine
hud.setEngineLabel(engine)
if (gpuName.isNotBlank()) hud.setGpuModel(gpuName)
hud.setResolution(if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString {
append(feed.outputWidth).append('x').append(feed.outputHeight)
if (feed.refreshMilliHz > 0) append(" @ ").append((feed.refreshMilliHz + 499) / 1000).append("Hz")
} else "")
val pid = feed.pid
if (pid > 0 && pid != protonPid) {
protonPid = pid
proton = protonName(pid) ?: proton
}
hud.setWineVersion(proton)
hud.setPresentedFps(presentedFps())
}
private fun presentedFps(): Float {
if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f
val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
}
// The HUD is clamped from where the user left it (wantX/wantY, set on a drop or restore), not from where
// it is drawn: a window that shrinks and grows back (picture-in-picture, a fold) must not leave it in the
// corner the small window pushed it to.
private fun keepOnScreen(v: View) {
val p = v.parent as? View ?: return
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return
if (wantX.isNaN()) { wantX = v.x; wantY = v.y }
val maxX = (p.width - v.width).toFloat().coerceAtLeast(0f)
val maxY = (p.height - v.height).toFloat().coerceAtLeast(0f)
val x = wantX.coerceIn(0f, maxX)
val y = wantY.coerceIn(0f, maxY)
if (v.x != x) v.x = x
if (v.y != y) v.y = y
}
companion object {
/** True while the HUD is on screen; DroidDeck keeps sampling VRAM for it (GpuMemComponent). */
@Volatile @JvmStatic var showing = false
private set
/** "Adreno (TM) 750" as the driver names it, "Adreno 750" as DroidDeck does elsewhere. */
internal fun cleanGpuName(name: String): String = name.replace("(TM)", "").replace(Regex("\\s+"), " ").trim()
/** The Proton build of a game process: the first STEAM_COMPAT_TOOL_PATHS entry's folder. */
internal fun protonName(pid: Int): String? = runCatching {
val environ = File("/proc/$pid/environ").readBytes().toString(Charsets.UTF_8).split('\u0000')
val paths = environ.firstOrNull { it.startsWith("STEAM_COMPAT_TOOL_PATHS=") }?.substringAfter('=') ?: return null
paths.split(':').firstOrNull { it.isNotBlank() }?.trimEnd('/')?.substringAfterLast('/')
}.getOrNull()?.takeIf { it.isNotBlank() }
}
}
@@ -0,0 +1,86 @@
/*
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
* Copyright (C) The412Banner <https://github.com/The412Banner>
*
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
* any use, fork, or distribution must preserve credit to "The412Banner" and a
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
*/
package com.droiddeck.launcher.hud
/**
* Size modes for the Fusion HUD (the 4th selectable in-game overlay style). One shared color-coded
* visual language, four amounts of detail — see the approved mockup. The config value is the lower-case
* token stored under the `hudSize` key; the label is the user-facing string.
*/
enum class FusionSize(val token: String, val label: String) {
FULL("full", "Full"),
TILES("tiles", "Tiles"),
PILL("pill", "Pill"),
MINIMAL("minimal", "Minimal"),
MEGA("mega", "Mega");
/** Next size in the tap-cycle: Full → Tiles → Pill → Minimal → Mega → Full. */
fun next(): FusionSize {
val all = values()
return all[(ordinal + 1) % all.size]
}
/**
* The metric toggle chips this size actually renders — the SINGLE source of truth queried by BOTH
* config surfaces ({@code FpsCounterConfigDialog} + in-game {@code XServerDrawer} HudContent) so the
* chip list can't drift from what the view draws. Chip ids are the chip LABELS used in the UI.
* (Hiding a chip is purely UI; buildConfig() still emits every key — strip-invariant.)
*/
fun supportedChips(): Set<String> = when (this) {
MINIMAL -> MINIMAL_CHIPS
PILL -> PILL_CHIPS
FULL, TILES -> STANDARD_CHIPS
MEGA -> MEGA_CHIPS
}
companion object {
fun from(token: String?): FusionSize =
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
// Chip-label ids (must match the labels the config UIs build). "Clock" is a small subtle
// corner readout available in EVERY size, so it's in all sets.
// The API/engine label ("Engine" chip) shows on the FPS row in EVERY size, so it's in all sets.
// "Wrapper" and "DX ver" are Mega-only: the wrapper appears solely below Mega's frametime graph,
// and "DX ver" gates the DX-version suffix on Mega's FPS-row engine label.
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "0.01% low", "FPS .1", "Engine", "Clock")
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
val STANDARD_CHIPS = setOf(
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
"Battery", "GPU model", "Engine", "0.01% low", "FPS .1", "Clock",
)
val MEGA_ONLY = setOf(
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
)
val MEGA_CHIPS = STANDARD_CHIPS + MEGA_ONLY
}
}
/**
* The Wayland HDR state the Fusion HUD shows on its own line, directly under the latency · display-server
* line (the host sets it with [FusionHudView.setHdrState]). [NONE] = no line at all: every session whose
* HDR gate is closed (X11, SDR screens, HDR off) keeps the HUD exactly as it was.
*/
object FusionHdr {
const val NONE = 0
const val ON = 1 // HDR frames on screen with HDR headroom
const val NO_HEADROOM = 2 // HDR frames on screen, but the display gives them no headroom (5 s+)
const val OFF = 3 // the drawer's HDR output switch is off (tone-mapped to SDR)
const val READY = 4 // HDR open for the session, no HDR frames on screen right now
const val TONEMAPPED = 5 // HDR output on, but the frames are shown tone-mapped (frame generation
// on a screen that offers no HDR10 swapchain)
const val NOT_ON_THIS_SCREEN = 6 // HDR open for the session, but the screen the game is on NOW
// reports no HDR10 (the TV was unplugged mid-game). The offer to the
// game cannot be withdrawn once made, so the gate stays open for the
// session — but "ready" would be a lie on a panel that cannot show it.
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,262 @@
package com.droiddeck.launcher.hud
import java.io.File
import kotlin.math.roundToInt
/**
* Frame statistics by MangoHud's rules, so the HUD and Steam's performance overlay agree: MangoHud
* overlay.cpp update_hud_info_with_frametime and hud_elements.cpp fps() / frame_timing(). The FPS is the
* frames counted over a sampling period of at least 500 ms, the frame time next to it is 1000 / FPS, and
* the graph holds the last 200 frame times (zeros until filled) on a fixed 0-50 ms scale, min and max
* taken over those 200. Average and lows are FusionHUD's own readouts.
*/
internal class FrameStats {
private val graph = FloatArray(GRAPH_FRAMES)
private var graphHead = 0
private var lastPresentNs = 0L
private var lastFpsUpdateNs = 0L
private var framesSinceUpdate = 0
private val lowsRing = LongArray(LOWS_FRAMES)
private var lowsHead = 0
private var lowsSize = 0
private var cachedLows = Lows.EMPTY
private var cachedLowsNs = 0L
private var sessionStartNs = 0L
private var sessionFrames = 0L
@Volatile var fps = 0f
private set
/** Completed sampling periods; MangoHud redraws its readouts when one completes. */
@Volatile var fpsUpdates = 0L
private set
/** Frames added so far; the HUD redraws its graph when this moves. */
@Volatile var count = 0L
private set
@Synchronized
fun add(frametimeNs: Long, timeNs: Long) {
if (frametimeNs <= 0L) return
if (lastPresentNs != 0L) {
graph[graphHead] = frametimeNs / 1e6f
graphHead = (graphHead + 1) % GRAPH_FRAMES
}
val elapsed = timeNs - lastFpsUpdateNs
if (elapsed >= FPS_PERIOD_NS) {
fps = (1e9 * framesSinceUpdate / elapsed).toFloat()
framesSinceUpdate = 0
lastFpsUpdateNs = timeNs
fpsUpdates++
}
lastPresentNs = timeNs
framesSinceUpdate++
if (frametimeNs < PAUSE_NS) {
lowsRing[lowsHead] = frametimeNs
lowsHead = (lowsHead + 1) % LOWS_FRAMES
if (lowsSize < LOWS_FRAMES) lowsSize++
if (sessionStartNs == 0L) sessionStartNs = timeNs - frametimeNs
sessionFrames++
}
count++
}
@Synchronized
fun reset() {
graph.fill(0f)
graphHead = 0
lastPresentNs = 0L
lastFpsUpdateNs = 0L
framesSinceUpdate = 0
lowsHead = 0
lowsSize = 0
cachedLows = Lows.EMPTY
cachedLowsNs = 0L
sessionStartNs = 0L
sessionFrames = 0L
fps = 0f
count++
}
/** MangoHud's frame time readout: 1000 / FPS. */
fun frametimeMs(): Float = 1000f / maxOf(fps, 1f)
/** The graph, oldest first, into [out] (GRAPH_FRAMES long). */
@Synchronized
fun graph(out: FloatArray) {
for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES]
}
@Synchronized
fun graphMinMs(): Float = graph.min()
@Synchronized
fun graphMaxMs(): Float = graph.max()
/** Average over the frames this session, from the first frame to [nowNs]'s last frame. */
@Synchronized
fun averageFps(): Float {
if (sessionFrames < 2 || lastPresentNs <= sessionStartNs) return 0f
return (1e9 * sessionFrames / (lastPresentNs - sessionStartNs)).toFloat()
}
@Synchronized
fun sessionSeconds(nowNs: Long): Float = if (sessionStartNs == 0L) 0f else (nowNs - sessionStartNs) / 1e9f
class Lows(val low1Fps: Float, val low01Fps: Float, val low001Fps: Float) {
companion object {
val EMPTY = Lows(0f, 0f, 0f)
}
}
/** FPS at the 99th, 99.9th and 99.99th percentile frame time of the last LOWS_FRAMES frames. */
fun lows(nowNs: Long): Lows {
val copy: LongArray
synchronized(this) {
if (cachedLows !== Lows.EMPTY && nowNs - cachedLowsNs < LOWS_RECOMPUTE_NS) return cachedLows
if (lowsSize < 2) return Lows.EMPTY
copy = LongArray(lowsSize)
val start = (lowsHead - lowsSize + LOWS_FRAMES) % LOWS_FRAMES
for (i in 0 until lowsSize) copy[i] = lowsRing[(start + i) % LOWS_FRAMES]
}
copy.sort()
fun at(p: Double): Float {
val ft = copy[(p * (copy.size - 1)).roundToInt().coerceIn(0, copy.size - 1)]
return if (ft > 0) (1e9 / ft).toFloat() else 0f
}
val result = Lows(at(0.99), at(0.999), at(0.9999))
synchronized(this) {
cachedLows = result
cachedLowsNs = nowNs
}
return result
}
companion object {
const val GRAPH_FRAMES = 200
const val GRAPH_MAX_MS = 50f
const val FPS_PERIOD_NS = 500_000_000L
const val LOWS_FRAMES = 8192
private const val PAUSE_NS = 1_000_000_000L
private const val LOWS_RECOMPUTE_NS = 250_000_000L
}
}
/**
* Feeds [stats] with the frame times gamescope shares (the ones MangoHud shows). Sessions without the
* shared file, or where gamescope stopped sending, fall back to the frames DroidDeck's compositor shows,
* which stop at the screen's refresh rate.
*/
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
private var handle = 0L
private var nextOpenNs = 0L
private var lastRingFrameNs = 0L
private var lastInfoNs = 0L
private val frametimes = LongArray(HudFrames.CAPACITY)
private val times = LongArray(HudFrames.CAPACITY)
private val info = IntArray(5)
@Volatile private var fromGamescope = false
private var lastCompositorNs = 0L
@Volatile private var compositorFrames = 0L // written by the compositor thread only
private var seenCompositorFrames = 0L
@Volatile var engine = ""
private set
@Volatile var steamFocused = false
private set
@Volatile var pid = 0
private set
@Volatile var outputWidth = 0
private set
@Volatile var outputHeight = 0
private set
@Volatile var refreshMilliHz = 0
private set
/** Main thread, once per display frame. True when new frames arrived. */
fun poll(nowNs: Long): Boolean {
val compositorAdded = compositorFrames != seenCompositorFrames
seenCompositorFrames = compositorFrames
if (handle == 0L) {
if (nowNs < nextOpenNs) return compositorAdded
nextOpenNs = nowNs + REOPEN_NS
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
if (handle == 0L) return compositorAdded
// Frames already in the file were written before this reader started.
HudFrames.nativePoll(handle, frametimes, times)
}
val n = HudFrames.nativePoll(handle, frametimes, times)
if (n > 0) {
if (!fromGamescope) {
stats.reset()
fromGamescope = true
}
for (i in 0 until n) stats.add(frametimes[i], times[i])
lastRingFrameNs = times[n - 1]
} else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) {
fromGamescope = false
}
// A new session writes the file again from the start; reopen when gamescope has gone quiet.
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
if (nowNs - lastInfoNs >= INFO_NS) {
lastInfoNs = nowNs
readInfo()
}
return n > 0 || compositorAdded
}
/** Compositor thread: one frame shown on the panel. */
fun onCompositorFrame(nowNs: Long) {
if (fromGamescope) {
lastCompositorNs = 0L
return
}
val last = lastCompositorNs
lastCompositorNs = nowNs
if (last != 0L) {
stats.add(nowNs - last, nowNs)
compositorFrames++
}
}
fun close() {
if (handle != 0L) HudFrames.nativeClose(handle)
handle = 0L
}
private fun readInfo() {
val name = if (handle != 0L && fromGamescope) HudFrames.nativeInfo(handle, info) else null
if (name == null) {
engine = ""
return
}
pid = info[0]
outputWidth = info[1]
outputHeight = info[2]
refreshMilliHz = info[3]
steamFocused = info[4] != 0
engine = engineLabel(name)
}
companion object {
private const val REOPEN_NS = 2_000_000_000L
private const val LIVE_NS = 2_000_000_000L
private const val STALE_NS = 5_000_000_000L
private const val INFO_NS = 500_000_000L
/** DroidDeck's mangoapp's names for gamescope's engine field (Valve's 20260902.1 build, app/main.cpp
* engine_type_from_str and overlay.h engines); gamescope sends "gamescope" when it knows none. */
fun engineLabel(name: String): String = when (name) {
"DXVK" -> "DXVK"
"vkd3d" -> "VKD3D"
"mesa zink" -> "ZINK"
"Damavand" -> "DAMAVAND"
"Feral3D" -> "Feral3D"
"gamescope", "" -> "GAMESCOPE"
else -> "VULKAN"
}
}
}
@@ -0,0 +1,17 @@
package com.droiddeck.launcher.hud
/** Reader for the frame-times file gamescope patch 0125 writes (hudframes.c). */
internal object HudFrames {
init {
System.loadLibrary("droiddeckwayland")
}
/** Under the Linux root: the session exports /run/droiddeck-hud/frames to gamescope. */
const val PATH = "run/droiddeck-hud/frames"
const val CAPACITY = 1024
@JvmStatic external fun nativeOpen(path: String): Long
@JvmStatic external fun nativeClose(handle: Long)
@JvmStatic external fun nativePoll(handle: Long, frametimes: LongArray, times: LongArray): Int
@JvmStatic external fun nativeInfo(handle: Long, info: IntArray): String?
}
@@ -0,0 +1,265 @@
/*
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
* Copyright (C) The412Banner <https://github.com/The412Banner>
*
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
* any use, fork, or distribution must preserve credit to "The412Banner" and a
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
*/
package com.droiddeck.launcher.hud;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Shared touch + lock behaviour for every in-game performance HUD (classic FrameRating(+Horizontal),
* GameHub PerfHudView, GameNative PerformanceHudView, and the Fusion HUD). One place so the four
* overlays can't drift:
*
* <ul>
* <li><b>tap</b> → {@link Callbacks#onTap()} (orientation-toggle for the first three; size-cycle for
* Fusion) — a no-op that only re-flashes the lock badge while locked.</li>
* <li><b>drag</b> → moves the host view and, on release, {@link Callbacks#onMoved} to persist the
* position — disabled (frozen) while locked.</li>
* <li><b>long-press</b> → toggles {@code hudLocked}, persisted via {@link Callbacks#onLockChanged}
* and kept in sync with the "Lock in place" menu chip. Works locked or unlocked (so a long-press
* always unlocks); a locked {@code FusionHudView} passes touches on only over on-screen controls.</li>
* </ul>
*
* <p>On every lock/unlock (and on a blocked gesture while locked) a small padlock badge fades in →
* holds → fades out in a corner of the panel. The fade is driven by a self-reposting Runnable that
* invalidates only while visible — nothing runs on the present path, nothing animates at rest.
*
* <p>All methods are Main-thread only (touch + draw), matching the epoll-thread rule: the views feed
* this from {@code onTouchEvent}/{@code dispatchDraw}, never from a present tick.
*/
public class HudLockController {
public interface Callbacks {
/** Unlocked single tap: orientation-toggle (classic/gamehub/gamenative) or size-cycle (fusion). */
void onTap();
/** Drag released (unlocked): persist the new (x, y). */
void onMoved(float x, float y);
/** Lock toggled by long-press: persist {@code hudLocked} + sync the menu chip. */
void onLockChanged(boolean locked);
}
// Fade timing (ms): in → hold → out. Lock/unlock hold ~1.5 s; a blocked-gesture re-flash is shorter.
private static final long FADE_IN_MS = 160;
private static final long HOLD_TOGGLE_MS = 1500;
private static final long HOLD_REFLASH_MS = 750;
private static final long FADE_OUT_MS = 420;
private static final long FRAME_MS = 32;
private final View view;
private final Callbacks cb;
private final GestureDetector detector;
private boolean locked = false;
// Drag state
private float downRawX, downRawY, startX, startY;
private boolean dragging = false;
// Fade state
private long fadeStart = 0;
private long holdMs = HOLD_TOGGLE_MS;
private boolean fadeShowLocked = false;
private final Paint iconFill = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint iconStroke = new Paint(Paint.ANTI_ALIAS_FLAG);
public HudLockController(Context context, View view, Callbacks cb) {
this.view = view;
this.cb = cb;
this.detector = new GestureDetector(context, new Listener());
this.detector.setIsLongpressEnabled(true);
iconFill.setStyle(Paint.Style.FILL);
iconStroke.setStyle(Paint.Style.STROKE);
iconStroke.setStrokeCap(Paint.Cap.ROUND);
iconStroke.setStrokeJoin(Paint.Join.ROUND);
}
/** Set lock state from config (applyConfig) WITHOUT firing the persist callback. */
public void setLocked(boolean locked) { this.locked = locked; }
public boolean isLocked() { return locked; }
public boolean isDragging() { return dragging; }
/** Feed from the host view's onTouchEvent. Always consumes (mirrors the legacy manual handlers). */
public boolean onTouchEvent(MotionEvent event) {
detector.onTouchEvent(event);
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
if (dragging && !locked) cb.onMoved(view.getX(), view.getY());
dragging = false;
}
return true;
}
private final class Listener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
downRawX = e.getRawX();
downRawY = e.getRawY();
startX = view.getX();
startY = view.getY();
dragging = false;
return true;
}
@Override
public void onLongPress(MotionEvent e) {
// Long-press always toggles — this is the only gesture that still works while locked.
locked = !locked;
cb.onLockChanged(locked);
flash(locked, HOLD_TOGGLE_MS);
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (locked) {
flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
} else {
cb.onTap();
}
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (locked) {
if (!dragging) flash(true, HOLD_REFLASH_MS);
dragging = true; // mark so the blocked drag doesn't fall through to a tap
return true;
}
view.setX(startX + (e2.getRawX() - downRawX));
view.setY(startY + (e2.getRawY() - downRawY));
dragging = true;
return true;
}
}
// ---- Fade badge -------------------------------------------------------
private void flash(boolean showLocked, long hold) {
fadeShowLocked = showLocked;
holdMs = hold;
fadeStart = SystemClock.elapsedRealtime();
view.removeCallbacks(fadeTick);
view.post(fadeTick);
}
private final Runnable fadeTick = new Runnable() {
@Override
public void run() {
view.invalidate();
if (currentAlpha() > 0f) view.postDelayed(this, FRAME_MS);
}
};
private float currentAlpha() {
if (fadeStart == 0) return 0f;
long e = SystemClock.elapsedRealtime() - fadeStart;
if (e < 0) return 0f;
if (e < FADE_IN_MS) return e / (float) FADE_IN_MS;
long holdEnd = FADE_IN_MS + holdMs;
if (e < holdEnd) return 1f;
long outEnd = holdEnd + FADE_OUT_MS;
if (e < outEnd) return 1f - (e - holdEnd) / (float) FADE_OUT_MS;
return 0f;
}
private static int withAlpha(int color, float a) {
return Color.argb(Math.round(255 * a), Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Draw the padlock badge in the top-right of the panel if a fade is in progress. Call from the
* host's onDraw (plain View) or dispatchDraw (ViewGroup), after the content.
*
* <p>No background box: the glyph is drawn twice — a slightly expanded, thicker semi-transparent
* black "halo" pass for legibility on any game frame, then the white glyph on top — so it reads as
* a floating icon, not an opaque tile.
*/
public void drawBadge(Canvas canvas) {
float a = currentAlpha();
if (a <= 0f) return;
float d = view.getResources().getDisplayMetrics().density;
float size = 15f * d;
float margin = 4f * d;
float right = view.getWidth() - margin;
float left = right - size;
float top = margin;
float cx = (left + right) / 2f;
float bottom = top + size;
float bodyTop = top + size * 0.46f;
float bodyLeft = left + size * 0.14f;
float bodyRight = right - size * 0.14f;
float r = size * 0.2f;
float shackleTop = top + size * 0.08f;
// Pass 1: dark halo (expanded body, thicker shackle) for contrast; Pass 2: white glyph.
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
Color.argb(Math.round(150 * a), 0, 0, 0), 3.0f * d, 0.9f * d, false);
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
withAlpha(0xFFFFFFFF, a), 1.7f * d, 0f, true);
}
/** One padlock pass. {@code halo} inflates the body/shackle in dark; the white pass punches the keyhole. */
private void drawLock(Canvas canvas, float cx, float bodyTop, float bodyLeft, float bodyRight,
float bottom, float r, float shackleTop, float d,
int color, float strokeW, float expand, boolean punchKeyhole) {
iconFill.setColor(color);
iconStroke.setColor(color);
iconStroke.setStrokeWidth(strokeW);
// Body
canvas.drawRoundRect(bodyLeft - expand, bodyTop - expand, bodyRight + expand, bottom + expand,
2.4f * d, 2.4f * d, iconFill);
if (punchKeyhole) {
int prev = iconFill.getColor();
iconFill.setColor(Color.argb(Color.alpha(color), 0, 0, 0));
canvas.drawCircle(cx, (bodyTop + bottom) / 2f, 1.6f * d, iconFill);
iconFill.setColor(prev);
}
RectF arc = new RectF(cx - r, shackleTop, cx + r, shackleTop + 2f * r);
if (fadeShowLocked) {
// Closed: both legs run straight down into the body.
Path p = new Path();
p.addArc(arc, 180f, 180f);
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
p.moveTo(cx + r, shackleTop + r); p.lineTo(cx + r, bodyTop);
canvas.drawPath(p, iconStroke);
} else {
// Open, clearly to the LEFT: the RIGHT leg stays seated in the body; the arc + LEFT leg
// hinge up-and-left off the right attachment so the left leg lifts well clear of the body.
canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke); // fixed right leg
Path p = new Path();
p.addArc(arc, 180f, 180f);
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg
canvas.save();
canvas.rotate(-42f, cx + r, shackleTop + r);
canvas.drawPath(p, iconStroke);
canvas.restore();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
/*
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
* Copyright (C) The412Banner <https://github.com/The412Banner>
*
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
* any use, fork, or distribution must preserve credit to "The412Banner" and a
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
*/
package com.droiddeck.launcher.hud;
import androidx.annotation.NonNull;
import java.util.Iterator;
public class KeyValueSet implements Iterable<String[]> {
private String data = "";
// Default constructor for an empty KeyValueSet
public KeyValueSet() {
this.data = "";
}
// Constructor to initialize with a string representation of key-value pairs
public KeyValueSet(String data) {
this.data = data != null && !data.isEmpty() ? data : "";
}
// Helper method to find the start and end indices of a key in the data string
private int[] indexOfKey(String key) {
int start = 0;
int end = data.indexOf(",");
if (end == -1) end = data.length();
while (start < end) {
int index = data.indexOf("=", start);
String currKey = data.substring(start, index);
if (currKey.equals(key)) return new int[]{start, end};
start = end + 1;
end = data.indexOf(",", start);
if (end == -1) end = data.length();
}
return null;
}
// Method to get the value associated with a key, or an empty string if the key is not present
public String get(String key) {
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
return "";
}
// Method to get the value associated with a key, or a fallback value if the key is not present
public String get(String key, String fallback) {
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
return fallback;
}
// Method to get a boolean value associated with a key, or a fallback value if the key is not present
public boolean getBoolean(String key, boolean fallback) {
String value = get(key);
if (value.isEmpty()) return fallback;
return value.equals("1") || value.equals("t") || value.equalsIgnoreCase("true");
}
// Method to get a float value associated with a key, or a fallback value if the key is not present
public float getFloat(String key, float fallback) {
String value = get(key);
try {
if (!value.isEmpty()) return Float.parseFloat(value);
} catch (NumberFormatException e) {
// Ignore exception and return fallback
}
return fallback;
}
// Method to set a value for a key in the key-value data
public void put(String key, Object value) {
int[] range = indexOfKey(key);
if (range != null) {
data = data.substring(0, range[0]) + key + "=" + value + data.substring(range[1]);
} else {
data = (!data.isEmpty() ? data + "," : "") + key + "=" + value;
}
}
// Method to set a float value for a key in the key-value data
public void put(String key, float value) {
put(key, String.valueOf(value));
}
// Iterator implementation for key-value pairs in the format [key, value]
@NonNull
@Override
public Iterator<String[]> iterator() {
final int[] start = {0};
final int[] end = {data.indexOf(",")};
// A single-item config (no comma) gives indexOf == -1, making hasNext() (start < end)
// immediately false so the sole pair was never iterated (get() then returned the
// fallback). Guard it exactly as next() already does. An empty string still yields
// end == 0 → no iteration, which is correct.
if (end[0] == -1) end[0] = data.length();
final String[] item = new String[2];
return new Iterator<String[]>() {
@Override
public boolean hasNext() {
return start[0] < end[0];
}
@Override
public String[] next() {
int index = data.indexOf("=", start[0]);
item[0] = data.substring(start[0], index);
item[1] = data.substring(index + 1, end[0]);
start[0] = end[0] + 1;
end[0] = data.indexOf(",", start[0]);
if (end[0] == -1) end[0] = data.length();
return item;
}
};
}
@NonNull
@Override
public String toString() {
return data;
}
}
@@ -0,0 +1,157 @@
package com.droiddeck.launcher.hud
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/**
* The readings Steam's performance overlay shows in a DroidDeck session (Valve's mangohud 20260902.1,
* tools/mangoapp), taken from the files the session hands it and computed the same way, so the two
* overlays agree. Sources and formulas follow that build: cpu.cpp calculateCPUData, deckard_temp.cpp,
* msm.cpp getQcomGpuInfo, memory.cpp update_meminfo and battery.cpp getPercent / getPower.
*/
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
class Battery(val percent: Int?, val watts: Float, val charging: Boolean)
private val cpuTimes = HashMap<String, LongArray>()
private val cpuPercents = HashMap<String, Int>()
/** Total and per-core load from the session's /proc/stat (DroidDeck's stand-in when the app can't read it). */
@JvmOverloads
fun cpu(stat: File = statFile()): Cpu? {
val lines = runCatching { stat.readLines() }.getOrNull() ?: return null
var total: Int? = null
val cores = ArrayList<Int>()
for (line in lines) {
if (!line.startsWith("cpu")) break
val parts = line.split(WHITESPACE)
if (parts.size < 11) continue
val values = LongArray(10) { parts[it + 1].toLongOrNull() ?: 0L }
val percent = cpuPercent(parts[0], values)
if (parts[0] == "cpu") total = percent else cores.add(percent)
}
return total?.let { Cpu(it, cores.toIntArray()) }
}
private fun statFile(): File =
File(sessionDir, "proc-stat").takeIf { !File("/proc/stat").canRead() && it.isFile } ?: File("/proc/stat")
private fun cpuPercent(key: String, v: LongArray): Int {
// user nice system idle iowait irq softirq steal guest guest_nice; guest time is already in user.
val user = v[0] - v[8]
val nice = v[1] - v[9]
val systemAll = v[2] + v[5] + v[6]
val idleAll = v[3] + v[4]
val virt = v[8] + v[9]
val totalTime = user + nice + systemAll + idleAll + v[7] + virt
val now = longArrayOf(user, nice, systemAll, v[7], virt, totalTime)
val last = cpuTimes.put(key, now) ?: LongArray(6)
fun period(i: Int) = if (now[i] > last[i]) now[i] - last[i] else 0L
val totalPeriod = period(5).toFloat()
if (totalPeriod == 0f) return cpuPercents[key] ?: 0
val busy = period(1) * 100f / totalPeriod + period(0) * 100f / totalPeriod +
period(2) * 100f / totalPeriod + (period(3) + period(4)) * 100f / totalPeriod
return busy.coerceIn(0f, 100f).toInt().also { cpuPercents[key] = it }
}
/** Average of the zones the session types cpuN-thermal, truncated. */
fun cpuTempC(): Int? {
var sum = 0f
var count = 0
for (zone in LinuxRuntime.cpuTempZones()) {
val milli = readLong(File(zone, "temp")) ?: continue
sum += milli / 1000f
count++
}
return if (count == 0) null else (sum / count).toInt()
}
fun gpuPercent(): Int? {
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/perf_now"))
val source = feed ?: LinuxRuntime.gpuLoadSource()?.let(::File) ?: return null
return leadingNumber(source)?.toInt()?.coerceIn(0, 100)
}
fun gpuClockMhz(): Int? {
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/cur_freq"))
val source = feed ?: listOf("$KGSL/devfreq/cur_freq", "$KGSL/gpuclk").map(::File).firstOrNull { it.canRead() } ?: return null
val hz = leadingNumber(source) ?: return null
return (hz / 1_000_000.0).toInt().takeIf { it > 0 }
}
fun gpuTempC(): Int? {
val milli = LinuxRuntime.gpuTempSource()?.let { readLong(File(it)) } ?: return null
return (milli / 1000.0).toInt()
}
/** MemTotal - MemAvailable and SwapTotal - SwapFree from /proc/meminfo. */
fun memory(): Memory? {
val kb = HashMap<String, Long>()
runCatching {
File("/proc/meminfo").forEachLine { line ->
val colon = line.indexOf(':')
if (colon > 0) line.substring(colon + 1).trim().split(WHITESPACE).firstOrNull()?.toLongOrNull()
?.let { kb[line.substring(0, colon)] = it }
}
}
val total = kb["MemTotal"] ?: return null
val available = kb["MemAvailable"] ?: return null
val swapTotal = kb["SwapTotal"] ?: 0L
val swapFree = kb["SwapFree"] ?: 0L
return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024)
}
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
/** BAT* under the session's power_supply (BatteryComponent): no watts while charging, full or unknown. */
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
if (dirs.isNullOrEmpty()) return null
var chargeNow = 0f
var chargeFull = 0f
var watts = 0f
var charging = false
for (dir in dirs) {
val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull()
if (status == "Charging" || status == "Unknown" || status == "Full") charging = true
val now = File(dir, "charge_now").takeIf { it.exists() } ?: File(dir, "energy_now")
val full = File(dir, "charge_full").takeIf { it.exists() } ?: File(dir, "energy_full")
if (now.exists()) {
chargeNow += (readFloat(now) ?: 0f) / 1_000_000f
chargeFull += (readFloat(full) ?: 0f) / 1_000_000f
} else {
chargeNow += (readFloat(File(dir, "capacity")) ?: 0f) / 100f
chargeFull = dirs.size.toFloat()
}
if (!charging) {
val power = File(dir, "power_now")
watts += if (power.exists()) kotlin.math.abs(readFloat(power) ?: 0f) / 1_000_000f
else kotlin.math.abs((readFloat(File(dir, "current_now")) ?: 0f) * (readFloat(File(dir, "voltage_now")) ?: 0f)) / 1e12f
}
}
val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null
return Battery(percent, if (charging) 0f else watts, charging)
}
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
file.takeIf { it.isFile && System.currentTimeMillis() - it.lastModified() < maxAgeMs }
companion object {
private const val KGSL = "/sys/class/kgsl/kgsl-3d0"
const val VRAM_FILE = "run/droiddeck-hud/gpu-mem"
private const val FEED_FRESH_MS = 10_000L
private const val VRAM_FRESH_MS = 15_000L
private val WHITESPACE = Regex("\\s+")
private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull()
private fun readFloat(file: File): Float? = runCatching { file.readLines().first().trim().toFloat() }.getOrNull()
/** std::stod on the first line: the leading number, "6 %" -> 6. */
fun leadingNumber(file: File): Double? = runCatching {
Regex("^\\s*-?\\d+(\\.\\d+)?").find(file.readLines().first())?.value?.trim()?.toDouble()
}.getOrNull()
}
}
@@ -4,7 +4,8 @@ import android.view.KeyEvent
import android.os.Handler
import android.os.Looper
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit) {
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>()
@@ -17,6 +18,18 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
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
@@ -48,7 +61,7 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
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, 500) }
else { tapPending = true; handler.postDelayed(singleTap, doubleTapMs()) }
} else if (event.isCanceled) cancelTap()
}
press != null || wasCancelled || enabled
@@ -63,6 +76,7 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
presses.values.forEach { handler.removeCallbacks(it.hold) }
cancelled.addAll(presses.keys)
presses.clear()
onCancel()
if (wasHeld) setPressed(false)
}
@@ -71,6 +85,9 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
val press = presses.remove(device) ?: return
handler.removeCallbacks(press.hold)
cancelTap()
if (press.held && presses.values.none { it.held }) setPressed(false)
if (press.held && presses.values.none { it.held }) {
onCancel()
setPressed(false)
}
}
}
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.input
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Build
import android.view.Gravity
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.R
@SuppressLint("ViewConstructor")
class DesktopKeyboardButton(context: Context, private val onTap: () -> Unit) : View(context) {
private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = dp(1.5f) }
private val box = RectF()
private var idleFill = 0
private var idleStroke = 0
private var heldStroke = 0
private var pressed = false
init {
contentDescription = context.getString(R.string.second_show_keyboard)
isClickable = true
visibility = GONE
layoutParams = FrameLayout.LayoutParams(dp(SIZE).toInt(), dp(SIZE).toInt(), Gravity.BOTTOM or Gravity.START)
place(0, 0)
applyColors()
}
private fun dp(value: Float) = value * resources.displayMetrics.density
fun applyColors() {
val settings = ControllerPrefs.read(context)
val tint = settings.tint
val alpha = settings.opacity / 100f
fun light(a: Int, f: Float) = Color.argb(
(a * alpha).toInt(),
(Color.red(tint) + (255 - Color.red(tint)) * f).toInt(),
(Color.green(tint) + (255 - Color.green(tint)) * f).toInt(),
(Color.blue(tint) + (255 - Color.blue(tint)) * f).toInt(),
)
idleFill = Color.argb(190, (Color.red(tint) * 0.12f).toInt(), (Color.green(tint) * 0.12f).toInt(), (Color.blue(tint) * 0.12f).toInt())
idleStroke = light(150, 0.25f)
heldStroke = light(230, 0.7f)
invalidate()
}
private fun place(left: Int, bottom: Int) {
val params = layoutParams as FrameLayout.LayoutParams
val marginStart = left + (dp(CENTER_X) - dp(SIZE) / 2f).toInt()
val marginBottom = bottom + (dp(CENTER_Y) - dp(SIZE) / 2f).toInt()
if (params.leftMargin == marginStart && params.bottomMargin == marginBottom) return
params.leftMargin = marginStart
params.bottomMargin = marginBottom
layoutParams = params
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
place(cutout?.safeInsetLeft ?: 0, cutout?.safeInsetBottom ?: 0)
return super.onApplyWindowInsets(insets)
}
override fun onDraw(canvas: Canvas) {
val x = width / 2f
val y = height / 2f
fill.color = idleFill
canvas.drawCircle(x, y, dp(18f), fill)
stroke.color = if (pressed) heldStroke else idleStroke
canvas.drawCircle(x, y, dp(18f), stroke)
box.set(x - dp(10f), y - dp(7f), x + dp(10f), y + dp(7f))
canvas.drawRoundRect(box, dp(2f), dp(2f), stroke)
for (row in 0..1) for (col in 0..2) {
val kx = x + dp(-6f + col * 5f)
val ky = y + dp(-3f + row * 4f)
canvas.drawLine(kx, ky, kx + dp(2f), ky, stroke)
}
canvas.drawLine(x - dp(5f), y + dp(4f), x + dp(5f), y + dp(4f), stroke)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> { pressed = true; invalidate() }
MotionEvent.ACTION_UP -> {
val inside = event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()
pressed = false
invalidate()
if (inside) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
performClick()
}
}
MotionEvent.ACTION_CANCEL -> { pressed = false; invalidate() }
}
return true
}
override fun performClick(): Boolean {
super.performClick()
onTap()
return true
}
private companion object {
const val SIZE = 52f
const val CENTER_X = 90f
const val CENTER_Y = 34f
}
}
@@ -8,52 +8,125 @@ import kotlin.math.abs
class DirectTouchHold(
private val slopPx: Float,
private val listener: PointerGestures.Listener,
private val cancelTouch: () -> Unit,
private val touch: Touch,
) {
interface Touch {
fun down(pointerId: Int, x: Float, y: Float)
fun move(pointerId: Int, x: Float, y: Float)
fun up(pointerId: Int, x: Float, y: Float)
fun cancel()
}
private val handler = Handler(Looper.getMainLooper())
private var x = 0f
private var y = 0f
private var consumed = false
private var pressed = false
private var downX = 0f
private var downY = 0f
private var downId = 0
private var delayMs = 0L
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK
private var forwarded = false
private var held = false
private var pressing = false
private var upX = 0f
private var upY = 0f
private var liftId = 0
private var liftPending = false
private val lift = Runnable {
liftPending = false
if (forwarded) {
touch.up(liftId, upX, upY)
forwarded = false
}
}
private val release = Runnable {
if (pressed) listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
pressed = false
if (pressing) listener.onButton(PointerGestures.BTN_RIGHT, false, downX, downY)
pressing = false
}
private val hold = Runnable {
cancelTouch()
consumed = true
held = true
listener.onLongPress()
listener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
pressed = true
handler.postDelayed(release, 50L)
listener.onButton(PointerGestures.BTN_RIGHT, true, downX, downY)
pressing = true
if (holdBehavior != TouchGestureConfig.MOUSE_BEHAVIOR_HOLD) handler.postDelayed(release, 50L)
}
fun configure(config: TouchGestureConfig) {
cancel()
delayMs = if (config.longPressEnabled) config.longPressDelay.toLong().coerceAtLeast(1L) else 0L
delayMs = config.longPressDelay.toLong().coerceAtLeast(1L)
holdBehavior = config.directHoldBehavior
}
fun cancel() {
handler.removeCallbacks(hold)
handler.removeCallbacks(release)
handler.removeCallbacks(lift)
liftPending = false
release.run()
consumed = false
if (forwarded) touch.cancel()
forwarded = false
held = false
}
fun onTouch(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
if (liftPending) {
handler.removeCallbacks(lift)
lift.run()
}
cancel()
downX = event.x
downY = event.y
downId = event.getPointerId(0)
if (holdBehavior == TouchGestureConfig.MOUSE_BEHAVIOR_NONE) forwardDown()
else handler.postDelayed(hold, delayMs)
return true
}
if (held) {
when (event.actionMasked) {
MotionEvent.ACTION_UP -> { release.run(); held = false }
MotionEvent.ACTION_CANCEL -> cancel()
}
return true
}
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
cancel()
x = event.x; y = event.y
if (delayMs > 0L) handler.postDelayed(hold, delayMs)
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(hold)
if (!forwarded) forwardDown()
val index = event.actionIndex
touch.down(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_MOVE -> {
if (!forwarded && (event.pointerCount > 1 ||
abs(event.x - downX) > slopPx || abs(event.y - downY) > slopPx)) {
handler.removeCallbacks(hold)
forwardDown()
}
if (forwarded) for (index in 0 until event.pointerCount)
touch.move(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_POINTER_UP -> {
val index = event.actionIndex
touch.up(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_UP -> {
handler.removeCallbacks(hold)
if (!forwarded) forwardDown()
upX = event.x
upY = event.y
liftId = event.getPointerId(event.actionIndex)
liftPending = true
handler.postDelayed(lift, LIFT_MS)
}
MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1 ||
abs(event.x - x) > slopPx || abs(event.y - y) > slopPx) handler.removeCallbacks(hold)
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_POINTER_UP,
MotionEvent.ACTION_UP -> handler.removeCallbacks(hold)
MotionEvent.ACTION_CANCEL -> cancel()
}
return consumed
return true
}
private fun forwardDown() {
touch.down(downId, downX, downY)
forwarded = true
}
private companion object {
const val LIFT_MS = 50L
}
}
@@ -0,0 +1,40 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.hardware.display.DisplayManager
import android.os.Build
import android.view.Display
import com.droiddeck.launcher.session.SessionPrefs
object DualScreen {
const val MODE_AUTO = "auto"
const val MODE_ON = "on"
const val MODE_OFF = "off"
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
private const val TYPE_INTERNAL = 1
private val knownModels = setOf("retroid pocket duo", "ayn thor")
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 &&
isBuiltIn(displayType(it), Build.MODEL)
}
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
when (SessionPrefs.dualScreenMode(context)) {
MODE_OFF -> null
MODE_ON -> builtInDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
else -> builtInDisplay(displayManager, primaryDisplayId)
}
fun anyDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0
}
internal fun isBuiltIn(type: Int?, model: String): Boolean =
if (type != null) type == TYPE_INTERNAL else model.trim().lowercase() in knownModels
private fun displayType(display: Display): Int? =
runCatching { Display::class.java.getMethod("getType").invoke(display) as Int }.getOrNull()
}
@@ -14,6 +14,7 @@ public class FakeInputWriter {
public static final short EV_SYN = 0x00;
public static final short EV_KEY = 0x01;
public static final short EV_REL = 0x02;
public static final short EV_ABS = 0x03;
public static final short EV_MSC = 0x04;
@@ -52,7 +53,8 @@ public class FakeInputWriter {
private static final int EVENT_SIZE = 24;
static final int MAX_EVENTS_PER_UPDATE = 32;
private static final int BUFFER_SIZE = EVENT_SIZE * MAX_EVENTS_PER_UPDATE;
private static final int MAX_FAKE_INPUT_SLOTS = 4;
private static final int MAX_FAKE_INPUT_SLOTS = 5;
public static final int MOUSE_SLOT = 4;
private static final int RING_CAPACITY_EVENTS = 4096;
private static final int RING_HEADER_SIZE = 64;
@@ -88,6 +90,17 @@ public class FakeInputWriter {
public static final int PAD_TYPE_XBOX = 2;
public static final int PAD_TYPE_DS4 = 3;
public static final int PAD_TYPE_DUALSENSE = 4;
public static final int PAD_TYPE_MOUSE = 5;
public static final short REL_X = 0x00;
public static final short REL_Y = 0x01;
public static final short REL_HWHEEL = 0x06;
public static final short REL_WHEEL = 0x08;
public static final short REL_WHEEL_HI_RES = 0x0b;
public static final short REL_HWHEEL_HI_RES = 0x0c;
public static final short MOUSE_BTN_LEFT = 0x110;
public static final short MOUSE_BTN_RIGHT = 0x111;
public static final short MOUSE_BTN_MIDDLE = 0x112;
private static volatile int padType = -1;
private static volatile boolean tritonConnected = false;
private static final int TRITON_OFFSET = RING_SIZE + 64;
@@ -136,6 +149,8 @@ public class FakeInputWriter {
private int prevThumbLX, prevThumbLY, prevThumbRX, prevThumbRY;
private int prevTriggerL, prevTriggerR;
private int prevHatX, prevHatY;
private final boolean[] prevMouseButtons = new boolean[3];
private float pendingMouseX, pendingMouseY;
private boolean hasChanges = false;
private boolean pendingFullResend = false;
private boolean forceResend = false;
@@ -201,7 +216,7 @@ public class FakeInputWriter {
return FakeInputRingPaths.ringFile(fakeInputDir, slot);
}
private static void initializeRingHeader(ByteBuffer data) {
private static void initializeRingHeader(int slot, ByteBuffer data) {
data.order(ByteOrder.LITTLE_ENDIAN);
data.putInt(RING_MAGIC_OFFSET, RING_MAGIC);
data.putInt(RING_VERSION_OFFSET, RING_VERSION);
@@ -221,7 +236,7 @@ public class FakeInputWriter {
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
}
data.putInt(DECK_CONTROLS_OFFSET, 0);
int type = padType;
int type = slot == MOUSE_SLOT ? PAD_TYPE_MOUSE : padType;
data.putInt(PAD_TYPE_OFFSET, type >= 0 ? PAD_TYPE_SET | type : 0);
data.putInt(LATENCY_OFFSET, latency);
data.putInt(TRITON_OFFSET, TRITON_MAGIC);
@@ -312,7 +327,7 @@ public class FakeInputWriter {
raf.setLength(RING_FILE_SIZE);
channel = raf.getChannel();
ByteBuffer data = channel.map(FileChannel.MapMode.READ_WRITE, 0, RING_FILE_SIZE);
initializeRingHeader(data);
initializeRingHeader(slot, data);
RingSlot ringSlot = new RingSlot();
ringSlot.data = data;
@@ -745,6 +760,14 @@ public class FakeInputWriter {
prevHatY = 0;
writeEvent(EV_ABS, ABS_HAT0Y, 0);
}
for (int i = 0; i < prevMouseButtons.length; i++) {
if (prevMouseButtons[i]) {
prevMouseButtons[i] = false;
writeEvent(EV_KEY, (short) (MOUSE_BTN_LEFT + i), 0);
}
}
pendingMouseX = 0;
pendingMouseY = 0;
if (hasChanges) {
writeEvent(EV_SYN, SYN_REPORT, 0);
@@ -874,4 +897,64 @@ public class FakeInputWriter {
public boolean isOpen() {
return isOpen;
}
public synchronized void writeMouseDelta(float dx, float dy) {
if (!isOpen && !open())
return;
pendingMouseX += dx;
pendingMouseY += dy;
int x = (int) Math.floor(pendingMouseX);
int y = (int) Math.floor(pendingMouseY);
if (x == 0 && y == 0)
return;
pendingMouseX -= x;
pendingMouseY -= y;
buffer.clear();
hasChanges = false;
if (x != 0) writeEvent(EV_REL, REL_X, x);
if (y != 0) writeEvent(EV_REL, REL_Y, y);
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse delta write error: fake input mmap ring unavailable");
}
public synchronized void writeMouseButton(short code, boolean pressed) {
if (code < MOUSE_BTN_LEFT || code > MOUSE_BTN_MIDDLE)
return;
int idx = code - MOUSE_BTN_LEFT;
if (!isOpen && !open())
return;
if (prevMouseButtons[idx] == pressed)
return;
prevMouseButtons[idx] = pressed;
buffer.clear();
hasChanges = false;
writeEvent(EV_KEY, code, pressed ? 1 : 0);
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse button write error: fake input mmap ring unavailable");
}
public synchronized void writeMouseWheel(int verticalClicks, int horizontalClicks, int value120) {
if (verticalClicks == 0 && horizontalClicks == 0)
return;
if (!isOpen && !open())
return;
buffer.clear();
hasChanges = false;
if (verticalClicks != 0) {
writeEvent(EV_REL, REL_WHEEL, verticalClicks);
writeEvent(EV_REL, REL_WHEEL_HI_RES, verticalClicks * value120);
}
if (horizontalClicks != 0) {
writeEvent(EV_REL, REL_HWHEEL, horizontalClicks);
writeEvent(EV_REL, REL_HWHEEL_HI_RES, horizontalClicks * value120);
}
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse wheel write error: fake input mmap ring unavailable");
}
}
@@ -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,57 @@
package com.droiddeck.launcher.input
import android.os.Build
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 (isQuickMenuKey(event)) {
if (event.action == KeyEvent.ACTION_DOWN) cancel()
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
private const val DUO_QUICK_MENU_SCAN_CODE = 194
fun isQuickMenuKey(event: KeyEvent) =
event.scanCode == DUO_QUICK_MENU_SCAN_CODE && "Retroid Pocket Duo".equals(Build.MODEL, ignoreCase = true)
}
}
@@ -23,6 +23,9 @@ class KeyboardHost(
private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
var shown = false
private set
var imeShowing = false
private set
var onImeChanged: ((Boolean) -> Unit)? = null
init {
isFocusable = false
@@ -42,6 +45,28 @@ class KeyboardHost(
return KeyConnection()
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val visible = insets.isVisible(WindowInsets.Type.ime())
if (visible != imeShowing) {
imeShowing = visible
onImeChanged?.invoke(visible)
}
}
return super.onApplyWindowInsets(insets)
}
override fun onKeyPreIme(keyCode: Int, event: KeyEvent): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R || keyCode != KeyEvent.KEYCODE_BACK || !shown) {
return super.onKeyPreIme(keyCode, event)
}
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) {
hide()
onImeChanged?.invoke(false)
}
return true
}
fun toggle() = if (shown && imeVisible()) hide() else show()
private fun imeVisible() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R ||
@@ -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 -> {
@@ -642,6 +672,11 @@ class OnScreenControls(
private fun closestSnap(position: Float, targets: List<Float>): Float? =
targets.minByOrNull { abs(position - it) }?.takeIf { abs(position - it) <= dp(SNAP_DP) }
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean =
editing || keyboardContains(x, y) || (!buttonsOnly && quickContains(x, y)) ||
(!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null)
private fun controlAt(x: Float, y: Float): Control? =
controls.firstOrNull {
!quickHidden && isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius)
@@ -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;
@@ -62,12 +63,20 @@ public final class PadBridge {
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;
@@ -130,6 +139,8 @@ public final class PadBridge {
}
private void resetBuiltin() {
homeGuidePressed = false;
clearBackQamWrites();
routedTouch.clear();
systemGuidePressed = false;
systemQamPressed = false;
@@ -152,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++) {
@@ -218,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
@@ -276,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;
@@ -310,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;
@@ -326,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();
@@ -355,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;
@@ -385,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();
@@ -461,6 +489,9 @@ public final class PadBridge {
}
public synchronized void releaseAll() {
homeGuidePressed = false;
homeGuideSlot = -1;
clearBackQamWrites();
routedTouch.clear();
backQamPressed = false;
releaseBackPaddles();
@@ -487,13 +518,142 @@ public final class PadBridge {
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()) {
@@ -572,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;
}
@@ -607,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;
@@ -633,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();
@@ -689,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() {
@@ -698,17 +868,17 @@ public final class PadBridge {
statDropped++;
return;
}
boolean guide = systemGuidePressed || qamChordActive;
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,145 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.util.Log
import android.view.InputDevice
import android.view.KeyEvent
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
object PhysicalShortcuts {
internal const val KEY = "physicalShortcuts"
private const val TAG = "PhysicalShortcuts"
enum class Action(@StringRes val label: Int) {
STEAM(R.string.drawer_steam_menu),
QAM(R.string.drawer_open_qam),
DROIDDECK(R.string.shortcuts_dd_menu),
}
data class Button(
val device: String,
val name: String,
val keyCode: Int,
val scanCode: Int,
) {
fun matches(event: KeyEvent): Boolean =
event.device?.let { device == identity(it) } == true &&
keyCode == event.keyCode && scanCode == event.scanCode
fun sameInput(other: Button): Boolean =
device == other.device && keyCode == other.keyCode && scanCode == other.scanCode
val label: String
get() = KeyEvent.keyCodeToString(keyCode).removePrefix("KEYCODE_").removePrefix("BUTTON_")
}
data class Binding(val button: Button, val action: Action)
private fun identity(device: InputDevice): String =
"${device.vendorId}:${device.productId}:${device.descriptor.ifBlank { device.name }}"
fun isVolumeKey(event: KeyEvent): Boolean = when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> true
else -> false
}
fun isDrawerNavigationKey(event: KeyEvent): Boolean = when (event.keyCode) {
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> true
else -> false
}
fun button(event: KeyEvent): Button? {
val device = event.device ?: return null
if (device.isVirtual || isVolumeKey(event)) return null
when (event.keyCode) {
KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_SLEEP,
KeyEvent.KEYCODE_WAKEUP, KeyEvent.KEYCODE_APP_SWITCH -> return null
}
if (event.keyCode == KeyEvent.KEYCODE_UNKNOWN && event.scanCode <= 0) return null
return Button(identity(device), device.name, event.keyCode, event.scanCode)
}
fun read(context: Context): List<Binding> {
val raw = ControllerPrefs.prefs(context).getString(KEY, null) ?: return emptyList()
return try {
val array = JSONArray(raw)
buildList {
for (i in 0 until array.length()) {
try {
val entry = array.getJSONObject(i)
val action = Action.entries.firstOrNull { it.name == entry.getString("action") }
val code = entry.getInt("keyCode")
val scan = entry.getInt("scanCode")
val device = entry.getString("device")
if (action == null || device.isBlank() || code < 0 || scan < 0) {
Log.w(TAG, "Ignoring invalid shortcut at index $i")
continue
}
val binding = Binding(Button(device, entry.getString("name"), code, scan), action)
if (none { it.button.sameInput(binding.button) }) add(binding)
} catch (e: JSONException) {
Log.w(TAG, "Ignoring malformed shortcut at index $i", e)
}
}
}
} catch (e: JSONException) {
Log.w(TAG, "Could not read physical shortcuts; reset shortcuts to restore defaults", e)
emptyList()
}
}
fun assign(context: Context, button: Button, action: Action) {
val bindings = read(context).filterNot {
it.button.sameInput(button) || (it.button.device == button.device && it.action == action)
} + Binding(button, action)
write(context, bindings)
}
fun remove(context: Context, binding: Binding) {
write(context, read(context).filterNot { it == binding })
}
private fun write(context: Context, bindings: List<Binding>) {
val array = JSONArray()
bindings.forEach {
array.put(JSONObject().put("device", it.button.device).put("name", it.button.name)
.put("keyCode", it.button.keyCode).put("scanCode", it.button.scanCode).put("action", it.action.name))
}
ControllerPrefs.prefs(context).edit().putString(KEY, array.toString()).apply()
}
}
class PhysicalShortcutRouter {
var bindings: List<PhysicalShortcuts.Binding> = emptyList()
private data class Press(val device: Int, val keyCode: Int, val scanCode: Int)
private val held = mutableSetOf<Press>()
fun onKey(event: KeyEvent, enabled: Boolean, steam: Boolean, perform: (PhysicalShortcuts.Action) -> Unit): Boolean {
val press = Press(event.deviceId, event.keyCode, event.scanCode)
if (event.action == KeyEvent.ACTION_UP) return held.remove(press)
if (event.action != KeyEvent.ACTION_DOWN) return false
if (press in held) return true
if (!enabled || bindings.isEmpty()) return false
val button = PhysicalShortcuts.button(event) ?: return false
val binding = bindings.firstOrNull { it.button.sameInput(button) } ?: return false
if (!steam && binding.action != PhysicalShortcuts.Action.DROIDDECK) return false
held.add(press)
if (event.repeatCount == 0) perform(binding.action)
return true
}
fun onDeviceRemoved(deviceId: Int) {
held.removeAll { it.device == deviceId }
}
fun clear() {
held.clear()
}
}
@@ -1,104 +1,22 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.ViewConfiguration
import kotlin.math.abs
import kotlin.math.roundToInt
class PointerGestures(
private val slopPx: Float,
private val listener: Listener,
) {
class PointerGestures {
interface Listener {
fun onMove(x: Float, y: Float)
fun onButton(button: Int, pressed: Boolean, x: Float, y: Float)
fun onWheel(steps: Int)
fun onLongPress()
}
private val handler = Handler(Looper.getMainLooper())
private var downX = 0f
private var downY = 0f
private var downAt = 0L
private var moved = false
private var held = false
private var dragging = false
private var scrolling = false
private var scrollAnchorY = 0f
private val longPress = Runnable {
held = true
listener.onLongPress()
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = event.x; downY = event.y; downAt = event.eventTime
moved = false; held = false; dragging = false; scrolling = false
listener.onMove(event.x, event.y)
handler.postDelayed(longPress, HOLD_MS)
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(longPress)
if (dragging) { listener.onButton(BTN_LEFT, false, event.x, event.y); dragging = false }
scrolling = true
scrollAnchorY = event.getY(0)
return true
}
MotionEvent.ACTION_MOVE -> {
if (scrolling) {
val dy = event.getY(0) - scrollAnchorY
val steps = (dy / SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * SCROLL_STEP_PX
}
return true
}
if (!moved && (abs(event.x - downX) > slopPx || abs(event.y - downY) > slopPx)) {
moved = true
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(BTN_LEFT, true, downX, downY)
}
}
if (moved) listener.onMove(event.x, event.y)
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(longPress)
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL
when {
scrolling -> {}
dragging -> listener.onButton(BTN_LEFT, false, event.x, event.y)
held && !moved && !cancelled -> {
listener.onButton(BTN_RIGHT, true, downX, downY)
listener.onButton(BTN_RIGHT, false, downX, downY)
}
!moved && !cancelled && event.eventTime - downAt < TAP_MS -> {
listener.onButton(BTN_LEFT, true, downX, downY)
listener.onButton(BTN_LEFT, false, downX, downY)
}
}
scrolling = false; dragging = false; held = false
return true
}
MotionEvent.ACTION_POINTER_UP -> return true
}
return false
fun onScroll(dx: Float, dy: Float) {}
fun onScrollEnd() {}
fun onZoom(steps: Int) {}
}
companion object {
const val BTN_LEFT = 0x110
const val BTN_RIGHT = 0x111
const val BTN_MIDDLE = 0x112
private const val HOLD_MS = 450L
private const val TAP_MS = 350L
private const val SCROLL_STEP_PX = 40f
fun slop(context: android.content.Context) = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
}
@@ -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,
)
}
@@ -609,6 +609,9 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
else -> entry.halfH
}
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean = editing || entryAt(x, y) != null
private fun entryAt(x: Float, y: Float): Entry? = entries.lastOrNull { entry ->
x >= entry.cx - entry.halfW && x <= entry.cx + entry.halfW && y >= entry.cy - entry.halfH && y <= entry.cy + entry.halfH
}
@@ -926,35 +929,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 {
@@ -86,27 +86,14 @@ class ScrollTouchGestures(
lastY = startY
tracker = VelocityTracker.obtain().also { it.addMovement(event) }
listener.onMove(startX, startY)
handler.postDelayed(longPress, HOLD_MS)
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
MotionEvent.ACTION_MOVE -> {
val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true
tracker?.addMovement(event)
val x = event.getX(index)
val y = event.getY(index)
if (!scrolling && !dragging && hypot(x - startX, y - startY) > slopPx) {
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true)
} else {
scrolling = true
vertical = abs(y - startY) >= abs(x - startX)
lastX = startX
lastY = startY
}
}
if (dragging) listener.onMove(x, y)
follow(event, x, y)
for (h in 0 until event.historySize)
sample(event.getHistoricalX(index, h), event.getHistoricalY(index, h), event.getHistoricalEventTime(h))
sample(event.getX(index), event.getY(index), event.eventTime)
}
MotionEvent.ACTION_POINTER_UP -> {
if (event.getPointerId(event.actionIndex) == pointerId) cancel()
@@ -115,7 +102,7 @@ class ScrollTouchGestures(
handler.removeCallbacks(longPress)
if (pointerId == -1 || event.getPointerId(0) != pointerId) return true
tracker?.addMovement(event)
follow(event, event.x, event.y)
follow(event.x, event.y, event.eventTime)
when {
scrolling -> tracker?.takeIf { event.eventTime - movedAt <= FLING_STILL_MS }?.let { t ->
t.computeCurrentVelocity(1000)
@@ -139,9 +126,26 @@ class ScrollTouchGestures(
return true
}
private fun follow(event: MotionEvent, x: Float, y: Float) {
private fun sample(x: Float, y: Float, t: Long) {
if (!scrolling && !dragging && hypot(x - startX, y - startY) > slopPx) {
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true)
} else {
scrolling = true
vertical = abs(y - startY) >= abs(x - startX)
lastX = startX
lastY = startY
}
}
if (dragging) listener.onMove(x, y)
follow(x, y, t)
}
private fun follow(x: Float, y: Float, t: Long) {
if (!scrolling || (x == lastX && y == lastY)) return
movedAt = event.eventTime
movedAt = t
if (vertical) listener.onScroll(0f, lastY - y) else listener.onScroll(lastX - x, 0f)
lastX = x
lastY = y
@@ -151,7 +155,7 @@ class ScrollTouchGestures(
releaseClick()
listener.onButton(button, true)
clicked = button
handler.postDelayed(clickUp, CLICK_MS)
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
}
private fun releaseClick() {
@@ -181,8 +185,6 @@ class ScrollTouchGestures(
return if (pixels < 0) -units else units
}
private const val HOLD_MS = 500L
private const val CLICK_MS = 50L
private const val FLING_TIME_S = 0.45f
private const val FLING_STOP_PX = 40f
private const val FLING_STILL_MS = 60L
@@ -9,7 +9,12 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
NONE("none", R.string.second_mode_none),
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
TERMINAL("terminal", R.string.second_mode_terminal),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls);
companion object {
fun opening(remembered: String?, deckPad: Boolean): SecondScreenMode =
entries.firstOrNull { it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) } ?: if (deckPad) DECK_CONTROLS else KEYBOARD_TRACKPAD
}
}
data class SecondScreenDisplay(val id: Int, val label: String)
@@ -16,13 +16,19 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
private val handler = Handler(Looper.getMainLooper())
private val hostFile = File(context.filesDir, "session/android-clipboard")
private var active = false
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh() }
private var published = false
private var shared: String? = null
private var echo: String? = null
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh(changed = true) }
private val guestListener = object : WaylandCompositor.ClipboardListener {
override fun onGuestClipboardText(text: String) {
handler.post {
if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
val current = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
shared = text
published = true
if (current?.toString() != text) {
echo = text
clipboard.setPrimaryClip(ClipData.newPlainText("DroidDeck", text))
}
}
@@ -46,17 +52,23 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
handler.removeCallbacksAndMessages(null)
}
fun refresh() {
fun refresh(changed: Boolean = false) {
if (!active || !hasFocus()) return
val clip = clipboard.primaryClip
if (clip == null) {
publish(null)
} else if (clip.itemCount > 0) {
publish(clip.getItemAt(0).text?.toString())
if (clip != null && clip.itemCount == 0) return
val text = clip?.getItemAt(0)?.text?.toString()
if (echo != null && text == echo) {
echo = null
return
}
echo = null
if (!changed && published && text == shared) return
publish(text)
}
private fun publish(text: String?) {
published = true
shared = text
WaylandCompositor.setClipboardText(text)
val pending = File(hostFile.parentFile, "android-clipboard.pending")
try {
@@ -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()
@@ -242,6 +244,9 @@ class SteamTouchControls(
private fun hit(list: List<Element>, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean = editing || menuOpen || hit(live(), x, y) != null
private fun live(): List<Element> =
if (shakenAway) emptyList() else if (options.inputMode == SteamTouchConfig.INPUT_MOUSE) elements.filter { it.type == SteamTouchConfig.THUMB } else elements
@@ -629,7 +634,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 +652,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 +671,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 +691,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
}
}
@@ -15,6 +15,7 @@ data class TouchGestureConfig(
val longPressAction: String = ACTION_RIGHT_CLICK,
val longPressMouseBehavior: String = MOUSE_BEHAVIOR_HOLD,
val longPressDelay: Int = DEFAULT_DELAY_MS,
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
val doubleTapEnabled: Boolean = true,
val doubleTapDelay: Int = DEFAULT_DELAY_MS,
val twoFingerDragEnabled: Boolean = true,
@@ -50,6 +51,7 @@ data class TouchGestureConfig(
put(KEY_LONG_PRESS_ACTION, longPressAction)
put(KEY_LONG_PRESS_MOUSE_BEHAVIOR, longPressMouseBehavior)
put(KEY_LONG_PRESS_DELAY, longPressDelay)
put(KEY_DIRECT_HOLD_BEHAVIOR, directHoldBehavior)
put(KEY_DOUBLE_TAP_ENABLED, doubleTapEnabled)
put(KEY_DOUBLE_TAP_DELAY, doubleTapDelay)
put(KEY_TWO_FINGER_DRAG_ENABLED, twoFingerDragEnabled)
@@ -85,6 +87,7 @@ data class TouchGestureConfig(
const val MOUSE_BEHAVIOR_HOLD = "hold"
const val MOUSE_BEHAVIOR_CLICK = "click"
const val MOUSE_BEHAVIOR_NONE = "none"
const val MOUSE_DRAG_MOVEMENT_DIRECT = "direct"
const val MOUSE_DRAG_MOVEMENT_RELATIVE = "relative"
@@ -110,6 +113,7 @@ data class TouchGestureConfig(
private const val KEY_LONG_PRESS_ACTION = "longPressAction"
private const val KEY_LONG_PRESS_MOUSE_BEHAVIOR = "longPressMouseBehavior"
private const val KEY_LONG_PRESS_DELAY = "longPressDelay"
private const val KEY_DIRECT_HOLD_BEHAVIOR = "directHoldBehavior"
private const val KEY_DOUBLE_TAP_ENABLED = "doubleTapEnabled"
private const val KEY_DOUBLE_TAP_DELAY = "doubleTapDelay"
private const val KEY_TWO_FINGER_DRAG_ENABLED = "twoFingerDragEnabled"
@@ -155,6 +159,9 @@ data class TouchGestureConfig(
obj.optString(KEY_LONG_PRESS_MOUSE_BEHAVIOR, MOUSE_BEHAVIOR_HOLD)
),
longPressDelay = obj.optInt(KEY_LONG_PRESS_DELAY, DEFAULT_DELAY_MS),
directHoldBehavior = normalizeDirectHoldBehavior(
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_CLICK)
),
doubleTapEnabled = obj.optBoolean(KEY_DOUBLE_TAP_ENABLED, true),
doubleTapDelay = obj.optInt(KEY_DOUBLE_TAP_DELAY, DEFAULT_DELAY_MS),
twoFingerDragEnabled = obj.optBoolean(KEY_TWO_FINGER_DRAG_ENABLED, true),
@@ -190,6 +197,10 @@ data class TouchGestureConfig(
}
}
private fun normalizeDirectHoldBehavior(value: String): String {
return if (value == MOUSE_BEHAVIOR_CLICK || value == MOUSE_BEHAVIOR_NONE) value else MOUSE_BEHAVIOR_HOLD
}
private fun normalizeMouseBehavior(value: String): String {
return if (value == MOUSE_BEHAVIOR_CLICK) MOUSE_BEHAVIOR_CLICK else MOUSE_BEHAVIOR_HOLD
}
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
object TouchRouter {
enum class Route { BLOCKED, GESTURES, SCROLL, OFF, TOUCHPAD, DIRECT }
data class Snapshot(
val uiBlocking: Boolean,
val mode: String,
val scrollLayer: Boolean,
val steamSession: Boolean,
val steamDesktopUi: Boolean,
)
fun decide(s: Snapshot): Route {
if (s.uiBlocking) return Route.BLOCKED
if (s.mode == SessionPrefs.TOUCH_GESTURES) return Route.GESTURES
if (s.scrollLayer) return Route.SCROLL
if (s.mode == SessionPrefs.TOUCH_OFF) return Route.OFF
return if (touchpad(s)) Route.TOUCHPAD else Route.DIRECT
}
fun steamKeyboardZone(s: Snapshot): Boolean = s.steamSession && !s.steamDesktopUi
private fun touchpad(s: Snapshot): Boolean = when (s.mode) {
SessionPrefs.TOUCH_PAD -> true
SessionPrefs.TOUCH_DIRECT -> false
else -> !s.steamSession || s.steamDesktopUi
}
}
@@ -0,0 +1,9 @@
package com.droiddeck.launcher.input
object TouchTiming {
const val HOLD_MS = 500L
const val TAP_MS = 300L
const val CLICK_MS = 30L
const val DOUBLE_TAP_MS = 300L
const val SCROLL_STEP_PX = 36f
}
@@ -4,6 +4,7 @@ import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import kotlin.math.abs
import kotlin.math.hypot
class TouchpadGestures(
private val slopPx: Float,
@@ -15,6 +16,7 @@ class TouchpadGestures(
private set
var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f)
var sensitivity = 1.15f
var desktop = false
private val handler = Handler(Looper.getMainLooper())
private var lastX = 0f
@@ -27,7 +29,11 @@ class TouchpadGestures(
private var secondDownAt = 0L
private var secondWasTap = false
private var twoFingers = false
private var scrollAnchorX = 0f
private var scrollAnchorY = 0f
private var fingers = 0
private var pinching = false
private var pinchSpan = 0f
private var scrolled = false
private var anchorId = -1
private var anchorStartX = 0f
@@ -52,7 +58,7 @@ class TouchpadGestures(
releaseClick()
listener.onButton(button, true, x, y)
clicked = button
handler.postDelayed(clickUp, CLICK_MS)
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
}
private fun releaseClick() {
@@ -79,6 +85,20 @@ class TouchpadGestures(
y = py.coerceIn(bounds.top, bounds.bottom)
}
private fun trackMove(px: Float, py: Float) {
val dx = px - lastX
val dy = py - lastY
lastX = px; lastY = py
travelled += abs(dx) + abs(dy)
if (travelled > slopPx) {
handler.removeCallbacks(longPress)
val speed = abs(dx) + abs(dy)
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
place(x + dx * gain, y + dy * gain)
listener.onMove(x, y)
}
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
@@ -86,18 +106,20 @@ class TouchpadGestures(
lastX = event.x; lastY = event.y
downAt = event.eventTime
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
fingers = 1; pinching = false
anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false
if (event.eventTime - lastTapAt < DOUBLE_TAP_MS) {
if (event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
} else {
dragging = false
handler.postDelayed(longPress, HOLD_MS)
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(longPress)
fingers = maxOf(fingers, event.pointerCount)
val i = event.actionIndex
if (moverId == -1 && event.getPointerId(i) != anchorId) {
moverId = event.getPointerId(i)
@@ -111,7 +133,9 @@ class TouchpadGestures(
twoFingers = true
secondDownAt = event.eventTime
secondWasTap = true
scrollAnchorX = (event.getX(0) + event.getX(1)) / 2f
scrollAnchorY = (event.getY(0) + event.getY(1)) / 2f
pinchSpan = span(event)
return true
}
MotionEvent.ACTION_MOVE -> {
@@ -146,29 +170,49 @@ class TouchpadGestures(
} else if (holdDrag) {
return true
}
if (twoFingers && event.pointerCount >= 2) {
val mid = (event.getY(0) + event.getY(1)) / 2f
val dy = mid - scrollAnchorY
val steps = (dy / SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * SCROLL_STEP_PX
if (twoFingers && event.pointerCount >= 2 && desktop) {
if (fingers >= 3) return true
val span = span(event)
if (!scrolled && !pinching && abs(span - pinchSpan) > slopPx * PINCH_SLOPS) {
pinching = true
secondWasTap = false
pinchSpan = span
}
if (pinching) {
val steps = ((span - pinchSpan) / PINCH_STEP_PX).toInt()
if (steps != 0) {
listener.onZoom(-steps)
pinchSpan += steps * PINCH_STEP_PX
}
return true
}
val midX = (event.getX(0) + event.getX(1)) / 2f
val midY = (event.getY(0) + event.getY(1)) / 2f
val dx = scrollAnchorX - midX
val dy = scrollAnchorY - midY
if (scrolled || abs(dx) + abs(dy) > slopPx) {
listener.onScroll(dx, dy)
scrollAnchorX = midX; scrollAnchorY = midY
scrolled = true
secondWasTap = false
}
return true
}
val dx = event.x - lastX
val dy = event.y - lastY
lastX = event.x; lastY = event.y
travelled += abs(dx) + abs(dy)
if (travelled > slopPx) {
handler.removeCallbacks(longPress)
val speed = (abs(dx) + abs(dy))
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
place(x + dx * gain, y + dy * gain)
listener.onMove(x, y)
if (twoFingers && event.pointerCount >= 2) {
val mid = (event.getY(0) + event.getY(1)) / 2f
val dy = mid - scrollAnchorY
val steps = (dy / TouchTiming.SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * TouchTiming.SCROLL_STEP_PX
scrolled = true
secondWasTap = false
}
return true
}
for (h in 0 until event.historySize)
trackMove(event.getHistoricalX(0, h), event.getHistoricalY(0, h))
trackMove(event.x, event.y)
return true
}
MotionEvent.ACTION_POINTER_UP -> {
@@ -194,7 +238,12 @@ class TouchpadGestures(
event.findPointerIndex(anchorId).takeIf { it >= 0 && it != event.actionIndex }?.let {
lastX = event.getX(it); lastY = event.getY(it)
}
if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TAP_MS && !scrolled) {
if (desktop && scrolled && event.pointerCount == 2) listener.onScrollEnd()
if (fingers >= 3) {
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2)
click(PointerGestures.BTN_MIDDLE)
if (event.pointerCount == 2) secondWasTap = false
} else if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TouchTiming.TAP_MS && !scrolled) {
click(PointerGestures.BTN_RIGHT)
secondWasTap = false
}
@@ -206,29 +255,30 @@ class TouchpadGestures(
when {
dragging -> listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
twoFingers -> {
if (secondWasTap && !scrolled && !cancelled && event.eventTime - downAt < TAP_MS * 2) {
if (secondWasTap && !scrolled && !cancelled && event.eventTime - downAt < TouchTiming.TAP_MS * 2) {
click(PointerGestures.BTN_RIGHT)
}
}
!cancelled && travelled <= slopPx && event.eventTime - downAt < TAP_MS -> {
!cancelled && travelled <= slopPx && event.eventTime - downAt < TouchTiming.TAP_MS -> {
click(PointerGestures.BTN_LEFT)
lastTapAt = event.eventTime
}
}
dragging = false; held = false; twoFingers = false
holdDrag = false; scrollLocked = false; anchorId = -1; moverId = -1
pinching = false; fingers = 0
return true
}
}
return false
}
private fun span(event: MotionEvent): Float =
if (event.pointerCount < 2) 0f else hypot(event.getX(0) - event.getX(1), event.getY(0) - event.getY(1))
companion object {
private const val HOLD_MS = 500L
private const val TAP_MS = 300L
private const val CLICK_MS = 50L
private const val DOUBLE_TAP_MS = 300L
private const val SCROLL_STEP_PX = 36f
private const val PINCH_SLOPS = 3f
private const val PINCH_STEP_PX = 60f
private const val HOLD_DRAG_MOVER_SLOPS = 2f
private const val HOLD_DRAG_ANCHOR_SLOPS = 0.5f
}
@@ -36,7 +36,7 @@ public final class TouchscreenGestures {
private final Output output;
private final float doubleTapSlop;
private TouchGestureConfig gestureConfig = new TouchGestureConfig();
private static final int CLICK_DELAYED_TIME = 50;
private static final int CLICK_DELAYED_TIME = 30;
private Runnable delayedPress, pendingHoldClickRelease;
private Runnable pendingTapPress;
private final ArrayDeque<TapClick> pendingTapClicks = new ArrayDeque<>();
@@ -0,0 +1,205 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import kotlin.math.abs
import kotlin.math.hypot
class TwoFingerGestures(private val slopPx: Float, private val listener: Listener) {
interface Listener {
fun cancelTouch()
fun replay(event: MotionEvent)
fun rightClick(x: Float, y: Float)
fun scrollStart(x: Float, y: Float)
fun scroll(dx: Float, dy: Float)
fun scrollEnd()
}
private enum class State { IDLE, PENDING, CANDIDATE, TAPPED, HELD, SCROLLING, PASSING }
private val handler = Handler(Looper.getMainLooper())
private var state = State.IDLE
private var x = 0f
private var y = 0f
private var twoAt = 0L
private var startSpan = 0f
private var lastX = 0f
private var lastY = 0f
private val starts = HashMap<Int, Pair<Float, Float>>()
private val held = ArrayList<MotionEvent>()
private val hold = Runnable {
if (state != State.CANDIDATE) return@Runnable
state = State.HELD
drop()
listener.cancelTouch()
listener.rightClick(x, y)
}
private val release = Runnable {
if (state == State.PENDING) pass(State.IDLE)
}
fun cancel() {
if (state == State.SCROLLING) listener.scrollEnd()
handler.removeCallbacks(hold)
handler.removeCallbacks(release)
drop()
state = State.IDLE
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
cancel()
starts.clear()
x = event.x
y = event.y
note(event, event.actionIndex)
state = State.PENDING
keep(event)
handler.postDelayed(release, LAND_MS)
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
note(event, event.actionIndex)
when (state) {
State.PENDING -> {
handler.removeCallbacks(release)
keep(event)
if (event.pointerCount != 2) {
pass(State.PASSING)
return true
}
state = State.CANDIDATE
twoAt = event.eventTime
startSpan = span(event)
lastX = midX(event)
lastY = midY(event)
handler.postDelayed(hold, HOLD_MS)
return true
}
State.CANDIDATE -> {
keep(event)
pass(State.PASSING)
return true
}
State.SCROLLING, State.HELD, State.TAPPED -> return true
else -> Unit
}
}
MotionEvent.ACTION_MOVE -> when (state) {
State.PENDING -> {
keep(event)
if (moved(event)) pass(State.IDLE)
return true
}
State.CANDIDATE -> {
if (event.pointerCount == 2 && moved(event)) {
handler.removeCallbacks(hold)
if (abs(span(event) - startSpan) > slopPx * 2) {
keep(event)
pass(State.PASSING)
return true
}
state = State.SCROLLING
drop()
listener.cancelTouch()
lastX = midX(event)
lastY = midY(event)
listener.scrollStart(lastX, lastY)
return true
}
keep(event)
return true
}
State.SCROLLING -> {
if (event.pointerCount >= 2) {
val mx = midX(event)
val my = midY(event)
listener.scroll(lastX - mx, lastY - my)
lastX = mx
lastY = my
}
return true
}
State.TAPPED, State.HELD -> return true
else -> Unit
}
MotionEvent.ACTION_POINTER_UP -> when (state) {
State.CANDIDATE -> {
handler.removeCallbacks(hold)
keep(event)
if (event.eventTime - twoAt < TAP_MS) {
state = State.TAPPED
drop()
return true
}
pass(State.PASSING)
return true
}
State.SCROLLING, State.HELD, State.TAPPED -> return true
else -> Unit
}
MotionEvent.ACTION_UP -> {
val was = state
if (was == State.PENDING) {
keep(event)
pass(State.IDLE)
return true
}
cancel()
when (was) {
State.TAPPED -> {
listener.cancelTouch()
listener.rightClick(x, y)
return true
}
State.SCROLLING, State.HELD -> return true
else -> Unit
}
}
MotionEvent.ACTION_CANCEL -> cancel()
}
return false
}
private fun keep(event: MotionEvent) {
held += MotionEvent.obtain(event)
}
private fun drop() {
held.forEach { it.recycle() }
held.clear()
}
private fun pass(next: State) {
handler.removeCallbacks(release)
handler.removeCallbacks(hold)
state = next
val events = held.toList()
held.clear()
events.forEach {
listener.replay(it)
it.recycle()
}
}
private fun note(event: MotionEvent, index: Int) {
starts[event.getPointerId(index)] = event.getX(index) to event.getY(index)
}
private fun moved(event: MotionEvent): Boolean = (0 until event.pointerCount).any { i ->
val start = starts[event.getPointerId(i)] ?: return@any false
hypot(event.getX(i) - start.first, event.getY(i) - start.second) > slopPx
}
private fun span(event: MotionEvent) = hypot(event.getX(1) - event.getX(0), event.getY(1) - event.getY(0))
private fun midX(event: MotionEvent) = (event.getX(0) + event.getX(1)) / 2f
private fun midY(event: MotionEvent) = (event.getY(0) + event.getY(1)) / 2f
companion object {
const val LAND_MS = 250L
const val TAP_MS = 350L
const val HOLD_MS = 500L
}
}
@@ -360,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
}
@@ -180,7 +180,8 @@ object BwrapSpawner {
val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
preload(session, rootfs, env).forEach { addBind(it) }
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
if (preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
zypakShims(binds, root, dir).forEach { addBind(it) }
browserSandboxes(env)
return Plan(root, binds, request.optString("cwd", "/").ifEmpty { "/" }, argv, env)
@@ -188,17 +189,21 @@ object BwrapSpawner {
private const val GPU_DIR = "/run/droiddeck-gpu"
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")
private fun runtimeLib(rootfs: String, name: String): File? =
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
val lib = File(rootfs, "usr/lib")
val driver = File(lib, "libvulkan_freedreno.so")
if (!driver.isFile || !File("/dev/kgsl-3d0").exists()) return null
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
if (driver == null || !File("/dev/kgsl-3d0").exists()) return null
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
if (env["BL_DESKTOP"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
val binds = ArrayList<Bind>()
for (name in listOf("libvulkan_freedreno.so", "libdisplay-info.so.3", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")) {
val f = File(lib, name)
if (!f.exists()) { Log.w(TAG, "gpu: the runtime has no $name; apps draw on the CPU"); return null }
val binds = arrayListOf(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_freedreno.so"))
for (name in GPU_LIBS) {
val f = runtimeLib(rootfs, name) ?: continue
binds.add(Bind(f.canonicalPath, "$GPU_DIR/$name"))
}
val icd = File(root.parentFile, "freedreno_icd.json")
@@ -250,6 +255,27 @@ object BwrapSpawner {
return binds
}
private val GLIBC_RELEASE = Regex("release version 2\\.(\\d+)")
private val GLIBC_NEED = Regex("GLIBC_2\\.(\\d+)")
private val glibcMinors = java.util.concurrent.ConcurrentHashMap<String, Int>()
private fun glibcMinor(file: File, pattern: Regex, pick: (Sequence<Int>) -> Int?): Int? {
val key = "${file.path}:${file.length()}:${file.lastModified()}:${pattern.pattern}"
glibcMinors[key]?.let { return it }
val text = runCatching { String(file.readBytes(), Charsets.ISO_8859_1) }.getOrNull() ?: return null
return pick(pattern.findAll(text).map { it.groupValues[1].toInt() })?.also { glibcMinors[key] = it }
}
internal fun preloadFits(rootfs: String, sandboxLibc: String): Boolean {
val libc = File(sandboxLibc)
if (!libc.isFile) return true
val have = glibcMinor(libc, GLIBC_RELEASE) { it.firstOrNull() } ?: return true
val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
?.map { it.trim() }?.filter { it.startsWith("/") } ?: return true
val need = libs.mapNotNull { File(rootfs + it).takeIf { f -> f.isFile }?.let { f -> glibcMinor(f, GLIBC_NEED) { m -> m.maxOrNull() } } }.maxOrNull() ?: return true
return have >= need
}
private const val PRELOAD_DIR = "/run/droiddeck-preload"
private const val NET_LINK = "etc/droiddeck-net"
@@ -344,7 +370,15 @@ object BwrapSpawner {
catch (e: IOException) { }
if (process.isAlive) {
Log.i(TAG, "sandbox $id: its bwrap is gone; stopping it")
process.destroy()
if (pid > 0) {
runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) }
} else {
process.destroy()
}
try {
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) process.destroyForcibly()
} catch (_: InterruptedException) {
}
}
}, "bwrap-$id-watch").apply { isDaemon = true; start() }
val buffer = ByteArray(16384)
@@ -22,8 +22,8 @@ object DesktopCatalog {
val icon: String, val category: String,
)
fun fetch(url: String = CATALOG_URL): List<Entry>? {
val body = Downloader.downloadString(url) ?: return null
fun fetch(url: String = CATALOG_URL, cancelled: java.util.function.BooleanSupplier? = null): List<Entry>? {
val body = Downloader.downloadString(url, cancelled) ?: return null
return try {
val json = JSONObject(body)
val arr = json.getJSONArray("packages")
@@ -71,9 +71,22 @@ object DesktopCatalog {
}
fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
resumeInterrupted(context, null, listener)
}
fun resumeInterrupted(
context: Context,
cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?,
): String? = synchronized(installLock) {
for (entry in interrupted(context)) {
Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}")
install(context, entry, listener)?.let { return it }
val problem = if (cancelled == null) {
install(context, entry, listener)
} else {
install(context, entry, cancelled, listener)
}
if (problem != null) return problem
}
null
}
@@ -102,19 +115,27 @@ object DesktopCatalog {
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
const val DESKTOP_ID = "desktop-kde"
const val EMULATORS_ID = "emulators"
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
fun desktopEntry(context: Context) = Entry(
DESKTOP_ID, context.getString(R.string.content_linux_desktop), 1, BuildConfig.DESKTOP_KDE_TAG, "tar",
BuildConfig.DESKTOP_KDE_URL, BuildConfig.DESKTOP_KDE_SHA256, BuildConfig.DESKTOP_KDE_SIZE, "",
"", "",
)
fun desktopEntry(context: Context): Entry {
val pack = DesktopPack.info(LinuxRuntime.rootDir(context))
return Entry(
DESKTOP_ID, context.getString(R.string.content_linux_desktop), 1, pack?.tag ?: BuildConfig.DESKTOP_KDE_TAG, "tar",
pack?.url ?: BuildConfig.DESKTOP_KDE_URL, pack?.sha256 ?: BuildConfig.DESKTOP_KDE_SHA256,
pack?.size ?: BuildConfig.DESKTOP_KDE_SIZE, "", "", "",
)
}
fun desktopInstalled(context: Context): Boolean = desktopInstalled(LinuxRuntime.rootDir(context))
fun desktopFromPack(root: File): Boolean = DesktopPack.info(root) != null
fun desktopInstalled(root: File): Boolean =
!File(root, DesktopRemoval.PENDING).exists() &&
File(root, "usr/bin/kwin_wayland").isFile &&
FileUtils.readString(File(root, ".droiddeck-pkg-$DESKTOP_ID"))?.trim() == BuildConfig.DESKTOP_KDE_TAG
FileUtils.readString(File(root, ".droiddeck-pkg-$DESKTOP_ID"))?.trim() ==
(DesktopPack.info(root)?.tag ?: BuildConfig.DESKTOP_KDE_TAG)
fun desktopPresent(context: Context): Boolean {
val root = LinuxRuntime.rootDir(context)
@@ -144,12 +165,19 @@ object DesktopCatalog {
}
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
installLocked(context, entry, listener)
installLocked(context, entry, null, listener)
}
private fun installLocked(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
fun install(context: Context, entry: Entry, cancelled: Downloader.Cancellation,
listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
installLocked(context, entry, cancelled, listener)
}
private fun installLocked(context: Context, entry: Entry, cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val root = LinuxRuntime.rootDir(context)
if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing)
if (entry.id == EMULATORS_ID && desktopFromPack(root)) return installEmulators(context, entry, cancelled, listener)
if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name)
val download = downloadFile(context, entry)
val journal = journal(root, entry.id)
@@ -166,14 +194,20 @@ object DesktopCatalog {
if (!downloaded(download, entry)) {
val downloading = context.getString(R.string.user_apps_downloading, entry.name)
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, 0)
val ok = Downloader.downloadFile(entry.url, download, true, entry.sha256) { f ->
val progress = java.util.function.Consumer<Float> { f ->
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, if (f < 0) -1 else Math.round(f * 100f))
}
if (!ok) return context.getString(R.string.user_apps_download_failed)
val ok = if (cancelled == null) {
Downloader.downloadFile(entry.url, download, true, entry.sha256, progress)
} else {
Downloader.downloadFile(entry.url, download, true, entry.sha256, cancelled, progress)
}
if (!ok || cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
report.onProgress(LinuxRuntimeInstaller.Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1)
val actual = Hashes.sha256(download)
if (!entry.sha256.equals(actual, ignoreCase = true)) return context.getString(R.string.deskpkg_checksum_mismatch)
}
if (cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
report.onProgress(context.getString(R.string.deskpkg_installing, entry.name), -1)
when (entry.kind) {
"appimage" -> {
@@ -192,11 +226,12 @@ object DesktopCatalog {
check(FileUtils.writeString(journal, entryJson(entry).toString())) { "Could not record the package installation" }
keepDownload = true
marker(context, entry.id).delete()
if (entry.id == DESKTOP_ID && desktopFromPack(root)) DesktopPack.prepareInstall(root)
if (!LinuxRuntimeInstaller.extract(context, download, root, report)) return context.getString(R.string.deskpkg_extract_failed)
}
}
if (entry.id == DESKTOP_ID) {
cleanLegacy(context, report)
if (desktopFromPack(root)) DesktopPack.finishInstall(root) else cleanLegacy(context, report)
val pending = File(root, DesktopRemoval.PENDING)
check(!pending.exists() || pending.delete()) { "Could not finish desktop installation" }
}
@@ -214,6 +249,47 @@ object DesktopCatalog {
}
}
private fun installEmulators(context: Context, entry: Entry, cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val release = RuntimeInstallService.holdForPackage(context, context.getString(R.string.deskpkg_installing, entry.name))
val stop = java.util.concurrent.atomic.AtomicBoolean(false)
val finished = java.util.concurrent.atomic.AtomicBoolean(false)
cancelled?.let { token ->
Thread({
try {
while (!finished.get() && !stop.get()) {
if (token.getAsBoolean()) stop.set(true) else Thread.sleep(200)
}
} catch (_: InterruptedException) {
}
}, "emulators-cancel").apply { isDaemon = true; start() }
}
try {
var failure: String? = null
val status = GuestCommand.run(context, listOf("/bin/bash", EMULATORS_SCRIPT, "install"), logName = "emulators",
cancelled = stop) { line ->
when {
line.startsWith("== STEP ") -> {
val stage = context.getString(R.string.deskpkg_installing, line.removePrefix("== STEP "))
RuntimeInstallService.packageProgress(stage, -1)
listener?.onProgress(stage, -1)
}
line.startsWith("== FAIL ") -> failure = line.removePrefix("== FAIL ")
}
}
if (stop.get()) return context.getString(R.string.user_apps_download_failed)
if (failure != null || status != 0) return context.getString(R.string.deskpkg_install_failed)
check(FileUtils.writeString(marker(context, entry.id), entry.version)) { "Could not finish package installation" }
return null
} catch (e: Exception) {
Log.e(TAG, "install ${entry.id}", e)
return e.message ?: context.getString(R.string.deskpkg_install_failed)
} finally {
finished.set(true)
release()
}
}
private fun unzipAppImage(zip: File, target: File): Boolean {
try {
java.util.zip.ZipInputStream(java.io.BufferedInputStream(java.io.FileInputStream(zip))).use { zin ->
@@ -73,10 +73,42 @@ internal object DesktopFileRemoval {
}
}
private val RECORD = Regex("[A-Za-z0-9@._+:-]+")
fun desktopRecords(root: File): Set<String> {
val list = safeFile(root, "usr/share/droiddeck/pacman/desktop-packages.txt") ?: return emptySet()
if (!Files.isRegularFile(list.toPath(), NOFOLLOW_LINKS)) return emptySet()
return list.readLines().mapNotNull { line ->
line.split(' ').takeIf { it.size == 2 }?.let { "${it[0]}-${it[1]}" }?.takeIf { RECORD.matches(it) && it != "." && it != ".." }
}.toSet()
}
fun removeRecords(root: File, records: Set<String>) {
val lib = File(root, "var/lib/pacman")
if (Files.isSymbolicLink(File(root, "var").toPath()) || Files.isSymbolicLink(lib.toPath())) return
val local = File(lib, "local")
if (!local.isDirectory || Files.isSymbolicLink(local.toPath())) return
for (record in records) {
if (!RECORD.matches(record) || record == "." || record == "..") continue
val dir = File(local, record)
if (Files.isSymbolicLink(dir.toPath()) || !dir.isDirectory) continue
for (file in dir.listFiles().orEmpty()) {
if (Files.isSymbolicLink(file.toPath()) || file.isFile) Files.delete(file.toPath())
}
if (!dir.delete()) throw IOException("Cannot remove $dir")
}
for (name in listOf("sync/droiddeck.db", "droiddeck-desktop")) {
val file = File(lib, name)
if (Files.isSymbolicLink(file.toPath()) || file.isFile) Files.delete(file.toPath())
}
}
fun runtimeFiles(root: File): Set<String> = buildSet {
val database = File(root, "var/lib/pacman/local")
if (!database.isDirectory || Files.isSymbolicLink(database.toPath())) throw IOException("Runtime package database missing")
val desktop = desktopRecords(root)
for (pkg in database.listFiles().orEmpty()) {
if (pkg.name in desktop) continue
val files = File(pkg, "files")
if (!pkg.isDirectory || Files.isSymbolicLink(pkg.toPath()) || !files.isFile || Files.isSymbolicLink(files.toPath())) continue
var inFiles = false
@@ -0,0 +1,178 @@
package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.Hashes
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.util.zip.GZIPInputStream
import org.json.JSONObject
internal object DesktopPack {
const val INFO = "usr/share/droiddeck/desktop-pack.json"
const val META = "usr/share/droiddeck/desktop"
private const val MANIFEST = "$META/files.tsv.gz"
private const val ORIGINALS = "$META/originals"
private const val STATUS = "var/lib/dpkg/status"
private const val STATUS_BEFORE = "var/lib/dpkg/status.droiddeck"
private const val PACK_STATUS = "$META/dpkg-status"
data class Info(val tag: String, val url: String, val sha256: String, val size: Long)
data class Entry(val kind: Char, val type: Char, val size: Long, val value: String, val path: String) {
companion object {
fun parse(line: String): Entry? {
val parts = line.split('\t', limit = 5)
if (parts.size != 5 || parts[0].length != 1 || parts[1].length != 1) return null
return Entry(parts[0][0], parts[1][0], parts[2].toLongOrNull() ?: return null, parts[3], parts[4])
}
}
}
data class Result(val removed: Int, val restored: Int, val kept: Int)
fun info(root: File): Info? = runCatching {
val json = JSONObject(FileUtils.readString(File(root, INFO)) ?: return null)
Info(json.getString("tag"), json.getString("url"), json.getString("sha256"), json.getLong("size"))
}.getOrNull()
fun installed(root: File): Boolean = File(root, MANIFEST).isFile
fun entries(root: File): List<Entry> =
GZIPInputStream(File(root, MANIFEST).inputStream()).bufferedReader().use { reader ->
reader.lineSequence().mapNotNull(Entry::parse).toList()
}
fun installedSize(root: File): Long =
if (installed(root)) entries(root).filter { it.kind == 'N' && it.type == 'F' }.sumOf { it.size } else 0L
fun prepareInstall(root: File) {
val live = File(root, STATUS)
val before = File(root, STATUS_BEFORE)
if (!before.exists() && live.isFile) Files.copy(live.toPath(), before.toPath(), StandardCopyOption.COPY_ATTRIBUTES)
}
fun finishInstall(root: File) {
for (entry in entries(root).filter { it.kind == 'R' }.sortedByDescending { it.path.length }) {
val file = inside(root, entry.path) ?: continue
if (entry.type == 'D') file.delete() else Files.deleteIfExists(file.toPath())
}
val live = File(root, STATUS)
val packStatus = File(root, PACK_STATUS)
if (live.isFile && !packStatus.exists()) Files.copy(live.toPath(), packStatus.toPath())
val before = File(root, STATUS_BEFORE)
val runtime = File(File(root, ORIGINALS), STATUS)
if (before.isFile && runtime.isFile && live.isFile) {
writeStatus(live, mergeStatus(runtime.readText(), packStatus.readText(), before.readText()))
}
Files.deleteIfExists(before.toPath())
}
internal fun mergeStatus(base: String, target: String, mine: String): String {
val from = stanzas(base)
val into = LinkedHashMap(stanzas(target))
val kept = stanzas(mine)
for ((key, stanza) in kept) {
if (from[key] != stanza && into[key] == from[key]) into[key] = stanza
}
for (key in from.keys) {
if (key !in kept && into[key] == from[key]) into.remove(key)
}
return into.values.joinToString("") { it + "\n\n" }
}
private fun stanzas(text: String): Map<String, String> {
val out = LinkedHashMap<String, String>()
for (stanza in text.split(Regex("\n[ \t]*\n")).map { it.trim('\n') }.filter { it.isNotBlank() }) {
val fields = stanza.lines()
fun field(name: String) = fields.firstOrNull { it.startsWith("$name:") }?.substringAfter(':')?.trim().orEmpty()
out["${field("Package")}:${field("Architecture")}"] = stanza
}
return out
}
private fun writeStatus(file: File, text: String) {
val part = LinuxRuntimeInstaller.partFile(file).toPath()
Files.deleteIfExists(part)
Files.copy(file.toPath(), part, StandardCopyOption.COPY_ATTRIBUTES)
Files.write(part, text.toByteArray(), java.nio.file.StandardOpenOption.TRUNCATE_EXISTING)
Files.move(part, file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
}
fun remove(root: File, progress: (Int) -> Unit = {}): Result {
val entries = entries(root)
var removed = 0
var restored = 0
var kept = 0
val originals = File(root, ORIGINALS)
val live = File(root, STATUS)
val userStatus = if (live.isFile) live.readText() else null
for (entry in entries.filter { it.kind == 'C' || it.kind == 'R' }) {
val file = inside(root, entry.path) ?: continue
if (entry.type == 'D') {
file.mkdirs()
continue
}
if (entry.kind == 'C' && !entry.path.startsWith("var/lib/dpkg/") && !matchesOrMissing(file, entry)) {
kept++
continue
}
val source = inside(originals, entry.path) ?: continue
val sourcePath = source.toPath()
if (!Files.exists(sourcePath, LinkOption.NOFOLLOW_LINKS)) continue
file.parentFile?.mkdirs()
val part = LinuxRuntimeInstaller.partFile(file).toPath()
Files.deleteIfExists(part)
if (Files.isSymbolicLink(sourcePath)) Files.createSymbolicLink(part, Files.readSymbolicLink(sourcePath))
else Files.copy(sourcePath, part, StandardCopyOption.COPY_ATTRIBUTES)
if (Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS)) FileUtils.delete(file)
Files.move(part, file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
restored++
}
val added = entries.filter { it.kind == 'N' }
val directories = ArrayList<File>()
added.forEachIndexed { index, entry ->
val file = inside(root, entry.path)
when {
file == null -> kept++
entry.type == 'D' -> directories += file
matches(file, entry) -> { Files.deleteIfExists(file.toPath()); removed++ }
Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS) -> kept++
}
if (index % 2000 == 0) progress(index * 100 / added.size.coerceAtLeast(1))
}
for (dir in directories.sortedByDescending { it.path.length }) {
if (Files.isDirectory(dir.toPath(), LinkOption.NOFOLLOW_LINKS) && dir.list()?.isEmpty() == true) dir.delete()
}
val packStatus = File(root, PACK_STATUS)
if (userStatus != null && packStatus.isFile && live.isFile) {
writeStatus(live, mergeStatus(packStatus.readText(), live.readText(), userStatus))
}
FileUtils.delete(File(root, META))
return Result(removed, restored, kept)
}
private fun matchesOrMissing(file: File, entry: Entry) =
!Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS) || matches(file, entry)
private fun matches(file: File, entry: Entry): Boolean {
val path = file.toPath()
return when (entry.type) {
'L' -> Files.isSymbolicLink(path) && Files.readSymbolicLink(path).toString() == entry.value
'F' -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) && file.length() == entry.size &&
Hashes.sha256(file).equals(entry.value, ignoreCase = true)
else -> false
}
}
internal fun inside(root: File, path: String): File? {
if (path.isEmpty() || path.startsWith("/")) return null
val normal = Paths.get(path).normalize()
if (normal.toString().isEmpty() || normal.startsWith("..")) return null
val parent = normal.parent
val dir = if (parent == null) root else com.droiddeck.launcher.core.ArchivePaths.inside(root, parent.toString()) ?: return null
return File(dir, normal.fileName.toString())
}
}
@@ -18,8 +18,11 @@ internal object DesktopRemoval {
private fun protected(context: Context, root: File) =
DesktopFileRemoval.runtimeFiles(root) + lines(context, "emulators-keep.txt.gzip")
fun installedSize(context: Context): Long =
lines(context, "kde-remove.tsv.gzip").sumOf { line -> line.split('\t').getOrNull(1)?.toLongOrNull() ?: 0L }
fun installedSize(context: Context): Long {
val root = LinuxRuntime.rootDir(context)
if (DesktopPack.info(root) != null) return DesktopPack.installedSize(root)
return lines(context, "kde-remove.tsv.gzip").sumOf { line -> line.split('\t').getOrNull(1)?.toLongOrNull() ?: 0L }
}
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) {
val root = LinuxRuntime.rootDir(context)
@@ -40,8 +43,12 @@ internal object DesktopRemoval {
Log.i("DesktopRemoval", "LXQt: $result")
}
fun remove(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
fun remove(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? {
val root = LinuxRuntime.rootDir(context)
return if (DesktopPack.info(root) != null) removePack(context, root, listener) else removeLegacy(context, root, listener)
}
private fun removeLegacy(context: Context, root: File, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
val pending = File(root, PENDING)
val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
val installing = DesktopCatalog.interrupted(root).firstOrNull { it.id == DesktopCatalog.DESKTOP_ID }
@@ -50,12 +57,14 @@ internal object DesktopRemoval {
check(version in versions && (installing == null || installing.version in versions)) { context.getString(R.string.desktop_removal_unknown) }
val entries = lines(context, "kde-remove.tsv.gzip").map(DesktopFileRemoval.Entry::parse)
val keep = protected(context, root)
val records = DesktopFileRemoval.desktopRecords(root)
cleanLegacy(context, listener)
FileUtils.writeString(pending, version!!)
check(FileUtils.readString(pending)?.trim() == version) { "Could not reserve desktop removal" }
if (marker.exists() && !marker.delete()) error("Could not clear desktop marker")
val removing = context.getString(R.string.desktop_removing)
val result = DesktopFileRemoval.remove(root, entries, keep) { listener.onProgress(removing, it) }
DesktopFileRemoval.removeRecords(root, records)
for ((asset, path) in com.droiddeck.launcher.session.SessionFiles.DESKTOP_FILES) {
val target = DesktopFileRemoval.safeFile(root, path) ?: continue
if (!isRegularFile(target)) continue
@@ -74,5 +83,29 @@ internal object DesktopRemoval {
e.message ?: context.getString(R.string.deskpkg_install_failed)
}
private fun removePack(context: Context, root: File, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
val pending = File(root, PENDING)
val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
FileUtils.writeString(pending, DesktopPack.info(root)!!.tag)
check(pending.isFile) { "Could not reserve desktop removal" }
if (marker.exists() && !marker.delete()) error("Could not clear desktop marker")
val removing = context.getString(R.string.desktop_removing)
for ((_, path) in com.droiddeck.launcher.session.SessionFiles.DESKTOP_FILES) {
DesktopFileRemoval.safeFile(root, path)?.takeIf { isRegularFile(it) }?.delete()
}
for (path in DESKTOP_STATE) DesktopPack.inside(root, path)?.let(FileUtils::delete)
val result = if (DesktopPack.installed(root)) DesktopPack.remove(root) { listener.onProgress(removing, it) } else null
DesktopCatalog.discardDesktopInstall(context)
if (!pending.delete()) error("Could not finish desktop removal")
Log.i("DesktopRemoval", "pack: $result")
listener.onProgress(context.getString(R.string.desktop_removed), 100)
null
} catch (e: Exception) {
Log.e("DesktopRemoval", "remove", e)
e.message ?: context.getString(R.string.deskpkg_install_failed)
}
private val DESKTOP_STATE = listOf("var/lib/PackageKit", "var/cache/swcatalog")
private fun isRegularFile(file: File) = java.nio.file.Files.isRegularFile(file.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)
}
@@ -1,18 +1,18 @@
package com.droiddeck.launcher.runtime
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
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.net.Uri
import android.os.FileObserver
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.provider.Settings
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
@@ -29,14 +29,16 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
private val directory = directory(root)
private val handler = Handler(Looper.getMainLooper())
private var running = false
private var pendingBrightness: Float? = null
private var permissionRequestAt = -5_000L
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 volumeSteps = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { if (running) publishVolume() }
}
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() }
@@ -46,25 +48,29 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
override fun run() {
if (!running) return
consume()
pendingBrightness?.let { value ->
if (Settings.System.canWrite(context)) {
pendingBrightness = null
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
brightness(value)
}
}
if (permissionNotified && Settings.System.canWrite(context))
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
publish()
handler.postDelayed(this, 250)
}
}
fun publish(force: Boolean = false) {
private fun publishVolume() {
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")
} catch (e: Exception) {
Log.w(TAG, "Could not publish Android volume", e)
}
}
fun publish(force: Boolean = false) {
publishVolume()
try {
directory.mkdirs()
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")
@@ -86,8 +92,13 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
File(directory, "$it.processing").delete()
}
running = true
permissionNotified = false
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
requests.startWatching()
context.registerReceiver(volumeSteps, IntentFilter().apply {
addAction(VOLUME_CHANGED_ACTION)
addAction(STREAM_MUTE_CHANGED_ACTION)
}, null, handler)
refresh.run()
}
}
@@ -97,8 +108,8 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
running = false
handler.removeCallbacks(refresh)
requests.stopWatching()
try { context.unregisterReceiver(volumeSteps) } catch (e: IllegalArgumentException) { }
context.contentResolver.unregisterContentObserver(observer)
pendingBrightness = null
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
}
}
@@ -134,13 +145,13 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
private fun brightness(value: Float) {
if (!Settings.System.canWrite(context)) {
pendingBrightness = value
val now = SystemClock.elapsedRealtime()
if (now - permissionRequestAt >= 5_000) {
permissionRequestAt = now
if (!permissionNotified) {
permissionNotified = true
try {
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:${context.packageName}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
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))
@@ -150,7 +161,8 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
.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()) context.startActivity(intent)
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)
}
@@ -177,6 +189,9 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
companion object {
private const val TAG = "DeviceControls"
// AudioService sends these on every stream step; the Settings observer and 250 ms poll lag a held volume key.
private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"
private const val STREAM_MUTE_CHANGED_ACTION = "android.media.STREAM_MUTE_CHANGED_ACTION"
private const val PERMISSION_CHANNEL = "brightness_permission"
private const val PERMISSION_NOTIFICATION = 0x4442
private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request")
@@ -43,7 +43,7 @@ object GuestCommand {
val fastPathKey = if (fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
cmd += listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
@@ -113,12 +113,16 @@ public final class LinuxRuntime {
}
public static boolean isInstalled(Context context) {
return hasRootfs(context) && (patchedProot(context) || rootfsProotReady(context));
}
/** The rootfs alone: enough to read the game library, while the proot pack can still be downloading. */
public static boolean hasRootfs(Context context) {
if (LinuxRuntimeInstaller.isRemoving() || LinuxRuntimeInstaller.hasRemovalPending(context)) return false;
File root = rootDir(context);
return new File(root, "usr/bin/gamescope").isFile()
return (new File(root, "usr/bin/gamescope").isFile() || new File(root, "usr/games/gamescope").isFile())
&& (new File(root, SESSION_SCRIPT.substring(1)).isFile()
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile())
&& (patchedProot(context) || rootfsProotReady(context));
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile());
}
public static File vulkanIcd(Context context) {
@@ -364,9 +368,9 @@ public final class LinuxRuntime {
}
public static String cpuTempSource() {
for (java.util.Map.Entry<String, File> e : new java.util.TreeMap<>(thermalZones()).entrySet()) {
File temp = new File(e.getValue(), "temp");
if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) return temp.getPath();
for (File zone : cpuTempZones()) {
File temp = new File(zone, "temp");
if (temp.canRead()) return temp.getPath();
}
return null;
}
@@ -376,7 +380,7 @@ public final class LinuxRuntime {
return firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
}
private static String gpuLoadSource() {
public static String gpuLoadSource() {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
return firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load");
}
@@ -390,7 +394,7 @@ public final class LinuxRuntime {
"/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"},
{gpuTemp, "/sys/class/thermal/thermal_zone28/temp"},
{gpuTemp, "/sys/class/thermal/thermal_zone26/temp"},
{thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"},
{ddrTempSource(), "/sys/class/thermal/thermal_zone22/temp"},
};
for (String[] stat : stats) {
boolean fed = false;
@@ -407,6 +411,36 @@ public final class LinuxRuntime {
return path != null ? path : "none";
}
private static String ddrTempSource() {
return thermalZone("ddr");
}
// MangoHud reads the GPU and DDR temperatures from these zone numbers (bindAdrenoStats). On phones
// where they are CPU zones, their type follows the temperature put there, so they stay out of the
// CPU average.
private static java.util.Map<String, String> replacedZoneTypes() {
java.util.Map<String, String> replaced = new java.util.HashMap<>();
if (gpuTempSource() != null) {
replaced.put("thermal_zone28", "gpu-thermal");
replaced.put("thermal_zone26", "gpu-thermal");
}
if (ddrTempSource() != null) replaced.put("thermal_zone22", "ddr-thermal");
return replaced;
}
/** The zones the session's MangoHud averages for the CPU temperature (all typed cpuN-thermal there). */
public static List<File> cpuTempZones() {
java.util.Map<String, String> replaced = replacedZoneTypes();
List<File> zones = new ArrayList<>();
for (java.util.Map.Entry<String, File> zone : new java.util.TreeMap<>(thermalZones()).entrySet()) {
String type = zone.getKey();
if (type.contains("cpu") && !type.contains("gpu") && !replaced.containsKey(zone.getValue().getName())) {
zones.add(zone.getValue());
}
}
return zones;
}
private static void bindCpuTemps(List<String> cmd, File root) {
File name = new File(root, "etc/droiddeck/cpu-thermal-type");
try {
@@ -414,9 +448,18 @@ public final class LinuxRuntime {
} catch (IOException e) {
return;
}
java.util.Map<String, String> replaced = replacedZoneTypes();
for (java.util.Map.Entry<String, File> zone : thermalZones().entrySet()) {
String type = zone.getKey();
if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) {
String other = replaced.get(zone.getValue().getName());
if (other != null) {
File typeFile = new File(root, "etc/droiddeck/" + other + "-type");
try {
if (!typeFile.isFile()) Files.write(typeFile.toPath(), (other + "\n").getBytes(StandardCharsets.US_ASCII));
bind(cmd, typeFile.getPath() + ":" + new File(zone.getValue(), "type").getPath());
} catch (IOException ignored) {
}
} else if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) {
bind(cmd, name.getPath() + ":" + new File(zone.getValue(), "type").getPath());
}
}
@@ -471,12 +514,72 @@ public final class LinuxRuntime {
+ "\\" + host.version + "\\" + host.machine + "\\localdomain\\-1\\";
}
public static void writeAccounts(Context context) throws IOException {
public static synchronized void writeAccounts(Context context) throws IOException {
File root = rootDir(context);
int uid = Process.myUid();
Files.write(new File(root, "etc/passwd").toPath(),
("root:x:" + uid + ":" + uid + ":root:/root:/bin/bash\n").getBytes(StandardCharsets.UTF_8));
Files.write(new File(root, "etc/group").toPath(),
("root:x:" + uid + ":\n").getBytes(StandardCharsets.UTF_8));
mergeAccounts(new File(root, "etc/passwd"), 2,
"root:x:" + uid + ":" + uid + ":root:/root:/bin/bash", "root:x:0:0:root:/root:/bin/bash", uid);
mergeAccounts(new File(root, "etc/group"), 2,
"root:x:" + uid + ":", "root:x:0:", uid);
File group = new File(root, "etc/group");
String groups = new String(Files.readAllBytes(group.toPath()), StandardCharsets.UTF_8);
writeIfChanged(group, groups, withStorageGroups(groups));
}
private static final String[][] STORAGE_GROUPS = {
{"sdcard_rw", "1015"}, {"media_rw", "1023"}, {"everybody", "9997"}};
static String withStorageGroups(String groups) {
StringBuilder out = new StringBuilder();
List<String> present = new ArrayList<>();
for (String line : groups.split("\n")) {
if (line.trim().isEmpty()) continue;
String[] fields = line.split(":", -1);
if (fields.length >= 4) {
for (String[] storage : STORAGE_GROUPS) {
if (fields[0].equals(storage[0])) present.add(storage[0]);
if (!fields[2].equals(storage[1])) continue;
present.add(storage[0]);
if (!java.util.Arrays.asList(fields[3].split(",")).contains("root")) {
fields[3] = fields[3].isEmpty() ? "root" : fields[3] + ",root";
line = String.join(":", fields);
}
}
}
out.append(line).append('\n');
}
for (String[] storage : STORAGE_GROUPS) {
if (!present.contains(storage[0])) {
out.append(storage[0]).append(":x:").append(storage[1]).append(":root\n");
}
}
return out.toString();
}
static String mergedAccounts(String existing, int idField, String own, String zero, int uid) {
StringBuilder out = new StringBuilder(own).append('\n').append(zero).append('\n');
if (existing == null) return out.toString();
String ownId = Integer.toString(uid);
for (String line : existing.split("\n")) {
if (line.trim().isEmpty()) continue;
String[] fields = line.split(":", -1);
if (fields.length <= idField) continue;
if (fields[0].equals("root") || fields[idField].equals("0") || fields[idField].equals(ownId)) continue;
out.append(line).append('\n');
}
return out.toString();
}
private static void mergeAccounts(File file, int idField, String own, String zero, int uid) throws IOException {
String existing = file.isFile() ? new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8) : null;
writeIfChanged(file, existing, mergedAccounts(existing, idField, own, zero, uid));
}
private static void writeIfChanged(File file, String existing, String merged) throws IOException {
if (merged.equals(existing)) return;
File staged = File.createTempFile(file.getName(), ".staged", file.getParentFile());
Files.write(staged.toPath(), merged.getBytes(StandardCharsets.UTF_8));
Files.move(staged.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.ATOMIC_MOVE);
}
}
@@ -35,7 +35,7 @@ public final class LinuxRuntimeInstaller {
private static final String TAG = "LinuxRuntimeInstaller";
public static final String CATALOG_URL =
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/linuxfs.json";
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/linuxfs-ubuntu.json";
private static final String VERSION_FILE = ".version";
@@ -88,8 +88,20 @@ public final class LinuxRuntimeInstaller {
return v == null ? null : v.trim();
}
private static String catalogUrl() {
if (!com.droiddeck.launcher.BuildConfig.DEBUG) return CATALOG_URL;
try {
Object value = Class.forName("android.os.SystemProperties").getMethod("get", String.class)
.invoke(null, "debug.droiddeck.linuxfs");
if (value instanceof String && ((String) value).startsWith("http")) return (String) value;
} catch (ReflectiveOperationException e) {
Log.w(TAG, "catalog override: " + e);
}
return CATALOG_URL;
}
public static Release fetchRelease() {
String body = Downloader.downloadString(CATALOG_URL);
String body = Downloader.downloadString(catalogUrl());
if (body == null || body.isEmpty()) return null;
try {
JSONObject json = new JSONObject(body);
@@ -292,7 +304,7 @@ public final class LinuxRuntimeInstaller {
recoverInterruptedSwap(root, staging, old);
if (!discard(staging, null) || !staging.mkdirs()) return false;
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1);
if (!extract(context, archive, staging, listener)) {
if (!extract(context, archive, staging, root, listener)) {
RuntimeFileTree.delete(staging, null);
return false;
}
@@ -346,7 +358,11 @@ public final class LinuxRuntimeInstaller {
return false;
}
new File(root, CARRY_MARKER).delete();
try { RuntimeFileTree.dropStaleState(root); }
catch (IOException e) { Log.w(TAG, "could not clear caches left by the previous runtime", e); }
discard(old, null);
try { com.droiddeck.launcher.session.SessionFiles.INSTANCE.stage(context, root, false); }
catch (Exception e) { Log.w(TAG, "could not stage the session files into the new runtime", e); }
return LinuxRuntime.isInstalled(context);
} catch (Exception e) {
Log.e(TAG, "install", e);
@@ -513,6 +529,10 @@ public final class LinuxRuntimeInstaller {
// Packages extract over the live runtime and their archives list a link before the file it
// names, so a kill mid-way must leave neither a truncated file nor a link to a missing one.
public static boolean extract(Context context, File archive, File destination, ProgressListener listener) {
return extract(context, archive, destination, destination, listener);
}
static boolean extract(Context context, File archive, File destination, File linkRoot, ProgressListener listener) {
long entries = 0;
String extracting = context.getString(R.string.rtinst_extracting);
java.util.LinkedHashMap<File, String> links = new java.util.LinkedHashMap<>();
@@ -537,7 +557,7 @@ public final class LinuxRuntimeInstaller {
links.remove(file);
links.put(file, entry.getLinkName());
} else if (entry.isLink()) {
File target = ArchivePaths.inside(destination, entry.getLinkName());
File target = hardLinkTarget(destination, entry.getLinkName());
if (target == null) {
Log.w(TAG, "skipping hard link outside the rootfs: " + entry.getLinkName());
continue;
@@ -548,11 +568,11 @@ public final class LinuxRuntimeInstaller {
try {
Files.createLink(part.toPath(), target.toPath());
} catch (IOException | UnsupportedOperationException e) {
if (target.isFile()) {
if (!l2sLink(target, part, destination, linkRoot) && target.isFile()) {
Files.copy(target.toPath(), part.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
if (part.exists()) place(part, file);
if (Files.exists(part.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) place(part, file);
} else if (entry.isFile()) {
links.remove(file);
File part = partFile(file);
@@ -589,6 +609,67 @@ public final class LinuxRuntimeInstaller {
}
}
static File hardLinkTarget(File destination, String name) throws IOException {
java.nio.file.Path path = java.nio.file.Paths.get(name).normalize();
java.nio.file.Path last = path.getFileName();
if (last == null || last.toString().isEmpty() || last.toString().equals("..")) return null;
java.nio.file.Path parent = path.getParent();
File dir = parent == null ? destination : ArchivePaths.inside(destination, parent.toString());
return dir == null ? null : new File(dir, last.toString());
}
private static final String L2S = ".l2s.";
static boolean l2sLink(File target, File link) {
return l2sLink(target, link, null, null);
}
static boolean l2sLink(File target, File link, File tree, File linkTree) {
java.nio.file.Path here = tree == null ? null : tree.toPath().toAbsolutePath().normalize();
java.nio.file.Path there = linkTree == null ? here : linkTree.toPath().toAbsolutePath().normalize();
java.util.function.UnaryOperator<java.nio.file.Path> shown = path -> {
java.nio.file.Path p = path.toAbsolutePath().normalize();
return here == null || !p.startsWith(here) ? p : there.resolve(here.relativize(p));
};
java.util.function.UnaryOperator<java.nio.file.Path> actual = path -> {
java.nio.file.Path p = path.toAbsolutePath().normalize();
return there == null || !p.startsWith(there) ? p : here.resolve(there.relativize(p));
};
try {
java.nio.file.Path original = target.toPath().toAbsolutePath().normalize();
java.nio.file.Path intermediate;
if (Files.isSymbolicLink(original)) {
intermediate = actual.apply(Files.readSymbolicLink(original));
if (!intermediate.getFileName().toString().startsWith(L2S) || !Files.isSymbolicLink(intermediate)) return false;
java.nio.file.Path fin = actual.apply(Files.readSymbolicLink(intermediate));
String name = fin.getFileName().toString();
int count = Integer.parseInt(name.substring(name.length() - 4)) + 1;
java.nio.file.Path next = fin.resolveSibling(name.substring(0, name.length() - 4) + String.format(java.util.Locale.ROOT, "%04d", count));
Files.move(fin, next, StandardCopyOption.ATOMIC_MOVE);
Files.delete(intermediate);
Files.createSymbolicLink(intermediate, shown.apply(next));
} else {
if (!Files.isRegularFile(original, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return false;
java.nio.file.Path dir = original.getParent();
String base = L2S + original.getFileName();
int suffix = 1;
do {
intermediate = dir.resolve(base + String.format(java.util.Locale.ROOT, "%04d", suffix++));
} while (Files.exists(intermediate, java.nio.file.LinkOption.NOFOLLOW_LINKS) && suffix < 1000);
java.nio.file.Path fin = dir.resolve(intermediate.getFileName() + ".0002");
Files.move(original, fin, StandardCopyOption.ATOMIC_MOVE);
Files.createSymbolicLink(intermediate, shown.apply(fin));
Files.createSymbolicLink(original, shown.apply(intermediate));
}
Files.deleteIfExists(link.toPath());
Files.createSymbolicLink(link.toPath(), shown.apply(intermediate));
return true;
} catch (IOException | RuntimeException e) {
Log.w(TAG, "l2s link " + link + " -> " + target + ": " + e);
return false;
}
}
static File partFile(File file) {
return new File(file.getParentFile(), ".dd-part-" + Integer.toHexString(file.getName().hashCode()));
}
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.Build
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
@@ -37,9 +38,10 @@ object ProotFastPath {
fun hostEnv(key: String): Pair<String, String> = "PROOT_FASTPATH" to key
fun guestEnv(root: File, binds: List<String>, key: String): List<String> = listOf(
fun guestEnv(root: File, binds: List<String>, key: String, sdk: Int = Build.VERSION.SDK_INT): List<String> = listOf(
"PROOT_FP_ROOT=" + root.path,
"PROOT_FP_BINDS=" + binds.joinToString("|"),
"PROOT_FP_KEY=$key",
"PROOT_FP_ANDROID_API=$sdk",
)
}
@@ -0,0 +1,201 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.os.ParcelFileDescriptor
import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.File
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.atomic.AtomicInteger
object RootSpawner {
private const val TAG = "RootSpawner"
fun socket(context: Context): String = "${context.packageName}.root"
private val seq = AtomicInteger()
@Volatile private var server: LocalServerSocket? = null
@Synchronized
fun start(context: Context) {
if (server != null) return
val app = context.applicationContext
val name = socket(app)
val socket = try {
LocalServerSocket(name)
} catch (e: IOException) {
Log.e(TAG, "cannot listen on $name", e)
return
}
server = socket
Thread({
while (true) {
val client = try { socket.accept() } catch (e: IOException) { Log.e(TAG, "accept", e); break }
Thread({ serve(app, client) }, "root-${seq.get() + 1}").apply { isDaemon = true; start() }
}
}, "root-server").apply { isDaemon = true; start() }
}
private fun serve(context: Context, client: LocalSocket) {
val id = seq.incrementAndGet()
val received = ArrayList<FileDescriptor>()
client.use {
val out = DataOutputStream(client.outputStream)
try {
if (client.peerCredentials.uid != Process.myUid()) {
Log.w(TAG, "refused root for uid ${client.peerCredentials.uid}")
return
}
val input = DataInputStream(client.inputStream)
val kind = input.readUnsignedByte()
client.ancillaryFileDescriptors?.let { received.addAll(it) }
val body = ByteArray(input.readInt()).also { input.readFully(it) }
client.ancillaryFileDescriptors?.let { received.addAll(it) }
if (kind != 'R'.code) return
run(context, JSONObject(String(body, Charsets.UTF_8)), received, client, input, out, id)
} catch (e: Exception) {
Log.e(TAG, "root $id", e)
runCatching {
frame(out, 'E', (e.message ?: e.toString()).toByteArray())
frame(out, 'X', "1".toByteArray())
}
} finally {
received.forEach { fd -> runCatching { android.system.Os.close(fd) } }
}
}
}
private class Stdio(val redirect: ProcessBuilder.Redirect?, val fd: FileDescriptor?, val dup: ParcelFileDescriptor?)
private fun stdio(fd: FileDescriptor?, write: Boolean): Stdio {
if (fd == null) return Stdio(null, null, null)
val dup = try { ParcelFileDescriptor.dup(fd) } catch (e: IOException) { return Stdio(null, fd, null) }
val path = File("/proc/self/fd/${dup.fd}")
val opens = try {
if (write) FileOutputStream(path, true).close() else FileInputStream(path).close()
true
} catch (e: IOException) { false }
if (!opens) return Stdio(null, fd, dup)
val redirect = if (write) ProcessBuilder.Redirect.appendTo(path) else ProcessBuilder.Redirect.from(path)
return Stdio(redirect, fd, dup)
}
private fun pump(from: InputStream, to: OutputStream, name: String) =
Thread({
val buffer = ByteArray(16384)
try {
while (true) {
val n = from.read(buffer)
if (n < 0) break
to.write(buffer, 0, n)
to.flush()
}
} catch (e: IOException) {
} finally {
runCatching { to.close() }
}
}, name).apply { isDaemon = true; start() }
private fun run(context: Context, request: JSONObject, fds: List<FileDescriptor>, client: LocalSocket,
input: DataInputStream, out: DataOutputStream, id: Int) {
val root = LinuxRuntime.rootDir(context)
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
if (argv.isEmpty()) throw IOException("no command")
val cwd = request.optString("cwd", "/root").ifEmpty { "/root" }
val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true)
cmd.add(1, "--link2symlink")
LinuxRuntime.lastBinds(context).filterNot { it.startsWith("/proc/self/fd/") }.forEach { cmd.add("-b"); cmd.add(it) }
cmd.add("/usr/bin/env")
cmd.add("-i")
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> cmd.add("$k=${e.getString(k)}") } }
cmd.addAll(argv)
val builder = ProcessBuilder(cmd).directory(root)
builder.environment().apply {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
val streams = listOf(stdio(fds.getOrNull(0), false), stdio(fds.getOrNull(1), true), stdio(fds.getOrNull(2), true))
try {
builder.redirectInput(streams[0].redirect ?: ProcessBuilder.Redirect.PIPE)
builder.redirectOutput(streams[1].redirect ?: ProcessBuilder.Redirect.PIPE)
builder.redirectError(streams[2].redirect ?: ProcessBuilder.Redirect.PIPE)
val process = builder.start()
val pid = HostProcess.pidOf(process)
OrphanReaper.keep(pid)
Log.i(TAG, "root $id pid $pid: ${argv.joinToString(" ")}")
synchronized(out) { frame(out, 'P', pid.toString().toByteArray()) }
val pumps = ArrayList<Thread>()
if (streams[0].redirect == null) {
val fd = streams[0].fd
if (fd != null) pumps.add(pump(FileInputStream(fd), process.outputStream, "root-$id-in").also { it.isDaemon = true })
else runCatching { process.outputStream.close() }
}
if (streams[1].redirect == null) pumps.add(pump(process.inputStream,
streams[1].fd?.let { FileOutputStream(it) } ?: OutputStream.nullOutputStream(), "root-$id-out"))
if (streams[2].redirect == null) pumps.add(pump(process.errorStream,
streams[2].fd?.let { FileOutputStream(it) } ?: OutputStream.nullOutputStream(), "root-$id-err"))
Thread({
try {
while (true) {
val kind = input.readUnsignedByte()
val body = ByteArray(input.readInt()).also { input.readFully(it) }
if (kind == 'S'.code) String(body).trim().toIntOrNull()?.let { signal(pid, it) }
}
} catch (e: IOException) {
}
if (process.isAlive) {
Log.i(TAG, "root $id: its caller is gone; stopping it")
signal(pid, android.system.OsConstants.SIGHUP)
android.os.Process.sendSignal(pid, android.system.OsConstants.SIGQUIT)
}
}, "root-$id-watch").apply { isDaemon = true; start() }
val status = process.waitFor()
pumps.filter { it.name.endsWith("-out") || it.name.endsWith("-err") }.forEach { it.join(2000) }
OrphanReaper.release(pid)
Log.i(TAG, "root $id exited $status")
runCatching { synchronized(out) { frame(out, 'X', status.toString().toByteArray()) } }
} finally {
streams.forEach { s -> runCatching { s.dup?.close() } }
}
}
private fun signal(top: Int, signal: Int) {
val parents = HashMap<Int, Int>()
File("/proc").listFiles()?.forEach { dir ->
val pid = dir.name.toIntOrNull() ?: return@forEach
val stat = try { File(dir, "stat").readText() } catch (e: IOException) { return@forEach }
val fields = stat.substringAfterLast(')').trim().split(' ')
fields.getOrNull(1)?.toIntOrNull()?.let { parents[pid] = it }
}
val tree = HashSet<Int>()
var grew = true
while (grew) {
grew = false
for ((pid, parent) in parents) {
if (pid !in tree && (parent == top || parent in tree)) { tree.add(pid); grew = true }
}
}
tree.forEach { runCatching { android.os.Process.sendSignal(it, signal) } }
}
private fun frame(out: DataOutputStream, kind: Char, payload: ByteArray) {
out.writeByte(kind.code)
out.writeInt(payload.size)
out.write(payload)
out.flush()
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.BuildConfig
object RuntimeAutoUpdate {
private const val PREFS = "runtime-auto-update"
const val MAX_ATTEMPTS = 3
const val RETRY_MS = 10 * 60_000L
fun due(installed: String?, release: String?, attempts: Int, lastAt: Long = 0L, now: Long = lastAt + RETRY_MS): Boolean =
installed != null && !release.isNullOrEmpty() && release != installed && attempts < MAX_ATTEMPTS &&
(attempts == 0 || now - lastAt !in 0 until RETRY_MS)
fun key(appVersion: Int, release: String) = "$appVersion:$release"
fun claim(context: Context, installed: String?, release: String?, now: Long = System.currentTimeMillis()): Boolean {
if (release.isNullOrEmpty()) return false
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val key = key(BuildConfig.VERSION_CODE, release)
synchronized(this) {
val attempts = prefs.getInt(key, 0)
if (!due(installed, release, attempts, prefs.getLong("$key@at", 0L), now)) return false
val edit = prefs.edit()
prefs.all.keys.filterNot { it.startsWith("${BuildConfig.VERSION_CODE}:") }.forEach { edit.remove(it) }
edit.putInt(key, attempts + 1).putLong("$key@at", now).apply()
return true
}
}
}
@@ -80,7 +80,7 @@ public final class RuntimeFileTree {
* be carried.
*/
static java.util.List<String> userPaths(File tree) throws IOException {
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps"));
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps", "opt/droiddeck/wincomponents"));
for (String n : children(new File(tree, "usr/local/share/applications"))) {
if (n.endsWith(".desktop") && (n.startsWith("droiddeck-app-") || n.startsWith("droiddeck-appimage-")))
paths.add("usr/local/share/applications/" + n);
@@ -109,10 +109,39 @@ public final class RuntimeFileTree {
static java.util.List<String> existingUserPaths(File from, File to) throws IOException {
java.util.List<String> paths = new java.util.ArrayList<>();
for (String rel : userPaths(from, to)) if (exists(safePath(from, rel).toPath())) paths.add(rel);
for (String rel : userPaths(from, to)) {
if (!exists(safePath(from, rel).toPath())) continue;
if (rel.startsWith("usr/share/applications/") && exists(safePath(to, rel).toPath())) continue;
paths.add(rel);
}
return paths;
}
private static final String[] STALE_HOME_STATE = {
".local/share/droiddeck/pacman", ".cache/droiddeck/pacman-restore.log",
".cache/appstream", ".cache/discover", ".cache/fontconfig", ".cache/kwin", ".cache/ksplash",
".cache/ksvg-elements", ".cache/plasmashell", ".cache/kwinsession.kcache", ".cache/icon-cache.kcache",
};
private static final String[] STALE_HOME_CACHE_PREFIXES = {
"mesa_shader_cache", "ksycoca", "plasma_theme_", "qtshadercache", "event-sound-cache.tdb.",
};
static void dropStaleState(File runtimeRoot) throws IOException {
File home = new File(runtimeRoot, "root");
java.util.List<String> stale = new java.util.ArrayList<>(java.util.Arrays.asList(STALE_HOME_STATE));
for (String n : children(new File(home, ".cache"))) {
for (String prefix : STALE_HOME_CACHE_PREFIXES) {
if (n.startsWith(prefix)) { stale.add(".cache/" + n); break; }
}
}
IOException failed = null;
for (String rel : stale) {
try { delete(safePath(home, rel), null); }
catch (IOException e) { if (failed == null) failed = e; else failed.addSuppressed(e); }
}
if (failed != null) throw failed;
}
private static java.util.List<String> children(File dir) throws IOException {
java.util.List<String> names = new java.util.ArrayList<>();
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir.toPath())) {
@@ -11,14 +11,15 @@ object RuntimeHealth {
fun brokenLibraryLinks(context: Context): List<String> = brokenLibraryLinks(LinuxRuntime.rootDir(context))
/** A complete runtime has no library link in usr/lib whose target is missing. */
fun brokenLibraryLinks(root: File): List<String> {
val lib = File(root, "usr/lib")
val names = lib.list() ?: return emptyList()
return names.sorted().filter { name ->
val path = File(lib, name).toPath()
Files.isSymbolicLink(path) && !resolves(root, path)
fun brokenLibraryLinks(root: File): List<String> =
listOf("usr/lib", "usr/lib/aarch64-linux-gnu").flatMap { dir ->
val lib = File(root, dir)
val names = lib.list() ?: return@flatMap emptyList()
names.sorted().filter { name ->
val path = File(lib, name).toPath()
Files.isSymbolicLink(path) && !resolves(root, path)
}.map { if (dir == "usr/lib") it else "aarch64-linux-gnu/$it" }
}
}
private fun resolves(root: File, link: Path): Boolean = try {
var path = link
@@ -156,8 +156,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 {
@@ -176,6 +175,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) {
@@ -13,6 +13,7 @@ object GameEnvironmentStore {
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
const val DXVK_CONFIG = "dxvkConfig"
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
const val GAME_DEBUG_LOGS = "gameDebugLogs"
@Synchronized
fun read(context: Context): GameEnvironment.Config {
@@ -87,7 +88,11 @@ object GameEnvironmentStore {
}
@Synchronized
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
fun publish(
context: Context,
config: GameEnvironment.Config = read(context),
gameDebugLogsOverride: Boolean? = null,
) {
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
val json = encode(resolved)
val dxvk = TextureFiltering.dxvkOptions(
@@ -110,6 +115,11 @@ object GameEnvironmentStore {
)
}
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
json.put(
GAME_DEBUG_LOGS,
gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) &&
SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)),
)
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
}
@@ -21,7 +21,7 @@ class GpuMemComponent(private val file: File, private val root: File) : SessionP
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (running && OverlayShown.check(root)) sample()?.let { write(it) }
if (running && (OverlayShown.check(root) || com.droiddeck.launcher.hud.FusionHudHost.showing)) sample()?.let { write(it) }
}
}, "gpu-mem").apply { isDaemon = true; start() }
}
@@ -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) {
@@ -1,178 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.util.Locale
import java.util.concurrent.atomic.AtomicInteger
class PerfHud(context: Context) {
var text by mutableStateOf("")
private set
var graph by mutableStateOf(FloatArray(0))
private set
private val context = context.applicationContext
private val frames = AtomicInteger()
private var lastTick = 0L
private var lastFps = 0f
private var running = false
private val handler = Handler(Looper.getMainLooper())
private val samples = FloatArray(GRAPH)
private var graphBase = 0L
private var graphSeen = 0L
@Volatile private var showFps = true
@Volatile private var showBattery = true
@Volatile private var showGraph = true
private val enabled: Boolean
get() = SessionPrefs.hudEnabled(context)
&& !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
private val anyPart: Boolean
get() = showFps || showBattery || showGraph
var onPresentingWindowChanged: (() -> Unit)? = null
private var lastWindow: String? = null
private val listener = object : WaylandCompositor.GameListener {
override fun onGameSurface(window: String?, gpuName: String?) {
if (window != null && window != lastWindow) {
lastWindow = window
handler.post { onPresentingWindowChanged?.invoke() }
}
}
override fun onGameFrame() {
frames.incrementAndGet()
}
}
private val tick = object : Runnable {
override fun run() {
if (!running) return
val now = SystemClock.elapsedRealtime()
val dt = (now - lastTick).coerceAtLeast(1L) / 1000f
lastTick = now
lastFps = frames.getAndSet(0) / dt
text = readout(lastFps)
if (showGraph) publishGraph() else clearGraph()
handler.postDelayed(this, TICK_MS)
}
}
fun refresh() {
readOptions()
if (!enabled || !anyPart) {
stop()
return
}
if (!running) start() else {
if (!showGraph) clearGraph() else publishGraph()
text = readout(lastFps)
}
}
fun start() {
readOptions()
if (!enabled || !anyPart || running) return
running = true
lastTick = SystemClock.elapsedRealtime()
frames.set(0)
graphBase = shownTotal()
graphSeen = graphBase
WaylandCompositor.setGameListener(listener)
handler.postDelayed(tick, TICK_MS)
}
fun stop() {
running = false
handler.removeCallbacks(tick)
WaylandCompositor.clearGameListener(listener)
text = ""
graph = FloatArray(0)
}
private fun readOptions() {
showFps = SessionPrefs.hudShowFps(context)
showBattery = SessionPrefs.hudShowBattery(context)
showGraph = SessionPrefs.hudShowGraph(context)
}
private fun readout(fpsValue: Float): String {
val parts = ArrayList<String>(2)
if (showFps) parts.add(line(fpsValue))
if (showBattery) batteryCelsius(readBatteryDeci())?.let { parts.add(it) }
return parts.joinToString("\n")
}
private fun readBatteryDeci(): Int {
val sticky = runCatching {
context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
}.getOrNull() ?: return 0
return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
}
private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L }
private fun clearGraph() {
graphBase = shownTotal()
graphSeen = graphBase
if (graph.isNotEmpty()) graph = FloatArray(0)
}
private fun publishGraph() {
val total = shownTotal()
if (total == graphSeen && graph.isNotEmpty()) return
graphSeen = total
graph = recent(samples, total, graphBase)
}
private fun line(base: Float): String {
val mode = FrameGen.mode(context)
if (mode.engine == FrameGen.ENGINE_OFF) return fps(base)
val lsfg = mode.engine == FrameGen.ENGINE_LSFG
val name = if (lsfg) "LSFG" else "DD-FG"
val label = FrameGen.label(context, mode)
if (lsfg && Lossless.cacheFile(context)?.isFile != true) return context.getString(R.string.hud_fg_needs_lossless, name)
val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null }
val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 }
return when {
problem == 1 -> context.getString(R.string.hud_fg_unsupported, name)
problem == 2 -> context.getString(R.string.hud_fg_failed, name)
stats != null && stats[3] > 1f -> String.format(Locale.US, "%s %.0f → %.0f fps", label, base, stats[3])
else -> context.getString(R.string.hud_fg_starting, label, fps(base))
}
}
private fun fps(value: Float) = String.format(Locale.US, "%.0f fps", value)
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) {
@@ -7,6 +7,9 @@ import com.droiddeck.launcher.core.SessionLogCapture
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.Writer
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -16,6 +19,9 @@ object SessionArtifacts {
const val COMPLETE_MARKER = ".complete"
private const val RECOVERY_RUNTIME_CAPTURED_MARKER = ".recovery-runtime-captured"
private const val RECOVERY_RUNTIME_EXPIRED_MARKER = ".recovery-runtime-expired"
private val SCRUBBED_MARKER = ".scrubbed-r${LogRedactor.RULES_VERSION}"
private val OLD_SCRUBBED_MARKER = Regex("""\.scrubbed-(r?\d+)""")
@@ -72,9 +78,9 @@ object SessionArtifacts {
copySteamLogs(context, dir, record, steamArch)
VacDiagnostics.collect(context, dir)
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
markScrubbed(scrubTree(record))
val scrubbed = markScrubbed(scrubTree(record))
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
if (scrubbed) File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
} catch (e: Exception) {
Log.w(TAG, "collecting session artifacts", e)
}
@@ -88,15 +94,10 @@ object SessionArtifacts {
}?.toList() ?: return
if (dirs.isEmpty()) return
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val workers = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4)
val pool = java.util.concurrent.Executors.newFixedThreadPool(workers) { r ->
Thread({ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); r.run() }, "scrub-logs")
}
val done = try {
pool.invokeAll(dirs.map { dir -> java.util.concurrent.Callable { scrubAndMark(dir) } })
.count { f -> try { f.get() } catch (e: Exception) { false } }
} finally {
pool.shutdown()
var done = 0
for (dir in dirs) {
if (SessionState.running) break
if (scrubAndMark(dir, stopWhenSessionStarts = true)) done++
}
val failed = dirs.size - done
Log.i(TAG, "logs: scrubbed $done folders under r${LogRedactor.RULES_VERSION}" +
@@ -114,35 +115,121 @@ object SessionArtifacts {
private class Record(val dir: File) {
val files = HashMap<File, Scrubbed>()
var failed = false
var deferred = false
}
private fun scrubFolder(dir: File, record: Record) {
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f ->
if (LogRedactor.isBinary(f)) return@forEach
// Too large to rewrite in memory: the folder must not be recorded as scrubbed.
if (!LogRedactor.isText(f)) { record.failed = true; return@forEach }
val done = scrubFile(dir, f)
if (done == null) record.failed = true else record.files[f] = done
private sealed class ScrubResult {
class Done(val scrubbed: Scrubbed) : ScrubResult()
object Failed : ScrubResult()
object Deferred : ScrubResult()
}
private fun scrubFolder(
dir: File,
record: Record,
shouldStop: () -> Boolean,
beforeReplace: (File) -> Unit,
listFiles: (File) -> Array<File>?,
): Boolean {
val files = listFiles(dir)?.filter { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }
if (files == null) {
record.failed = true
return true
}
for (f in files) {
if (shouldStop()) return false
if (LogRedactor.isBinary(f)) continue
when (val result = scrubFile(dir, f, shouldStop, beforeReplace)) {
is ScrubResult.Done -> record.files[f] = result.scrubbed
ScrubResult.Failed -> record.failed = true
ScrubResult.Deferred -> {
record.failed = true
record.deferred = true
return false
}
}
}
return true
}
private fun scrubFile(dir: File, f: File): Scrubbed? {
private fun scrubFile(
dir: File,
f: File,
shouldStop: () -> Boolean,
beforeReplace: (File) -> Unit,
): ScrubResult {
val tmp = File(dir, ".${f.name}.scrub")
return try {
val before = Scrubbed(f.length(), f.lastModified())
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
val scrubbed = tmp.readBytes()
if (scrubbed.contentEquals(f.readBytes())) {
val scrubbed = tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w, shouldStop) }
if (!scrubbed) {
tmp.delete()
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
} else {
if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() }
Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length }
return ScrubResult.Deferred
}
val scrubbedLength = tmp.length()
when (sameContents(tmp, f, shouldStop)) {
null -> {
tmp.delete()
ScrubResult.Deferred
}
true -> {
tmp.delete()
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed
}
false -> {
if (shouldStop()) {
tmp.delete()
return ScrubResult.Deferred
}
beforeReplace(f)
if (f.length() != before.length || f.lastModified() != before.modified) {
tmp.delete()
return ScrubResult.Failed
}
if (!tmp.renameTo(f)) {
tmp.delete()
return ScrubResult.Failed
}
Scrubbed(scrubbedLength, f.lastModified()).takeIf { f.length() == it.length }
?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed
}
}
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${f.name}", e)
tmp.delete()
null
ScrubResult.Failed
}
}
internal fun sameContents(a: File, b: File, shouldStop: () -> Boolean = { false }): Boolean? {
if (shouldStop()) return null
if (a.length() != b.length()) return false
fun readChunk(input: java.io.InputStream, buffer: ByteArray): Int? {
var count = 0
while (count < buffer.size) {
if (shouldStop()) return null
val read = input.read(buffer, count, buffer.size - count)
if (shouldStop()) return null
if (read < 0) break
if (read == 0) continue
count += read
}
return count
}
return a.inputStream().buffered().use { left ->
b.inputStream().buffered().use { right ->
val leftBuffer = ByteArray(64 * 1024)
val rightBuffer = ByteArray(64 * 1024)
while (true) {
val leftCount = readChunk(left, leftBuffer) ?: return null
val rightCount = readChunk(right, rightBuffer) ?: return null
if (leftCount != rightCount) return false
if (leftCount == 0) break
if (shouldStop()) return null
for (i in 0 until leftCount) if (leftBuffer[i] != rightBuffer[i]) return false
}
true
}
}
}
@@ -183,10 +270,44 @@ object SessionArtifacts {
}.toSet()
}
internal fun scrubAndMark(dir: File): Boolean = markScrubbed(scrubTree(Record(dir)))
internal fun scrubAndMark(
dir: File,
stopWhenSessionStarts: Boolean = false,
beforeReplace: (File) -> Unit = {},
listFiles: (File) -> Array<File>? = { it.listFiles() },
sessionStarted: () -> Boolean = { SessionState.running },
): Boolean {
val shouldStop = { stopWhenSessionStarts && sessionStarted() }
val record = scrubTree(
Record(dir),
listFiles = listFiles,
beforeReplace = beforeReplace,
shouldStop = shouldStop,
)
if (shouldStop()) {
record.failed = true
record.deferred = true
}
return markScrubbed(record)
}
private fun scrubTree(record: Record): Record {
record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) }
private fun scrubTree(
record: Record,
listFiles: (File) -> Array<File>? = { it.listFiles() },
beforeReplace: (File) -> Unit = {},
shouldStop: () -> Boolean = { false },
): Record {
for (dir in record.dir.walkTopDown().filter { it.isDirectory }) {
if (shouldStop() || !scrubFolder(dir, record, shouldStop, beforeReplace, listFiles)) {
record.failed = true
record.deferred = true
break
}
}
if (shouldStop()) {
record.failed = true
record.deferred = true
}
return record
}
@@ -205,6 +326,7 @@ object SessionArtifacts {
private const val HEAD = 4096L
private class Mark(val size: Long, val head: String)
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
fun markSteamLogs(dir: File, logs: File) {
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
@@ -240,23 +362,54 @@ object SessionArtifacts {
.firstOrNull { m -> heads.getOrPut(minOf(m.size, HEAD)) { head(src, m.size) } == m.head }?.size ?: 0L
}
private fun copySteamLogs(context: Context, dir: File, record: Record, steamArch: String? = null) {
private fun copySteamLogs(
context: Context,
dir: File,
record: Record,
steamArch: String? = null,
stopWhenSessionStarts: Boolean = false,
) {
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() }
copySessionLogs(logs, dir, out).forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
record.failed = record.failed || result.failed
record.deferred = record.deferred || result.deferred
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
internal fun copySessionLogs(logs: File, dir: File, out: File): List<File> {
internal fun copySessionLogs(
logs: File,
dir: File,
out: File,
openWriter: (File) -> Writer = { it.bufferedWriter() },
): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files
private fun copySessionLogsResult(
logs: File,
dir: File,
out: File,
openWriter: (File) -> Writer = { it.bufferedWriter() },
shouldStop: () -> Boolean,
): CopyResult {
val marks = steamLogMarks(dir)
val copied = ArrayList<File>()
logs.listFiles { f -> f.isFile }?.forEach { src ->
var failed = false
var deferred = false
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
for (src in sources) {
if (shouldStop()) {
failed = true
deferred = true
break
}
val size = src.length()
val from = marks?.let { startOf(src, size, it) } ?: 0L
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) return@forEach
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) continue
val dst = File(out, src.name)
val staging = File(out, ".${src.name}.copy")
try {
val dst = File(out, src.name)
src.inputStream().buffered().use { input ->
var left = if (from > 0) from - 1 else 0L
while (left > 0) {
@@ -270,49 +423,183 @@ object SessionArtifacts {
if (c < 0 || c == '\n'.code) break
}
}
dst.bufferedWriter().use { w ->
input.bufferedReader().forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
val complete = openWriter(staging).use { w -> scrubSteamLog(input, w, shouldStop) }
if (!complete) {
staging.delete()
failed = true
deferred = true
}
}
copied.add(dst)
if (deferred) break
Files.move(
staging.toPath(),
dst.toPath(),
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING,
)
copied += dst
} catch (e: Exception) {
staging.delete()
Log.w(TAG, "could not scrub ${src.name}", e)
failed = true
}
}
return copied
return CopyResult(copied, failed, deferred)
}
private fun scrubSteamLog(
input: java.io.InputStream,
out: java.io.Writer,
shouldStop: () -> Boolean,
): Boolean {
input.reader().use { reader ->
val chunk = CharArray(8192)
val line = StringBuilder(4096)
var oversized = false
var pendingContent = false
var pendingCarriageReturn = false
fun emit() {
out.write(if (oversized) LogRedactor.OVERSIZED_LINE else LogRedactor.redact(line.toString()))
out.write("\n")
line.setLength(0)
oversized = false
pendingContent = false
}
while (true) {
if (shouldStop()) return false
val count = reader.read(chunk)
if (count < 0) break
if (shouldStop()) return false
for (i in 0 until count) {
if (shouldStop()) return false
val char = chunk[i]
if (pendingCarriageReturn) {
emit()
pendingCarriageReturn = false
if (char == '\n') continue
}
when (char) {
'\r' -> pendingCarriageReturn = true
'\n' -> emit()
else -> {
pendingContent = true
if (!oversized) {
if (line.length < LogRedactor.MAX_LINE_LENGTH) line.append(char)
else {
line.setLength(0)
oversized = true
}
}
}
}
}
}
if (pendingCarriageReturn || pendingContent) {
if (shouldStop()) return false
emit()
}
}
return true
}
@Synchronized
fun finishAbandoned(context: Context) {
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) {
val stopWhenSessionStarts = !beforeGuestStart
val parent = LinuxRuntime.logDir(context)
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f)
}?.sortedWith(SessionPaths.chronological) ?: return
if (abandoned.isEmpty()) return
val current = SessionPaths.current()
val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current }
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
abandoned.forEachIndexed { i, dir ->
if (dir == current) return@forEachIndexed
val newest = i == abandoned.lastIndex
for (dir in abandoned) {
if (stopWhenSessionStarts && SessionState.running) break
if (dir == current) continue
if (beforeGuestStart && dir != latestPreviousSession) continue
val newest = dir == latestPreviousSession
try {
File(dir, "ended-without-teardown.txt").writeText(
"This session's process ended without running its own teardown - killed by\n" +
"Android, a native crash, or the device going down - so the files below were\n" +
"gathered when the app next started, at ${now()}.\n" +
"The logs written during the session (session.log, app.log, wayland.log,\n" +
"audio.log, device.txt) were on disk already and are as they were left.\n" +
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
)
val recoveryNote = File(dir, "ended-without-teardown.txt")
val runtimeCaptured = File(dir, RECOVERY_RUNTIME_CAPTURED_MARKER)
val runtimeExpired = File(dir, RECOVERY_RUNTIME_EXPIRED_MARKER)
val recoveryPreviouslyAttempted = recoveryNote.exists()
val recoveryAttempted = recoveryPreviouslyAttempted &&
(runtimeCaptured.exists() || runtimeExpired.exists() || !beforeGuestStart)
if (!recoveryAttempted) {
recoveryNote.writeText(
"This session's process ended without running its own teardown - killed by\n" +
"Android, a native crash, or the device going down - so the files below were\n" +
"gathered when the app next started, at ${now()}.\n" +
"The logs written during the session (session.log, app.log, wayland.log,\n" +
"audio.log, device.txt) were on disk already and are as they were left.\n" +
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
)
}
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
(runtimeExpired.exists() || !beforeGuestStart) &&
!recoveryNote.readText().contains("runtime capture did not finish")) {
recoveryNote.appendText(
"Steam's logs and VAC evidence are not included: runtime capture did not finish " +
"before its evidence expired.\n"
)
}
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() && !beforeGuestStart) {
runtimeExpired.writeText("runtime evidence no longer belongs to this session, at ${now()}\n")
}
val record = Record(dir)
if (newest) {
copySteamLogs(context, dir, record, recordedClient(dir))
VacDiagnostics.collect(context, dir)
if (newest && !recoveryAttempted) {
copySteamLogs(
context,
dir,
record,
steamArch = recordedClient(dir),
stopWhenSessionStarts = stopWhenSessionStarts,
)
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
if (!record.failed && VacDiagnostics.collect(context, dir)) {
try {
runtimeCaptured.writeText("collected at ${now()}\n")
} catch (e: Exception) {
record.failed = true
if (beforeGuestStart) {
runtimeExpired.writeText("runtime capture marker failed, at ${now()}\n")
}
Log.w(TAG, "could not mark runtime capture for $dir", e)
}
} else {
record.failed = true
if (beforeGuestStart) {
runtimeExpired.writeText("runtime capture failed, at ${now()}\n")
}
}
}
}
if (record.deferred || stopWhenSessionStarts && SessionState.running) {
record.failed = true
record.deferred = true
markScrubbed(record)
break
}
val crashLog = File(dir, "crash.log")
if (!crashLog.exists()) {
SessionLogCapture.dumpCrashBuffer(crashLog)
}
if (stopWhenSessionStarts && SessionState.running) {
record.failed = true
record.deferred = true
markScrubbed(record)
break
}
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
markScrubbed(scrubTree(record))
if (beforeGuestStart) return
val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running }
val marked = markScrubbed(scrubbed)
if (scrubbed.deferred) break
if (!marked) continue
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
Log.i(TAG, "finished the abandoned session folder $dir")
} catch (e: Exception) {
@@ -25,6 +25,8 @@ object SessionFiles {
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
"usr/local/bin/droiddeck-desktop-window-rules" to "usr/local/bin/droiddeck-desktop-window-rules",
"usr/local/bin/droiddeck-library-perms" to "usr/local/bin/droiddeck-library-perms",
"usr/local/bin/droiddeck-ime" to "usr/local/bin/droiddeck-ime",
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
@@ -32,7 +34,7 @@ object SessionFiles {
/** Puts the session's files in place; [startsSession] is true only for the call that starts the Steam session. */
fun stage(context: Context, root: File, startsSession: Boolean = false) {
if (DesktopCatalog.desktopInstalled(root)) try { DesktopCatalog.cleanLegacy(context) }
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
GameEnvironmentStore.publish(context)
WinComponents.publish(context)
@@ -70,10 +72,21 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
"usr/local/bin/droiddeck-snap-run" to "usr/local/bin/droiddeck-snap-run",
"usr/local/bin/droiddeck-snap-confine" to "usr/local/bin/droiddeck-snap-confine",
"usr/local/bin/droiddeck-snapctl" to "usr/local/bin/droiddeck-snapctl",
"usr/local/bin/droiddeck-systemd-run" to "usr/local/bin/systemd-run",
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
"usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim",
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
"usr/local/bin/droiddeck-gog-maintenance" to "usr/local/bin/droiddeck-gog-maintenance",
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
@@ -237,6 +250,7 @@ object SessionFiles {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n")
@@ -244,6 +258,12 @@ object SessionFiles {
stagedSocket.delete()
Log.e(TAG, "could not write bwrap-socket")
}
val stagedRoot = File(droiddeckEtc, "root-socket.staged")
if (!FileUtils.writeString(stagedRoot, com.droiddeck.launcher.runtime.RootSpawner.socket(context) + "\n")
|| !stagedRoot.renameTo(File(droiddeckEtc, "root-socket"))) {
stagedRoot.delete()
Log.e(TAG, "could not write root-socket")
}
BootMovie.syncFromSteam(context)
val startupMovie = BootMovie.prepare(context)
@@ -588,6 +608,28 @@ object SessionFiles {
* The fonts themselves are bind-mounted by LinuxRuntime.bindSystemFonts() into
* /usr/local/share/fonts/android; here we only need to point fontconfig at them.
*/
private val DESKTOP_STRINGS = listOf(
"desktop_restore_title" to R.string.desktop_restore_title,
"desktop_restore_body" to R.string.desktop_restore_body,
"desktop_restore_done_title" to R.string.desktop_restore_done_title,
"desktop_restore_done_body" to R.string.desktop_restore_done_body,
"desktop_restore_failed_title" to R.string.desktop_restore_failed_title,
"desktop_restore_failed_body" to R.string.desktop_restore_failed_body,
)
private fun writeDesktopStrings(context: Context, dir: File) {
val text = DESKTOP_STRINGS.joinToString("") { (key, id) ->
key + "=" + context.getString(id).replace("\\", "\\\\").replace("%", "%%").replace("\n", "\\n") + "\n"
}
val target = File(dir, "strings")
if (FileUtils.readString(target) == text) return
val staged = File(dir, "strings.staged")
if (!FileUtils.writeString(staged, text) || !staged.renameTo(target)) {
staged.delete()
Log.e(TAG, "could not write desktop strings")
}
}
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.session
enum class SessionLaunchFailure {
STEAM_ILLEGAL_INSTRUCTION,
VULKAN_DEVICE_MISSING;
companion object {
private val ANSI = Regex("\u001b\\[[0-?]*[ -/]*[@-~]")
private val STEAM_EXIT = Regex("== steam exited rc=(\\d+)")
fun find(lines: Sequence<String>): SessionLaunchFailure? {
var steamStarted = false
var illegalInstruction = false
var missingDevice = false
lines.forEach { raw ->
val line = ANSI.replace(raw, "").trim()
when {
line.startsWith("== droiddeck-session ") -> {
steamStarted = false
illegalInstruction = false
missingDevice = false
}
line.startsWith("== STEP ") && line.contains("starting the Steam client") -> {
steamStarted = true
illegalInstruction = false
}
STEAM_EXIT.matches(line) && steamStarted ->
illegalInstruction = STEAM_EXIT.matchEntire(line)?.groupValues?.get(1) == "132"
line.startsWith("[gamescope]") && line.contains("vulkan:") -> when {
line.contains("failed to find physical device") -> missingDevice = true
line.contains("selecting physical device") -> missingDevice = false
}
}
}
return when {
illegalInstruction -> STEAM_ILLEGAL_INSTRUCTION
missingDevice -> VULKAN_DEVICE_MISSING
else -> null
}
}
}
}
@@ -44,6 +44,10 @@ object SessionPaths {
fun current(): File? = dir
/** Whether the current session folder will survive teardown. No session means the next one can retain logs. */
fun currentSessionLogsRetained(context: Context): Boolean =
dir?.let { it.parentFile == SessionFiles.logDirectory(context) } ?: true
fun lastEnded(): File? = ended?.takeIf { it.isDirectory }
@Synchronized
@@ -21,6 +21,8 @@ object SessionPrefs {
private const val LEGACY_SUSPEND_DOWNLOADS = "downloads"
private const val STEAM_DOWNLOADS_IN_BACKGROUND = "steamDownloadsInBackground"
private const val DECKY_ZIP_WARNING_SEEN = "deckyZipWarningSeen"
private const val SLOW_USB_WARNING_OFF = "slowUsbWarningOff"
private const val SLOW_USB_DISMISSED = "slowUsbDismissed"
const val CONTROLLER_DECK = "deck"
const val CONTROLLER_XBOX360 = "xbox360"
@@ -84,6 +86,32 @@ object SessionPrefs {
prefs(context).edit().putBoolean("animations", on).apply()
}
fun dualScreenMode(context: Context): String =
prefs(context).getString("dualScreenMode", null)?.takeIf { it in com.droiddeck.launcher.input.DualScreen.modes }
?: com.droiddeck.launcher.input.DualScreen.MODE_AUTO
fun setDualScreenMode(context: Context, mode: String) {
prefs(context).edit().putString("dualScreenMode", mode).apply()
}
fun secondScreenPanel(context: Context): String? = prefs(context).getString("secondScreenPanel", null)
fun setSecondScreenPanel(context: Context, mode: String) {
prefs(context).edit().putString("secondScreenPanel", mode).apply()
}
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
fun setDualScreenLauncher(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("dualScreenLauncher", on).apply()
}
fun dualScreenSessionControls(context: Context): Boolean = prefs(context).getBoolean("dualScreenSessionControls", true)
fun setDualScreenSessionControls(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("dualScreenSessionControls", on).apply()
}
fun gameStoresEnabled(context: Context): Boolean = prefs(context).getBoolean("gameStoresEnabled", true)
fun setGameStoresEnabled(context: Context, on: Boolean) {
@@ -125,6 +153,30 @@ object SessionPrefs {
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
}
fun libraryCardLevel(context: Context): Int = prefs(context).getInt("libraryCardLevel", 2)
fun setLibraryCardLevel(context: Context, level: Int) {
prefs(context).edit().putInt("libraryCardLevel", level).apply()
}
fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", true)
fun setLibraryShowTitle(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowTitle", show).apply()
}
fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", true)
fun setLibraryShowSize(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowSize", show).apply()
}
fun railLabels(context: Context): Boolean = prefs(context).getBoolean("railLabels", false)
fun setRailLabels(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("railLabels", show).apply()
}
fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false)
fun setLibraryShowUninstalled(context: Context, show: Boolean) {
@@ -195,7 +247,7 @@ object SessionPrefs {
prefs(context).edit().putInt("gameStoresParallel", count.coerceIn(1, 3)).apply()
}
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), !mangoappSession(context))
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false)
fun setHudEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean(hudKey(context), on).apply()
@@ -233,6 +285,20 @@ object SessionPrefs {
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
}
fun fusionHudConfig(context: Context): String? = prefs(context).getString("fusionHud", null)
fun setFusionHudConfig(context: Context, config: String) {
prefs(context).edit().putString("fusionHud", config).apply()
}
fun fusionHudPosition(context: Context): Pair<Float, Float>? =
prefs(context).getString("fusionHudPos", null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
?.takeIf { it.size == 2 }?.let { it[0] to it[1] }
fun setFusionHudPosition(context: Context, x: Float, y: Float) {
prefs(context).edit().putString("fusionHudPos", "$x,$y").apply()
}
const val HUD_COLOR_MINT = "mint"
val HUD_COLORS = listOf(HUD_COLOR_MINT, "white", "sky", "amber", "violet")
val HUD_OPACITY_RANGE = 30..100
@@ -249,12 +315,34 @@ object SessionPrefs {
prefs(context).edit().putBoolean("lowLatency", on).apply()
}
fun evdevMouse(context: Context): Boolean = prefs(context).getBoolean("evdevMouse", false)
fun setEvdevMouse(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("evdevMouse", on).apply()
}
fun directCursor(context: Context): Boolean = prefs(context).getBoolean("directCursor", false)
fun setDirectCursor(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("directCursor", on).apply()
}
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
fun setBackActionsInverted(context: Context, inverted: Boolean) {
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"
@@ -592,6 +680,8 @@ object SessionPrefs {
}
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true)
fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", true)
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
@@ -642,8 +732,74 @@ object SessionPrefs {
fun logsEnabled(context: Context): Boolean =
prefs(context).getBoolean("logs", true)
fun setLogsEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("logs", on).apply()
fun setLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
setLogPreference(
context,
key = "logs",
oldValue = logsEnabled(context),
newValue = on,
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
)
}
/** Extra Proton, Wine and graphics diagnostics for the next game launch; off unless chosen. */
fun gameDebugLogsEnabled(context: Context): Boolean =
prefs(context).getBoolean("gameDebugLogsEnabled", false)
fun setGameDebugLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
setLogPreference(
context,
key = "gameDebugLogsEnabled",
oldValue = gameDebugLogsEnabled(context),
newValue = on,
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
)
}
private fun setLogPreference(
context: Context,
key: String,
oldValue: Boolean,
newValue: Boolean,
newEffective: Boolean,
): Boolean {
if (oldValue == newValue) return true
val saved = prefs(context)
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
SessionPaths.currentSessionLogsRetained(context)
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
if (oldEffective == newEffective) {
if (saved.edit().putBoolean(key, newValue).commit()) return true
saved.edit().putBoolean(key, oldValue).commit()
return false
}
if (oldEffective && !newEffective) {
try {
publish(false)
} catch (e: Exception) {
android.util.Log.e("GameEnvironment", "Could not disable game diagnostics", e)
return false
}
if (saved.edit().putBoolean(key, newValue).commit()) return true
saved.edit().putBoolean(key, oldValue).commit()
runCatching { publish(oldEffective) }
.onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) }
return false
}
if (!saved.edit().putBoolean(key, newValue).commit()) {
saved.edit().putBoolean(key, oldValue).commit()
return false
}
return try {
publish(newEffective)
true
} catch (e: Exception) {
saved.edit().putBoolean(key, oldValue).commit()
runCatching { publish(oldEffective) }
.onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) }
android.util.Log.e("GameEnvironment", "Could not update game diagnostics", e)
false
}
}
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
@@ -951,22 +1107,24 @@ object SessionPrefs {
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
}
/**
* Performance mode: 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
/** Mirroring still follows the glasses' refresh rate when Performance mode is on. */
fun compositorFpsLimit(mirrorRefreshLimit: Int, performanceMode: Boolean): Int =
if (performanceMode && mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
/** The drawer's frame limit slider: its first stop is Off. */
const val FPS_LIMIT_OFF = 15
const val FPS_LIMIT_MAX = 120
/**
* 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 Steam games, and the drawer's limit caps games
* launched without Steam. Mirroring still follows the glasses' refresh rate.
*/
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0): Int = when {
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
mirrorRefreshLimit <= 0 -> sessionLimit
sessionLimit <= 0 -> mirrorRefreshLimit
else -> minOf(mirrorRefreshLimit, sessionLimit)
}
val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
@@ -1147,7 +1305,7 @@ object SessionPrefs {
resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP
else prefMode(mode)
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", false)
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
fun setPipAutoEnter(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
@@ -1190,7 +1348,8 @@ object SessionPrefs {
}
fun suspendPolicy(context: Context, mode: String): String =
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
prefs(context).getString("suspendPolicy.${prefMode(mode)}",
if (mode == SessionService.MODE_STEAM) SUSPEND_NATIVE else SUSPEND_MANUAL)
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
?.takeIf { it in setOf(SUSPEND_AUTO, SUSPEND_NATIVE, SUSPEND_MANUAL, SUSPEND_NEVER) }
?.let { if (mode != SessionService.MODE_STEAM && it == SUSPEND_NATIVE) SUSPEND_AUTO else it }
@@ -1216,6 +1375,18 @@ object SessionPrefs {
prefs(context).edit().putBoolean(DECKY_ZIP_WARNING_SEEN, true).apply()
}
fun slowUsbWarningOff(context: Context): Boolean = prefs(context).getBoolean(SLOW_USB_WARNING_OFF, false)
fun setSlowUsbWarningOff(context: Context) {
prefs(context).edit().putBoolean(SLOW_USB_WARNING_OFF, true).apply()
}
fun slowUsbDismissed(context: Context): Set<String> = prefs(context).getStringSet(SLOW_USB_DISMISSED, null)?.toSet().orEmpty()
fun setSlowUsbDismissed(context: Context, keys: Set<String>) {
prefs(context).edit().putStringSet(SLOW_USB_DISMISSED, keys.toSet()).apply()
}
fun steamDownloadsInBackground(context: Context): Boolean {
val prefs = prefs(context)
return prefs.getBoolean(STEAM_DOWNLOADS_IN_BACKGROUND, false) ||
@@ -91,6 +91,7 @@ class SessionService : Service() {
private var screenOn = true
private var sessionDisplayId = Display.DEFAULT_DISPLAY
private var manualPauseRequested = false
private var manualHold = false
private var steamSleepToken: String? = null
private var nativeSleepToken: String? = null
private var nativeSleepReady = false
@@ -274,7 +275,11 @@ class SessionService : Service() {
val hold = intent?.getBooleanExtra(EXTRA_HOLD, false) == true
if (hold == signInHold) return START_NOT_STICKY
signInHold = hold
if (hold) manualPauseRequested = false
if (hold) {
manualPauseRequested = false
manualHold = false
SessionState.manualPause = false
}
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
@@ -304,6 +309,14 @@ class SessionService : Service() {
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_PAUSE_NOW -> {
if (!SessionState.running || SessionState.suspended || signInHold) return START_NOT_STICKY
manualHold = true
SessionState.manualPause = true
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_RESUME -> {
resumeSession()
return START_NOT_STICKY
@@ -321,6 +334,7 @@ class SessionService : Service() {
return START_NOT_STICKY
}
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
SessionState.fpsLimit = 0
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
activityVisible = true
@@ -346,6 +360,8 @@ class SessionService : Service() {
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
manualHold = false
SessionState.manualPause = false
SessionState.pipActive = false
pipTask = false
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
@@ -385,10 +401,10 @@ class SessionService : Service() {
}
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
SessionLogCapture.stopFor(dir)
try {
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
} finally {
SessionLogCapture.stopFor(dir)
SessionPaths.release(this, dir)
}
}
@@ -461,13 +477,20 @@ class SessionService : Service() {
SessionFiles.stage(this, root, startsSession = true)
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
SessionArtifacts.awaitCollections()
SessionArtifacts.finishAbandoned(this)
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
VacDiagnostics.arm(this)
com.droiddeck.launcher.agent.AgentGuest.reset(this)
com.droiddeck.launcher.stores.gog.GogComet.begin()
com.droiddeck.launcher.stores.StoreLaunchRequests.start(this)
val sessionDir = openSessionFolder()
try {
GameEnvironmentStore.publish(this)
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
stopSession(-1)
return
}
val sessionLog = File(sessionDir, "session.log")
val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})"
Log.i(TAG, prootLine)
@@ -480,6 +503,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) }
@@ -508,16 +534,9 @@ class SessionService : Service() {
guest.add("DXVK_HDR=1")
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
}
// 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 (SessionState.performanceMode) {
// 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"))
// 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")
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
@@ -525,6 +544,7 @@ class SessionService : Service() {
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
SessionState.deckPad = false
SessionState.secondScreenAutoOpened = false
deckBinds = emptyList()
inputSysfs = null
if (controllersOn) {
@@ -735,7 +755,7 @@ class SessionService : Service() {
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
guest.add("HOME=/root")
guest.add("USER=root")
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
guest.add("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games")
guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8")
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
@@ -880,7 +900,7 @@ class SessionService : Service() {
}
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
FakeInputWriter.prepareRingSlots(fakeInputDir, 5)
val builtinPad = SessionPrefs.builtinPad(this)
val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad &&
!com.droiddeck.launcher.input.PadBridge.anyControllerConnected()
@@ -1038,7 +1058,7 @@ class SessionService : Service() {
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
}
}
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRoots(this)) {
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRootsForXodus(this)) {
if (host.isDirectory && host.canRead()) {
File(LinuxRuntime.rootDir(this), guest.removePrefix("/")).mkdirs()
binds.add(host.path + ":" + guest)
@@ -1354,6 +1374,8 @@ class SessionService : Service() {
if (panelVisible) activityVisible = true
screenOn = readScreenOn()
manualPauseRequested = false
manualHold = false
SessionState.manualPause = false
suspendDownloadNow = false
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
completeNativeSleep()
@@ -1561,12 +1583,12 @@ class SessionService : Service() {
manualPauseRequested = false
}
val controller = suspendController ?: return
if (downloadsBlockingSuspend) acquireLocks()
val steamPause = SessionState.mode == MODE_STEAM && !downloadsBlockingSuspend && when (suspendPolicy) {
if (downloadsBlockingSuspend && !manualHold) acquireLocks()
val steamPause = SessionState.mode == MODE_STEAM && (manualHold || !downloadsBlockingSuspend && when (suspendPolicy) {
SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE -> hidden
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested
else -> false
}
})
if (!steamPause) {
completeNativeSleep()
} else if (nativeSleepToken == null && steamSleepToken == null &&
@@ -1574,12 +1596,15 @@ class SessionService : Service() {
prepareNativeSleep()
}
val prepared = SessionState.mode != MODE_STEAM || nativeSleepReady
val shouldSuspend = steamSleepToken != null || when (suspendPolicy) {
val shouldSuspend = steamSleepToken != null || (manualHold && prepared) || when (suspendPolicy) {
SessionPrefs.SUSPEND_AUTO -> hidden && prepared && !downloadsBlockingSuspend
SessionPrefs.SUSPEND_NATIVE -> hidden && nativeSleepReady && !downloadsBlockingSuspend
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()
@@ -1619,6 +1644,8 @@ class SessionService : Service() {
SessionEvents.record("session.suspend_cancelled")
} else {
suspendAttemptFailed = true
manualHold = false
SessionState.manualPause = false
Log.w(TAG, "could not confirm that the session stopped")
}
}
@@ -1667,7 +1694,7 @@ class SessionService : Service() {
}
private fun resumeSteamSleepOnReturn() {
if (suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
if (!manualHold && suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
completeNativeSleep()
completeSteamSleep()
@@ -1725,42 +1752,48 @@ class SessionService : Service() {
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
}
private fun finishSessionStop(status: Int, stoppedGen: Int) {
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
mainHandler.post {
if (stoppedGen != sessionGen || SessionState.running) {
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
return@post
try {
if (stoppedGen != sessionGen || SessionState.running) {
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
return@post
}
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
manualHold = false
SessionState.manualPause = false
SessionState.pipActive = false
pipTask = false
SessionState.guestPid = -1
com.droiddeck.launcher.agent.AgentGuest.stop()
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks()
MemoryLog.stop()
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else {
val code = SessionState.failureCode ?: "GUEST_EXIT"
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
val failureStatus = SessionState.failureStatus ?: status
SessionEvents.fail(code, message, failureStatus)
}
SessionState.steamVr = false
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
SessionState.notifyEnded(status)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
} finally {
afterStopped()
}
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
SessionState.pipActive = false
pipTask = false
SessionState.guestPid = -1
com.droiddeck.launcher.agent.AgentGuest.stop()
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks()
MemoryLog.stop()
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else {
val code = SessionState.failureCode ?: "GUEST_EXIT"
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
val failureStatus = SessionState.failureStatus ?: status
SessionEvents.fail(code, message, failureStatus)
}
SessionState.steamVr = false
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
SessionState.notifyEnded(status)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
@@ -1791,7 +1824,9 @@ class SessionService : Service() {
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
SessionState.running = false
SessionPaths.take() to SessionState.steamClientArch
val ended = SessionPaths.take()
if (ended != null) SessionArtifacts.collectionStarted(ended)
ended to SessionState.steamClientArch
}
SessionState.micAvailable = false
SessionState.micEnabled = false
@@ -1820,8 +1855,6 @@ class SessionService : Service() {
suspendController = null
if (ended != null) {
VacDiagnostics.snapshot(this, ended)
SessionArtifacts.collectionStarted(ended)
Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
}
components.reversed().forEach {
try {
@@ -1831,6 +1864,9 @@ class SessionService : Service() {
}
}
components.clear()
val collectEnded = {
if (ended != null) Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
}
FakeInputWriter.releaseAllRingSlots()
com.droiddeck.launcher.input.SteamTouchDevice.release()
val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
@@ -1842,13 +1878,13 @@ class SessionService : Service() {
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
finishSessionStop(status, stoppedGen)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "session-teardown").start()
} else {
Thread({
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "gog-session-stop").start()
}
@@ -1866,6 +1902,9 @@ class SessionService : Service() {
}
override fun onTaskRemoved(rootIntent: Intent?) {
if (rootIntent?.component?.className in setOf(
com.droiddeck.launcher.ui.DualScreenActivity::class.java.name,
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return
if (pipTask || xrActivityVisible) {
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
activityVisible = false
@@ -2087,6 +2126,7 @@ class SessionService : Service() {
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
const val ACTION_SUSPEND_NOW = "com.droiddeck.launcher.SUSPEND_NOW"
private const val ACTION_PAUSE_NOW = "com.droiddeck.launcher.PAUSE_NOW"
private const val ACTION_PIP_BEGIN = "com.droiddeck.launcher.PIP_BEGIN"
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
@@ -2161,6 +2201,7 @@ class SessionService : Service() {
fun stop(context: Context) {
if (!SessionState.running) {
SessionState.stopRequested = true
SessionState.installCancellation?.cancel()
return
}
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
@@ -2206,6 +2247,10 @@ class SessionService : Service() {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SIGN_IN_HOLD).putExtra(EXTRA_HOLD, hold))
}
fun pause(context: Context) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PAUSE_NOW))
}
fun resume(context: Context) {
if (!SessionState.running) return
if (SessionState.suspended) SessionState.resumeRequested = true
@@ -37,6 +37,9 @@ object SessionState {
@Volatile
var installing: String? = null
@Volatile
var installCancellation: com.droiddeck.launcher.core.Downloader.Cancellation? = null
@Volatile
var stopRequested = false
@@ -53,6 +56,7 @@ object SessionState {
var resuming by mutableStateOf(false)
var resumeFailures by mutableIntStateOf(0)
var resumeFailed by mutableStateOf(false)
var manualPause by mutableStateOf(false)
@Volatile var pipActive = false
@Volatile
var program: String? = null
@@ -87,6 +91,7 @@ object SessionState {
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
@Volatile var secondScreenDisplay = -1
@Volatile var secondScreenAutoOpened = false
@Volatile
var mode = "steam"
@@ -103,8 +108,9 @@ object SessionState {
@Volatile
var upscaleRatio: Float = 0f
/** Frame limit chosen in the drawer for a game launched without Steam; 0 is off. */
@Volatile
var performanceMode = false
var fpsLimit: Int = 0
@Volatile
var firstFrameSeen = false
@@ -12,16 +12,17 @@ object SettingsReset {
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
"dualScreenMode", "dualScreenLauncher", "dualScreenSessionControls",
"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", "fusionHud", "fusionHudPos", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition",
"stretch16x9", "picturePosition", "railLabels",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
@@ -37,6 +38,7 @@ object SettingsReset {
internal fun isSessionSetting(key: String) = key in SESSION_KEYS || SESSION_PREFIXES.any { key.startsWith(it) }
fun resetAll(context: Context, gameProfiles: Boolean, gameScopes: Collection<String> = emptyList()): Boolean {
if (!SessionPrefs.setGameDebugLogsEnabled(context, false)) return false
var ok = true
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
session.edit().apply { session.all.keys.filter { isSessionSetting(it) }.forEach { remove(it) } }.commit()
@@ -0,0 +1,26 @@
package com.droiddeck.launcher.session
import org.json.JSONObject
import java.io.File
object SteamImportPrompt {
data class Ask(val token: String, val games: List<String>)
private fun folder(root: File) = File(root, "root/.cache/droiddeck")
fun read(root: File): Ask? {
val text = runCatching { File(folder(root), "steam-import.json").readText() }.getOrNull() ?: return null
val json = runCatching { JSONObject(text) }.getOrNull() ?: return null
val token = json.optString("token").takeIf { it.isNotEmpty() } ?: return null
val list = json.optJSONArray("games")
val games = if (list == null) emptyList() else (0 until list.length()).mapNotNull { list.optString(it).takeIf(String::isNotBlank) }
return Ask(token, games)
}
fun answer(root: File, token: String, now: Boolean): Boolean = runCatching {
val dir = folder(root).apply { mkdirs() }
val temp = File(dir, "steam-import.answer.tmp")
temp.writeText(JSONObject().put("token", token).put("choice", if (now) "now" else "later").toString())
temp.renameTo(File(dir, "steam-import.answer"))
}.getOrDefault(false)
}
@@ -0,0 +1,122 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.storage.StorageManager
import com.droiddeck.launcher.frontend.AddedGames
import java.io.File
object UsbLink {
data class Link(val device: String, val mbps: Double, val name: String, val portMbps: Double?, val plug: String = "")
class SlowDrive(val key: String, val name: String, val mbps: Double, val portMbps: Double?) {
val portLimited get() = portMbps != null && portMbps < FAST_MBPS
}
const val FAST_MBPS = 5000.0
fun markShown(context: Context, drive: SlowDrive) = synchronized(this) {
SessionPrefs.setSlowUsbDismissed(context, SessionPrefs.slowUsbDismissed(context) + drive.key)
}
fun stillDue(context: Context, drive: SlowDrive) =
!SessionPrefs.slowUsbWarningOff(context) && drive.key !in SessionPrefs.slowUsbDismissed(context)
fun slowLibrary(context: Context): SlowDrive? {
if (SessionPrefs.slowUsbWarningOff(context)) return null
val mounts = runCatching { File("/proc/self/mounts").readText() }.getOrNull() ?: return null
val sm = context.getSystemService(StorageManager::class.java)
val boot = runCatching { android.provider.Settings.Global.getInt(context.contentResolver, android.provider.Settings.Global.BOOT_COUNT) }.getOrDefault(0)
val drives = libraries(context).mapNotNull { path ->
val link = forPath(path, mounts) ?: return@mapNotNull null
if (link.mbps >= FAST_MBPS) return@mapNotNull null
val volume = runCatching { sm?.getStorageVolume(File(path))?.getDescription(context) }.getOrNull()
SlowDrive(dismissKey(boot, link), link.name.ifBlank { volume.orEmpty() }.ifBlank { File(path).name }, link.mbps, link.portMbps)
}
return synchronized(this) {
val dismissed = SessionPrefs.slowUsbDismissed(context)
val current = dismissed.intersect(drives.map { it.key }.toSet())
if (current != dismissed) SessionPrefs.setSlowUsbDismissed(context, current)
drives.firstOrNull { it.key !in current }
}
}
internal fun dismissKey(boot: Int, link: Link) = "$boot/${link.plug}/${link.device}@${link.mbps}"
private fun libraries(context: Context): List<String> {
val pref = SessionPrefs.gameStorage(context)
val storage = when (pref) {
SessionPrefs.GAME_STORAGE_OFF -> null
"" -> GameStorage.effective(context)?.path
else -> pref
}
val folders = runCatching { AddedGames.roots(context).map { it.host.absolutePath } }.getOrDefault(emptyList())
return (listOfNotNull(storage) + folders).map(::storagePath).filter { external(it) }.distinct()
}
internal fun storagePath(path: String) = if (path.startsWith("/mnt/media_rw/")) "/storage/" + path.removePrefix("/mnt/media_rw/") else path
internal fun external(path: String) = path.startsWith("/storage/") && !path.startsWith("/storage/emulated/") && !path.startsWith("/storage/self/")
fun forPath(path: String, mounts: String, sys: File = File("/sys")): Link? {
val device = mountDevice(rawPath(path), mounts) ?: return null
val block = blockDir(device, sys) ?: return null
val usb = usbDevice(block, sys) ?: return null
val mbps = readSpeed(usb) ?: return null
val name = listOf("manufacturer", "product").mapNotNull { read(File(usb, it)) }.joinToString(" ").trim()
val plug = listOf("busnum", "devnum").mapNotNull { read(File(usb, it)) }.joinToString("-")
return Link(device, mbps, name, portSpeed(usb, sys), plug)
}
internal fun rawPath(path: String) = if (external(path)) "/mnt/media_rw/" + path.removePrefix("/storage/") else path
internal fun mountDevice(path: String, mounts: String): String? {
var best: Pair<String, String>? = null
for (line in mounts.lineSequence()) {
val parts = line.split(' ')
if (parts.size < 2) continue
val point = parts[1].replace("\\040", " ")
if (path != point && !path.startsWith("${point.trimEnd('/')}/")) continue
if (best == null || point.length > best.first.length) best = point to parts[0]
}
val source = best?.second ?: return null
Regex(":(\\d+),(\\d+)$").find(source)?.let { return "${it.groupValues[1]}:${it.groupValues[2]}" }
return if (source.startsWith("/dev/block/") || source.startsWith("/dev/sd")) "name:" + source.substringAfterLast('/') else null
}
internal fun blockDir(device: String, sys: File): File? {
if (device.startsWith("name:")) return File(sys, "class/block/${device.removePrefix("name:")}").takeIf { it.exists() }?.canonicalFile
File(sys, "dev/block/$device").takeIf { it.exists() }?.let { return it.canonicalFile }
return File(sys, "class/block").listFiles()?.firstOrNull { read(File(it, "dev")) == device }?.canonicalFile
}
internal fun usbDevice(block: File, sys: File): File? {
val top = sys.canonicalFile
var dir: File? = block
while (dir != null && dir != top) {
if (File(dir, "speed").isFile && File(dir, "idVendor").isFile) return dir
dir = dir.parentFile
}
return null
}
private fun portSpeed(usb: File, sys: File): Double? {
val bus = read(File(usb, "busnum")) ?: return null
val hub = File(sys, "bus/usb/devices/usb$bus").takeIf { it.exists() }?.canonicalFile ?: return null
val controller = hub.parentFile ?: return null
return controller.listFiles { f -> f.name.matches(Regex("usb\\d+")) }?.mapNotNull { readSpeed(it) }?.maxOrNull()
}
private fun readSpeed(dir: File) = read(File(dir, "speed"))?.toDoubleOrNull()
private fun read(file: File) = runCatching { file.readText().trim() }.getOrNull()?.takeIf { it.isNotEmpty() }
fun generation(mbps: Double) = when {
mbps <= 12 -> "USB 1.1"
mbps < FAST_MBPS -> "USB 2.0"
mbps < 10000 -> "USB 3.2 Gen 1"
mbps < 20000 -> "USB 3.2 Gen 2"
else -> "USB 3.2 Gen 2x2"
}
fun megabytesPerSecond(mbps: Double) = (mbps / 8 * 0.7).toInt()
}
@@ -68,13 +68,13 @@ object VacDiagnostics {
}
}
fun collect(context: Context, dir: File) {
fun collect(context: Context, dir: File): Boolean {
val root = LinuxRuntime.rootDir(context)
val kept = File(dir, SNAPSHOT_MARKER).takeIf { it.isFile }
val marker = kept ?: File(root, MARKER)
val launchList = if (kept != null) File(dir, SNAPSHOT_LAUNCHES) else File(root, LAUNCHES)
if (!marker.isFile) return
try {
if (!marker.isFile) return true
return try {
val armed = marker.readLines().map { it.trim() }
val since = (armed.getOrNull(0)?.toLongOrNull() ?: 0L) * 1000 - 5_000
val arch = armed.getOrNull(1)?.takeIf { it.isNotEmpty() } ?: SessionPrefs.steamClientArch(context)
@@ -125,8 +125,10 @@ object VacDiagnostics {
File(dir, SNAPSHOT_MARKER).delete()
File(dir, SNAPSHOT_LAUNCHES).delete()
Log.i(TAG, "VAC diagnostics: ${consoles.size} console log(s), ${steamHits.size} client VAC line(s), into $dir")
true
} catch (e: Exception) {
Log.w(TAG, "collecting VAC diagnostics", e)
false
}
}
@@ -19,7 +19,7 @@ enum class Bucket { GAMES, GAME_DATA, TOOLS, COMPONENTS, STORES, DESKTOP, SYSTEM
class GameUsage(
val appId: Int, val name: String, val art: File?, val library: String, val internal: Boolean, val lastPlayed: Long,
val game: Long, val prefix: Long, val shaders: Long, val workshop: Long, val shaderDir: File?,
val x64: Boolean = false,
val x64: Boolean = false, val prefixDir: File? = null,
) {
val data: Long get() = prefix + shaders + workshop
val total: Long get() = game + data
@@ -175,14 +175,16 @@ object StorageScan {
}
if (!m.installed) continue
val gameBytes = dir?.let { File(lib.root, "steamapps/common/$it") }?.takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val prefix = File(lib.data, "steamapps/compatdata/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val compatRoot = File(lib.data, "steamapps/compatdata").takeIf { it.isDirectory } ?: File(lib.root, "steamapps/compatdata")
val prefixDir = File(compatRoot, m.appId.toString()).takeIf { it.isDirectory }
val prefix = prefixDir?.let { walker.measure(it) } ?: 0
val shaderDir = File(lib.data, "steamapps/shadercache/${m.appId}").takeIf { it.isDirectory }
val shaders = shaderDir?.let { walker.measure(it) } ?: 0
val workshop = File(lib.root, "steamapps/workshop/content/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val known = art[lib.x64]?.get(m.appId)
games.add(GameUsage(
m.appId, known?.name ?: m.name, known?.art, lib.label, lib.internal, m.lastPlayed,
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64,
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64, prefixDir,
))
}
}
@@ -140,6 +140,13 @@ object StorageState {
FileOps.delete(dir)
})
fun resetPrefix(context: Context, game: GameUsage) = act(context, "prefix-${game.appId}", { _, fresh ->
val dir = fresh.games.firstOrNull { it.appId == game.appId && it.x64 == game.x64 && it.prefixDir?.path == game.prefixDir?.path }
?.prefixDir ?: error("prefix not found")
check(FileOps.delete(dir)) { "cannot delete $dir" }
true
})
fun removeLeftover(context: Context, l: Leftover) = act(context, "leftover-${l.appId}", { _, fresh ->
val leftover = fresh.leftovers.firstOrNull { it.appId == l.appId && it.prefix?.path == l.prefix?.path && it.shaders?.path == l.shaders?.path }
?: return@act false
@@ -63,7 +63,7 @@ class StoreGameSidecar(
val file = File(folder, FILE_NAME)
val tmp = File(folder, "$FILE_NAME.tmp")
tmp.writeText(toJson().toString(2))
if (!tmp.renameTo(file)) { file.delete(); tmp.renameTo(file) }
if (!tmp.renameTo(file)) java.nio.file.Files.move(tmp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
companion object {
@@ -137,10 +137,7 @@ object StoreInstallRoot {
.filter { !isInternal(context, it) && (library == null || !it.absolutePath.startsWith("$library/")) }
.map { root ->
val base = guestFor(context, root)
val guest = if (used.add(base)) base else {
val suffix = "%08x".format(CRC32().apply { update(root.absolutePath.toByteArray()) }.value)
"$base-$suffix".also { used.add(it) }
}
val guest = if (used.add(base)) base else "$base-${pathKey(root)}".also { used.add(it) }
root to guest
}
}
@@ -168,15 +165,20 @@ object StoreInstallRoot {
/** Xodus has its own PRoot mount table and cannot see the selected Steam library's SD bind. */
fun externalRootsForXodus(context: Context): List<Pair<File, String>> {
val roots = externalRoots(context).toMutableList()
val roots = externalRoots(context)
val selectedLibrary = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
?.takeUnless { isInternal(context, it) }
if (selectedLibrary != null && roots.none { it.first.absolutePath == selectedLibrary.absolutePath }) {
roots += selectedLibrary to guestFor(context, selectedLibrary)
}
return roots
?.takeUnless { isInternal(context, it) } ?: return roots
return withSelectedLibrary(roots, selectedLibrary, guestFor(context, selectedLibrary))
}
internal fun withSelectedLibrary(roots: List<Pair<File, String>>, library: File, base: String): List<Pair<File, String>> {
if (roots.any { it.first.absolutePath == library.absolutePath }) return roots
val guest = if (roots.none { it.second == base }) base else "$base-${pathKey(library)}"
return roots + (library to guest)
}
private fun pathKey(root: File): String = "%08x".format(CRC32().apply { update(root.absolutePath.toByteArray()) }.value)
fun externalBindSpecs(context: Context): List<String> = externalBindSpecs(externalRoots(context), LinuxRuntime.rootDir(context))
fun externalBindSpecsForXodus(context: Context): List<String> =
@@ -192,7 +194,7 @@ object StoreInstallRoot {
private fun guestFor(context: Context, root: File): String {
val sm = context.getSystemService(StorageManager::class.java)
val uuid = runCatching { sm?.getStorageVolume(root)?.uuid }.getOrNull()?.takeIf { it.isNotBlank() }?.replace(Regex("[^A-Za-z0-9-]"), "")
val key = uuid ?: "%08x".format(CRC32().apply { update(root.absolutePath.toByteArray()) }.value)
val key = uuid ?: pathKey(root)
return "$GUEST_EXTERNAL/$key"
}
@@ -254,6 +256,7 @@ object StoreInstallRoot {
val sidecar = StoreGameSidecar.read(folder)
when {
sidecar == null -> Unfinished(store, null, folder)
store == Store.GOG && sidecar.state == StoreGameSidecar.STATE_UPDATING -> null
!sidecar.isInstalled -> Unfinished(store, sidecar.id, folder)
else -> null
}
@@ -30,7 +30,12 @@ object StoreInstalls {
it.write(before.copy(state = StoreGameSidecar.STATE_UPDATING, installVersion = "").toJson().toString(2).toByteArray(Charsets.UTF_8))
it.fd.sync()
}
Files.move(stage.toPath(), StoreGameSidecar.file(folder).toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
val record = StoreGameSidecar.file(folder).toPath()
try {
Files.move(stage.toPath(), record, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} catch (e: java.nio.file.AtomicMoveNotSupportedException) {
Files.move(stage.toPath(), record, StandardCopyOption.REPLACE_EXISTING)
}
} finally {
stage.delete()
}
Loaded 100 of 731 files, more files were not shown because too many files have changed in this diff. Show more